0% found this document useful (0 votes)
293 views116 pages

Principles of Modelling Peter Fritzen PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
293 views116 pages

Principles of Modelling Peter Fritzen PDF

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Principles of Object-Oriented

Modeling and Simulation


with Modelica
Mini-Tutorial for MODPROD Workshop 2009

Peter Fritzson
Linköping University, Dept. of Comp. & Inform. Science
SE 581-83, Linköping, Sweden
[email protected]

Reference Disturbance

Controller Actuator System Output

2009-02-03 MODPROD’2009
Tutorial Aim

This tutorial aims to give the participant an


• introduction to object-oriented modeling and simulation
• introduction to the Modelica language
• hands-on experience in textual modeling
• (Probably not enough time: hands-on experience in
graphical modeling)

After the course participants should be


able to develop basic models on their own.

2 Copyright © Peter Fritzson


Software Installation

• Start the software installation

• Install OpenModelica-1.4.5.msi from the OpenModelica


USB Stick (Windows)
• If you have Mac, install OpenModelica-1.4.5.dmg

3 Copyright © Peter Fritzson


Tutorial Based on Recent Book, 2004

Peter Fritzson
Principles of Object Oriented
Modeling and Simulation with
Modelica 2.1

Wiley-IEEE Press

940 pages

4 Copyright © Peter Fritzson


Acknowledgements, Usage, Copyrights
• If you want to use the Powerpoint version of these slides in your
own course, send an email to: [email protected]
• Thanks to Emma Larsdotter Nilsson for contributions to the layout
of these slides
• Most examples and figures in this tutorial are adapted with
permission from Peter Fritzson’s book ”Principles of Object
Oriented Modeling and Simulation with Modelica 2.1”, copyright
Wiley-IEEE Press
• Some examples and figures reproduced with permission from
Modelica Association, Martin Otter, Hilding Elmqvist, and
MathCore
• Modelica Association: www.modelica.org
• OpenModelica: www.ida.liu.se/projects/OpenModelica

5 Copyright © Peter Fritzson


Why Modeling & Simulation?

• Increase understanding of complex systems


• Design and optimization
• Virtual prototyping
• Verification Build more complex systems

6 Copyright © Peter Fritzson


Examples of Complex Systems
• Robotics
• Automotive
• Aircrafts
• Satellites
• Biomechanics
• Power plants
• Hardware-in-the-loop,
real-time simulation

7 Copyright © Peter Fritzson


Kinds of Mathematical Models

• Dynamic vs. Static models

• Continuous-time vs. Discrete-time dynamic models

• Quantitative vs. Qualitative models

8 Copyright © Peter Fritzson


Dynamic vs. Static Models

A dynamic model includes time in the model


A static model can be defined without involving
time
Resistor voltage – static system

Input current
pulse
Capacitor voltage - dynamic

time

9 Copyright © Peter Fritzson


Continuous vs. Discrete-Time Dynamic Models

Continuous-time models may evolve their variable values


continuously during a time period
Discrete-time variables change values a finite number of
times during a time period

Continuous

Discrete

time

10 Copyright © Peter Fritzson


Principles of Graphical Equation-Based Modeling
• Each icon represents a physical component i.e. Resistor, mechanical Gear
Box, Pump

• Composition lines represent the actual physical connections i.e. electrical line,
mechanical connection, heat flow
Component 1 Component 2

Connection

Component 3

• Variables at the interfaces describe interaction with other component

• Physical behavior of a component is described by equations

• Hierarchical decomposition of components

11 Copyright © Peter Fritzson


Application Example – Industry Robot
k2

i
axis6
qddRef cut joint
qdRef
1
qRef
1
k1 r3Control
r3Motor r3Drive1 tn
i 1
S S
qd axis5

qdRef Kd
S
0.03 rel

Jmotor=J joint=0
spring=c axis4
S
qRef pSum Kv sum w Sum rate2 rate3 iRef gear=i

fric=Rv0
+1 b(s) 340.8
0.3
- +1 - a(s) S

axis3

rate1 tacho2 tacho1


b(s) b(s)
PT1
a(s) a(s)
axis2
g5

q
qd

Rp2=50

Ra=250 La=(250/(2*D*wm))
Rd1=100
C=0.004*D/w m Rp1=200 axis1

Rd2=100
Ri=10
- -
-
+ +
dif f + pow er
OpI
Vs

Rd4=100
Srel = n*transpose(n)+(identity(3)- n*transpose(n))*cos(q)- skew(n)*sin(q);
emf
y
wrela = n*qd;
Rd3=100

x
g3
zrela = n*qdd; inertial
Sb = Sa*transpose(Srel); g1

r0b = r0a;
hall2

vb = Srel*va; hall1 w r
wb = Srel*(wa + wrela);
ab = Srel*aa;
zb = Srel*(za + zrela + cross(wa, wrela)); qd g4
q g2

Courtesy of Martin Otter

12 Copyright © Peter Fritzson


GTX Gas Turbine Power Cutoff Mechanism

Developed by
Hello
MathCore for
Siemens
Courtesy of Siemens Industrial Turbomachinery AB

13 Copyright © Peter Fritzson


Modelica –
The Next Generation Modeling Language

14 Copyright © Peter Fritzson


Stored Knowledge

Model knowledge is stored in books and human minds


which computers cannot access

“The change of motion is proportional to


the motive force impressed “
– Newton

15 Copyright © Peter Fritzson


The Form – Equations

• Equations were used in the third millennium B.C.


• Equality sign was introduced by Robert Recorde in 1557

Newton still wrote text (Principia, vol. 1, 1686)


“The change of motion is proportional to the motive force impressed ”

CSSL (1967) introduced a special form of “equation”:


variable = expression
v = INTEG(F)/m

Programming languages usually do not allow equations!

16 Copyright © Peter Fritzson


