Modelica Lectures
Modelica Lectures
Object--Oriented
Modeling and Simulation
with Modelica
Peter Fritzson
Linköping University, [email protected]
Mohsen Torabzadeh-
Torabzadeh-Tari
Linköping University, [email protected]
Martin Sjölund
Linköping University, [email protected]
Slides
Based on book and lecture notes by Peter Fritzson
Contributions 2004-2005 by Emma Larsdotter Nilsson, Peter Bunus
Contributions 2007-2008 by Adrian Pop, Peter Fritzson
Contributions 2009 by David Broman, Jan Brugård, Mohsen
Torabzadeh-Tari, Peter Fritzson
Contributions 2010 by Mohsen Torabzadeh-Tari, Peter Fritzson
Peter Fritzson
Principles of Object Oriented
Modeling and Simulation with
Modelica 2.1
Wiley-IEEE Press
940 pages
1
Outline Day 1
Part I Part II
Introduction to Modelica and a Modelica environments
demo example
2
Software Installation
• (If
( you
y have a Mac or Linux computer,
p install
OpenModelica-1.5.0)
Outline
• Introduction to Modeling and Simulation
• Modelica - The next generation modeling and
g g
Simulation Language
• Modeling and Simulation Environments and
OpenModelica
• Classes
• Components, Connectors and Connections
q
• Equations
• Discrete Events and Hybrid Systems
• Algorithms and Functions
• Demonstrations
6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab
3
Why Modeling & Simulation ?
What is a system?
Collector
Storage tank
Hot water
Heater
Electricity
4
Examples of Complex Systems
• Robotics
• Automotive
• Aircrafts
• Satellites
• Biomechanics
• Power plants
• Hardware-in-the-loop,
real-time simulation
Experiments
5
Model concept
Simulation
6
Reasons for Simulation
Dangers of Simulation
7
Building Models Based on Knowledge
System knowledge
• The collected general experience in relevant domains
• The system itself
8
Dynamic vs. Static Models
Input current
pulse
Capacitor voltage - dynamic
time
Continuous-Time vs.
Continuous-
Discrete--Time Dynamic Models
Discrete
Continuous-time models may evolve their variable values
continuously during a time period
Discrete-time variables changeg values a finite number of times
during a time period
Continuous
Discrete
time
9
Quantitative vs. Qualitative Models
Superb
Tasty
Good
Mediocre
time
Level of Abstraction
Experience Feedback
System Maintenance
requirements
Product verification and
Calibration
Specification deployment
Preliminary feature design
Subsystem level integration test
Design calibration and verification
Integration
Architectural design and
Design Subsystem level integration and
system functional design Verification
Refinement verification
Detailed feature design and
implementation Component verification
erification
Realization
10
Principles of Graphical Equation-
Equation-Based Modeling
Component 3
• Physical behavior of a component is
described by equations
• Hierarchical decomposition of components
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
q
qd
Rp2=50
Rd1=100
C=0.004*D/w m Rp1=200 axis1
Rd2=100
Ri=10
- -
-
+ +
diff + pow er
OpI
Vs
Rd4=100
Srel = n*transpose(n)+(identity(3)- n*transpose(n))*cos(q)- emf
y
skew(n)*sin(q);
Rd3=100
x
g3
wrela = n*qd; inertial
zrela = n*qdd; g1
Sb = Sa*transpose(Srel);
hall2
11
GTX Gas Turbine Power Cutoff Mechanism
Developed
Hello
by MathCore
for Siemens
Courtesy of Siemens Industrial Turbomachinery AB
12
Modelica in Avionics
Modelica in Biomechanics
13
Modelica –
The Next Generation
Modeling Language
Stored Knowledge
14
The Form – Equations
• Equations were used in the third millennium B.C.
• Equality sign was introduced by Robert Recorde in 1557
What is Modelica?
• Robotics
R b ti
• Automotive
• Aircrafts
• Satellites
• Power plants
• Systems biology
15
What is Modelica?
What is Modelica?
16
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
MATLAB similarities
MATLAB-like array and scalar arithmetic, but strongly typed and
efficiency comparable to C.
Non-Proprietary
• Open Language Standard
• Both
B th Open-Source
O S and
dCCommercial
i l iimplementations
l t ti
17
Modelica Language Properties
Object Oriented
Mathematical Modeling with Modelica
• 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
36 Peter Fritzson Copyright © Open Source Modelica Consortium pelab
18
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
3.0 l dSSeptember
t b 2007
• 3.1 released May 2009
Modelica Conferences
• The 1st International Modelica conference October, 2000
19
Exercises Part I
Hands--on graphical modeling
Hands
(20 minutes)
Graphical Modeling
Using Drag and Drop Composition
Courtesy
MathCore
Engineering AB
20
Exercises Part I – Basic Graphical Modeling
• (See instructions on next two pages)
• Start the simForge editor
• Draw the RL-Circuit
• Simulate
R1 L
R=10
R=100 L=1
L=0.1
A
C
21
Exercises Part I – simForge Instructions Page 2
• Go to File menu and choose New File. Write RL_circuit and press OK.
• In the Add Class pop-up dialog box change the Type from package to
class and press OK.
• Double click on the RL_circuit under the Modelica classes and the
graphical window will appear.
• Drag and Drop components from the standard Modelica library to your
model.
• For connecting components, move the cursor to the target pin and press
shift+click once and just move the cursor with the mouse to the
destination pin and press again shift+click.
• Under the Edit menu ->
Advanced properties you can
• Start the simulation with simulation button. tick
i k the
h visible
i ibl legend
l d bar.
b
• In the simulation pop-up you can leave out
some fields like the Stop time, which will result
in a default value of 1 sec. will be used.
22
Modelica Environments and OpenModelica
p
Dymola
1
Simulation X
• ITI
• Germany
• Mechatronic systems
y
• www.simulationx.com
MapleSim
• Maplesoft
• Canada
• Recent Modelica tool on the
market
• Integrated with Maple
• www.maplesoft.com
2
MathModelica
• MathCore
• Sweden
• Released 2006
• General purpose
• Mathematica connection
• www.mathcore.com
3
OpenModelica and simForge
• OpenModelica
• Open Source Modelica
Consortium (OSMC)
• Sweden and other countries
• Open source
• www.openmodelica.org
OpenModelica
• Advanced Interactive Modelica compiler (OMC)
• Supports most of the Modelica Language
• Basic environment for creating models
• OMShell – an interactive command handler • ModelicaML UML Profile
• OMNotebook – a literate programming notebook • MetaModelica extension
• MDT – an advanced textual environment in Eclipse
4
Open Source Modelica Consortium
Open-source community services Founded Dec 4, 2007
• Website and Support Forum Industrial members (12)
• Version-controlled source base •ABB Corporate Research
•Bosch-Rexroth AG, Germany
• Bug database
•Siemens Turbo Machinery y AB
• Development courses •Creative Connections, Prague
• www.openmodelica.org •Equa Simulation AB, Sweden
•IFP, Paris, France
•MostforWater, Belgium
•MathCore Engineering AB
Code Statistics •MapleSoft, Canada
•TLK Thermo, Germany
•VTT, Finland
•XRG Simulation AB, Germany
University members (9)
•Linköping University, Sweden
Hamburg University of Technology/TuTech, Institute of
•Hamburg
Thermo-Fluid Dynamics, Germany
•Technical University of Braunschweig, the Institut of
Thermodynamik, Germany
•Université Laval, the modelEAU group, Canada
•Griffith University, Australia
•University of Queensland, Australia
•Politecnico di Milano, Italy
•Mälardalen University, Sweden
•Technical University Dresden, Germany
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)
5
Interactive Session Handler – on dcmotor Example
(Session handler called 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;
ode ca. ect ca . a og. as c.
Modelica.Electrical.Analog.Basic.EMF e
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;
6
Run Scripts in OpenModelica
7
OpenModelica MDT – Usage Example
Code Assistance on
function calling.
Interactive
Emacs session handler Textual
Editor/Browser Model Editor
DrModelica
OMNoteBook Execution Modelica
Model Editor Compiler
Modelica
Debugger
8
OpenModelica Client
Client--Server Architecture
Parse
Client: Graphic
Model Editor
Server: M
S Main
i Program
P
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.
9
Corba Client
Client--Server API
• Simple text-based (string) communication in
Modelica Syntax
• API supporting model structure query and update
Example Calls:
Calls fulfill the normal Modelica function call syntax.:
saveModel("MyResistorFile.mo",MyResistor)
20getInheritanceCount(A1<cref>)
Peter Fritzson Copyright © Open SourceReturns the number
Modelica (as a string) of inherited classes of a class.
Consortium
getNthInheritedClass(A1<cref>, Returns the type name of the nth inherited class of a class. The first class has number 1.
10
Platforms
11
Modelica Language Concepts
and Textual Modeling
Classes and Inheritance
Typed
Declarative Hybrid
Equation-based Modeling
Textual Language
Acausal Modeling
Visual
Component
Level
1
Typical Simulation Process
• Multi-Domain Modeling
• Visual acausal hierarchical component modeling
• Typed declarative equation-based textual
language
• Hybrid modeling and simulation
2
What is Special about Modelica?
Multi-Domain
Modeling
Acausal model
(Modelica)
Causal
block-based
model
(Simulink)
3
What is Special about Modelica?
Multi-Domain Hierarchical system Visual Acausal
Modeling modeling Hierarchical
k2
i
Component
qddRef
qdRef qRef k1 r3Control
r3Motor r3Drive1
cut joint
tn
axis6
Modeling
1 1
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
Srel = n*transpose(n)+(identity(3)-
Rd2=100 n*transpose(n))*cos(q)- axis1
Ri=10
skew(n)*sin(q); - -
-
wrela = n*qd; +
diff +
+
pow er
zrela = n*qdd; OpI
Sb = Sa*transpose(Srel);
Vs
Rd4=100
r0b = r0a; emf
Rd3=100
vb = Srel*va; g3
wb = Srel*(wa + wrela); y
ab = Srel*aa;
g1 x
inertial
zb = Srel*(za + zrela + cross(wa, wrela));
hall2
g2 qd
g4
q
7CourtesyPeter Fritzson
of Martin Otter Copyright © Open Source Modelica Consortium pelab
4
What is Special about Modelica?
Multi-Domain Visual Acausal
Modeling Component
Modeling
Hybrid modeling =
continuous-time + discrete-time modeling
Continuous-time
Discrete-time
Typed
Declarative time
Hybrid
Equation-based Modeling
Textual Language
5
Simplest Model – Hello World!
0.4
0.2
0.5 1 1.5 2
1.0 time
0.2 0.4 0.6 0.8 1
0.95
0.90
6
Example class: 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
d ( ) = y;
der(x) // This
hi iis the
h 1st diff equation
i //
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
• Start
S OMNotebook
O
• Start->Programs->OpenModelica->OMNotebook
• Open File: Exercise01-classes-simple-textual.onb
• Open Exercise01-classes-simple-textual.pdf
7
Exercises 2.1 and 2.2
• Open the Exercise01-classes-simple-textual.onb
found in the Tutorial directory.
• Locate the VanDerPol model in DrModelica (link from
S ti 2
Section 2.1),
1) using
i OMN
OMNotebook!
t b k!
• Exercise 2.1: Simulate and plot VanDerPol. Do a slight
change in the model, re-simulate and re-plot.
• Exercise 2.2. 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;
8
Variables and Constants cont’
Comments in Modelica
9
A Simple Rocket Model
thrust − mass ⋅ gravity
Rocket acceleration =
mass
apollo13 thrust
mass ′ = − massLossRate ⋅ abs ( thrust )
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;
i // Gravity
i forcefield
i
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;
10
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 protected
inside the class parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
access by dot public
t ti
notation outside
t id Rocket apollo(name "apollo13")
apollo(name="apollo13");
the 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;
30000
50 100 150 200
25000
-100
20000
-200
15000
10000 -300
5000 -400
11
Restricted Class Keywords
Modelica Functions
12
Inheritance
parent class to Color
Inheriting definitions
Legal!
Identical to the
Inheriting multiple
record ColorData
inherited field blue identical
parameter Real red = 0.2;
0 2; definitions results
parameter Real blue = 0.6; in only one
Real green; definition
end ColorData;
class ErrorColor
extends ColorData;
parameter Real blue = 0.6;
parameter Real red = 0.3;
equation
q
red + blue + green = 1; Inheriting
Illegal!
end ErrorColor; Same name, but multiple different
different value definitions of the
same item is an
error
13
Inheritance of Equations
class Color
parameter Real red=0.2;
parameter Real blue=0.6;
Real green;
equation
red + blue + green = 1;
end Color;
Multiple Inheritance
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;
14
Multiple Inheritance cont’
class Rectangle
extends VerticalLine;
extends HorizontalLine;
end Rectangle;
class SameColor
inheritance extends Color; connector MyPin = Pin;
end SameColor;
15
Inheritance Through Modification
16
The Moon Landing
Example using Inheritance cont’
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
apo o.g a ty =moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
oo .g oo . ass/(apo o.a t tude oo . ad us) ;
end Landing;
17
Advanced Topic
• Class parameterization
Colored- Colored-
Class Class
Equivalent to
object object
class C2
Green- BlueClass obj1(p1=5);
Class
YellowClass obj2;
BlueClass obj3;
A yellow A red
object object
RedClass obj4;
equation
end C2;
18
Class Parameterization when Class Parameters
are Components
R1
Class
class ElectricalCircuit class GenericElectricalCircuit
Resistor R1(R=100);
parameterization replaceable Resistor R1(R=100);
Resistor R2(R=200); replaceable Resistor R2(R=200);
Resistor R3(R=300); replaceable Resistor R3(R=300);
Inductor L1; Inductor L1;
SineVoltage AC; SineVoltage AC;
Groung G; Groung G;
equation
ti equation
connect(R1.n,R2.n); connect(R1.n,R2.n);
connect(R1.n,L1.n); connect(R1.n,L1.n);
connect(R1.n,R3.n); connect(R1.n,R3.n);
connect(R1.p,AC.p); connect(R1.p,AC.p);
..... .....
end ElectricalCircuit; end GenericElectricalCircuit;
AC R2 L1 2 R3
class TemperatureElectricalCircuit =
G GenericElectricalCircuit (redeclare TempResistor R1
redeclare TempResistor R3);
19
Exercises 1 Simple Textual Continued
• C
Continue exercises in Exercise01-classes-
simple-textual.onb
20
Components, Connectors
and Connections
1
Connectors and Connector Classes
Connectors are instances of connector classes
electrical connector
2
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 Mechanical.
Rotational Angle Torque
momentum Rotational
Magnetic Magnetic
Magnetic Magnetic flux
potential flux rate
Hydraulic Pressure Volume flow Volume HyLibLight
Heat Temperature Heat flow Heat HeatFlow1D
Chemical Under
Chemical Particle flow Particles
potential construction
PneuLibLight
Pneumatic Pressure Mass flow Air
connect-equations
Connections between connectors are realized as equations in Modelica
connect(connector1,connector2)
+ 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;
3
Connection Equations
Pin pin1,pin2;
//A connect equation
//in Modelica
connect(pin1,pin2);
Corresponds to pin1.v = pin2.v;
pin1 i + pin2
pin1.i pin2.i
i =0;
v1 = v2 = v3 = vn
Each primitive connection set of flow variables is used to generate
sum-to-zero equations of the form: Through
variable
i1 + i2 + (−ik ) + in = 0
4
Common Component Structure
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;
5
Electrical Components cont’
model Source
extends TwoPin; v(t)
p.i n.i
parameter Real A,w;
+
equation
i
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;
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
connect(R1.p, R2.p);
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;
6
An Oscillating Mass Connected to a Spring
fixed1 model Oscillator
Mass mass1(L=1, s(start=-0.5));
Spring spring1(srel0=2, c=10000);
s0
Fixed fixed1(s0=1.0);
equation
b
connect(spring1.flange_b, fixed1.flange_b);
spring1 srel0 connect(mass1.flange_b, spring1.flange_a);
end Oscillator;
a
L -1
s -1.5
-mg
mg
t
0.1 0.2 0.3 0.4 0.5
-2.5
Extra Exercise
• Locate the Oscillator model in DrModelica using
OMNotebook!
• Simulate and pplot the example.
p Do a slight
g change g in the
model e.g. different elasticity c, re-simulate and re-plot.
fixed1
• Draw the Oscillator model using
the graphic connection editor e.g.
using the library Modelica. b
Mechanical.Translational spring1
a
• Including components SlidingMass,
Force, Blocks.Sources.Constant mass1
7
Signal Based Connector Classes
connector InPort "Connector with input signals of type Real"
parameter Integer n=1 "Dimension of signal vector";
fixed causality input Real signal[n] "Real input signals";
end InPort;
inPort outPort
Connecting Components
from Multiple Domains
• Block domain ind R1
1
ex ac iner vsen
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;
8
Simple Modelica DCMotor Model
Multi--Domain (Electro
Multi (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
( p, emf.n);
connect(L.p, );
connect(emf.p, DC.n); load
connect(DC.n,G.p);
connect(emf.flange,load.flange);
G
end DCMotor;
9
Graphical Modeling
Using Drag and Drop Composition
Courtesy
MathCore
Engineering AB
Courtesy MathCore
Engineering AB
10
Graphical Exercise 3.1
• Open Exercise02-graphical-modeling.onb and the
corresponding .pdf
• Draw the DCMotor model using the graphic connection
editor using models from the following Modelica libraries:
Mechanics.Rotational,
Electrical.Analog.Basic,
Electrical.Analog.Sources
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
spring.
11
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 simForge.
12
Hierarchically
Structured Components cont’
partialDCMotor1
step1 inertia1
model DCMotorCircuit2
Step step1;
PartialDCMotor partialDCMotor1;
Inertia inertia1;
equation
connect(step1.outPort, partialDCMotor1.inPort);
connect(partialDCMotor1.rotFlange_b, inertia1.rotFlange_a);
end DCMotorCircuit2;
Connection Restrictions
• Two acausal connectors can be connected to each other
• An input connector can be connected to an output connector
or vice versa
• An input or output connector can be connected to an acausal
connector, i.e. a connector without input/output prefixes
• An outside input connector behaves approximately like an
output connector internally
• An outside output connector behaves approximately like an
input connector internally
C1 C2 C3 C4
input output input output input output input output
input
M1 output
C1 C2 C3 C4
input output input output input output input output
13
Connector Restrictions cont’
connector RealInput
input Real signal; class C
end RealInput; RealInput u; // input connector
RealOutput y; // output connector
connector RealOutput end C;
output Real signal;
end RealOutput;
class CInst
C C1, C2, C3, C4; // Instances of C
A circuit consisting of four
equation connected components
connect(C1.outPort, C2.inPort); C1, C2, C3, and C4
connect(C2.outPort, C3.inPort);
connect(C3.outPort, C4.inPort); which are instances of the
end CInst; class
l C
C1 C2 C3 C4
input output input output input output input output
class MInst
M M1; // Instance of M
equation
connect(C1.y, M1.u); // Normal connection of outPort to inPort
connect(M1.u, C2.u); // Outside inPort connected to inside inPort
connect(C2.y, C3.u); // Inside outPort connected to inside inPort
connect(C3.y, M1.y); // Inside outPort connected to outside outPort
connect(M1.y, C4.u); // Normal connection of outPort to inPort
end MInst;
;
input
M1 output
C1 C2 C3 C4
input output input output input output input output
14
Parameterization and Extension of Interfaces
connector Stream External interfaces to
Real pressure; component classes are
flow Real volumeFlowRate;
inlet end Stream; defined primarily through the
use of connectors
connectors.
Tank
model Tank
parameter Real Area=1;
replaceable connector TankStream = Stream;
outlet TankStream inlet, outlet; // The connectors
Real level;
Parameterization
equation
of interfaces // Mass balance
Area*der(level) = inlet.volumeFlowRate +
outlet.volumeFlowRate;
outlet.pressure = inlet.pressure;
The Tank model has an end Tank;
connector Stream // Connector class
external interface in terms of Real pressure;
the connectors inlet and flow Real volumeFlowRate;
outlet end Stream
connector HeatStream
extends Stream;
Real temp;
end HeatStream;
15
Arrays of Connectors
Part built up with a for-equation (see Lecture 4)
model ArrayOfLinks
constant Integer n=10 "Number of segments (>0)";
The model parameter Real[3,n] r={fill(1,n),zeros(n),zeros(n)};
uses a for- ModelicaAdditions.MultiBody.Parts.InertialSystem InertialSystem1;
equation to ModelicaAdditions.MultiBody.Parts.BoxBody[n]
connect the
different
boxBody(r = r, Width=fill(0.4,n));
segments of ModelicaAdditions.MultiBody.Joints.Spherical spherical[n];
the links equation
connect(InertialSystem1.frame_b, spherical[1].frame_a);
connect(spherical[1].frame_b, boxBody[1].frame_a);
for i in 1:n-1 loop
connect(boxBody[i].frame_b, spherical[i+1].frame_a);
connect(spherical[i+1].frame_b, boxBody[i+1].frame_a);
end for;
end ArrayOfLinks;
16
Equations
Usage of Equations
In Modelica equations are used for many tasks
• The main usage of equations is to represent relations in
mathematical models
models.
• Assignment statements in conventional languages are
usually represented as equations in Modelica
• Attribute assignments are represented as equations
• Connections between objects generate equations
1
Equation Categories
Equations in Modelica can informally be classified
into three different categories
• N
Normall equations
ti (
(e.g., expr1
1 = expr2)
2) occurring
i iin
equation sections, including connect equations and other
equation types of special syntactic form
• Declaration equations, (e.g., Real x = 2.0) which are part of
variable, parameter, or constant declarations
• Modifier equations, (e.g. x(unit="V")
x(unit V ) )which are commonly
used to modify attributes of classes.
2
Declaration Equations
Declaration equations: It is also possible to specify a declaration
constant Integer one = 1;
equation for a normal non-constant variable:
parameter Real mass = 22.5; Real speed = 72.4;
model MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
declaration
equations 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");
q
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;
Modifier Equations
Modifier equations occur for example in a variable declaration when there
is a need to modify the default value of an attribute of the variable
A common usage is modifier equations for the start attribute of variables
Real speed(start=72
speed(start=72.4);
4);
Modifier equations also occur in type definitions:
type Voltage = Real(unit="V", min=-220.0, max=220.0);
model MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
modifier
Rocket apollo(name="apollo13", mass(start=1038.358) );
equations 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;
3
Kinds of Normal Equations in Equation
Sections
Kinds of equations that can be present in equation sections:
• equality equations • repetitive equation structures with for-equations
• connect equations • conditional equations with if-equations
• assert and terminate • conditional equations with when-equations
when equations
• reinit 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
conditional if (time<thrustDecreaseTime) then
if-equation
q apollo.thrust = force1;
elseif (time<thrustEndTime) then
apollo.thrust = force2;
else
apollo.thrust = 0;
end if;
equality apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
equation
end Landing;
Equality Equations
expr1 = expr2:
(out1, out2, out3,...) = function_name(in_expr1, in_expr2, ...);
class EqualityEquations
Real x,y,z;
equation
simple equality (x, y, z) = f(1.0, 2.0); // Correct!
equation (x+1, 3.0, z/y) = f(1.0, 2.0); // Illegal!
// Not a list of variables
// on the left-hand
left hand side
end EqualityEquations;
4
Repetitive Equations
The syntactic form of a for-equation is as follows:
for <iteration-variable> in <iteration-set-expression> loop
<equation1>
<equation2>
...
end for;
connect-equations
In Modelica connect-equations are used to establish
connections between components via connectors
connect(connector1 connector2)
connect(connector1,connector2)
Repetitive connect-equations
class RegComponent
Component components[n];
equation
for i in 1:n-1 loop
connect(components[i] o tlet components[i+1] inlet)
connect(components[i].outlet,components[i+1].inlet);
end for;
end RegComponent;
5
Conditional Equations: if-equations
if <condition> then if-equations for which the conditions have higher
<equations> variability than constant or parameter must include an
elseif <condition> then else-part
<equations>
else
<equations> E h then-, elseif-,
Each i and d else-branch
b h mustt h
have th
the
end if; same number of equations
model MoonLanding
parameter Real force1 = 36350;
...
Rocket apollo(name="apollo13", mass(start=1038.358) );
CelestialBody moon(mass=7.382e22,radius=1.738e6,name="moon");
equation
if (time<thrustDecreaseTime) then
apollo.thrust = force1;
elseif (time<thrustEndTime) then
apollo.thrust = force2;
else
apollo.thrust = 0;
end if;
apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
end Landing;
time
event 1 event 2 event 3
6
Conditional Equations: when-equations cont'
when <conditions> then when-equations are used to express
<equations>
end when; instantaneous equations that are only
valid (become active) at events, e.g. at
discontinuities or when certain conditions
become true
when x > 2 then when {x > 2, sample(0,2), x < 5} then
y1 = sin(x); y1 = sin(x);
y3 = 2*x + y1+y2; y3 = 2*x + y1+y2;
end when; end when;
Restrictions on when-equations
Form restriction Modelica restricts the allowed equations
model WhenNotValid
within a when-equation to: variable =
Real x, y; expression, if-equations, for-equations,...
equation
x + y = 5
5; In the WhenNotValid model when the
when sample(0,2) then equations within the when-equation are
2*x + y = 7;
not active it is not clear which variable,
// Error: not valid Modelica
end when; either x or y, that is a “result” from the
end WhenNotValid;
when-equation to keep constant outside
the when-equation.
A corrected version appears in the class WhenValidResult below
model WhenValidResult
Real x,y;
equation
x + y = 5; // Equation to be used to compute x.
when sample(0,2) then
y = 7 - 2*x; // Correct, y is a result variable from the when!
end when;
end WhenValidResult;
7
Restrictions on when-equations cont’
Restriction on nested when-equations
model ErrorNestedWhen
Real x,y1,y2;
equation
when x > 2 then
when y1 > 3 then // Error!
y2 = sin(x); // when-equations
end when; // should not be nested
end when;
end ErrorNestedWhen;
8
Restrictions on when-equations cont’
Solution to assignment conflict between equations in
independent when-equations:
• Use elsewhen to give higher priority to the first when-equation
when equation
model DoubleWhenConflictResolved
Boolean close;
equation
...
when condition1 then
close = true; // First equation has higher priority!
elsewhen
l h condition2
di i 2 then
th
close = false; //Second equation
end when;
end DoubleWhenConflictResolved
model VectorWhen
Boolean close;
equation
...
when {condition1,condition2} then
close = true;
end when;
end DoubleWhenConflict
9
assert-equations
assert(assert-expression, message-string)
class AssertTest
parameter Real lowlimit = -5;
parameter Real highlimit = 5;
Real x;
equation
assert(x >= lowlimit and x <= highlimit,
"Variable x out of limit");
end AssertTest;
terminate-equations
The terminate-equation successfully terminates the
current simulation, i.e. no error condition is indicated
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.height + moon.radius)^2;
when apollo.height < 0 then // termination condition
terminate("The moon lander touches the ground of the moon");
end when;
end MoonLanding;
10
Algorithms and Functions
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;
...
1
Iteration Using for-
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
algorithm elements of the vector z,
sum := 0;
for i in 1:n loop // 1:5 is {1,2,3,4,5} within the class SumZ
sum := sum + z[i];
end for;
end SumZ;
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
delta := exp(-0.01*i);
while delta>=eps loop terms become smaller than eps.
sum := sum + delta;
i := i+1;
delta := exp(-0.01*i);
end while;
end SumSeries;
2
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
<statements> more times whereas the optional else-part can
else
<statementss> occur at most 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 for i in 1:n loop
a combined if v[i]>0 then
sum := sum + v[i];
summation and elseif
l if v[i]
[i] > -1
1 then
h
computation on a sum := sum + v[i] -1;
else
vector v. sum := sum - v[i];
end if;
end for;
end SumVector;
when-statements
when <conditions> then when-statements are used to express
<statements>
elsewhen <conditions> then actions (statements) that are only
<statements>
end when;
executed at events, e.g. at discontinuities
or when
h certaini conditions
di i b
become true
when x > 2 then
There are situations where several y1 := sin(x);
assignment statements within the y3 := 2*x + y1 + y2;
end when;
same when-statement is convenient
algorithm when {x > 2, sample(0,2), x < 5} then
when x > 2 then y1 := sin(x);
y1 := sin(x); y3 := 2*x + y
y y1 + y
y2;
;
end when; end when;
equation
y2 = sin(y1);
algorithm Algorithm and equation sections can
when x > 2 then
y3 := 2*x + y1 + y2; be interleaved.
end when;
3
Function Declaration
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
4
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)
Example calls:
(out1,out2,out3,...) = function_name(in1, in2, in3, in4, ...); // Equation
(out1,out2,out3,...) := function_name(in1, in2, in3, in4, ...); // Statement
(px,py) = PointOnCircle(1.2, 2); // Equation form
(px,py) := PointOnCircle(1.2, 2); // Statement form
5
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
t l function
f ti isi
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;
6
Packages
1
Packages as Abstract Data Type:
Data and Operations in the Same Place
Keywords
encapsulated package ComplexNumber
denoting a Usage of the
package
record Complex ComplexNumber
Real re;
encapsulated Real im;
package
makes
k end
d Complex;
C l
package class ComplexUser
dependencies function add ComplexNumbers.Complex a(re=1.0, im=2.0);
(i.e., imports) input Complex x,y; ComplexNumbers.Complex b(re=1.0, im=2.0);
explicit output Complex z; ComplexNumbers.Complex z,w;
algorithm equation
z.re := x.re + y.re; z = ComplexNumbers.multiply(a,b);
z.im := x.im + y.im w = ComplexNumbers.add(a,b);
end add; end ComplexUser
function multiply
input
p Complex
p x,y;
y The type
yp Complex
p and the
output Complex z;
Declarations of algorithm operations multiply and add
substract,
divide,
z.re := x.re*y.re – x.im*y.im; are referenced by prefixing
z.im := x.re*y.im + x.im*y.re;
realPart,
imaginaryPart,
end multiply; them with the package name
etc are not shown ………………………………………………………. ComplexNumber
here end ComplexMumbers
2
Importing Definitions from Packages
• Qualified import import <packagename>
• Single definition import import <packagename> . <definitionname>
• Unqualified import import <packagename> . *
• Renaming import import <shortpackagename> = <packagename>
Qualified Import
Qualified import import <packagename>
3
Single Definition Import
Single definition import import <packagename> . <definitionname>
Unqualified Import
Unqualified import import <packagename> . *
class ComplexUser3
import ComplexNumbers.*;
Complex a(x=1.0, y=2.0);
This example also shows
Complex b(x=1.0, y=2.0); direct import into a class
Complex zz,w;
w;
equation i t d off into
instead i t an enclosing
l i
z = multiply(a,b); package
w = add(a,b);
end ComplexUser3;
4
Renaming Import
Renaming import import <shortpackagename> = <packagename>
class ComplexUser4
import Co = ComplexNumbers;
Co.Complex a(x=1.0, y=2.0); This is as safe as qualified
Co.Complex
p b(x=1.0, y
y=2.0); import but gives more
Co.Complex z,w;
equation concise code
z = Co.multiply(a,b);
w = Co.add(a,b);
end ComplexUser4;
5
Subpackages and Hierarchical Libraries
6
within Declaration for Package Placement
Use short names without dots when declaring the package or class in
question, e.g. on a separate file or storage unit. Use within to specify
within which package it is to be placed.
The within within Modelica.Mechanics;
declaration encapsulated package Rotational // Modelica.Mechanics.Rotational
states the prefix
encapsulated package Interfaces
needed to form
import ...;
the fully
qualified name connector Flange_a;
...
end Flange_a;
...
end Interfaces;
model Inertia The subpackage Rotational declared
... within Modelica.Mechanics has the fully
end Inertia;
... qualified name
end Rotational; Modelica.Mechanics.Rotational,
by concatenating the packageprefix with the
short name of the package.
C:\library Modelica
\Modelica
package.mo
\Blocks
package.mo
Continuous.mo Mechanics
Blocks
Interfaces.mo
\Examples
package.mo
Example1.mo
\M h i
\Mechanics ...
Rotational
i l
package.mo
Rotational.mo Examples
... Continuous Interfaces
Example1
7
Mapping a Package Hierachy into a Directory
Hirarchy
within; It contains an empty Modelica package declaration since all
encapsulated package Modelica subpackages under Modelica are represented as subdirectories of
"Modelica root package"; their own. The empty within statement can be left out if desired
end Modelica; within Modelica.Blocks;
encapsulated package Examples
"Examples for Modelica.Blocks";
C:\library import ...;
\Modelica
package.mo end Examples; within Modelica.Blocks.Examples;
\Blocks model Example1
package.mo "Usage example 1 for Modelica.Blocks";
Continuous.mo ...
end Example1;
Interfaces.mo
\Examples within Modelica.Mechanics;
package.mo encapsulated package Rotational
encapsulated package Interfaces The subpackage
Example1.mo
import ...; Rotational stored as the
\Mechanics
connector Flange_a; file Rotational.mo. Note
package.mo ... that Rotational contains
Rotational.mo end Flange_a; the subpackage
... ... Interfaces, which also
end Interfaces; is stored in the same file
model Inertia since we chose not to
... represent Rotational as
end Inertia; a directory
...
end Rotational;
8
Modelica Libraries
1
Modelica Standard Library cont’
The Modelica Standard Library contains components from
various application areas, including 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
• Fluid 1-dim Flow in networks of vessels, pipes, fluid machines, valves, etc.
• Math Mathematical functions
• Magnetic Magnetic.Fluxtubes – for magnetic applications
• 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
Modelica.Blocks
Library
Continuous
Examples:
2
Modelica.Constants
Examples:
constant Real pi=2*Modelica.Math.asin(1.0);
constant Real small=1.e-60 "Smallest number such that small and –small
are representable on the machine";
Modelica.Electrical
Examples:
V2
R2 R4
Gnd9
C2 Gnd3 Gnd6 C4
R1 Transistor1 Transistor2 R3
V1 C1 I1 C5 C3 Gnd4
3
Modelica.Icons
Examples:
Library
Modelica.Math
4
Modelica.Mechanics
Modelica.SIunits
5
Modelica.Stategraph
Modelica.Thermal
Sub
S b package
k HeatTransfer f with ith components
t to
t model
d l11-
dimensional heat transfer with lumped elements
Example:
6
ModelicaAdditions Library (OLD)
ModelicaAdditions.Multibody (OLD)
7
MultiBody (MBS) - Example Kinematic Loop
8
ModelicaAdditions.PetriNets
Transition
Place
9
Power System Stability - SPOT
10
Vehicle Dynamics Library – VehicleDynamics
There is a Greatly Extended Commercial Version
• Powertrain
• SmartElectricDrives
• VehicleDynamics
• AirConditioning
• HyLib
• PneuLib
• CombiPlant
• HydroPlant
• …
11
Hydraulics Library HyLib
• Licensed Modelica package developed
originally by Peter Beater
• More than 90 models for Pumps
• Pumps
HyLib - Example
12
Pneumatics Library PneuLib
•Licensed Modelica package
developed by Peter Beater
Directional valves
•More than 80 models for
• Cylinders
• Motors
• Valves and nozzles
Flow control valves
• Lumped volumes
• Lines and sensors
• Models can be connected in an arbitrary
way, e.g. in series or in parallel.
•PneuLibLight is a free subset of Cylinders
HyLib.
• More info: www.pneulib.com
PneuLib - Example
13
Powertrain Library - Powertrain
14
Example Fighter Aircraft Library
• Simple PID
• Controls alpha and height
15
Example Aircraft Animation
Power output
Air Exhaust
C
Compressor T bi
Turbine
16
Example Gas Turbine
Load rejection
17
Example Gas Turbine – Load Rejection
18
Discrete Events and Hybrid Systems
Events
time
event 1 event 2 event 3
1
Hybrid Modeling
Hybrid modeling = continuous-time + discrete-time modeling
Continuous-time Real x;
Voltage v;
Current i;
Discrete-time
discrete Real x;
Integer i;
Boolean b;
time
Events
• A point in time that is instantaneous, i.e., has zero duration
• A eventt condition
An diti so that
th t the
th eventt can take
t k place
l
• A set of variables that are associated with the event
• Some behavior associated with the event,
e.g. conditional equations that become active or are deactivated at
the event
Event creation – if
2
Event creation – when
when-equations
when <conditions> then
<equations> time
end when; event 1 event 2 event 3
sample(t0,d)
The call sample(t0,d) returns
true and triggers events at times true
t0+i*d where i=0,1,
t0+i*d, i 0 1 …
false time
t0 t0+d t0+2d t0+3d t0+4d
Variables need to be
discrete
model SamplingClock Creates an event
Integer i;
discrete Real r;
after 2 s, then
equation each 0.5 s
when sample(2,0.5) then
i = pre(i)+1;
r = pre(r)+0.3;
end when;
end SamplingClock; pre(...) takes the
previous value
before the event.
3
Reinit – Discontinuous Changes
The value of a continuous-time state variable can be instantaneously
changed by a reinit-equation within a when-equation
Initial conditions
Reinit ”assigns”
continuous-time variable
velocity a new value
initial()
true
false time
event at start
t
terminal()
i l()
true
false time
event at end
4
Terminating a Simulation
5
Event Priority
Erroneous multiple definitions, single assignment rule violated
model WhenConflictX // Erroneous model: two equations define x
discrete Real x;
equation
when
hen time>=2
ti > 2 then // Wh
When A
A: I
Increase x b
by 1
1.5
5 at
t ti
time=2
2
x = pre(x)+1.5;
end when;
when time>=1 then // When B: Increase x by 1 at time=1
x = pre(x)+1;
end when;
end WhenConflictX;
model WhenPriorityX
discrete Real x;
Using event priority equation
when time>=2 then // Higher priority
to avoid erroneous x = pre(x)+1.5;
elsewhen time>=1 then // Lower priority
multiple definitions x = pre(x)+1;
end when;
end WhenPriorityX;
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
6
Detecting Changes of Boolean
Variables Using edge()and change()
Creating Time
Time--Delayed Expressions
v
4.5
4.1
3.2 delay(v,d)
4.5
4.1
3.2
time
7
A Sampler Model
model Sampler
parameter Real sample_interval = 0.1;
Real x(start=5);
Real y;
q
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
8
A Mode Switching Model Example
Elastic transmission with slack DC motor transmission with elastic backlash
tau Motor side Load side
resistor inductor
inertia1 inertia2
signalVoltage
emf
ground
9
A Mode Switching Model Example cont’
1 elastoBacklash.w_rel
-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,
0 4
-0.4 to show even more dramatic
-0.6
inertia2.w
backlash phenomena
-0.8
The figure depicts the rotational
-1
speeds for the two flanges of the
-1.2
transmission with elastic backlash
10
Water Tank System with PI Controller – cont’
partial model BaseController
parameter Real Ts(unit = "s") = 0.1 "Time period between discrete samples";
parameter Real K = 2 "Gain";
parameter Real T(unit = "s") = 10 "Time constant";
ReadSignal cIn "Input sensor level, connector";
ActSignal cOut "Control to actuator, connector";
parameter Real ref "Reference level";
Real error "Deviation from reference level";
Real outCtr "Output control signal";
equation
error = ref - cIn.val;
cOut.act = outCtr;
end BaseController;
mutex
model DiningTable
parameter Integer n = 5 "Number of philosophers and forks";
parameter Real sigma = 5 " Standard deviation for the random function";
// Give each philosopher a different random start seed
// Comment out the initializer to make them all hungry simultaneously.
Philosopher phil[n](startSeed=[1:n,1:n,1:n], sigma=fill(sigma,n));
Mutex mutex(n=n);
Fork fork[n];
equation Eating
Thinking
for i in 1:n loop
Eating
connect(phil[i].mutexPort, mutex.port[i]); Thinking
connect(phil[i].right, fork[i].left); Eating
connect(fork[i].right, phil[mod(i, n) + 1].left); Thinking
end for; Eating
end DiningTable; Thinking
Eating
Thinking
11
Biological Models
Population Dynamics
Predator--Prey
Predator
Some Well-
Well-known Population Dynamics
Applications
1
Population Dynamics of Single Population
• P – population size = number of individuals in a population
• P – population change rate, change per time unit
• g – growth factor of population (e
(e.g.
g % births per year)
• d – death factor of population (e.g. % deaths per year)
growthrate g P
Exponentially increasing
deathrate d P population if (g-d)>0
P growthrate deathrate
class PopulationGrowth
parameter Real g = 0.04 "Growth factor of population";
parameter Real d = 0.0005 "Death factor of population";
Real P(start=10) "Population size, initially 10";
equation
der(P) = (g-d)*P;
end PopulationGrowth;
2
Simulation of PopulationGrowth
simulate(PopulationGrowth, stopTime=100)
plot(P)
500
Exponentially increasing
population if (g-d)>0 400
300
200
100
t
20 40 60 80 100
class PopulationGrowth
parameter Real g = 0.04 "Growth factor of population";
parameter Real d = 0.0005 "Death factor of population";
Real P(start=10) "Population size, initially 10";
equation
der(P) = (g-d)*P;
end PopulationGrowth;
3
Population Dynamics with both Predators
and Prey Populations
• Predator-Prey models
4
Predator--Prey (Foxes and Rabbits) Model
Predator
class LotkaVolterra
parameter Real g_r =0.04 "Natural growth rate for rabbits";
parameter Real d_rf=0.0005 "Death rate of rabbits due to foxes";
parameter Real d_f =0.09 "Natural deathrate for foxes";
parameter Real g_fr=0.1 "Efficency in growing foxes from rabbits";
Real rabbits(start=700) "Rabbits,(R) with start population 700";
Real foxes(start=10) "Foxes,(F) with start population 10";
equation
der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes;
der(foxes) = g
g_fr*d_rf*rabbits*foxes
fr*d rf*rabbits*foxes - d_f*foxes;
d f*foxes;
end LotkaVolterra;
Simulation of Predator-
Predator-Prey (LotkaVolterra)
simulate(LotkaVolterra, stopTime=3000)
plot({rabbits, foxes}, xrange={0,1000})
rabbits
foxes
5000
4000
3000
2000
1000
t
200 400 600 800 1000
5
Exercise of Predator-
Predator-Prey
• Locate the LotkaVolterra model in DrModelica
• Change the death and growth rates for foxes and
rabbits, simulate, and observe the effects
simulate(LotkaVolterra, stopTime=3000)
plot({rabbits, foxes}, xrange={0,1000})
class LotkaVolterra
parameter Real g_r =0.04 "Natural growth rate for rabbits";
parameter Real d_rf=0.0005 "Death rate of rabbits due to foxes";
parameter Real d_f =0.09 "Natural deathrate for foxes";
parameter Real g
g_fr
fr=0
0.1
1 "Efficency
Efficency in growing foxes from rabbits";
rabbits ;
Real rabbits(start=700) "Rabbits,(R) with start population 700";
Real foxes(start=10) "Foxes,(F) with start population 10";
equation
der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes;
der(foxes) = g_fr*d_rf*rabbits*foxes - d_f*foxes;
end LotkaVolterra;
6
Model Design
Modeling Approaches
• Traditional state space approach
• Traditional signal-style block-oriented approach
• Object-oriented approach based on finished
library component models
• Object-oriented flat model approach
• Object-oriented approach with design of library
model components
1
Modeling Approach 1
T diti
Traditional
l state
t t space approach
h
2
Difficulties in State Space Approach
Modeling Approach 2
3
Physical Modeling Style (e.g Modelica) vs
signal flow Block-
Block-Oriented Style (e.g. Simulink)
Modelica: Block-oriented:
Physical model – easy to Signal-flow model – hard to
understand understand for physical systems
R1=10 R2=100
sum2
p
n n +1
+1
AC=220
n n
p
G
4
Physical Modeling Style (e.g Modelica) vs
signal flow Block-
Block-Oriented Style (e.g. Simulink)
Modelica: Block-oriented:
Physical model – easy to Signal-flow model – hard to
understand understand for physical systems
R1=10 R2=100
sum2
p
n n +1
+1
AC=220
n n
p
G
Control +
+ K
- e 1 / TI -
k1 J 1 J 2 k 22 ω2
Rotational 1/
k2
+
Mechanics
- θ2
k2
+ k3 θ3
+
1/ J 3
-
τ
-
load
ω3
5
Properties of Block Diagram Modeling
• Approach 3: Object
Object-oriented
oriented approach based on
finished library component models
• Approach 4: Object-oriented flat model approach
• Approach 5: Object-oriented approach with
design of library model components
6
Object-Oriented Component
Object- Component--Based
Approaches in General
7
Approach 3: Top-
Top-Down Object
Object--oriented
approach using library model components
Electrical Rotational
Controller Circuit Mechanics
8
Modeling the Controller Subsystem
Electrical Rotational
Controller Circuit Mechanics
feedback1
- PI
step1 PI1
Electrical Rotational
Controller Circuit Mechanics
resistor1 inductor1
EMF1
signalVoltage1
ground1
9
Modeling the Mechanical Subsystem
Electrical Rotational
Controller Circuit Mechanics
speedSensor1
• Approach 4: Object
Object-oriented
oriented flat model approach
• Approach 5: Object-oriented approach with
design of library model components
10
Example: OO Modeling of a Tank System
source
levelSensor controller
maxLevel out in
level h tank valve
Object--Oriented Modeling
Object
11
Tank System Model FlatTank – No Graphical
Structure
model FlatTank
• No component // Tank related variables and parameters
structure parameter Real flowLevel(unit="m3/s")=0.02;
parameter Real area(unit="m2") =1;
parameter Real flowGain(unit="m2/s") =0.05;
• Just flat set of Real h(start=0
h(start=0,unit=
unit="m")
m ) "Tank
Tank level";
level ;
equations Real qInflow(unit="m3/s") "Flow through input valve";
Real qOutflow(unit="m3/s") "Flow through output valve";
// Controller related variables and parameters
• Straight- parameter Real K=2 "Gain";
parameter Real T(unit="s")= 10 "Time constant";
forward but parameter Real minV=0, maxV=10; // Limits for flow output
less flexible, Real ref = 0.25 "Reference level for control";
no graphical Real error "Deviation from reference level";
structure Real outCtr "Control signal without limiter";
Real x; "State variable for controller";
equation
assert(minV>=0,"minV must be greater or equal to zero");//
der(h) = (qInflow-qOutflow)/area; // Mass balance equation
qInflow = if time>150 then 3*flowLevel else flowLevel;
qOutflow = LimitValue(minV,maxV,-flowGain*outCtr);
error = ref-h;
der(x) = error/T;
outCtr = K*(error+x);
end FlatTank;
0.4
0.3
0.2
0.1
time
50 100 150 200 250
12
Object--Oriented Modeling
Object
• Approach 5:
Object-oriented approach with design of
library model components
• Tank cIn
piContinuous
cOut
model TankPI
LiquidSource source(flowLevel=0.02);
PIcontinuousController piContinuous(ref=0.25);
T k
Tank t
tank(area=1);
k( 1)
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, piContinuous.cOut);
connect(tank.tSensor, piContinuous.cIn);
end TankPI;
13
Tank model
• The central equation regulating the behavior of the tank is the mass balance
equation (input flow, output flow), assuming constant pressure
model Tank
ReadSignal tSensor "Connector
Connector, sensor reading tank level (m)";
(m) ;
ActSignal tActuator "Connector, actuator controlling input flow";
LiquidFlow qIn "Connector, flow (m3/s) through input valve";
LiquidFlow qOut "Connector, flow (m3/s) through output valve";
parameter Real area(unit="m2") = 0.5;
parameter Real flowGain(unit="m2/s") = 0.05;
parameter Real minV=0, maxV=10; // Limits for output valve flow
Real h(start=0.0, unit="m") "Tank level";
equation
assert(minV>=0,"minV
( , – minimum Valve level must be >= 0 ");//
)
der(h) = (qIn.lflow-qOut.lflow)/area; // Mass balance
equation
qOut.lflow = LimitValue(minV,maxV,-flowGain*tActuator.act);
tSensor.val = h;
end Tank;
end ActSignal;
model LiquidSource
LiquidFlow qOut;
parameter flowLevel = 0.02;
equation
qOut.lflow = if time>150 then 3*flowLevel else flowLevel;
end LiquidSource;
14
Continuous PI Controller for Tank System
• error = (reference level – dx error
actual tank level) dt T
• T is a time constant outCtr K * ( error x )
• x is controller state Integrating equations gives
variable Proportional & Integrative (PI)
• K is a gain factor error
outCtr K * ( error T
dt )
base class for controllers – to be defined
model PIcontinuousController
extends BaseController(K=2,T=10);
Real x "State variable of continuous PI controller";
equation error – to be defined in controller base class
der(x) = error/T;
outCtr = K*(error+x);
end PIcontinuousController;
15
Simulate Component-
Component-Based Tank System
• As expected (same equations), TankPI gives the
same result as the flat model FlatTank
simulate(TankPI, stopTime=250)
plot(h, stopTime=250)
0.4
0.3
0.2
0.1
time
50 100 150 200 250
Flexibility of Component
Component--Based Models
g of components
• Exchange p p
possible in a
component-based model
• Example:
Exchange the PI controller component for a PID
controller component
p
16
Tank System with Continuous PID Controller
Instead of Continuous PI Controller
• Liquid source TankPID
• Tank cIn
pidContinuous
cOut
model TankPID
LiquidSource source(flowLevel=0.02);
PIDcontinuousController pidContinuous(ref=0.25);
T k
Tank t
tank(area=1);
k( 1)
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, pidContinuous.cOut);
connect(tank.tSensor, pidContinuous.cIn);
end TankPID;
T dt T
error d error
• K is a gain factor outCtr K * ( error )
dt
base class for controllers – to be defined
model PIDcontinuousController
extends BaseController(K=2,T=10);
Real x; // State variable of continuous PID controller
Real y; // State variable of continuous PID controller
equation
der(x) = error/T;
y = T*der(error);
outCtr = K*(error + x + y);
end PIDcontinuousController;
17
Simulate TankPID and TankPI Systems
• TankPID with the PID controller gives a
slightly different result compared to the
TankPI model with the PI controller
simulate(compareControllers, stopTime=250)
plot({tankPI.h,tankPID.h})
tankPI.h
0.4 tankPID.h
0.3
0.2
0.1
time
50 100 150 200 250
piContinuous piContinuous
cIn cOut cIn cOut
model TanksConnectedPI
LiquidSource source(flowLevel=0.02);
Tank tank1(area=1), tank2(area=1.3);;
PIcontinuousController p
piContinuous1(ref=0.25),
( ), p
piContinuous2(ref=0.4);
( );
equation
connect(source.qOut,tank1.qIn);
connect(tank1.tActuator,piContinuous1.cOut);
connect(tank1.tSensor,piContinuous1.cIn);
connect(tank1.qOut,tank2.qIn);
connect(tank2.tActuator,piContinuous2.cOut);
connect(tank2.tSensor,piContinuous2.cIn);
end TanksConnectedPI;
18
Simulating Two Connected Tank Systems
• Fluid level in tank2 increases after tank1 as it should
• Note: tank1 has reference level 0.25, and tank2 ref level 0.4
simulate(TanksConnectedPI, stopTime=400)
plot({tank1.h,tank2.h})
tank1.h
0.8
tank2.h
0.6
0.4
0.2
time
100 200 300 400
19
Exercises
20
Simplification of Models
• Simplification approaches
• Neglect small effects that are not important for the phenomena to be
modeled
• Aggregate state variables into fewer variables
• Approximate
A i t subsystems
b t with
ith very slow
l d
dynamics
i withith constants
t t
• Approximate subsystems with very fast dynamics with static
relationships, i.e. not involving time derivatives of those rapidly changing
state variables
21
2010-10-19
An Introduction to Shakespeare
The Dynamics of Shakespearian Characters
Peter Bunus
Department of Computer and Information Science
SE 584-32 Linköping University, Sweden
{[email protected]}
Problem formulation
1
2010-10-19
dx
ax by where x is the Romeo love for Julia
dt
x>0
2
2010-10-19
ddy y>0
cy dx
dt y = 0 Julia doesn’t care about Romeo
3
2010-10-19
dx
dt ax by
The mathematician’s remark:
dy cx dy
dt
William Shakespeare needed 25 674
words and 1938 paragraphs to explain
this
dx
dt ax by x[0] 0; y[0] 0
dy cx dy
dt
@
D
@
D
x t
y t
0.5
t
2 4 6 8 10
-0.5
-1
4
2010-10-19
Love Affair #1
Do opposites attract?
Take c = -b and d = -a 1
dx
0.5
dt ax by 2 4 6 8 10
dy bx ay
-0.5
dt -1
• Romeo’s’ feelings
f li show
h thath he
h really
ll likes
lik Julia
li but
b as soon as
his affections are not met, he gets discouraged and cools down
• In the true spirit of a woman, Julia starts to like him as soon as
his attention fades
0.5
-1 -0.5 0.5 1
-0.5
-1
5
2010-10-19
Take a = 0 , b = 0 x[0]=0
20000
dx
dt 0
15000
10000
dy cx dy 5000
dt 2 4 6 8 10
• Can
C beb either
i h love
l or hate
h depending
d di on the
h sign
i off y, c andd d.
d
• Romeo’s indifference drives Julia insane with passion
• Her feelings never dies
6
2010-10-19
Love Affair #3
a = 0 , b = -1 1
c = 1, d = 0 0.5
dx 2 4 6 8 10
dt by -0.5
dy x
-1
dt
• The same never ending cycle from Love affair #1
• At t=0 Julia likes Romeo and Romeo dislikes Julia
• Again their feelings oscillate, neither sure they love each other
Love Affair #4
a = 2 , b = -2
8
6´10
c = -1, d = 1 4´10 8
8
2´10
dx
dt 2 x 2 y
2 4 6 8 10
8
-2 ´10
-4 ´10 8
dy x y
8
-6 ´10
dt
• During the first 7 years of knowledge R&J feel indifference to
each other
• At the same time R realizes his love for J, J realizes that he is
repulsed of him
7
2010-10-19
Love Affair #5
a = 0 , b = -2 0.4
0.3
c = 1, d = -1
0.2
dx 0.1
dt 2 y 2 4 6 8 10
-0.1
dy x y -0.2
dt
-0.3
Love Affair #6
8
2010-10-19
Love Affair #6
dx
dt 0.2( y 2)
3
2
dy 0.8( x 2)
1
dt 10 20 30 40 50
9
2010-10-19
a=1,b=1
c = 1, d = 1
7
1.75 ´10
1.5 ´10 7
dx
1.25 ´10 7
dt ax by
1´10 7
7.5 ´10 6
5´10
6
dy cx dy 2.5 ´10 6
dt 2 4 6 8 10
Shakespeare’s Version
10
2010-10-19
7
1.75 ´10
1´10 7
to find another model
7.5 ´10 6
6
5´10
2.5 ´10 6
2 4 6 8 10
200
p
k=0.3
150
k=0.2
ddp 50
kp
dt
t
2 4 6 8 10
What if ?
11
2010-10-19
dxJuliet
axJuliet b( y z )
dt
dy
cxJuliet dy
dt
dxRowena
axRowena b( z y )
dt
dz
exRowena fz
dt
System is 4D (4 variables)
There are 6 parameters
System is linear (no chaos)
Romeo’s fate ?
12
2010-10-19
How about me ?
1.4
num=1; 1.2
den=[1 5 10];
1
Kp=200;
Amplitude
0.8
t=0:0.01:6; 0.4
step(numCL,
t ( CL denCL,t)
d CL t)
0.2
0
-8 -6 -4 -2 0 2 4 6
Time (sec)
Happiness model ?
d2x dx
2
2 x F (t )
dt dt
dx
Happiness H
dt
13
2010-10-19
What is x ?
d2x dx
2
2
x F (t )
d
dt d
dt
x = integral of H
x is what others perceive
In the love model x is what the other feels
H (your happiness) must average to zero (with positive
damping)
x does not average to zero
14
2010-10-19
Random Events ?
15
2010-10-19
Real Life ?
Some implications
Constant
C t t happiness
h i is
i an unrealistic
li ti goal.
l
Others see less volatility in you and often
wrongly conclude how you feel.
Rome and Julia might not be so happy as it
looks.
Individuals can be categorized by their values
of and .
Long prison terms may be ineffective.
16
2010-10-19
Conclusions
but
17
Library Design
Influenza Model
1 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
2 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
1
Spreading of Influenza Epidemic
3 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
4 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
2
Influenza Model Parameters
• Average weekly contacts of a person with others, CWk=15
• Contraction rate per contact, RateC=0.25
5 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
Governing Equations
_ _
_
_
_
_
_
_
_
6 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
3
Block Oriented Approach
7 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
Less
Components
Infected
8 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
4
Object Oriented Approach #2
Immune
Constants
C
Non Infected
Sick
Base class
Infected
9 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
Constants
C
Non Infected
Sick
Base class
Infected
10 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
5
Simulation
Immune
Non Infected
Sick
Infected
11 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
Coclusions
12 Mohsen Torabzadeh-
Torabzadeh-Tari pelab
6
Excersize
13 Mohsen Torabzadeh-
Torabzadeh-Tari pelab