Professional Documents
Culture Documents
Slides
Based on book and lecture notes by Peter Fritzson
Contributions 2004-2005 by Emma Larsdotter Nilsson, Peter
Bunus
Contributions 2006-2008 by Adrian Pop and Peter Fritzson
Contributions 2009 by David Broman, Peter Fritzson, Jan
Brugård, and Mohsen Torabzadeh-Tari
Contributions 2010 by Peter Fritzson
Contributions 2011 by Peter F., Mohsen T,. Adeel Asghar,
Contributions 2012, 2013, 2014, 2015, 2016 by Peter Fritzson,
Lena Buffoni, Mahder Gebremedhin, Bernhard Thiele
2017-02-07
Tutorial Based on Book, December 2014
Download OpenModelica Software
Peter Fritzson
Principles of Object Oriented
Modeling and Simulation with
Modelica 3.3
A Cyber-Physical Approach
• OpenModelica
• www.openmodelica.org
• Modelica Association
• www.modelica.org
2015 –Translations
available in
Chinese,
Japanese,
Spanish
Wiley
IEEE Press
For Introductory
Short Courses on
Object Oriented
Mathematical Modeling
Part I Part II
Introduction to Modelica and a Modelica environments
demo example
• Go to
https://openmodelica.org/index.php/download/down
load-linux and follow the instructions.
• Go to
https://openmodelica.org/index.php/download/down
load-mac and follow the instructions or follow the
instructions written below.
• The installation uses MacPorts. After setting up a
MacPorts installation, run the following commands
on the terminal (as root):
• echo rsync://build.openmodelica.org/macports/ >>
/opt/local/etc/macports/sources.conf # assuming you installed into /opt/local
• port selfupdate
• port install openmodelica-devel
• Robotics
• Automotive
• Aircrafts
• Satellites
• Power plants
• Systems biology
• Multi-Domain Modeling
• Visual acausal hierarchical component modeling
• Typed declarative equation-based textual language
• Hybrid modeling and simulation
Cyber
Acausal model
(Modelica)
Causal
block-based
model
(Simulink)
qddRef
qdRef qRef k1 r3Control
r3Motor r3Drive1
cut joint
tn
axis6
Modeling
1 1
i 1
S S
qd axis5
q: angle
qd: angular velocity
qdRef Kd qdd: angular acceleration 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
skew(n)*sin(q); -
Ri=10
-
-
wrela = n*qd; + +
Sb = Sa*transpose(Srel);
Vs
Rd4=100
r0b = r0a; emf
vb = Srel*va; iRef
Rd3=100
g3
wb = Srel*(wa + wrela); y
ab = Srel*aa;
g1 x
zb = Srel*(za + zrela + cross(wa, wrela)); inertial
hall2
hall1 w r
Continuous-time
Discrete-time
Clocked discrete-time
Typed
Declarative time
Hybrid
Equation-based Modeling
Textual Language
Causality
Systems
Derivation
Definition Modeling of
Subsystems (manual derivation of
System
Decomposition input/output relations) Implementation Simulation
Proprietary
Code
Block Diagram
Modelica
R es2 sum 3 In d l2
p p
-1 1
R2 1 /L
1 s
R1=10 R2=100
sum 2
p
n n +1
+1
AC=220
p p s in ln sum 1 R es1 C ap l1
n +1 1
1 /R 1 1 /C
-1 s
C = 0 .0 1 L = 0 .1
n n
p
G
connect(DC.n,G.p);
connect(EM.flange,load.flange); G
end DCMotor
The following equations are automatically derived from the Modelica model:
Modelica
Graphical Editor Modelica Modelica
Modelica Model Source code
Textual Editor Modelica Model
Frontend Translator
Modeling Flat model Hybrid DAE
Environment Analyzer
"Middle-end"
Sorted equations
Optimizer
Optimized sorted
equations
Backend Code generator
C Code
C Compiler
Executable
Simulation
29 Copyright © Open Source Modelica Consortium
Modelica in Power Generation
GTX Gas Turbine Power Cutoff Mechanism
H e llo
Developed
by MathCore
for Siemens
Courtesy of Siemens Industrial Turbomachinery AB
(Movie demo)
• Low-temperature parts
(condenser, feedwater
system, LP circuits) are
represented by trivial
boundary conditions.
DLR ROboMObil
• experimental electric car Tesla model S
• Modelica models range 480 km
Almost Sustainable
• India, recently 1.4 ton C02/person/year
• Healthy vegetarian food
• Small-scale agriculture
• Small-scale shops
• Simpler life-style (Mahatma Gandhi)
Non-sustainable
• USA 17 ton CO2, Sweden 7 ton CO2/yr
• High meat consumption (1 kg beef uses ca
4000 L water for production)
• Hamburgers, unhealthy , includes beef
• Energy-consuming mechanized agriculture Gandhi – role model for
• Transport dependent shopping centres future less materialistic
life style
• Stressful materialistic lifestyle
44 Copyright © Open Source Modelica Consortium
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
• 3.1 released May 2009
• 3.2 released March 2010
• 3.3 released May 2012
• 3.2 rev 2 released November 2013
• 3.3 rev 1 released July 2014
• 3.4 planned spring 2017
• Modelica Association established 2000 in Linköping
• Open, non-profit organization
R=10
R=100 L=1
L=0.1
AC
• Wolfram Research
• USA, Sweden
• General purpose
• Mathematica integration
• www.wolfram.com
• www.mathcore.com
Mathematica
Simulation and
analysis
Courtesy Car model graphical view
Wolfram
Research
• Maplesoft
• Canada
• Recent Modelica tool on the
market
• Integrated with Maple
• www.maplesoft.com
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)
OMweb
OMNote
book book
Contents in
OMWebbook
Generated from
OMNotebook
Latex instructions
can be hidden by
double clicking the
Cell in tree view
Identifier Info on
Hovering
Code Outline for
easy navigation within
68
Modelica files
Copyright © Open Source Modelica Consortium
68
OpenModelica Simulation in Web Browser Client
MultiBody RobotR3.FullRobot
OpenModelica compiles
to efficient
Java Script code which is
executed in web browser
Simulation Control
Simulation Center
Plot View
Source.flowLevel
0.02
Source.flowLevel
Req.001: tank1 Violation warning
Show violations (2)
1. Start Time: 22 (sec) | End Time: 50 (sec)
Requirements
Req.001: tank2 Violated Start Value: tank1 = 8 (m)
MaxLevel
Status: Simulation is running... Liquid Domain-Specific
Level h
Source
Level h
Visualization View
Tank 1 Tank 2
New
Animation
Window
HeatRobin h_glass(h_heat=30000);
T inf 20
HeatTransfer ht;
Rectangle2D dom;
equation
dom.eq=ht;
dom.left.bc=h_glass;
dom.top.bc=h_iso; Conducting boundary:
dom.right.bc=h_iso;
u 60
dom.bottom.bc=h_heated;
end PDEModel;
Automated
generation
MULTIPLE_COLLOCATION
16,0
14,0
12,0
10,0
8,0
6,0
4,0
2,0
0,0
1 2 4 8 16
etc.
The largest 8-bit AVR processor MCUs (Micro Controller Units) have 16 kB SRAM.
The ATmega16 we target has 1 kB SRAM available (stack, heap, and global variables)
• No initialization (yet)
• No strongly connected components
• No events
• No functions (except external C and built-in)
• Only parts that OpenModelica can generate good and efficient code for right
now (extensions might need changes in the intermediate code)
• Unused variables are not accepted (OM usually duplicates all variables
for pre() operators, non-linear system guesses, etc… but only a few of
them are actually used)
• FMU-like interface (but statically linked)
Feedback
System
System
Simulation
Simulation
Business
Business Requirements
Requirements Model-Driven
Driven Compilation
Compilation
Model
Process
Process Capture
Capture Design &
& Code
Code Gen
Gen
Design
Control
Control (PIM) (PSM)
Software
Software&&
Syst Product
System Product
Process
Process Requirements
Requirements Product
Product Platform
Platform
models
models models
models models
models models
models
Level of Abstraction
Experience Feedback
System Maintenance
requirements
Product verification and
Specification Calibration
deployment
Preliminary feature design
Subsystem level integration test
Design
Integration calibration and verification
Architectural design and
Design Subsystem level integration and
system functional design Refinement Verification verification
Detailed feature design and
implementation Component verification
Realization
Verification Model
Provider from
Design Model design model
Requirement
Models
Client from requirement model
tank-height is 0.6m
Formalize RMM
Requirement
Requirements Monitor Models
Designs
Formalize Designs DAM
Alternative
Models
Formalize SM Scenario
Scenarios Models
Analyze Results
Showing
equation
transformations
of a model:
(1) substitution:
y + der(x * (time * z))
=>
y + der(x * (time * 1.0))
(2) simplify:
y + der(x * (time * 1.0))
=>
y + der(x * time)
(4) solve:
0.0 = y + (x + der(x) * time)
=>
der(x) = ((-y) - x) / time
Mapping run-time error to source model position time <> 0
equation
z = if x > 0 then -1 else 1;
y = 2 * z;
…
Typed
Declarative Hybrid
Equation-based Modeling
Textual Language
Visual
Component
Level
0.8
simulate(HelloWorld, stopTime = 2)
0.6
plot(x)
0.4
0.2
0.5 1 1.5 2
v e lo c ity a c c e le r a tio n
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;
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
notation outside Rocket 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
function sum
input Real arg1;
input Real arg2;
output Real result;
algorithm
result := arg1+arg2;
end sum;
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;
class Rectangle
extends VerticalLine;
extends HorizontalLine;
end Rectangle;
...
Real altitude(start= 59404);
...
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;
0.4
0.2
0.5 1 1.5 2
simulate(VanDerPol,stopTime = 25)
1
plotParametric(x,y)
-2 -1 1 2
-1
-2
1.0 time
0.2 0.4 0.6 0.8 1
0.95
0.90
sample(t0,d)
The call sample(t0,d) returns
true and triggers events at times true
t0+i*d, where 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.
class ClockTicks
// Integer quotient rational number interval clock
Clock c1 = Clock(3,10); // ticks: 0, 3/10, 6/10, ..
// Clock with real value interval between ticks
Clock c2 = Clock(0.2); // ticks: 0.0, 0.2, 0.4, ...
end ClockTicks;
Initial conditions
Reinit ”assigns”
continuous-time variable
velocity a new value
Control System
A control system is a device, or set of devices, that manages,
commands, directs or regulates the behavior of other devices
or systems (wikipedia).
Control
Measurements Controller Outputs
Computing
Sensors Actuators
Controller Plant
(Physical System)
r (t ) reference (setpoint)
e (t ) error
y (t ) measured process variable (plant output)
u (t ) control output variable (plant input)
Usual Objective
Plant output should follow the reference signal.
Clock
Computer
Algorithm
Plant
// time-discrete controller
when {initial(),sample(3,3)} then
E*xd = A*pre(xd)+ B*y;
ud = C*pre(xd) + D*y;
end when;
y
ud
f
an instance flange Flange flange;
of class Flange
+ v v +
p in 1 p in 2
i i
Pin pin1,pin2;
//A connect equation
//in Modelica: pin1.v = pin2.v;
connect(pin1,pin2);
Corresponds to
pin1.i + pin2.i =0;
Pin pin1,pin2;
//A connect equation
//in Modelica pin1.v = pin2.v;
connect(pin1,pin2);
Corresponds to
pin1.i + pin2.i =0;
v1 v 2 v 3 vn
Each primitive connection set of flow variables is used to generate
sum-to-zero equations of the form:
i1 i 2 ( ik ) in 0
respectively i
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;
equation
p.v = 0;
end Ground;
i1 i2
n R1 p p R2 n
v1 v2
v3
p n
i3 R3
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;
L ib r a r y
C o n t in u o u s
Examples:
Examples:
V2
R2 R4
G nd9
C2 G nd3 G nd6 C4
R1 T r a n s is t o r 1 T r a n s is t o r 2 R3
V1 C1 I1 C5 C3 G nd4
• Powertrain
• SmartElectricDrives
• VehicleDynamics
• AirConditioning
• HyLib
• PneuLib
• CombiPlant
• HydroPlant
• …
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;
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); em f
connect(R.p,L.n); DC
connect(L.p, emf.n);
connect(emf.p, DC.n); lo a d
connect(DC.n,G.p);
connect(emf.flange,load.flange); G
end DCMotor;
using
OpenModelica
Simulation
Inputs Output
Simulation
(known) (result)
Inputs Output
Simulation
(result) (desired)
MULTIPLE_COLLOCATION
16,0
14,0
12,0
10,0
8,0
6,0
4,0
2,0
0,0
1 2 4 8 16
Annotation
Mayer-Term Real costM annotation(isMayer=true);
Lagrange-Term Real costL annotation(isLagrange=true);
Constraints Real x(max=0) annotation(isConstraint=true);
Final constraints Real y(min=0) annotation(isFinalConstraint=true);
where
𝑔𝑟 = 4 ∙ 10−2 , Natural growth rate 𝑑𝑟ℎ = 5 ∙ 10−3 , Death rate of
for rabbits rabbits due to hunters
𝑔𝑓𝑟 = 1 ∙ 10−1 , Efficiency in growing 𝑑𝑓 = 9 ∙ 10−2 , Natural death rate
foxes from rabbits for foxes
𝑑𝑟𝑓 = 5 ∙ 10−3 , Death rate of rabbits 𝑑𝑓ℎ = 9 ∙ 10−2 , Death rate of
due to foxes foxes due to hunters
setCommandLineOptions("+gDynOpt");
optimize(ForestOCP, stopTime=400, tolerance=1e-8, numberOfIntervals=50,
simflags="-s optimization");
+gDynOpt
optimization
190 Copyright © Open Source Modelica Consortium
Predator-Prey Example – Plots
using
OpenModelica
connect(DC.n,G.p);
connect(EM.flange,load.flange); G
end DCMotor
The following equations are automatically derived from the Modelica model:
em f
variables for the outgoing u
• OpenModelica
• www.openmodelica.org
• Modelica Association
• www.modelica.org
• Books
• Principles of Object Oriented Modeling and Simulation with
Modelica 3.3: A Cyber-Physical Approach, Peter Fritzson
2015.
Typed
Declarative Hybrid
Textual Language Thanks for listening! Modeling