Modelica – The Next Generation Modeling Language
Declarative language
Equations and mathematical functions allow acausal modeling,
high level specification, increased correctness
Multi-domain modeling
Combine electrical, mechanical, thermodynamic, hydraulic,
biological, control, event, real-time, etc...
Everything is a class
Strongly typed object-oriented language with a general class
concept, Java & MATLAB-like syntax
Visual component programming
Hierarchical system architecture capabilities
Efficient, non-proprietary
Efficiency comparable to C; advanced equation compilation,
e.g. 300 000 equations, ~150 000 lines on standard PC

17 Copyright © Peter Fritzson


Object Oriented Mathematical Modeling

• The static declarative structure of a mathematical model


is emphasized
• OO is primarily used as a structuring concept
• OO is not viewed as dynamic object creation and
sending messages
• Dynamic model properties are expressed in a
declarative way through equations.
• Acausal classes supports better reuse of modeling and
design knowledge than traditional classes
18 Copyright © Peter Fritzson
Modelica Acausal Modeling

What is acausal modeling/design?


Why does it increase reuse?
The acausality makes Modelica library classes more reusable
than traditional classes containing assignment statements
where the input-output causality is fixed.
Example: a resistor equation:
R*i = v;
can be used in three ways:
i := v/R;
v := R*i;
R := v/i;
19 Copyright © Peter Fritzson
Brief Modelica History

• First Modelica design group meeting in fall 1996


• International group of people with expert knowledge in both
language design and physical modeling
• Industry and academia

• Modelica Versions
• 1.0 released September 1997
• 2.0 released March 2002
• 2.2 released March 2005
• 3.0 released September 2007

• Modelica Association established 2000


• Open, non-profit organization

20 Copyright © Peter Fritzson


Modelica Conferences
• The 1st International Modelica conference October, 2000

• The 2nd International Modelica conference March 18-19, 2002

• The 3rd International Modelica conference November 5-6, 2003 in


Linköping, Sweden

• The 4th International Modelica conference March 6-7, 2005 in


Hamburg, Germany
• The 5th International Modelica conference September 4-5, 2006 in
Vienna, Austria
• The 6th International Modelica conference March 3-4, 2008 in
Bielefeld, Germany

21 Copyright © Peter Fritzson


Demo – Basic Graphical Modeling

• Demo (Can use the SimForge Graphical Editor)

22 Copyright © Peter Fritzson


Graphical Modeling - Using Drag and Drop Composition

23 Copyright © Peter Fritzson


Completed DCMotor using Graphical Composition

Courtesy
MathCore
Engineering AB

24 Copyright © Peter Fritzson


Multi-Domain (Electro-Mechanical) Modelica Model

• A DC motor can be thought of as an electrical circuit which also


contains an electromechanical component
model DCMotor
Resistor R(R=100);
Inductor L(L=100);
VsourceDC DC(f=10);
Ground G;
ElectroMechanicalElement EM(k=10,J=10, b=2);
Inertia load;
equation R L
connect(DC.p,R.n);
EM
connect(R.p,L.n); DC
connect(L.p, EM.n);
connect(EM.p, DC.n); load
connect(DC.n,G.p);
connect(EM.flange,load.flange);
G
end DCMotor

25 Copyright © Peter Fritzson


Corresponding DCMotor Model Equations

The following equations are automatically derived from the Modelica model:

(load component not included)

Automatic transformation to ODE or DAE for simulation:

26 Copyright © Peter Fritzson


The OpenModelica Environment
www.OpenModelica.org

27 Copyright © Peter Fritzson


OpenModelica

• Goal: comprehensive modeling and simulation


environment for research, teaching, and industrial usage
• Free, open-source for academic use
• Commercial users have to be members of
Open Source Modelica Consortium (OSMC)
• Available under OSMC-PL license
• The OpenModelica compiler (OMC) implemented in
MetaModelica, a slightly extended Modelica
• Invitation for open-source cooperation around
OpenModelica, tools, and applications

28 Copyright © Peter Fritzson


OpenModelica Environment Architecture

Eclipse Plugin Graphical Model


Editor/Browser Editor/Browser

Interactive
Emacs session handler Textual
Editor/Browser Model Editor

DrModelica
OMNoteBook Execution Modelica
Model Editor Compiler

Modelica
Debugger

29 Copyright © Peter Fritzson


OpenModelica Client-Server Architecture

Parse
Client: Graphic
Model Editor
Server: Main Program
Corba
Including Compiler,
Interpreter, etc. Client: OMShell
Interactive
Session Handler

SCode Interactive
Client: Eclipse
Untyped API
Plugin MDT
Inst
Typed Checked Command API
system
plot
Ceval
etc.

30 Copyright © Peter Fritzson


Translation of Models to Simulation Code
Modelica
Graphical Editor Modelica Modelica
Modelica Model Source code
Textual Editor Modelica Model
Translator
Flat model
Analyzer
Sorted equations
Optimizer
Optimized sorted
equations
Code generator
C Code
C Compiler
Executable
Simulation

31 Copyright © Peter Fritzson


Released in OpenModelica 1.4.5

• Compiler/interpreter – OMC
• Interactive session handler – OMShell
• Notebook with DrModelica – OMNotebook
• Eclipse plugin Modelica Development Tooling (MDT)

• Also available: SimForge graphical editor

32 Copyright © Peter Fritzson


Platforms

• All OpenModelica GUI tools (OMShell, MDT,


OMNotebook) are developed on the Qt4 GUI library,
portable between Windows, Linux, Mac
• Both compilers (OMC, MMC) are portable between the
three platforms

• Windows – main development and release platform


• Linux – available
• Mac –available

33 Copyright © Peter Fritzson


Interactive Session Handler – dcmotor Example

• OMShell – OpenModelica Shell


