ModeliCA Tutorial
ModeliCA Tutorial
ModeliCA Tutorial
Introduction to Object-Oriented
Modeling and Simulation with Modelica
Using OpenModelica
Peter Fritzson
Abstract
Object-Oriented modeling is a fast-growing area of modeling and simulation that provides a structured,
computer-supported way of doing mathematical and equation-based modeling. Modelica is today the most
promising modeling and simulation language in that it effectively unifies and generalizes previous objectoriented modeling languages and provides a sound basis for the basic concepts.
The Modelica modeling language and technology is being warmly received by the world community in
modeling and simulation with major applications in virtual prototyping. It is bringing about a revolution in
this area, based on its ease of use, visual design of models with combination of lego-like predefined model
building blocks, its ability to define model libraries with reusable components, its support for modeling
and simulation of complex applications involving parts from several application domains, and many more
useful facilities. To draw an analogy, Modelica is currently in a similar phase as Java early on, before the
language became well known, but for virtual prototyping instead of Internet programming.
The tutorial presents an object-oriented component-based approach to computer supported
mathematical modeling and simulation through the powerful Modelica language and its associated
technology. Modelica can be viewed as an almost universal approach to high level computational
modeling and simulation, by being able to represent a range of application areas and providing general
notation as well as powerful abstractions and efficient implementations.
The tutorial gives an introduction to the Modelica language to people who are familiar with basic
programming concepts. It gives a basic introduction to the concepts of modeling and simulation, as well as
the basics of object-oriented component-based modeling for the novice, and an overview of modeling and
simulation in a number of application areas.
The tutorial has several goals:
Being easily accessible for people who do not previously have a background in modeling,
simulation.
Introducing the concepts of physical modeling, object-oriented modeling and component-based
modeling and simulation.
Giving an introduction to the Modelica language.
Demonstrating modeling examples from several application areas.
Giving a possibility for hands-on exercises.
Presenters data
Peter Fritzson is Professor and research director of the Programming Environment Laboratory, at
Linkping University. He is also director of the Open Source Modelica Consortium, director of the
MODPROD center for model-based product development, and vice chairman of the Modelica Association,
organizations he helped to establish. During 1999-2007 he served as chairman of the Scandinavian
Simulation Society, and secretary of the European simulation organization, EuroSim. Prof. Fritzson's
current research interests are in software technology, especially programming languages, tools and
environments; parallel and multi-core computing; compilers and compiler generators, high level
specification and modeling languages with special emphasis on tools for object-oriented modeling and
simulation where he is one of the main contributors and founders of the Modelica language. Professor
Fritzson has authored or co-authored more than 250 technical publications, including 17
books/proceedings.
Principles of Object-Oriented
Modeling and Simulation
with Modelica
Peter Fritzson
Linkping University, [email protected]
Slides
Based on book and lecture notes by Peter Fritzson
Contributions 2004-2005 by Emma Larsdotter, Peter Bunus, Peter F
Contributions 2007-2008 by Adrian Pop, Peter Fritzson
Contributions 2009 by David Broman, Jan Brugrd, Mohsen
Torabzadeh-Tari, Peter Fritzson
Contributions 2010 by Mohsen Torabzadeh-Tari, Peter Fritzson
Contributions 2012 by Olena Rogovchenko, Peter Fritzson
2012-10-24 Course
940 pages
OpenModelica
www.openmodelica.org
Modelica Association
www.modelica.org
2
Peter Fritzson
pelab
New Introductory
Modelica Book
September 2011
232 pages
Wiley
IEEE Press
For Introductory
Short Courses on
Object Oriented
Mathematical
Modeling
3
Peter Fritzson
pelab
Outline Day 1
Part I
Introduction to Modelica and a
demo example
Part III
Modelica language concepts
and textual modeling
Peter Fritzson
Part II
Modelica environments
Part IV
Graphical modeling and the
Modelica standard library
pelab
Peter Fritzson
pelab
Peter Fritzson
pelab
Go to
https://openmodelica.org/index.php/download/do
wnload-linux and follow the instructions.
Peter Fritzson
pelab
Peter Fritzson
pelab
Outline
Introduction to Modeling and Simulation
Modelica - The next generation modeling and
Simulation Language
Modeling and Simulation Environments and
OpenModelica
Classes
Components, Connectors and Connections
Equations
Discrete Events and Hybrid Systems
Algorithms and Functions
Demonstrations
9
Peter Fritzson
pelab
10
Peter Fritzson
pelab
What is a system?
A system is an object or collection of
objects whose properties we want to study
Natural and artificial systems
Reasons to study: curiosity, to build it
Collector
Hot water
Storage tank
Heater
Electricity
Cold water
11
Peter Fritzson
Pump
pelab
12
Robotics
Automotive
Aircrafts
Satellites
Biomechanics
Power plants
Hardware-in-the-loop,
real-time simulation
Peter Fritzson
pelab
Experiments
An experiment is the process of extracting information
from a system by exercising its inputs
Problems
Experiment might be too expensive
Experiment might be too dangerous
System needed for the experiment might not yet exist
13
Peter Fritzson
pelab
Model concept
A model of a system is anything an experiment can be
applied to in order to answer questions about that system
Kinds of models:
14
Peter Fritzson
pelab
Simulation
A simulation is an experiment performed on a model
Examples of simulations:
Industrial process such as steel or pulp
manufacturing, study the behaviour under different
operating conditions in order to improve the process
Vehicle behaviour e.g. of a car or an airplane, for
operator training
Packet switched computer network study behaviour
under different loads to improve performance
15
Peter Fritzson
pelab
16
Peter Fritzson
pelab
Dangers of Simulation
Falling in love with a model
The Pygmalion effect (forgetting that model is not the real
world, e.g. introduction of foxes to hunt rabbits in Australia)
17
Peter Fritzson
pelab
18
Peter Fritzson
pelab
19
Peter Fritzson
pelab
Input current
pulse
Capacitor voltage - dynamic
time
20
Peter Fritzson
pelab
10
Continuous-Time 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
21
Peter Fritzson
pelab
Superb
Tasty
Good
Mediocre
time
Peter Fritzson
pelab
11
System
requirements
Calibration
Specification
Design
Refinement
Verification
Component verification
Realization
23
Peter Fritzson
pelab
Component 1
Component 3
Component 2
Connection
24
Peter Fritzson
pelab
12
qdRef
qRef
k1
axis6
cut joint
r3Control
r3Motor
tn
r3Drive1
qd
axis5
l
qdRef
Kd
S
rel
0.03
Jmotor=J
pSum
Kv
0.3
sum
w Sum
+1
+1
rate2
rate3
b(s)
340.8
a(s)
joint=0
axis4
iRef
gear=i
fric=Rv0
qRef
spring=c
axis3
rate1
tacho2
b(s)
b(s)
a(s)
a(s)
tacho1
PT1
axis2
g5
C=0.004*D/w m
Rd1=100
Rp1=200
Rd2=100
Ri=10
+
diff
pow er
OpI
Rp2=50
qd
axis1
Vs
Rd4=100
emf
y
x
inertial
Rd3=100
25
Peter Fritzson
pelab
Peter Fritzson
EM
load
pelab
13
27
Peter Fritzson
pelab
Modelica
Model
Modelica Model
Frontend
Modeling
Environment
Modelica
Source code
Translator
Flat model Hybrid DAE
"Middle-end"
Analyzer
Sorted equations
Optimizer
Backend
Optimized sorted
equations
Code generator
C Code
C Compiler
Executable
Simulation
28
Peter Fritzson
pelab
14
Hello
29
Peter Fritzson
Developed
by MathCore
for Siemens
pelab
30
Peter Fritzson
pelab
15
Modelica in Avionics
31
Peter Fritzson
pelab
Modelica in Biomechanics
32
Peter Fritzson
pelab
16
33
Peter Fritzson
pelab
Low-temperature parts
(condenser, feedwater
system, LP circuits) are
represented by trivial
boundary conditions.
34
Peter Fritzson
pelab
17
35
Peter Fritzson
pelab
36
Peter Fritzson
pelab
18
Modelica
The Next Generation
Modeling Language
37
Peter Fritzson
pelab
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
38
Peter Fritzson
pelab
19
Peter Fritzson
pelab
What is Modelica?
A language for modeling of complex physical systems
40
Robotics
Automotive
Aircrafts
Satellites
Power plants
Systems biology
Peter Fritzson
pelab
20
What is Modelica?
A language for modeling of complex physical systems
41
Peter Fritzson
pelab
What is Modelica?
A language for modeling of complex cyber physical systems
i.e., Modelica is not a tool
Free, open language
specification:
Peter Fritzson
pelab
21
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
Efficient, non-proprietary
Efficiency comparable to C; advanced equation compilation,
e.g. 300 000 equations, ~150 000 lines on standard PC
43
Peter Fritzson
pelab
MATLAB similarities
MATLAB-like array and scalar arithmetic, but strongly typed and
efficiency comparable to C.
Non-Proprietary
Open Language Standard
Both Open-Source and Commercial implementations
44
Peter Fritzson
pelab
22
Peter Fritzson
pelab
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
46
Peter Fritzson
pelab
23
Systems
Definition
Modeling of
Subsystems
System
Decomposition
Causality
Derivation
(manual derivation of
input/output relations)
Implementation Simulation
Proprietary
Code
Block Diagram
Modelica
47
Peter Fritzson
pelab
Keeps the
physical
structure
Simulink:
Signal-flow model hard to
understand
Res2
p
R2
R1=10
sum3
-1
1
Ind
1/L
l2
1
s
R2=100
sum2
+1
+1
AC=220
p
sinln
sum1
+1
-1
C=0.01
Res1
1/R1
Cap
1/C
l1
1
s
L=0.1
n
48
Peter Fritzson
pelab
24
Modelica Versions
Peter Fritzson
pelab
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
Linkping, 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
The 7th International Modelica conference Sept 21-22, 2009 in Como, Italy
The 8th International Modelica conference March 20-22, 2011 in Dresden,
Germany
The 9th International Modelica conference Sept 3-5, 2012 in Munich,
Germany
50
Peter Fritzson
pelab
25
Exercises Part I
Hands-on graphical modeling
(20 minutes)
51
Peter Fritzson
pelab
52
Peter Fritzson
pelab
26
R=10
R=100
L=1
L=0.1
A
C
The RLCircuit
Simulation
53
Peter Fritzson
pelab
54
Peter Fritzson
pelab
27
Go to Simulation menu and choose simulate or click on the siumulate button in the
toolbar.
55
Once the simulation is completed, a plot variables list will appear on the right side.
Select the variable that you want to plot.
Peter Fritzson
pelab
28
Peter Fritzson
Dymola
Peter Fritzson
Simulation X
Peter Fritzson
ITI
Germany
Mechatronic systems
www.simulationx.com
Maplesoft
Canada
Recent Modelica tool on the
market
Integrated with Maple
www.maplesoft.com
MapleSim
Peter Fritzson
Wolfram Research
USA, Sweden
General purpose
Mathematica integration
www.wolfram.com
www.mathcore.com
Mathematica
Courtesy
Wolfram
Research
Simulation and
analysis
Peter Fritzson
OpenModelica (Part I)
OpenModelica
Open Source Modelica
Consortium (OSMC)
Sweden and other countries
Open source
www.openmodelica.org
Peter Fritzson
Peter Fritzson
Code Statistics
Peter Fritzson
10
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 (shifttab)
11
Peter Fritzson
12
Peter Fritzson
13
Peter Fritzson
>>simulate(BouncingBall,
stopTime=3.0);
>>plot({h,flying});
14
Peter Fritzson
model BouncingBall
parameter Real e=0.7 "coefficient of restitution";
parameter Real g=9.81 "gravity acceleration";
Real h(start=1) "height of ball";
Real v "velocity of ball";
Boolean flying(start=true) "true, if ball is flying";
Boolean impact;
Real v_new;
equation
impact=h <= 0.0;
der(v)=if flying then -g else 0;
der(h)=v;
when {h <= 0.0 and v <= 0.0,impact} then
v_new=if edge(impact) then -e*pre(v) else 0;
flying=v_new > 0;
reinit(v, v_new);
end when;
end BouncingBall;
15
Peter Fritzson
Examples of Simulation
Visualization
Simulation Control
Plot View
Requirements
Evaluation View
in ModelicaML
MaxLevel
Liquid
Source
Level h
Level h
Tank 1
16
Peter Fritzson
Domain-Specific
Visualization View
Tank 2
17
Peter Fritzson
Code Assistance on
function calling.
18
Peter Fritzson
Identifier Info on
Hovering
Code Outline for
19
Peter Fritzson
19
20
Peter Fritzson
10
21
Peter Fritzson
22
Peter Fritzson
Model Variables
Optimized
parameters
Optimized
Objectives
11
Problems
Solved problems
23
Peter Fritzson
2
ipopt [scaled]
24
Peter Fritzson
16
jac_g [scaled]
12
25
Interpretation of Modelica
commands and expressions
Interactive Session handling
Library / Tool
Optimized Parser results
Helper functions
Deployable, Extensible and
Distributable
Peter Fritzson
PySimulator Package
PySimulator, a
simulation and
analysis package
developed by DLR
Free, downloadable
Uses OMPython to
simulate Modelica
models by
OpenModelica
26
Peter Fritzson
13
Modelica3D Library
Modelica 3D
Graphics Library
by Fraunhofer
FIRST, Berlin
Free,
downloadable
Can be used for
3D graphics in
OpenModelica
Shipped with
OpenModelica
27
Peter Fritzson
class PDEModel
HeatNeumann h_iso;
Dirichlet h_heated(g=50);
HeatRobin h_glass(h_heat=30000);
HeatTransfer ht;
Rectangle2D dom;
equation
dom.eq=ht;
dom.left.bc=h_glass;
dom.top.bc=h_iso;
dom.right.bc=h_iso;
dom.bottom.bc=h_heated;
end PDEModel;
Tinf 20
Conducting boundary:
u 60
Peter Fritzson
14
etc.
Engine
with ECU
Gearbox
with ECU
Thermal
systems
Automated
cargo door
Chassis components,
roadway, ECU (e.g. ESP)
29
Peter Fritzson
Business
Process
Control
Requirements
Capture
Model-Driven
Design
(PIM)
Compilation
& Code Gen
(PSM)
System
Simulation
Software &
Syst Product
Process
models
Requirements
models
Product
models
Platform
models
Peter Fritzson
15
ModelicaML
Defines graphical concrete syntax (graphical notation for diagram) for
representing Modelica constructs integrated with UML
Includes graphical formalisms (e.g. State Machines, Activities,
Requirements)
Which do not exist in Modelica language
Which are translated into executable Modelica code
Is defined towards generation of executable Modelica code
Current implementation based on the Papyrus UML tool + OpenModelica
31
Peter Fritzson
tank-height is 0.6m
32
Peter Fritzson
16
vVDR Method
virtual Verification of Designs vs Requirements
Actor
Task
Created Artifact
Requirement
Monitor Models
Formalize
Requirements
RMM
Formalize Designs
DAM
Formalize
Scenarios
SM
Scenario
Models
VM
Verification Models
AUTOMATED
Create Verification
Models
AUTOMATED
Execute and
Create Report
Designs
Alternative
Models
Reports
Analyze Results
33
Peter Fritzson
34
Peter Fritzson
17
Eclipse Plugin
Editor/Browser
Interactive
session handler
OMOptim
Optimization
DrModelica
OMNoteBook
Model Editor
Textual
Model Editor
Modelica
Compiler
Execution
Modelica
Debugger
35
Peter Fritzson
SCode
Client: Graphic
Model Editor
Corba
Client: OMShell
Interactive
Session Handler
Interactive
Client: Eclipse
Plugin MDT
Untyped API
Inst
system
Ceval
36
Peter Fritzson
plot
etc.
18
Modelica
Model
Modelica
Source code
Modelica Model
Translator
Flat model
Analyzer
Sorted equations
Optimizer
Optimized sorted
equations
Code generator
C Code
C Compiler
Executable
Simulation
37
Peter Fritzson
Peter Fritzson
19
Saves the model (A2) in a file given by a string (A1). This call is also in typed API.
loadFile(A1<string>)
Loads all models in the file. Also in typed API. Returns list of names of top level classes in the
loaded files.
loadModel(A1<cref>)
Loads the model (A1) by looking up the correct file to load in $MODELICAPATH. Loads all models
in that file into the symbol table.
deleteClass(A1<cref>)
addComponent(A1<ident>,A2<cref>,
A3<cref>,annotate=<expr>)
Adds a component with name (A1), type (A2), and class (A3) as arguments. Optional annotations
are given with the named argument annotate.
deleteComponent(A1<ident>,
A2<cref>)
updateComponent(A1<ident>,
A2<cref>,
A3<cref>,annotate=<expr>)
Updates an already existing component with name (A1), type (A2), and class (A3) as arguments.
Optional annotations are given with the named argument annotate.
addClassAnnotation(A1<cref>,
annotate=<expr>)
Adds annotation given by A2( in the form annotate= classmod(...)) to the model definition
referenced by A1. Should be used to add Icon Diagram and Documentation annotations.
getComponents(A1<cref>)
getComponentAnnotations(A1<cref>)
Returns a list {...} of all annotations of all components in A1, in the same order as the
components, one annotation per component.
getComponentCount(A1<cref>)
Returns the number (as a string) of components in a class, e.g return 2 if there are 2 components.
getNthComponent(A1<cref>,A2<int>)
Returns the belonging class, component name and type name of the nth component of a class, e.g.
A.B.C,R2,Resistor, where the first component is numbered 1.
getNthComponentAnnotation(
A1<cref>,A2<int>)
Returns the flattened annotation record of the nth component (A2) (the first is has no 1) within
class/component A1. Consists of a comma separated string of 15 values, see Annotations in
Section 2.4.4 below, e.g false,10,30,...
getNthComponentModification(
A1<cref>,A2<int>)??
Returns the modification of the nth component (A2) where the first has no 1) of class/component
A1.
the number
(as a string) of inherited classes of a class.
Peter Fritzson Copyright Open SourceReturns
Modelica
Consortium
39getInheritanceCount(A1<cref>)
getNthInheritedClass(A1<cref>,
Returns the type name of the nth inherited class of a class. The first class has number 1.
Platforms
All OpenModelica GUI tools (OMShell,
OMNotebook, ...) are developed on the Qt4 GUI
library, portable between Windows, Linux, Mac
Both compilers (OMC, MMC) are portable between
the three platforms
Windows currently main development and release
platform
Linux available. Also used for development
Mac available
40
Peter Fritzson
20
41
Peter Fritzson
42
Peter Fritzson
21
Typed
Declarative
Equation-based
Textual Language
Peter Fritzson
Hybrid
Modeling
pelab
Acausal Modeling
The order of computations is not decided at modeling time
Acausal
Causal
Visual
Component
Level
Equation
Level
Peter Fritzson
A resistor equation:
R*i = v;
Causal possibilities:
i := v/R;
v := R*i;
R := v/i;
pelab
Peter Fritzson
pelab
Multi-Domain Modeling
Visual acausal hierarchical component modeling
Typed declarative equation-based textual
language
Hybrid modeling and simulation
Peter Fritzson
pelab
Peter Fritzson
pelab
Visual Acausal
Hierarchical
Component
Modeling
Acausal model
(Modelica)
Causal
block-based
model
(Simulink)
Peter Fritzson
pelab
Multi-Domain
Modeling
k2
i
qddRef
qdRef
qRef
k1
axis6
cut joint
r3Control
r3Motor
tn
r3Drive1
Visual Acausal
Hierarchical
Component
Modeling
qd
axis5
l
qdRef
Kd
S
rel
0.03
Jmotor=J
pSum
Kv
sum
w Sum
+1
0.3
+1
joint=0
rate3
b(s)
340.8
a(s)
axis4
iRef
rate2
gear=i
fric=Rv0
qRef
spring=c
axis3
tacho2
b(s)
b(s)
a(s)
a(s)
tacho1
g5
PT1
axis2
qd
C=0.004*D/w m
Rd1=100
Rp1=200
axis1
Vs
Srel = n*transpose(n)+(identity(3)n*transpose(n))*cos(q)Rd2=100
Ri=10
skew(n)*sin(q);
+
+
wrela = n*qd;
+
diff
pow er
OpI
zrela = n*qdd;
Sb = Sa*transpose(Srel);
Rd4=100
r0b = r0a;
vb = Srel*va;
g3
wb = Srel*(wa + wrela);
g1
ab = Srel*aa;
zb = Srel*(za + zrela + cross(wa, wrela));
Rp2=50
rate1
Rd3=100
emf
hall2
hall1
g2
Fritzson
7CourtesyPeter
of Martin
Otter
qd
g4
y
x
inertial
w
pelab
Multi-Domain
Modeling
Variable
declarations
Typed
Declarative
Equation-based
Textual Language
8
Peter Fritzson
Differential equations
pelab
Visual Acausal
Component
Modeling
Hybrid modeling =
continuous-time + discrete-time modeling
Continuous-time
Discrete-time
Typed
Declarative
Equation-based
Textual Language
9
Peter Fritzson
time
Hybrid
Modeling
pelab
10
Peter Fritzson
pelab
simulate(HelloWorld, stopTime = 2)
plot(x)
0.8
0.6
0.4
0.2
0.5
11
Peter Fritzson
1.5
pelab
class DAEexample
Real x(start=0.9);
Real y;
equation
der(y)+(1+0.5*sin(y))*der(x)
= sin(time);
x - y = exp(-0.9*x)*cos(y);
end DAEexample;
simulate(DAEexample, stopTime = 1)
plot(x)
1.15
1.10
1.05
time
1.0
0.2
0.4
0.6
0.8
0.95
0.90
12
Peter Fritzson
pelab
x starts at 1
y starts at 1
simulate(VanDerPol,stopTime = 25)
plotParametric(x,y)
-2
-1
-1
-2
13
Peter Fritzson
pelab
Start OMNotebook
Start->Programs->OpenModelica->OMNotebook
Open File: Exercise01-classes-simple-textual.onb
Open Exercise01-classes-simple-textual.pdf
14
Peter Fritzson
pelab
15
Peter Fritzson
pelab
16
Peter Fritzson
pelab
17
Peter Fritzson
Real
String
Integer
Real
PI=3.141592653589793;
redcolor = "red";
one = 1;
mass = 22.5;
pelab
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; //
Real y(start = 1) "y coordinate;
//
parameter Real lambda = 0.3;
equation
der(x) = y;
// This is the
der(y) = -x + lambda*(1 - x*x)*y; /* This is the
end VanDerPol;
x starts at 1
y starts at 1
18
Peter Fritzson
pelab
thrust
altitude velocity
velocity acceleration
mg
new model
parameters (changeable
before the simulation)
floating point
type
differentiation with
regards to time
19
Peter Fritzson
Rocket
declaration
comment
start value
pelab
g = 6.672e-11;
radius;
name;
mass;
...
CelestialBody moon;
...
20
Peter Fritzson
pelab
10
Moon Landing
Rocket
apollo13
thrust
apollo. gravity
mg
altitude
CelestialBody
only access
inside the class
access by dot
notation outside
the class
21
moon. g moon.mass
apollo.altitude moon.radius 2
Peter Fritzson
class MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
protected
parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
public
Rocket
apollo(name="apollo13");
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;
pelab
100
150
200
25000
-100
20000
-200
15000
10000
-300
5000
-400
50
100
150
200
Peter Fritzson
pelab
11
Peter Fritzson
g = 6.672e-11;
radius;
name;
mass;
pelab
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 in
Lecture 4
function sum
input Real arg1;
input Real arg2;
output Real result;
algorithm
result := arg1+arg2;
end sum;
24
Peter Fritzson
pelab
12
Inheritance
parent class to Color
restricted kind
of class without
equations
child class or
subclass
keyword
denoting
inheritance
record ColorData
parameter Real red = 0.2;
parameter Real blue = 0.6;
Real
green;
end ColorData;
class ExpandedColor
parameter Real red=0.2;
parameter Real blue=0.6;
Real green;
equation
red + blue + green = 1;
end ExpandedColor;
class Color
extends ColorData;
equation
red + blue + green = 1;
end Color;
25
Peter Fritzson
pelab
Inheriting definitions
record ColorData
parameter Real red = 0.2;
parameter Real blue = 0.6;
Real
green;
end ColorData;
Legal!
Identical to the
inherited field blue
class ErrorColor
extends ColorData;
parameter Real blue = 0.6;
parameter Real red = 0.3;
equation
red + blue + green = 1;
end ErrorColor;
26
Peter Fritzson
Illegal!
Same name, but
different value
Inheriting multiple
identical
definitions results
in only one
definition
Inheriting
multiple different
definitions of the
same item is an
error
pelab
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;
Color2 is overdetermined
Same equation twice leaves
gives overdetermined eq syst
27
Peter Fritzson
Color3 is overdetermined
Different equations means
two equations!
pelab
Multiple Inheritance
Multiple Inheritance is fine inheriting both geometry and color
class Color
parameter Real red=0.2;
parameter Real blue=0.6;
Real green;
equation
red + blue + green = 1;
end Color;
class Point
Real x;
Real y,z;
end Point;
multiple inheritance
class ColoredPointWithoutInheritance
Real x;
Real y, z;
parameter Real red = 0.2;
parameter Real blue = 0.6;
Real green;
equation
red + blue + green = 1;
end ColoredPointWithoutInheritance;
28
Peter Fritzson
class ColoredPoint
extends Point;
extends Color;
end ColoredPoint;
Equivalent to
pelab
14
class VerticalLine
extends Point;
Real vlength;
end VerticalLine;
Diamond Inheritance
class HorizontalLine
extends Point;
Real hlength;
end HorizontalLine;
class Rectangle
extends VerticalLine;
extends HorizontalLine;
end Rectangle;
29
Peter Fritzson
pelab
Equivalent to:
inheritance
30
Peter Fritzson
class SameColor
extends Color;
end SameColor;
pelab
15
31
Peter Fritzson
pelab
thrust
mg
altitude
CelestialBody
model CelestialBody
extends Body;
constant Real g = 6.672e-11;
parameter Real radius;
end CelestialBody;
32
Peter Fritzson
pelab
16
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;
33
Peter Fritzson
pelab
class Point
Real x;
Real y,z;
end Point;
class Color
Real red;
Real blue;
Real green;
equation
red + blue + green = 1;
end Color;
Peter Fritzson
Equivalent to
class ColoredPointWithoutInheritance
Real x;
Real y,z;
protected Real red;
protected Real blue;
protected Real green;
equation
red + blue + green = 1;
end ColoredPointWithoutInheritance;
pelab
17
Advanced Topic
Class parameterization
35
Peter Fritzson
pelab
ColoredClass
object
class C
replaceable class ColoredClass = GreenClass;
ColoredClass
obj1(p1=5);
replaceable YellowClass obj2;
ColoredClass
obj3;
RedClass
obj4;
equation
end C;
class C2 =
C(redeclare class ColoredClass = BlueClass);
ColoredClass
object
GreenClass
A yellow
object
36
Peter Fritzson
A red
object
Equivalent to
class C2
BlueClass
YellowClass
BlueClass
RedClass
equation
end C2;
obj1(p1=5);
obj2;
obj3;
obj4;
pelab
18
AC
R2
L1
R3
Class
parameterization
class ElectricalCircuit
Resistor R1(R=100);
Resistor R2(R=200);
Resistor R3(R=300);
Inductor L1;
SineVoltage AC;
Groung G;
equation
connect(R1.n,R2.n);
connect(R1.n,L1.n);
connect(R1.n,R3.n);
connect(R1.p,AC.p);
.....
end ElectricalCircuit;
37
Peter Fritzson
class GenericElectricalCircuit
replaceable Resistor R1(R=100);
replaceable Resistor R2(R=200);
replaceable Resistor R3(R=300);
Inductor L1;
SineVoltage AC;
Groung G;
equation
connect(R1.n,R2.n);
connect(R1.n,L1.n);
connect(R1.n,R3.n);
connect(R1.p,AC.p);
.....
end GenericElectricalCircuit;
pelab
AC
L1
R3
class TemperatureElectricalCircuit =
GenericElectricalCircuit (redeclare TempResistor R1
redeclare TempResistor R3);
38
Peter Fritzson
pelab
19
39
Peter Fritzson
pelab
40
Peter Fritzson
pelab
20
Components, Connectors
and Connections
Peter Fritzson
pelab
Interface
Connector
Component
Connection
Component
Causal coupling
Peter Fritzson
pelab
connector Pin
Voltage
flow Current
end Pin;
v;
i;
pin
i
Pin pin;
an instance pin
of class Pin
mechanical connector
connector class
an instance flange
of class Flange
Peter Fritzson
connector Flange
Position
s;
flow Force
f;
end Flange;
flange
f
Flange flange;
pelab
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
Peter Fritzson
pelab
Physical Connector
Classes Based on Energy Flow
Domain
Type
Potential
Flow
Carrier
Modelica
Library
Electrical
Voltage
Current
Charge
Electrical.
Analog
Position
Force
Linear momentum
Mechanical.
Translational
Rotational
Angle
Torque
Angular
momentum
Mechanical.
Rotational
Magnetic
Magnetic
potential
Magnetic
flux rate
Magnetic flux
Hydraulic
Pressure
Volume flow
Volume
HyLibLight
Heat
Temperature
Heat flow
Heat
HeatFlow1D
Chemical
Chemical
potential
Particle flow
Particles
Under
construction
Pneumatic
Pressure
Mass flow
Air
Translational
Peter Fritzson
PneuLibLight
pelab
connect-equations
Connections between connectors are realized as equations in Modelica
connect(connector1,connector2)
pin1
Pin pin1,pin2;
//A connect equation
//in Modelica:
connect(pin1,pin2);
Peter Fritzson
Corresponds to
pin2
pin1.v = pin2.v;
pin1.i + pin2.i =0;
pelab
Connection Equations
Pin pin1,pin2;
//A connect equation
//in Modelica
connect(pin1,pin2);
Corresponds to
pin1.v = pin2.v;
pin1.i + pin2.i =0;
v1 v2 v3 vn
Each primitive connection set of flow variables is used to generate
sum-to-zero equations of the form:
i1 i2 (ik ) in 0
7
Peter Fritzson
pelab
connector class
fixed causality
Peter Fritzson
connector OutPort
output Real signal;
end OutPort
pelab
Peter Fritzson
p.v
TwoPin
n.v
n.i
p.i
i
pelab
Electrical Components
model Resistor Ideal electrical resistor
extends TwoPin;
parameter Real R;
equation
R*i = v;
end Resistor;
10
Peter Fritzson
p.i
n.i
+
p.v
n.v
v
p.i
n.i
+
p.v
p.i
n.v
n.i
+
p.v
n.v
pelab
Peter Fritzson
n.i
p.v
model Ground
Pin p;
equation
p.v = 0;
end Ground;
11
v(t)
p.i
n.v
p.i
p.v
pelab
Resistor Circuit
i1
R1
i2
p
v1
v3
i3
model ResistorCircuit
Resistor R1(R=100);
Resistor R2(R=200);
Resistor R3(R=300);
equation
connect(R1.p, R2.p);
connect(R1.p, R3.p);
end ResistorCircuit;
12
Peter Fritzson
R2
R3
v2
Corresponds to
R1.p.v = R2.p.v;
R1.p.v = R3.p.v;
R1.p.i + R2.p.i + R3.p.i = 0;
pelab
spring1
srel0
model Oscillator
Mass
mass1(L=1, s(start=-0.5));
Spring spring1(srel0=2, c=10000);
Fixed
fixed1(s0=1.0);
equation
connect(spring1.flange_b, fixed1.flange_b);
connect(mass1.flange_b, spring1.flange_a);
end Oscillator;
mass1
srel
L
-0.5
-1
-1.5
-mg
t
0.1
0.2
0.3
0.4
0.5
-2.5
13
Peter Fritzson
pelab
Extra Exercise
Locate the Oscillator model in DrModelica using
OMNotebook!
Simulate and plot the example. Do a slight change in the
model e.g. different elasticity c, re-simulate and re-plot.
fixed1
spring1
a
mass1
Peter Fritzson
pelab
fixed causality
inPort
multiple input
single output
block
15
Peter Fritzson
outPort
pelab
Connecting Components
from Multiple Domains
Block domain
1
ind
Mechanical domain
R2
emf
ex
Electrical domain
R1
Block
domain
ac
Mechanical
domain
iner
vsen
Electrical
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;
16
Peter Fritzson
pelab
17
Peter Fritzson
L
emf
DC
load
G
pelab
18
Peter Fritzson
pelab
19
Peter Fritzson
pelab
20
Peter Fritzson
pelab
10
21
Peter Fritzson
L
emf
u
J
G
pelab
22
Peter Fritzson
rotFlange_b
rotFlange_b
pelab
11
Hierarchically
Structured Components cont
partialDCMotor1
inertia1
step1
model DCMotorCircuit2
Step
step1;
PartialDCMotor partialDCMotor1;
Inertia
inertia1;
equation
connect(step1.outPort, partialDCMotor1.inPort);
connect(partialDCMotor1.rotFlange_b, inertia1.rotFlange_a);
end DCMotorCircuit2;
23
Peter Fritzson
pelab
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
input
input
24
C1
input
output
C1
Peter Fritzson
input
output
input
C2
output
C2
output
input
M1
input
C3
output
C3
output
input
output
input
C4
output
C4
output
pelab
12
class C
RealInput u;
RealOutput y;
end C;
connector RealOutput
output Real signal;
end RealOutput;
// input connector
// output connector
class CInst
C C1, C2, C3, C4; // Instances of C
equation
connect(C1.outPort, C2.inPort);
connect(C2.outPort, C3.inPort);
connect(C3.outPort, C4.inPort);
end CInst;
input
25
C1
output
Peter Fritzson
input
C2
output
input
C3
output
input
C4
output
pelab
class M
"Structured class M"
RealInput u; // Outside input connector
RealOutput y; // Outside output connector
C C2;
C C3;
end M;
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
26
C1
Peter Fritzson
input
output
input
C2
output
M1
input
C3
output
output
input
C4
output
pelab
13
inlet
connector Stream
Real pressure;
flow Real volumeFlowRate;
end Stream;
Tank
outlet
Parameterization
of interfaces
Peter Fritzson
External interfaces to
component classes are
defined primarily through the
use of connectors.
model Tank
parameter Real Area=1;
replaceable connector TankStream = Stream;
TankStream inlet, outlet; // The connectors
Real level;
equation
// Mass balance
Area*der(level) = inlet.volumeFlowRate +
outlet.volumeFlowRate;
outlet.pressure = inlet.pressure;
end Tank;
connector Stream
// Connector class
Real pressure;
flow Real volumeFlowRate;
end Stream
pelab
inlet
Tank
outlet
connector HeatStream
extends Stream;
Real temp;
end HeatStream;
28
Peter Fritzson
pelab
14
Arrays of Connectors
Part built up with a for-equation (see Lecture 4)
InertialSystem1
Spherical1
The model
uses a forequation to
connect the
different
segments of
the links
29
Peter Fritzson
BoxBody1
Spherical2
BoxBody2
SphericalN
BoxBodyN
model ArrayOfLinks
constant Integer n=10 "Number of segments (>0)";
parameter Real[3,n] r={fill(1,n),zeros(n),zeros(n)};
ModelicaAdditions.MultiBody.Parts.InertialSystem InertialSystem1;
ModelicaAdditions.MultiBody.Parts.BoxBody[n]
boxBody(r = r, Width=fill(0.4,n));
ModelicaAdditions.MultiBody.Joints.Spherical spherical[n];
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;
pelab
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.
30
Peter Fritzson
pelab
15
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.
31
Peter Fritzson
pelab
16
Equations
pelab
Usage of Equations
In Modelica equations are used for many tasks
The main usage of equations is to represent relations in
mathematical models.
Assignment statements in conventional languages are
usually represented as equations in Modelica
Attribute assignments are represented as equations
Connections between objects generate equations
pelab
Equation Categories
Equations in Modelica can informally be classified
into three different categories
Normal equations (e.g., expr1 = expr2) occurring in
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") )which are commonly
used to modify attributes of classes.
pelab
pelab
Declaration Equations
Declaration equations:
constant Integer one = 1;
parameter Real mass = 22.5;
declaration
equations
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;
pelab
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.4);
modifier
equations
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;
pelab
equality equations
connect equations
assert and terminate
reinit model MoonLanding
conditional
if-equation
equality
equation
pelab
Equality Equations
expr1 = expr2:
(out1, out2, out3,...) = function_name(in_expr1, in_expr2, ...);
simple equality
equation
class EqualityEquations
Real x,y,z;
equation
(x, y, z)
= f(1.0, 2.0); //
(x+1, 3.0, z/y) = f(1.0, 2.0); //
//
//
end EqualityEquations;
Correct!
Illegal!
Not a list of variables
on the left-hand side
pelab
Repetitive Equations
The syntactic form of a for-equation is as follows:
for <iteration-variable> in <iteration-set-expression> loop
<equation1>
<equation2>
...
end for;
class FiveEquationsUnrolled
Real[5] x;
equation
x[1] = 2;
x[2] = 3;
x[3] = 4;
x[4] = 5;
x[5] = 6;
end FiveEquationsUnrolled;
pelab
connect-equations
In Modelica connect-equations are used to establish
connections between components via connectors
connect(connector1,connector2)
Repetitive connect-equations
class RegComponent
Component components[n];
equation
for i in 1:n-1 loop
connect(components[i].outlet,components[i+1].inlet);
end for;
end RegComponent;
10
pelab
if <condition> then
<equations>
elseif <condition> then
<equations>
else
<equations>
end if;
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;
11
pelab
event 1
event 2
event 3
time
pelab
13
pelab
Restrictions on when-equations
Form restriction
model WhenNotValid
Real x, y;
equation
x + y = 5;
when sample(0,2) then
2*x + y = 7;
// Error: not valid Modelica
end when;
end WhenNotValid;
14
pelab
15
pelab
16
pelab
model DoubleWhenConflictResolved
Boolean close;
equation
...
when condition1 then
close = true; // First equation has higher priority!
elsewhen condition2 then
close = false; //Second equation
end when;
end DoubleWhenConflictResolved
17
pelab
18
pelab
assert-equations
assert(assert-expression, message-string)
19
pelab
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;
20
pelab
10
Exercise03-classes-textual-circuit.onb
21
pelab
11
pelab
pelab
2 dimensions
Real[3]
Real[3,3]
Integer[n,m,k]
Boolean[2]
Voltage[10]
String[3]
Real[0,3]
positionvector = {1,2,3};
identitymatrix = {{1,0,0}, {0,1,0}, {0,0,1}};
arr3d;
truthvalues = {false,true};
voltagevector;
str3 = {"one", "two", "blue"};
M;
// An empty matrix M
1 dimension
positionvector[3] = {1,2,3};
identitymatrix[3,3] = {{1,0,0}, {0,1,0}, {0,0,1}};
arr3d[n,m,k];
truthvalues[2] = {false,true};
voltagevector[10]
str3[3] = {"one", "two", "blue"};
x[0];
// An empty vector x
pelab
Real[:,:]
Real[:,3]
Real
Y;
Y2;
M[:,size(M,1)]
Real[:]
v1, v2;
Real[:]
v3 = fill(3,14, n);
pelab
same
A7 as
model C
Crec A7[2,3](each b = {1,2,3,4});
end C;
pelab
//
//
//
//
//
startexpr : endexpr
or
pelab
equivalent to
{ exprij for i in A, j in B }
// Multiple iterators
// Nested array constructors
pelab
// Result: {1,2,10,12,13}
// Result: {{1,2,10},{3,4,11}}
The common special cases of concatenation along the first and second dimensions
are supported through the special syntax forms [A;B;C;...] and [A,B,C,...]
respectively, that also can be mixed
Scalar and vector arguments to these special operators are promoted to become
matrices before concatenation this gives MATLAB compatibility
[1,2; 3,4]
[ [1,2; 3,4], [10; 11] ]
cat(2, [1,2; 3,4], [10; 11] )
pelab
Array Indexing
The array indexing operator ...[...] is used to access array elements
for retrieval of their values or for updating these values
arrayname [ indexexpr1, indexexpr2, ...]
Real[2,2] A = {{2,3},{4,5}};
A[2,2]
A[1,2] := ...
// Definition of Array A
// Retrieves the array element value 5
// Assignment to the array element A[1,2]
A[end-1,end]
A[v[end],end]
// Same as:
// Same as:
A[size(A,1)-1,size(A,2)]
A[v[size(v,1)],size(A,2)]
pelab
//
//
//
//
Not allowed!
Result: {0,0,3}
Not allowed, different array sizes!
Result: {{2,3},{5,6}}
//
//
//
//
//
Result: {2,3,4}
Result: {2,3,4}
Result: {0,0,3}
Not allowed, different array sizes!
Result: {{2,3},{5,6}}
10
pelab
Array Multiplication
The linear algebra multiplication operator (*) is interpreted as scalar product or
matrix multiplication depending on the dimensionality of its array arguments.
{1,2,3} * 2
3 * {1,2,3}
{1,2,3} * {1,2,2}
{{1,2},{3,4}} * {1,2}
{1,2,3} * {{1},{2},{10}}
{1,2,3} * [1;2;10]
// Matrix mult:
// Matrix mult:
// Matrix mult:
{5,11}
{35}
{35}
Element-wise multiplication between scalars and/or arrays can be done with the (*)
and (.*) operators. The (.*) operator is equivalent to (*) when both operands are
scalars.
{1,2,3} .* 2
2 .* {1,2,3}
{2,4,6} .* {1,2,2}
{1,2,3} .* {1,2}
11
//
//
//
//
Result: {2,4,6}
Result: {2,4,6}
Result: {2,8,12}
Not allowed, different array sizes!
pelab
size(A,i)
size(A)
Real[4,1,6] x;
// declared array x
ndims(x);
// returns
size(x,1);
// returns
size(x);
// returns
size(2*x+x) = size(x); //
12
3 no of dimensions
4 size of 1st dimension
the vector {4, 1, 6}
this equation holds
pelab
max(A)
sum(A)
product(A)
min({1,-1,7})
max([1,2,3; 4,5,6])
sum({{1,2,3},{4,5,6}})
product({3.14, 2, 2})
//
//
//
//
Gives
Gives
Gives
Gives
the
the
the
the
value
value
value
value
-1
6
21
12.56
13
pelab
14
pelab
15
pelab
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>
16
equation
x = y*2;
z = w;
algorithm
x1 := z+x;
x2 := y-5;
x1 := x2+y;
equation
u = x1+x2;
...
pelab
class SumZ
parameter Integer n = 5;
Real[n] z(start = {10,20,30,40,50});
Real sum;
algorithm
sum := 0;
for i in 1:n loop
// 1:5 is {1,2,3,4,5}
sum := sum + z[i];
end for;
end SumZ;
A simple for-loop
summing the five
elements of the vector z,
within the class SumZ
17
pelab
class SumSeries
parameter Real eps = 1.E-6;
Integer i;
Real sum;
Real delta;
algorithm
i := 1;
delta := exp(-0.01*i);
while delta>=eps loop
sum := sum + delta;
i := i+1;
delta := exp(-0.01*i);
end while;
end SumSeries;
18
pelab
if-statements
if <condition> then
<statements>
elseif <condition> then
<statements>
else
<statementss>
end if
The if-statements
used in the class
SumVector perform
a combined
summation and
computation on a
vector v.
19
class SumVector
Real sum;
parameter Real v[5] = {100,200,-300,400,500};
parameter Integer n = size(v,1);
algorithm
sum := 0;
for i in 1:n loop
if v[i]>0 then
sum := sum + v[i];
elseif v[i] > -1 then
sum := sum + v[i] -1;
else
sum := sum - v[i];
end if;
end for;
end SumVector;
pelab
when-statements
when <conditions> then
<statements>
elsewhen <conditions> then
<statements>
end when;
20
pelab
10
Functions
21
pelab
Function Declaration
The structure of a typical function declaration is as follows:
function <functionname>
input TypeI1 in1;
input TypeI2 in2;
input TypeI3 in3;
...
output TypeO1 out1;
output TypeO2 out2;
...
protected
<local variables>
...
algorithm
...
<statements>
...
end <functionname>;
22
pelab
11
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;
protected
Real
xpower;
// local variable xpower
algorithm
sum := 0;
xpower := 1;
for i in 1:size(A,1) loop
sum := sum + A[i]*xpower;
xpower := xpower*x;
end for;
end PolynomialEvaluator;
23
The function
PolynomialEvaluator
computes the value of a
polynomial given two
arguments:
a coefficient vector A and
a value of x.
pelab
24
pelab
12
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
// Statement form
25
pelab
External Functions
It is possible to call functions defined outside the Modelica
language, implemented in C or FORTRAN 77
function polynomialMultiply
input Real a[:], b[:];
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external
end polynomialMultiply;
The body of an
external function is
marked with the
keyword
external
26
pelab
13
Exercise04-equations-algorithms-functions.onb
27
pelab
14
Packages
pelab
pelab
encapsulated
makes
package
dependencies
(i.e., imports)
explicit
Declarations of
substract,
divide,
realPart,
imaginaryPart,
etc are not shown
here
x,y;
z;
y.re;
y.im
Usage of the
ComplexNumber
package
class ComplexUser
ComplexNumbers.Complex a(re=1.0, im=2.0);
ComplexNumbers.Complex b(re=1.0, im=2.0);
ComplexNumbers.Complex z,w;
equation
z = ComplexNumbers.multiply(a,b);
w = ComplexNumbers.add(a,b);
end ComplexUser
function multiply
input Complex x,y;
output Complex z;
algorithm
z.re := x.re*y.re x.im*y.im;
z.im := x.re*y.im + x.im*y.re;
end multiply;
.
end ComplexMumbers
pelab
pelab
import
import
import
import
<packagename>
<packagename> . <definitionname>
<packagename> . *
<shortpackagename> = <packagename>
import
import
import
import
Modelica.Math.ComplexNumbers;
Modelica.Math.ComplexNumbers.add;
Modelica.Math.ComplexNumbers.*
Co = Modelica.Math.ComplexNumbers
//Access
//Access
//Access
//Access
as
as
as
as
ComplexNumbers.add
add
add
Co.add
pelab
Qualified Import
Qualified import
import <packagename>
pelab
pelab
Unqualified Import
Unqualified import
import <packagename> . *
pelab
Renaming Import
Renaming import
pelab
10
pelab
11
pelab
12
pelab
within Modelica.Mechanics;
encapsulated package Rotational // Modelica.Mechanics.Rotational
encapsulated package Interfaces
import ...;
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,
13
pelab
C:\library
\Modelica
package.mo
\Blocks
package.mo
Continuous.mo
Interfaces.mo
\Examples
package.mo
Example1.mo
\Mechanics
package.mo
Rotational.mo
...
Modelica
Mechanics
Blocks
Rotational
Continuous Interfaces
...
Examples
Example1
14
pelab
\Modelica
package.mo
\Blocks
package.mo
Continuous.mo
Interfaces.mo
\Examples
package.mo
Example1.mo
\Mechanics
package.mo
Rotational.mo
...
15
end Examples;
within Modelica.Blocks.Examples;
model Example1
"Usage example 1 for Modelica.Blocks";
...
end Example1;
within Modelica.Mechanics;
encapsulated package Rotational
encapsulated package Interfaces
import ...;
connector Flange_a;
...
end Flange_a;
...
end Interfaces;
model Inertia
...
end Inertia;
...
end Rotational;
The subpackage
Rotational stored as the
file Rotational.mo. Note
that Rotational contains
the subpackage
Interfaces, which also
is stored in the same file
since we chose not to
represent Rotational as
a directory
pelab
Modelica Libraries
pelab
pelab
Blocks
Constants
Electrical
Icons
Fluid
Math
Magnetic
Mechanics
Media
SIunits
Stategraph
Thermal
Utilities
pelab
Modelica.Blocks
Continuous, discrete, and logical input/output blocks
to build block diagrams.
Library
Continuous
Examples:
pelab
Modelica.Constants
A package with often needed constants from mathematics,
machine dependent constants, and constants of nature.
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";
constant Real G(final unit="m3/(kg.s2)") = 6.673e-11 "Newtonian constant
of gravitation";
constant Real h(final unit="J.s") = 6.62606876e-34 "Planck constant";
constant Modelica.SIunits.CelsiusTemperature T_zero=-273.15 "Absolute
zero temperature;
pelab
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
R1
V1
C1
Gnd1
Gnd6 C4
Transistor1
Transistor2
I1
Gnd2
C5
Gnd7
C3
Gnd8
R3
Gnd4
Gnd5
pelab
Modelica.Icons
Package with icons that can be reused in other libraries
Examples:
Info
Info
RotationalSensor
Library
Example
Library
Library2
Library1
Example
GearIcon
TranslationalSensor
MotorIcon
pelab
Modelica.Math
Package containing basic mathematical functions:
sin(u)
sine
cos(u)
cosine
tan(u)
tangent
asin(u)
acos(u)
atan(u)
inverse tangent
atan2(u1, u2)
sinh(u)
hyperbolic sine
cosh(u)
hyperbolic cosine
tanh(u)
hyperbolic tangent
exp(u)
exponential, base e
log(u)
log10(u)
base 10 logarithm (u 0)
pelab
Modelica.Mechanics
Package containing components for mechanical systems
Subpackages:
Rotational
Translational
MultiBody
pelab
Modelica.SIunits
This package contains predefined types based on the
international standard of units:
ISO 31-1992 General principles concerning quantities, units and symbols
ISO 1000-1992 SI units and recommendations for the use of their
multiples and of certain other units.
10
pelab
Modelica.Stategraph
Hierarchical state machines (similar to Statecharts)
11
pelab
Modelica.Thermal
Subpackage FluidHeatFlow with components for heat flow
modeling.
Sub package HeatTransfer with components to model 1dimensional heat transfer with lumped elements
Example:
12
pelab
libraries from DLR. This has been largely replaced by the new
release of the Modelica 3.1 libraries.
Sublibraries:
Blocks
Input/output block sublibrary
HeatFlow1D 1-dimensional heat flow (replaced by Modelica.Thermal)
Multibody
PetriNets
Tables
13
pelab
ModelicaAdditions.Multibody (OLD)
This is a Modelica library to model 3D Mechanical systems
including visualization
New version has been released (march 2004) that is called
Modelica.Mechanics.MultiBody in the standard library
Improvements:
Easier to use
Automatic handling of kinematic loops.
Built-in animation properties for all components
14
pelab
15
New library
(no cutjoint needed)
pelab
16
pelab
ModelicaAdditions.PetriNets (OLD)
This package contains components to model Petri nets
Used for modeling of computer hardware, software, assembly
lines, etc
Transition
Place
17
pelab
18
pelab
PNLib Cont
19
pelab
20
WasteWater
ATPlus
MotorCycleDymanics
NeuralNetwork
VehicleDynamics
SPICElib
SystemDynamics
BondLib
MultiBondLib
ModelicaDEVS
ExtendedPetriNets
External.Media Library
VirtualLabBuilder
SPOT
...
pelab
10
21
pelab
22
pelab
11
23
pelab
24
Powertrain
SmartElectricDrives
VehicleDynamics
AirConditioning
HyLib
PneuLib
CombiPlant
HydroPlant
pelab
12
Cylinders
Valves
pelab
HyLib - Example
Hydraulic drive system with closed circuit
26
pelab
13
Directional valves
Cylinders
Motors
Valves and nozzles
Lumped volumes
Cylinders
pelab
PneuLib - Example
Pneumatic circuit with multi-position cylinder, booster and
different valves
28
pelab
14
29
pelab
30
pelab
15
pelab
Simple PID
Controls alpha and height
32
pelab
16
33
pelab
Compressed air
Combustion
chamber
Exhaust gas
Power output
Air
Compressor
Turbine
Exhaust
34
pelab
17
35
pelab
36
Switch pilot
to main fuel
pelab
18
37
pelab
19
Peter Fritzson
pelab
Events
Events are ordered in time and form an event history
event 1
event 2
event 3
time
Peter Fritzson
pelab
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
pelab
Event creation if
if-equations, if-statements, and if-expressions
if <condition> then
<equations>
elseif <condition> then
<equations>
else
<equations>
end if;
Peter Fritzson
False if s<0
If-equation choosing
equation for v
If-expression
pelab
event 1
event 2
time
event 3
Time event
State event
Peter Fritzson
pelab
sample(t0,d)
true
false
time
t0
t0+d
t0+2d
t0+3d
t0+4d
Variables need to be
discrete
model SamplingClock
Integer i;
discrete Real r;
equation
when sample(2,0.5) then
i = pre(i)+1;
r = pre(r)+0.3;
end when;
end SamplingClock;
Peter Fritzson
Creates an event
after 2 s, then
each 0.5 s
pelab
Initial conditions
Reinit assigns
continuous-time variable
velocity a new value
7
Peter Fritzson
pelab
true
time
false
event at start
true
false
time
event at end
Peter Fritzson
pelab
Terminating a Simulation
There terminate() function is useful when a wanted result is
achieved and it is no longer useful to continue the simulation. The
example below illustrates the use:
model terminationModel
Real y;
equation
y = time;
terminate
when y >5 then
terminate("The time has elapsed 5s");
end when;
end terminationMode;
Peter Fritzson
pelab
10
Peter Fritzson
equation
when x > y.start then
...
pelab
Event Priority
Erroneous multiple definitions, single assignment rule violated
model WhenConflictX
discrete Real x;
equation
when time>=2 then
x = pre(x)+1.5;
end when;
when time>=1 then
x = pre(x)+1;
end when;
end WhenConflictX;
// When B: Increase x by 1 at
11
Peter Fritzson
model WhenPriorityX
discrete Real x;
equation
when time>=2 then
x = pre(x)+1.5;
elsewhen time>=1 then
x = pre(x)+1;
end when;
end WhenPriorityX;
time=2
time=1
// Higher priority
// Lower priority
pelab
event
time
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
12
Peter Fritzson
pelab
false
edge(b)
true
false
time
event
event
4.1
3.2
change(v)
true
true
false
time
event
13
Peter Fritzson
event
pelab
4.1
3.2
delay(v,d)
4.5
4.1
3.2
time
start+d
t1
t1+d
t2
t2+d
14
Peter Fritzson
pelab
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})
5
4
3
2
1
2
15
Peter Fritzson
10
pelab
16
Peter Fritzson
pelab
tau
resistor
Motor side
inductor
Load side
inertia1
signalVoltage
phi_dev
- b/2
inertia2
emf
elastoBacklash
step
b/2
ground
Backward
Slack
tau < 0
tau = 0
phi_dev >= -b/2
17
Peter Fritzson
Forward
tau > 0
phi_dev > b/2
pelab
18
Peter Fritzson
pelab
0.75
0.5
0.25
5
10
15
20
25
-0.25
-0.5
t
5
10
15
inertia1.w
-0.2
-0.4
-0.6
inertia2.w
-0.8
25
-1
-1.2
19
20
Peter Fritzson
pelab
source
qOut
tank
tSensor
cIn
tActuator
piContinuous
levelSensor
maxLevel
out
level
tank
20
cOut
Peter Fritzson
in
pump
model TankPI
LiquidSource
source(flowLevel=0.02);
Tank
tank(area=1);
PIcontinuousController piContinuous(ref=0.25);
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, piContinuous.cOut);
connect(tank.tSensor, piContinuous.cIn);
end TankPI;
model Tank
ReadSignal tOut; // Connector, reading tank level
ActSignal tInp; // Connector, actuator controlling input flow
parameter Real flowVout = 0.01;
// [m3/s]
parameter Real area = 0.5;
// [m2]
parameter Real flowGain = 10;
// [m2/s]
Real h(start=0);
// tank level [m]
Real qIn;
// flow through input valve[m3/s]
Real qOut;
// flow through output valve[m3/s]
equation
der(h)=(qIn-qOut)/area;
// mass balance equation
qOut=if time>100 then flowVout else 0;
qIn = flowGain*tInp.act;
tOut.val = h;
end Tank;
pelab
10
model PIDcontinuousController
extends BaseController(K = 2, T = 10);
Real x;
Real y;
equation
der(x) = error/T;
y
= T*der(error);
outCtr = K*(error + x + y);
end PIDcontinuousController;
21
Peter Fritzson
model PIdiscreteController
extends BaseController(K = 2, T = 10);
discrete Real x;
equation
when sample(0, Ts) then
x = pre(x) + error * Ts / T;
outCtr = K * (x+error);
end when;
end PIdiscreteController;
pelab
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
for i in 1:n loop
connect(phil[i].mutexPort, mutex.port[i]);
connect(phil[i].right, fork[i].left);
connect(fork[i].right, phil[mod(i, n) + 1].left);
end for;
end DiningTable;
22
Peter Fritzson
Eating
Thinking
Eating
Thinking
Eating
Thinking
Eating
Thinking
Eating
Thinking
pelab
11
23
Clock Constructors
Base-clock conversion operators
Sub-clock conversion operators
Previous and Interval operators
Peter Fritzson
pelab
24
Peter Fritzson
pelab
12
Clocks
Clock(): Returns a clock that is inferred
Clock(i,r): Returns a variable interval clock where the next
interval at the current clock tick is defined by the rational
number i/r. If i is parameteric the clock is periodic.
Clock(ri) : Returns a variable interval clock where the next
interval at the current clock tick is defined by the Real number
ri. If ri is parametric, the clock is periodic.
Clock(cond, ri0): Returns a Boolean clock that ticks
whenever the condition cond changes from false to true. The
optional ri0 argument is the value returned by operator
interval() at the first tick of the clock.
Clock(c, m): Returns clock c and associates the solver
method m to the returned clock .
25
Peter Fritzson
pelab
26
Peter Fritzson
pelab
13
Clocks : an example
model MassWithSpringDamper
parameter Modelica.SIunits.Mass m=1;
parameter Modelica.SIunits.TranslationalSpringConstant k=1;
parameter Modelica.SIunits.TranslationalDampingConstant
d=0.1;
Modelica.SIunits.Position x(start=1,fixed=true) "Position";
Modelica.SIunits.Velocity v(start=0,fixed=true) "Velocity";
Modelica.SIunits.Force f "Force";
equation
der(x) = v; model SpeedControl
extends
MassWithSpringDamper;
m*der(v) = f - k*x
- d*v;
parameter Real K = 20 "Gain of speed P controller";
end MassWithSpringDamper;
parameter Modelica.SIunits.Velocity vref = 100 "Speed ref.";
discrete Real vd;
discrete Real u(start=0);
equation
// speed sensor
vd = sample(v, Clock(0.01)); // P controller for speed
u = K*(vref-vd);
// force actuator
f = hold(u);
end SpeedControl;
27
Peter Fritzson
pelab
14
Biological Models
Population Dynamics
Predator-Prey
Peter Fritzson
pelab
Peter Fritzson
pelab
growthrate g P
deathrate d P
P growthrate deathrate
Exponentially increasing
population if (g-d)>0
Exponentially decreasing
population if (g-d)<0
P ( g d ) P
3
Peter Fritzson
pelab
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;
Peter Fritzson
pelab
Simulation of PopulationGrowth
simulate(PopulationGrowth, stopTime=100)
plot(P)
Exponentially increasing
population if (g-d)>0
500
400
300
200
100
20
Peter Fritzson
40
60
80
t
100
pelab
Exponentially decreasing
population if (g-d)<0
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;
Peter Fritzson
pelab
Predator-Prey models
Peter Fritzson
pelab
R g r R d rf F R
F g fr d rf R F d f F
Peter Fritzson
pelab
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_fr*d_rf*rabbits*foxes - d_f*foxes;
end LotkaVolterra;
Peter Fritzson
pelab
4000
3000
2000
1000
t
200
10
Peter Fritzson
400
600
800
1000
pelab
Exercise of 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_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_fr*d_rf*rabbits*foxes - d_f*foxes;
end LotkaVolterra;
11
Peter Fritzson
pelab
Model Design
Peter Fritzson
pelab
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
Peter Fritzson
pelab
Modeling Approach 1
Peter Fritzson
pelab
x (t ) f ( x (t ), u (t ))
y (t ) g ( x (t ), u (t ))
4
Peter Fritzson
pelab
Peter Fritzson
pelab
Modeling Approach 2
Peter Fritzson
pelab
Block-oriented:
Signal-flow model hard to
understand for physical systems
sum3
Res2
p
R2
R1=10
Ind
-1
1/L
l2
1
s
R2=100
sum2
+1
+1
AC=220
p
sinln
-1
C=0.01
Res1
sum1
+1
Cap
1/R1
1/C
l1
1
s
L=0.1
n
Peter Fritzson
pelab
Integrator
Adder
Multiplier
f(x,y)
Function
Branch Point
Peter Fritzson
pelab
Block-oriented:
Signal-flow model hard to
understand for physical systems
sum3
Res2
R1=10
l2
Ind
-1
R2
1
s
1/L
R2=100
sum2
+1
+1
AC=220
p
sinln
Res1
sum1
+1
C=0.01
l1
Cap
1/R1
-1
1
s
1/C
L=0.1
n
Peter Fritzson
pelab
+
-
k1 / k 2
1/ L
Control
+
-
k3
Peter Fritzson
J 1 J 2 k 22
k2
1 / TI
1/
+
k2
10
k1
Rotational
Mechanics
load
1/ J 3
pelab
Peter Fritzson
pelab
12
Peter Fritzson
pelab
Object-Oriented Component-Based
Approaches in General
Define the system briefly
What kind of system is it?
What does it do?
13
Peter Fritzson
pelab
14
Peter Fritzson
pelab
15
Peter Fritzson
pelab
Controller
Electrical
Circuit
Rotational
Mechanics
16
Peter Fritzson
pelab
Controller
Rotational
Mechanics
feedback1
PI
step1
PI1
17
Peter Fritzson
pelab
Electrical
Circuit
resistor1
Rotational
Mechanics
inductor1
signalVoltage1
EMF1
ground1
18
Peter Fritzson
pelab
inertia1
idealGear1
inertia2
Electrical
Circuit
spring1
Rotational
Mechanics
inertia3
speedSensor1
19
Peter Fritzson
pelab
20
Peter Fritzson
pelab
10
source
levelSensor
maxLevel
level h
controller
out
tank
in
valve
21
Peter Fritzson
pelab
Object-Oriented Modeling
22
Peter Fritzson
pelab
11
No component
structure
Straightforward but
less flexible,
no graphical
structure
23
Peter Fritzson
model FlatTank
// Tank related variables and parameters
parameter Real flowLevel(unit="m3/s")=0.02;
parameter Real area(unit="m2")
=1;
parameter Real flowGain(unit="m2/s") =0.05;
Real
h(start=0,unit="m")
"Tank level";
Real
qInflow(unit="m3/s") "Flow through input valve";
Real
qOutflow(unit="m3/s") "Flow through output valve";
// Controller related variables and parameters
parameter Real K=2
"Gain";
parameter Real T(unit="s")= 10
"Time constant";
parameter Real minV=0, maxV=10;
// Limits for flow output
Real
ref = 0.25 "Reference level for control";
Real
error
"Deviation from reference level";
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;
pelab
0.4
0.3
0.2
0.1
time
50
24
Peter Fritzson
100
150
200
250
pelab
12
Object-Oriented Modeling
Approach 5:
Object-oriented approach with design of
library model components
25
Peter Fritzson
pelab
TankPI
qIn
source
qOut
tank
tSensor
cIn
tActuator
piContinuous
cOut
model TankPI
LiquidSource
source(flowLevel=0.02);
PIcontinuousController piContinuous(ref=0.25);
Tank
tank(area=1);
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, piContinuous.cOut);
connect(tank.tSensor, piContinuous.cIn);
end TankPI;
26
Peter Fritzson
pelab
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, sensor reading tank level (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;
27
Peter Fritzson
pelab
TankPI
source
qIn
qOut
tank
tSensor
cIn
tActuator
piContinuous
cOut
Peter Fritzson
pelab
14
dx error
dt
T
outCtr K * ( error x )
Integrating equations gives
Proportional & Integrative (PI)
outCtr K * ( error
error
dt )
T
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;
29
Peter Fritzson
pelab
tank
tSensor
30
Peter Fritzson
cIn
tActuator
piContinuous
cOut
pelab
15
0.4
0.3
0.2
0.1
time
50
31
Peter Fritzson
100
150
200
250
pelab
32
Peter Fritzson
pelab
16
TankPID
source
qOut
qIn
tank
tSensor
cIn
tActuator
pidContinuous
cOut
model TankPID
LiquidSource
source(flowLevel=0.02);
PIDcontinuousController pidContinuous(ref=0.25);
Tank
tank(area=1);
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, pidContinuous.cOut);
connect(tank.tSensor, pidContinuous.cIn);
end TankPID;
33
Peter Fritzson
pelab
dx error
dt
T
d error
y T
dt
outCtr K * (error x y )
T dt T
base class for controllers to be defined
outCtr K * ( error
error
d error
)
dt
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;
34
Peter Fritzson
pelab
17
0.4
0.3
0.2
0.1
time
50
35
Peter Fritzson
100
150
200
250
pelab
qIn
qOut
qIn
tank1
tSensor
cIn
tActuator
piContinuous
qOut
tank2
cOut
tSensor
cIn
tActuator
piContinuous
cOut
model TanksConnectedPI
LiquidSource source(flowLevel=0.02);
Tank
tank1(area=1), tank2(area=1.3);;
PIcontinuousController piContinuous1(ref=0.25), 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;
36
Peter Fritzson
pelab
18
tank1.h
0.8
tank2.h
0.6
0.4
0.2
time
100
37
Peter Fritzson
200
300
400
pelab
model PIDcontinuousController
extends BaseController(K = 2, T = 10);
Real x;
Real y;
equation
der(x) = error/T;
y
= T*der(error);
outCtr = K*(error + x + y);
end PIDcontinuousController;
38
Peter Fritzson
model PIdiscreteController
extends BaseController(K = 2, T = 10);
discrete Real x;
equation
when sample(0, Ts) then
x = pre(x) + error * Ts / T;
outCtr = K * (x+error);
end when;
end PIdiscreteController;
pelab
19
Exercises
Replace the PIcontinuous controller by the
PIdiscrete controller and simulate. (see also the
book, page 461)
Create a tank system of 3 connected tanks and
simulate.
39
Peter Fritzson
pelab
Peter Fritzson
pelab
20
Simplification of Models
When need to simplify models?
Simplification approaches
Neglect small effects that are not important for the phenomena to be
modeled
Aggregate state variables into fewer variables
Approximate subsystems with very slow dynamics with constants
Approximate subsystems with very fast dynamics with static
relationships, i.e. not involving time derivatives of those rapidly changing
state variables
41
Peter Fritzson
pelab
21
Library Design
Influenza Model
Peter Fritzson
pelab
Peter Fritzson
pelab
Peter Fritzson
pelab
Peter Fritzson
pelab
Peter Fritzson
pelab
Governing Equations
_
Peter Fritzson
pelab
Peter Fritzson
pelab
Peter Fritzson
pelab
Non Infected
Sick
Less
Components
9
Peter Fritzson
Infected
pelab
Non Infected
Sick
Infected
10
Peter Fritzson
pelab
Simulation
Immune
Non Infected
Sick
Infected
11
Peter Fritzson
pelab
Coclusions
The influenza epidemic spreads rapidly
Within 4 weeks, the percentage of sick people
reaches its maximum of roughly 25%
A steady state is reached about 20 weeks
The disease does not die out naturally.
A certain percentage loses immunity sufficiently
fast to get infected before the virus stem has
disappeared.
12
Peter Fritzson
pelab
Goal
Design the influenza library by implement the
different design patterns discussed :
Block Oriented
Object Oriented
Object Oriented #2
13
Peter Fritzson
pelab
The complete exercises can be found under the Modelica course in the OpenModelica.org home page.
Install OpenModelica. Start the OpenModelica Connection Editor OMEdit. Do the RLCircuit graphical exercise.
See instructions in slides.
2.1 HelloWorld
Simulate and plot the following example with one differential equation and one initial condition. Do a slight
change in the model, re-simulate and re-plot.
model HelloWorld "A simple equation"
Real x(start=1);
equation
der(x)= -x;
end HelloWorld;
2.3 DAEExample
Locate the DAEExample in DrModelica (Section 2.1: Differential Algebraic Equation System). Simulate and plot.
2.4 A Simple Equation System
Develop a Modelica model that solves the following equation system with initial conditions:
You can simulate and plot the model directly from the graphical editor. Simulate for 15s and plot the variables for
the outgoing rotational speed on the inertia axis and the voltage on the voltage source (denoted u in the figure) in
the same plot.
Option: You can also save the model, load it and simulate it using OMShell or OMNotebook. You can also go to
the graphical editor text view and copy/paste the model into a cell in OMNotebook.
Hint: if you use the plot command in OMNotebook and you have difficulty finding the names of the variables to
plot, you can flatten the model by calling instantiateModel, which exposes all variable names.