>>simulate(dcmotor,startTime=0.0,stopTime=10.0)
>>plot({load.w,load.phi})
model dcmotor
Modelica.Electrical.Analog.Basic.Resistor r1(R=10);
Modelica.Electrical.Analog.Basic.Inductor i1;
Modelica.Electrical.Analog.Basic.EMF emf1;
Modelica.Mechanics.Rotational.Inertia load;
Modelica.Electrical.Analog.Basic.Ground g;
Modelica.Electrical.Analog.Sources.ConstantVoltage v;
equation
connect(v.p,r1.p);
connect(v.n,g.p);
connect(r1.n,i1.p);
connect(i1.n,emf1.p);
connect(emf1.n,g.p);
connect(emf1.flange_b,load.flange_a);
end dcmotor;

34 Copyright © Peter Fritzson


OpenModelica MDT – Eclipse Plugin

• Browsing of packages, classes, functions


• Automatic building of executables;
separate compilation
• Syntax highlighting
• Code completion,
Code query support for developers
• Automatic Indentation
• Debugger
(Prel. version for algorithmic subset)

35 Copyright © Peter Fritzson


OpenModelica MDT – Usage Example

Code Assistance on
function calling.

36 Copyright © Peter Fritzson


The Modelica Language –
Modelica Classes and Inheritance

37 Copyright © Peter Fritzson


Variables and Constants

Built-in primitive data types


Boolean true or false
Integer Integer value, e.g. 42 or –3
Real Floating point value, e.g. 2.4e-6
String String, e.g. “Hello world”
Enumeration Enumeration literal e.g. ShirtSize.Medium

38 Copyright © Peter Fritzson


Variables and Constants cont’

• Names indicate meaning of constant


• Easier to maintain code
• Parameters are constant during simulation
• Two types of constants in Modelica
• constant
• parameter
constant Real PI=3.141592653589793;
constant String redcolor = "red";
constant Integer one = 1;
parameter Real mass = 22.5;

39 Copyright © Peter Fritzson


Comments in Modelica

1) Declaration comments, e.g. Real x "state variable";

class VanDerPol "Van der Pol oscillator model"


Real x(start = 1) "Descriptive string for x”; // x starts at 1
Real y(start = 1) "y coordinate”; // y starts at 1
parameter Real lambda = 0.3;
equation
der(x) = y; // This is the 1st diff equation //
der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */
end VanDerPol;

2) Source code comments, disregarded by compiler


2a) C style, e.g. /* This is a C style comment */
2b) C++ style, e.g. // Comment to the end of the line…

40 Copyright © Peter Fritzson


A Simple Rocket Model
thrust − m ass ⋅ gravity
Rocket acceleration =
m ass
thrust
m ass ′ = − m assLossRate ⋅ abs ( thrust )
apollo13

mg altitude ′ = velocity
velocity ′ = acceleration

declaration
new model class Rocket "rocket class" comment
parameters (changeable parameter String name;
before the simulation) Real mass(start=1038.358);
Real altitude(start= 59404);
floating point Real velocity(start= -2003); start value
type Real acceleration;
Real thrust; // Thrust force on rocket
Real gravity; // Gravity forcefield
parameter Real massLossRate=0.000277; name + default value
equation
(thrust-mass*gravity)/mass = acceleration; mathematical
der(mass) = -massLossRate * abs(thrust); equation (acausal)
der(altitude) = velocity;
differentiation with der(velocity) = acceleration;
regards to time end Rocket;

41 Copyright © Peter Fritzson


Celestial Body Class

A class declaration creates a type name in Modelica


class CelestialBody
constant Real g = 6.672e-11;
parameter Real radius;
parameter String name;
parameter Real mass;
end CelestialBody;

An instance of the class can be


...
declared by prefixing the type name to
CelestialBody moon;
a variable name ...

The declaration states that moon is a variable


containing an object of type CelestialBody

42 Copyright © Peter Fritzson


Moon Landing
Rocket apollo13
thrust moon . g ⋅ moon .mass
apollo . gravity =
mg
(apollo .altitude + moon . radius )2

altitude
CelestialBody

class MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
only access inside protected
the class parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
access by dot public
notation outside the Rocket apollo(name="apollo13");
class CelestialBody moon(name="moon",mass=7.382e22,radius=1.738e6);
equation
apollo.thrust = if (time < thrustDecreaseTime) then force1
else if (time < thrustEndTime) then force2
else 0;
apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
end MoonLanding;

43 Copyright © Peter Fritzson


Simulation of Moon Landing
simulate(MoonLanding, stopTime=230)
plot(apollo.altitude, xrange={0,208})
plot(apollo.velocity, xrange={0,208})

30000
50 100 150 200
25000
-100
20000
-200
15000

10000 -300

5000 -400

50 100 150 200

It starts at an altitude of 59404 (not The rocket initially has a high negative
shown in the diagram) at time zero, velocity when approaching the lunar
gradually reducing it until surface. This is reduced to zero at
touchdown at the lunar surface touchdown, giving a smooth landing
when the altitude is zero

44 Copyright © Peter Fritzson


Restricted Class Keywords

• The class keyword can be replaced by other keywords, e.g.: model, record,
block, connector, function, ...
• Classes declared with such keywords have restrictions
• Restrictions apply to the contents of restricted classes

• Example: A model is a class that cannot be used as a connector class


• Example: A record is a class that only contains data, with no equations
• Example: A block is a class with fixed input-output causality
model CelestialBody
constant Real g = 6.672e-11;
parameter Real radius;
parameter String name;
parameter Real mass;
end CelestialBody;

45 Copyright © Peter Fritzson


Modelica Functions

• Modelica Functions can be viewed as a special kind of


restricted class with some extensions
• A function can be called with arguments, and is
instantiated dynamically when called
• More on functions and algorithms later

function sum
input Real arg1;
input Real arg2;
output Real result;
algorithm
result := arg1+arg2;
end sum;

46 Copyright © Peter Fritzson


Inheritance
parent class to Color

restricted kind of record ColorData


class without parameter Real red = 0.2;
equations parameter Real blue = 0.6;
Real green; class ExpandedColor
end ColorData; parameter Real red=0.2;
child class or parameter Real blue=0.6;
subclass
Real green;
class Color equation
keyword extends ColorData; red + blue + green = 1;
denoting equation
inheritance
end ExpandedColor;
red + blue + green = 1;
end Color;

Data and behavior: field declarations, equations, and


certain other contents are copied into the subclass

47 Copyright © Peter Fritzson


Multiple Inheritance

Multiple Inheritance is fine – inheriting both geometry and color


class Point
Real x;
class Color
Real y,z;
parameter Real red=0.2;
end Point;
parameter Real blue=0.6;
Real green; class ColoredPoint
equation extends Point;
red + blue + green = 1; extends Color;
multiple inheritance
end Color; end ColoredPoint;

class ColoredPointWithoutInheritance
Real x;
Real y, z;
parameter Real red = 0.2; Equivalent to
parameter Real blue = 0.6;
Real green;
equation
red + blue + green = 1;
end ColoredPointWithoutInheritance;

48 Copyright © Peter Fritzson


Simple Class Definition

• Simple Class Definition • Often used for


• Shorthand Case of Inheritance
introducing new
• Example: names of types:
class SameColor = Color;

type Resistor = Real;


Equivalent to:
connector MyPin = Pin;
class SameColor
inheritance extends Color;
end SameColor;

49 Copyright © Peter Fritzson


Inheritance Through Modification

• Modification is a concise way of combining inheritance


with declaration of classes or instances
• A modifier modifies a declaration equation in the
inherited class
• Example: The class Real is inherited, modified with a
different start value equation, and instantiated as an
altitude variable:

...
Real altitude(start= 59404);
...

50 Copyright © Peter Fritzson


The Moon Landing - Example Using Inheritance (I)
Rocket
apollo13 thrust

mg model Rocket "generic rocket class"


extends Body;
altitude parameter Real massLossRate=0.000277;
CelestialBody Real altitude(start= 59404);
Real velocity(start= -2003);
Real acceleration;
Real thrust;
model Body "generic body" Real gravity;
Real mass; equation
String name; thrust-mass*gravity= mass*acceleration;
end Body; der(mass)= -massLossRate*abs(thrust);
der(altitude)= velocity;
der(velocity)= acceleration;
model CelestialBody
end Rocket;
extends Body;
constant Real g = 6.672e-11;
parameter Real radius;
end CelestialBody;

51 Copyright © Peter Fritzson


The Moon Landing - Example using Inheritance (II)

inherited
parameters

model MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
Rocket apollo(name="apollo13", mass(start=1038.358) );
CelestialBody moon(mass=7.382e22,radius=1.738e6,name="moon");
equation
apollo.thrust = if (time<thrustDecreaseTime) then force1
else if (time<thrustEndTime) then force2
else 0;
apollo.gravity =moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
end Landing;

52 Copyright © Peter Fritzson


Inheritance of Protected Elements
If an extends-clause is preceded by the protected keyword, all
inherited elements from the superclass become protected elements of
the subclass
class ColoredPoint
class Point protected
Real x; extends Color;
class Color
Real y,z; public
Real red;
end Point; extends Point;
Real blue;
Real green; end ColoredPoint;
equation
red + blue + green = 1; Equivalent to
end Color;
class ColoredPointWithoutInheritance
The inherited fields from Point keep their Real x;
protection status since that extends- Real y,z;
protected Real red;
clause is preceded by public protected Real blue;
protected Real green;
A protected element cannot be equation
red + blue + green = 1;
accessed via dot notation! end ColoredPointWithoutInheritance;

53 Copyright © Peter Fritzson


Exercises Part II
(30 minutes)

54 Copyright © Peter Fritzson


Exercises Part II

• Start OMNotebook
• Start->Programs->OpenModelica->OMNotebook
• Open File: Exercises-ModelicaTutorial.onb

• Open Exercises-ModelicaTutorial.pdf

55 Copyright © Peter Fritzson


Exercises 2.1 and 2.2
• Open the Exercises-ModelicaTutorial.onb found in the Tutorial
directory.
• Exercise 2.1. Simulate and plot the HelloWorld example. Do a
slight change in the model, re-simulate and re-plot. Try command-
completion, val( ), etc.
class HelloWorld "A simple equation"
Real x(start=1);
equation simulate(HelloWorld, stopTime = 2)
der(x)= -x; plot(x)
end HelloWorld;

• Locate the VanDerPol model in DrModelica (link from Section


2.1), using OMNotebook!
• Exercise 2.2: Simulate and plot VanDerPol. Do a slight change in
the model, re-simulate and re-plot.

56 Copyright © Peter Fritzson


Exercise 2.1 – Hello World!

A Modelica “Hello World” model


Equation: x’ = - x class HelloWorld "A simple equation”
Initial condition: x(0) = 1 parameter Real a=-1;
Real x(start=1);
equation
der(x)= a*x;
end HelloWorld;

Simulation in OpenModelica environment


1

0.8 simulate(HelloWorld, stopTime = 2)


0.6
plot(x)

0.4

0.2

0.5 1 1.5 2

57 Copyright © Peter Fritzson


Exercise 2.2 – Van der Pol Oscillator
class VanDerPol "Van der Pol oscillator model"
Real x(start = 1) "Descriptive string for x"; // x starts at 1
Real y(start = 1) "y coordinate"; // y starts at 1
parameter Real lambda = 0.3;
equation
der(x) = y; // This is the 1st diff equation //
der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */
end VanDerPol;

simulate(VanDerPol,stopTime = 25)
1
plotParametric(x,y)

-2 -1 1 2

-1

-2

58 Copyright © Peter Fritzson


Exercise 2.5 – Model the system below

• Model this Simple System of Equations in Modelica

59 Copyright © Peter Fritzson


OMNotebook Electronic Notebook with DrModelica

• Primarily for teaching


• Interactive electronic
book
• Platform independent

60 Copyright © Peter Fritzson


Cells with both Text and Graphics

• Text Cells
• Input Cells
• Graphic Cells

61 Copyright © Peter Fritzson


Exercises and Answers in OMNotebook DrModelica

Easy to follow
Exercises with
solutions hidden in
collapsed cells

62 Copyright © Peter Fritzson


Some OMNotebook Commands

• Shift-return (evaluates a cell)


• File Menu (open, close, etc.)
• Text Cursor (vertical), Cell cursor (horizontal)
• Cell types: text cells & executable code cells
• Copy, paste, group cells
• Copy, paste, group text
• Command Completion (shift-tab)

• (see also OpenModelica Users Guide or OMNotebook help)

63 Copyright © Peter Fritzson


OMNotebook Cell Editing Exercises (optional)

• Select and copy a cell (tree to the right)


• Position the horizontal cell cursor: first click between
cells; then click once more on top of the horizontal line
• Paste the cell

• Note: You can find most Users Guide examples in the


UsersGuideExamples.onb in the testmodels directory of
the OpenModelica installation.

64 Copyright © Peter Fritzson


Components, Connectors and Connections –
Modelica Libraries and Graphical Modeling

65 Copyright © Peter Fritzson


Software Component Model
Interface Acausal coupling
Connector

Component Connection Component


Causal coupling

A component class should be defined independently of the


environment, very essential for reusability
A component may internally consist of other components, i.e.
hierarchical modeling
Complex systems usually consist of large numbers of connected
components

66 Copyright © Peter Fritzson


Connectors and Connector Classes

Connectors are instances of connector classes


electrical connector

connector class connector Pin


Voltage v; v +
keyword flow indicates flow Current i;
that currents of
pin
end Pin;
connected pins sum to i
zero.
Pin pin;
an instance pin of
class Pin
mechanical connector

connector class connector Flange


Position s;
flow Force f; s
end Flange; flange
f
an instance flange of Flange flange;
class Flange

67 Copyright © Peter Fritzson


The flow prefix

Two kinds of variables in connectors:


• Non-flow variables potential or energy level
• Flow variables represent some kind of flow
Coupling
• Equality coupling, for non-flow variables
• Sum-to-zero coupling, for flow variables

The value of a flow variable is positive when the current or the


flow is into the component
v
pin
positive flow direction:
i +

68 Copyright © Peter Fritzson


Physical Connector

• Classes Based on Energy Flow


Domain Potential Flow Carrier Modelica
Type Library
Electrical.
Electrical Voltage Current Charge
Analog
Mechanical.
Translational Position Force Linear momentum Translational
Angular momentum Mechanical.
Rotational Angle Torque Rotational
Magnetic potential Magnetic flux
Magnetic Magnetic flux
rate
Hydraulic Pressure Volume flow Volume HyLibLight
Heat Temperature Heat flow Heat HeatFlow1D
Chemical potential Under
Chemical Particle flow Particles
construction

Pneumatic Pressure Mass flow Air PneuLibLight

69 Copyright © Peter Fritzson


connect-equations
Connections between connectors are realized as equations in Modelica
connect(connector1,connector2)

The two arguments of a connect-equation must be references to connectors,


either to be declared directly within the same class or be members of one of
the declared variables in that class

+ v v +
pin1 pin2
i i

Pin pin1,pin2;
//A connect equation
//in Modelica:
connect(pin1,pin2);
Corresponds to pin1.v = pin2.v;
pin1.i + pin2.i =0;

70 Copyright © Peter Fritzson


Connection Equations

Pin pin1,pin2;
//A connect equation
//in Modelica
connect(pin1,pin2);
Corresponds to pin1.v = pin2.v;
pin1.i + pin2.i =0;

Multiple connections are possible:


connect(pin1,pin2); connect(pin1,pin3); ... connect(pin1,pinN);

Each primitive connection set of nonflow variables is used to


generate equations of the form:

v1 = v 2 = v 3 = … v n
Each primitive connection set of flow variables is used to generate sum-
to-zero equations of the form:
i1 + i 2 + … ( − i k ) + … i n = 0

71 Copyright © Peter Fritzson


Acausal, Causal, and Composite Connections

Two basic and one composite kind of connection in Modelica


• Acausal connections
• Causal connections, also called signal connections
• Composite connections, also called structured connections, composed of basic or
composite connections

connector class connector OutPort


fixed causality output Real signal;
end OutPort

72 Copyright © Peter Fritzson


Common Component Structure

The base class TwoPin has


two connectors p and n for p.v i + Tw oP in
n
- i n.v
p
positive and negative pins p.i n.i
respectively i

partial class partial model TwoPin


(cannot be Voltage v connector Pin electrical connector class
instantiated) Current i Voltage v;
positive pin Pin p; flow Current i;
negative pin Pin n; end Pin;
equation
v = p.v - n.v;
0 = p.i + n.i;
i = p.i;
end TwoPin;
// TwoPin is same as OnePort in
// Modelica.Electrical.Analog.Interfaces

73 Copyright © Peter Fritzson


Electrical Components
model Resistor ”Ideal electrical resistor”
extends TwoPin; p.i n.i
parameter Real R; +
equation
p.v n.v
R*i = v; v
end Resistor;

model Inductor ”Ideal electrical inductor”


extends TwoPin; p.i n.i
parameter Real L ”Inductance”; +
equation
p.v n.v
L*der(i) = v; v
end Inductor;

model Capacitor ”Ideal electrical capacitor”


extends TwoPin; p.i n.i
parameter Real C ; +
equation p.v n.v
i=C*der(v); v
end Capacitor;

74 Copyright © Peter Fritzson


Electrical Components cont’

model Source
extends TwoPin; v(t)
p.i n.i
parameter Real A,w;
+
equation
v = A*sin(w*time); p.v n.v
end Resistor;

model Ground
Pin p; p.v p.i
equation
p.v = 0;
end Ground;

75 Copyright © Peter Fritzson


Resistor Circuit

i1 i2
n R1 p p R2 n
v1 v2

v3
p R3 n
i3

model ResistorCircuit
Resistor R1(R=100);
Resistor R2(R=200);
Resistor R3(R=300);
equation R1.p.v = R2.p.v;
connect(R1.p, R2.p); Corresponds to R1.p.v = R3.p.v;
connect(R1.p, R3.p); R1.p.i + R2.p.i + R3.p.i = 0;
end ResistorCircuit;

76 Copyright © Peter Fritzson


Modelica Standard Library - Graphical Modeling

• Modelica Standard Library (called Modelica) is a


standardized predefined package developed by
Modelica Association

• It can be used freely for both commercial and


noncommercial purposes under the conditions of The
Modelica License.

• Modelica libraries are available online including


documentation and source code from
http://www.modelica.org/library/library.html

77 Copyright © Peter Fritzson


Modelica Standard Library cont’

Modelica Standard Library contains components from various


application areas, with the following sublibraries:
• Blocks Library for basic input/output control blocks
• Constants Mathematical constants and constants of nature
• Electrical Library for electrical models
• Icons Icon definitions
• Math Mathematical functions
• Mechanics Library for mechanical systems
• Media Media models for liquids and gases
• SIunits Type definitions based on SI units according to ISO 31-1992
• Stategraph Hierarchical state machines (analogous to Statecharts)
• Thermal Components for thermal systems
• Utilities Utility functions especially for scripting

78 Copyright © Peter Fritzson


Modelica.Blocks

This library contains input/output blocks to build up block diagrams.

Library Library Library Library Library Library

Continuous Sources Math Interfaces NonLinear D iscrete

Example:

79 Copyright © Peter Fritzson


Modelica.Electrical

Electrical components for building analog, digital, and multiphase


circuits

Library Library Library Library

Analog Digital Machines MultiPhase

Examples:
V2

R2 R4

Gnd9

C2 Gnd3 Gnd6 C4
R1 Transistor1 Transistor2 R3

V1 C1 I1 C5 C3 Gnd4

Gnd1 Gnd2 Gnd7 Gnd8 Gnd5

80 Copyright © Peter Fritzson


Modelica.Mechanics

Package containing components for mechanical systems


Subpackages:
• Rotational 1-dimensional rotational mechanical components
• Translational 1-dimensional translational mechanical components
• MultiBody 3-dimensional mechanical components

81 Copyright © Peter Fritzson


Connecting Components from Multiple Domains

• Block domain ind R1


1

• Mechanical domain emf


R2

ex ac iner vsen

• Electrical domain Block Mechanical Electrical


2

domain domain G domain

model Generator
Modelica.Mechanics.Rotational.Accelerate ac;
Modelica.Mechanics.Rotational.Inertia iner;
Modelica.Electrical.Analog.Basic.EMF emf(k=-1);
Modelica.Electrical.Analog.Basic.Inductor ind(L=0.1);
Modelica.Electrical.Analog.Basic.Resistor R1,R2;
Modelica.Electrical.Analog.Basic.Ground G;
Modelica.Electrical.Analog.Sensors.VoltageSensor vsens;
Modelica.Blocks.Sources.Exponentials ex(riseTime={2},riseTimeConst={1});
equation
connect(ac.flange_b, iner.flange_a); connect(iner.flange_b, emf.flange_b);
connect(emf.p, ind.p); connect(ind.n, R1.p); connect(emf.n, G.p);
connect(emf.n, R2.n); connect(R1.n, R2.p); connect(R2.p, vsens.n);
connect(R2.n, vsens.p); connect(ex.outPort, ac.inPort);
end Generator;

82 Copyright © Peter Fritzson


DCMotor Model Multi-Domain (Electro-Mechanical)

A DC motor can be thought of as an electrical circuit which


also contains an electromechanical component.

model DCMotor
Resistor R(R=100);
Inductor L(L=100);
VsourceDC DC(f=10);
Ground G;
EMF emf(k=10,J=10, b=2);
Inertia load;
equation R L
connect(DC.p,R.n); emf
connect(R.p,L.n); DC
connect(L.p, emf.n);
connect(emf.p, DC.n); load
connect(DC.n,G.p);
connect(emf.flange,load.flange);
G
end DCMotor;

83 Copyright © Peter Fritzson


Graphical Modeling

84 Copyright © Peter Fritzson


Exercises Part III
Graphical Modeling Exercises

(Probably not enough time


Need to install simForge)

85 Copyright © Peter Fritzson


Exercise 3.1

• Draw the DCMotor model using the graphic connection editor


using models from the following Modelica libraries:
Mechanics.Rotational,
Electrical.Analog.Basic,
Electrical.Analog.Sources

• Simulate it for 15s and plot the R L


emf
variables for the outgoing rotational u
speed on the inertia axis and the
J
voltage on the voltage source
(denoted u in the figure) in the G
same plot.

86 Copyright © Peter Fritzson


Exercise 3.2
• If there is enough time: Add a torsional spring to the outgoing
shaft and another inertia element. Simulate again and see the
results. Adjust some parameters to make a rather stiff spring.

87 Copyright © Peter Fritzson


Exercise 3.3
• If there is enough time: Add a PI controller to the system and try
to control the rotational speed of the outgoing shaft. Verify the
result using a step signal for input. Tune the PI controller by
changing its parameters in MathModelica.

88 Copyright © Peter Fritzson


Live example – Graphical Modeling

• Building a component with icon

89 Copyright © Peter Fritzson


Exercise 3.4

• Make a component of the model in Exercise 2.2, and


use it when building the model in exercise 2.3.
Replace with component

90 Copyright © Peter Fritzson


The End

OpenModelica: www.openmodelica.org

91 Copyright © Peter Fritzson


Additional non-covered slides for
Algorithms and Functions
and
Discrete Events and Hybrid Systems

92 Copyright © Peter Fritzson


Algorithms and Functions

93 Copyright © Peter Fritzson


Algorithm Sections
Whereas equations are very well suited for physical modeling, there
are situations where computations are more conveniently
expressed as algorithms, i.e., sequences of instructions, also called
statements
algorithm
...
<statements>
...
<some keyword>
equation
x = y*2;
z = w;
Algorithm sections can be embedded algorithm
among equation sections x1 := z+x;
x2 := y-5;
x1 := x2+y;
equation
u = x1+x2;
...

94 Copyright © Peter Fritzson


Iteration using for-statements in Algorithm sections
for <iteration-variable> in <iteration-set-expression> loop
<statement1> The general structure of a for-
<statement2> statement with a single iterator
...
end for

class SumZ
parameter Integer n = 5;
Real[n] z(start = {10,20,30,40,50});
A simple for-loop
Real sum; summing the five elements
algorithm of the vector z, within the
sum := 0;
for i in 1:n loop // 1:5 is {1,2,3,4,5} class SumZ
sum := sum + z[i];
end for;
end SumZ;

Examples of for-loop headers with different range expressions


for k in 1:10+2 loop // k takes the values 1,2,3,...,12
for i in {1,3,6,7} loop // i takes the values 1, 3, 6, 7
for r in 1.0 : 1.5 : 5.5 loop // r takes the values 1.0, 2.5, 4.0, 5.5

95 Copyright © Peter Fritzson


Iterations using while-stmts in Algorithm Sections
while <conditions> loop The general structure of a while-
<statements>
end while; loop with a single iterator.

class SumSeries
parameter Real eps = 1.E-6;
The example class SumSeries
Integer i; shows the while-loop construct
Real sum; used for summing a series of
Real delta;
algorithm exponential terms until the loop
i := 1; condition is violated , i.e., the terms
delta := exp(-0.01*i);
while delta>=eps loop become smaller than eps.
sum := sum + delta;
i := i+1;
delta := exp(-0.01*i);
end while;
end SumSeries;

96 Copyright © Peter Fritzson


if-statements
if <condition> then The general structure of if-statements.
<statements>
elseif <condition> then The elseif-part is optional and can occur zero or more
<statements> times whereas the optional else-part can occur at most
else
<statementss> once
end if class SumVector
Real sum;
parameter Real v[5] = {100,200,-300,400,500};
The if-statements parameter Integer n = size(v,1);
algorithm
used in the class sum := 0;
SumVector perform a for i in 1:n loop
if v[i]>0 then
combined summation sum := sum + v[i];
and computation on a elseif v[i] > -1 then
vector v. sum := sum + v[i] -1;
else
sum := sum - v[i];
end if;
end for;
end SumVector;

97 Copyright © Peter Fritzson


Function Declaration

The structure of a typical function declaration is as follows:


function <functionname>
input TypeI1 in1; All internal parts of a function are
input TypeI2 in2;
input TypeI3 in3; optional, the following is also a
... legal function:
output TypeO1 out1;
output TypeO2 out2; function <functionname>
... end <functionname>;
protected
<local variables>
...
algorithm
...
Modelica functions are declarative
<statements> mathematical functions:
...
end <functionname>; • Always return the same result(s) given
the same input argument values

98 Copyright © Peter Fritzson


Function Call

Two basic forms of arguments in Modelica function calls:


• Positional association of actual arguments to formal parameters
• Named association of actual arguments to formal parameters

Example function called on next page:


function PolynomialEvaluator
input Real A[:]; // array, size defined
// at function call time
input Real x := 1.0;// default value 1.0 for x
output Real sum; The function
protected PolynomialEvaluator
Real xpower; // local variable xpower
computes the value of a
algorithm
sum := 0; polynomial given two
xpower := 1; arguments:
for i in 1:size(A,1) loop a coefficient vector A and a
sum := sum + A[i]*xpower;
xpower := xpower*x;
value of x.
end for;
end PolynomialEvaluator;

99 Copyright © Peter Fritzson


Positional and Named Argument Association
Using positional association, in the call below the actual argument {1,2,3,4}
becomes the value of the coefficient vector A, and 21 becomes the value of the
formal parameter x.
...
algorithm
...
p:= polynomialEvaluator({1,2,3,4},21)

The same call to the function polynomialEvaluator can instead be made


using named association of actual parameters to formal parameters.

...
algorithm
...
p:= polynomialEvaluator(A={1,2,3,4},x=21)

100 Copyright © Peter Fritzson


External Functions
It is possible to call functions defined outside the Modelica
language, implemented in C or FORTRAN 77
function polynomialMultiply The body of an
input Real a[:], b[:]; external function is
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external marked with the
end polynomialMultiply; keyword external

If no language is specified, the implementation language for the external function


is assumed to be C. The external function polynomialMultiply can also be
specified, e.g. via a mapping to a FORTRAN 77 function:

function polynomialMultiply
input Real a[:], b[:];
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external ”FORTRAN 77”
end polynomialMultiply;

101 Copyright © Peter Fritzson


If enough time, Do Exercise 2.6
on Functions and algorithms

102 Copyright © Peter Fritzson


Discrete Events and Hybrid Systems

Picture: Courtesy Hilding Elmqvist

103 Copyright © Peter Fritzson


Events

Events are ordered in time and form an event history

time
event 1 event 2 event 3

• A point in time that is instantaneous, i.e., has zero duration


• An event condition that switches from false to true in order for the event to
take place
• A set of variables that are associated with the event, i.e. are referenced or
explicitly changed by equations associated with the event
• Some behavior associated with the event, expressed as conditional equations
that become active or are deactivated at the event. Instantaneous equations
is a special case of conditional equations that are only active at events.

104 Copyright © Peter Fritzson


initial and terminal events
Initialization actions are triggered by initial()

initial()

true

false time
event at start

Actions at the end of a simulation are triggered by terminal()

terminal()

true

false time
event at end

105 Copyright © Peter Fritzson


Generating Repeated Events

The call sample(t0,d) sample(t0,d)


returns true and triggers events
at times t0+i*d, where true

i=0,1, … false time


t0 t0+d t0+2d t0+3d t0+4d

class SamplingClock
parameter Modelica.SIunits.Time first,interval;
Boolean clock;
equation
clock = sample(first,interval);
when clock then
...
end when;
end SamplingClock;

106 Copyright © Peter Fritzson


Expressing Event Behavior in Modelica

if-equations, if-statements, and if-expressions express different behavior in different


operating regions
if <condition> then model Diode "Ideal diode"
<equations> extends TwoPin;
elseif <condition> then Real s;
<equations> Boolean off;
else equation
<equations> off = s < 0;
end if; if off then
v=s
else
v=0;
end if;
i = if off then 0 else s;
end Diode;

when-equations become active at events


when <conditions> then equation
<equations> when x > y.start then
end when; ...

107 Copyright © Peter Fritzson


Obtaining Predecessor Values using pre()

At an event, pre(y) gives the previous value of y immediately


before the event, except for event iteration of multiple events at the
same point in time when the value is from the previous iteration
y y

pre(y)

time
event

• The variable y has one of the basic types Boolean, Integer, Real, String,
or enumeration, a subtype of those, or an array type of one of those basic
types or subtypes
• The variable y is a discrete-time variable
• The pre operator can not be used within a function

108 Copyright © Peter Fritzson


Detecting Changes using edge()and change()

Detecting changes of boolean variables using edge()


true
b
false The expression edge(b) is
true
edge(b) true at events when b
false
time switches from false to true
event event

Detecting changes of discrete-time variables using change()


v
4.5
4.1
3.2 The expression change(v) is
change(v)
true true
true at instants when v changes
false
time value
event event

109 Copyright © Peter Fritzson


Creating Time-Delayed Expressions

Creating time-delayed expressions using delay()

v
4.5
4.1
3.2 delay(v,d)
4.5
4.1
3.2
time

start+d t1 t1+d t2 t2+d

In the expression delay(v,d) v is delayed by a delay time d

110 Copyright © Peter Fritzson


A Sampler Model

model Sampler
parameter Real sample_interval = 0.1;
Real x(start=5);
Real y;
equation
der(x) = -x;
when sample(0, sample_interval) then
y = x;
end when;
simulate(Sampler, startTime = 0, stopTime = 10)
end Sampler;
plot({x,y})

t
2 4 6 8 10

111 Copyright © Peter Fritzson


Discontinuous Changes to Variables at
Events via When-Equations/Statements
The value of a discrete-time variable can be changed by placing the variable on
the left-hand side in an equation within a when-equation, or on the left-hand side of
an assignment statement in a when-statement
The value of a continuous-time state variable can be instantaneously changed by
a reinit-equation within a when-equation
model BouncingBall "the bouncing ball model"
parameter Real g=9.18; //gravitational acc.
parameter Real c=0.90; //elasticity constant
Real height(start=0),velocity(start=10);
equation t
der(height) = velocity;
der(velocity)=-g;
when height<0 then
reinit(velocity, -c*velocity);
end when;
end BouncingBall;

112 Copyright © Peter Fritzson


A Mode Switching Model Example
Elastic transmission with slack DC motor transmission with elastic backlash
M otor side Load side
tau resistor inductor

inertia1 inertia2
signalV oltage
em f

step elastoB acklash


phi_dev
- b/2 b/2
ground

phi_dev < -b/2 phi_dev <= b/2

A finite state automaton


SimpleElastoBacklash model Backward Slack Forward
tau < 0 tau = 0 tau > 0
phi_dev >= -b/2 phi_dev > b/2

113 Copyright © Peter Fritzson


A Mode Switching Model Example cont’

partial model SimpleElastoBacklash


Boolean backward, slack, forward; // Mode variables
parameter Real b "Size of backlash region";
parameter Real c = 1.e5 "Spring constant (c>0), N.m/rad";
Flange_a flange_a "(left) driving flange - connector";
Flange_b flange_b "(right) driven flange - connector";
parameter Real phi_rel0 = 0 "Angle when spring exerts no torque";
Real phi_rel "Relative rotation angle betw. flanges";
Real phi_dev "Angle deviation from zero-torque pos";
Real tau "Torque between flanges";
equation
phi_rel = flange_b.phi - flange_a.phi;
phi_dev = phi_rel - phi_rel0;
backward = phi_rel < -b/2; // Backward angle gives torque tau<0
forward = phi_rel > b/2; // Forward angle gives torque tau>0
slack = not (backward or forward); // Slack angle gives no torque
tau = if forward then // Forward angle gives
c*(phi_dev – b/2) // positive driving torque
else (if backward then // Backward angle gives
c*(phi_dev + b/2) // negative braking torque
else // Slack gives
0); // zero torque
end SimpleElastoBacklash

114 Copyright © Peter Fritzson


A Mode Switching Model Example cont’

1 elastoBacklash.w_rel

0.75 Relative rotational speed between the


0.5 flanges of the Elastobacklash
0.25
transmission
5 10 15 20 25 t
-0.25

-0.5

t
We define a model with less mass in
5 10 15 20 25
inertia2(J=1), no damping d=0,
-0.2 inertia1.w and weaker string constant c=1e-5, to
-0.4 show even more dramatic backlash
-0.6
inertia2.w
phenomena
-0.8
The figure depicts the rotational
-1

-1.2
speeds for the two flanges of the
transmission with elastic backlash

115 Copyright © Peter Fritzson


Exercise 2.3 – BouncingBall

• Locate the BouncingBall model in one of the hybrid


modeling sections of DrModelica (the When-Equations
link in Section 2.9), run it, change it slightly, and re-run
it.

116 Copyright © Peter Fritzson

You might also like