Modelica Tutorial PDF
Modelica Tutorial PDF
Introduction to Object-Oriented
Modeling and Simulation with Modelica
Using OpenModelica
Peter Fritzson
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 object-
oriented 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.
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
OpenModelica
www.openmodelica.org
Modelica Association
www.modelica.org
1
New Introductory
Modelica Book
September 2011
232 pages
Wiley
IEEE Press
For Introductory
Short Courses on
Object Oriented
Mathematical
Modeling
3 Peter Fritzson Copyright Open Source Modelica Consortium pelab
Outline Day 1
Part I Part II
Introduction to Modelica and a Modelica environments
demo example
2
Acknowledgements, Usage, Copyrights
If you want to use the Powerpoint version of these slides
in your own course, send an email to:
[email protected]
Thanks to Emma Larsdotter Nilsson, Peter Bunus, David
Broman, Jan Brugrd, Mohsen-Torabzadeh-Tari, Adeel
Asghar for contributions to these slides.
Most examples and figures in this tutorial are adapted
with permission from Peter Fritzsons book Principles
of Object Oriented Modeling and Simulation with
Modelica 2.1, copyright Wiley-IEEE Press
Some examples and figures reproduced with permission
from Modelica Association, Martin Otter, Hilding
Elmqvist, and MathCore
Modelica Association: www.modelica.org
OpenModelica: www.openmodelica.org
3
Software Installation Linux (requires internet connection)
Go to
https://openmodelica.org/index.php/download/do
wnload-linux and follow the instructions.
Go to
https://openmodelica.org/index.php/download/do
wnload-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
4
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 Copyright Open Source Modelica Consortium pelab
5
What is a system?
Collector
Storage tank
Hot water
Heater
Electricity
6
Experiments
Model concept
7
Simulation
8
Dangers of Simulation
System knowledge
The collected general experience in relevant domains
The system itself
9
Kinds of Mathematical Models
Input current
pulse
Capacitor voltage - dynamic
time
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
Superb
Tasty
Good
Mediocre
time
11
Using Modeling and Simulation
within the Product Design-V
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
Realization
Component 3
Physical behavior of a component is
described by equations
Hierarchical decomposition of components
12
Application Example Industry Robot
k2
i
axis6
qddRef cut joint
qdRef
1
qRef
1
k1 r3Control
r3Motor r3Drive1 tn
i 1
S S
qd axis5
qdRef Kd
S
0.03 rel
Jmotor=J joint=0
spring=c axis4
S
qRef pSum Kv sum w Sum rate2 rate3 iRef gear=i
fric=Rv0
+1 b(s) 340.8
0.3
- +1 - a(s) S
axis3
q
qd
Rp2=50
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
13
Corresponding DCMotor Model Equations
The following equations are automatically derived from the 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
28 Peter Fritzson Copyright Open Source Modelica Consortium pelab
14
GTX Gas Turbine Power Cutoff Mechanism
Developed
Hello
by MathCore
for Siemens
Courtesy of Siemens Industrial Turbomachinery AB
15
Modelica in Avionics
Modelica in Biomechanics
16
Application of Modelica in Robotics Models
Real-time Training Simulator for Flight, Driving
Using Modelica models
generating real-time
code
Different simulation
environments (e.g.
Flight, Car Driving,
Helicopter)
Developed at DLR
Munich, Germany
Dymola Modelica tool
Low-temperature parts
(condenser, feedwater
system, LP circuits) are
represented by trivial
boundary conditions.
17
Combined-Cycle Power Plant
Steam turbine unit
Detailed model in order
to represent all the start-
up phases
Bypass paths for both
the HP and IP turbines
allow to start up the
boilers with idle turbines,
dumping the steam to
the condenser
HP and IP steam
turbines are modelled,
including inertia,
electrical generator, and
connection to the grid
Courtesy Francesco Casella, Politecnico di
Milano Italy
and Francesco Pretolani, CESI SpA - Italy
18
Modelica
The Next Generation
Modeling Language
Stored Knowledge
19
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
Automotive
Aircrafts
Satellites
Power plants
Systems biology
20
What is Modelica?
What is Modelica?
A language for modeling of complex cyber physical systems
i.e., Modelica is not a tool
Free, open language
There exist several free and commercial
specification:
tools, for example:
OpenModelica from OSMC
Dymola from Dassault systems
Wolfram System Modeler from Wolfram
SimulationX from ITI
MapleSim from MapleSoft
AMESIM from LMS
Jmodelica.org from Modelon
Available at: www.modelica.org MWORKS from Tongyang Sw & Control
Developed and standardized IDA Simulation Env, from Equa
by Modelica Association CyDesign Modeling tool, CyDesign Labs
21
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 Open-Source and Commercial implementations
22
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
46 Peter Fritzson Copyright Open Source Modelica Consortium pelab
23
Modelica Faster Development, Lower
Maintenance than with Traditional Tools
Causality
Systems
Derivation
Definition Modeling of
Subsystems (manual derivation of
System
Decomposition input/output relations) Implementation Simulation
Proprietary
Code
Block Diagram
Modelica
R1=10 R2=100
sum2
p
n n +1
+1
AC=220
n n
p
G
24
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
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
25
Exercises Part I
Hands-on graphical modeling
(20 minutes)
26
Exercises Part I Basic Graphical Modeling
(See instructions on next two pages)
Start the OMEdit editor (part of OpenModelica)
Draw the RLCircuit
Simulate
R1 L
R=10
R=100 L=1
L=0.1
A
C
27
Exercises Part I OMEdit Instructions (Part II)
For the RLCircuit model, browse the Modelica standard library and add
the following component models:
Add Ground, Inductor and Resistor component models from
Modelica.Electrical.Analog.Basic package.
Add SineVolagte component model from Modelica.Electrical.Analog.Sources
package.
Make the corresponding connections between the component models
as shown in previous slide on the RLCiruit.
Simulate the model
Go to Simulation menu and choose simulate or click on the siumulate button in the
toolbar.
Plot the instance variables
Once the simulation is completed, a plot variables list will appear on the right side.
Select the variable that you want to plot.
28
Modelica Environments and OpenModelica
Dymola
1
Simulation X
ITI
Germany
Mechatronic systems
www.simulationx.com
MapleSim
Maplesoft
Canada
Recent Modelica tool on the
market
Integrated with Maple
www.maplesoft.com
2
Wolfram System Modeler MathCore / Wolfram Research
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
3
OpenModelica (Part I)
OpenModelica
Open Source Modelica
Consortium (OSMC)
Sweden and other countries
Open source
www.openmodelica.org
4
OSMC Open Source Modelica Consortium
45 organizational members October 2012
Founded Dec 4, 2007
Open-source community services
Website and Support Forum
Version-controlled source base
Bug database
Development courses
www.openmodelica.org
Code Statistics
5
OMNotebook Electronic Notebook with DrModelica
Primarily for teaching
Interactive electronic book
Platform independent
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)
6
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;
Modelica.Electrical.Analog.Basic.EMF emf1;
Modelica.Mechanics.Rotational.Inertia load;
Modelica.Electrical.Analog.Basic.Ground g;
Modelica.Electrical.Analog.Sources.ConstantVoltage v;
equation
connect(v.p,r1.p);
connect(v.n,g.p);
connect(r1.n,i1.p);
connect(i1.n,emf1.p);
connect(emf1.n,g.p);
connect(emf1.flange_b,load.flange_a);
end dcmotor;
7
Run Scripts in OpenModelica
Examples of Simulation
Visualization
Simulation Control
Plot View
Requirements
Evaluation View
in ModelicaML
MaxLevel
Liquid
Source
Level h
Level h Domain-Specific
Visualization View
Tank 1 Tank 2
8
OpenModelica MDT Eclipse Plugin
Browsing of packages, classes, functions
Automatic building of executables;
separate compilation
Syntax highlighting
Code completion,
Code query support for developers
Automatic Indentation
Debugger
(Prel. version for algorithmic subset)
Code Assistance on
function calling.
9
OpenModelica MDT: Code Outline and Hovering Info
Identifier Info on
Hovering
Code Outline for
easy navigation within
Modelica files
19 Peter Fritzson Copyright Open Source Modelica Consortium
19
10
The OpenModelica MDT Debugger (Eclipse-based)
Using Japanese Characters
11
Problems OMOptim Optimization (2)
Solved problems Result plot Export result data .csv
, , , , , ,
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
12
OMPython Python Scripting with OpenModelica
Interpretation of Modelica
commands and expressions
Interactive Session handling
Library / Tool
Optimized Parser results
Helper functions
Deployable, Extensible and
Distributable
PySimulator Package
PySimulator, a
simulation and
analysis package
developed by DLR
Free, downloadable
Uses OMPython to
simulate Modelica
models by
OpenModelica
13
Modelica3D Library
Modelica 3D
Graphics Library
by Fraunhofer
FIRST, Berlin
Free,
downloadable
Can be used for
3D graphics in
OpenModelica
Shipped with
OpenModelica
HeatRobin h_glass(h_heat=30000);
HeatTransfer ht;
Tinf 20
Rectangle2D dom;
equation
dom.eq=ht;
dom.left.bc=h_glass;
dom.top.bc=h_iso; Conducting boundary:
dom.right.bc=h_iso;
dom.bottom.bc=h_heated;
u 60
end PDEModel;
14
General Tool Interoperability & Model Exchange
Functional Mock-up Interface (FMI)
The FMI development is part of the MODELISAR 29-partner project
FMI development initiated by Daimler
Improved Software/Model/Hardware-in-the-Loop Simulation, of physical
models and of AUTOSAR controller models from different vendors for
automotive applications with different levels of detail.
Open Standard
14 automotive use cases for evaluation
> 10 tool vendors are supporting it
etc.
Feedback
System
Simulation
Business Requirements Model-Driven Compilation
Process Capture Design & Code Gen
Control (PIM) (PSM)
Software &
Syst Product
Process Requirements Product Platform
models models models models
15
OpenModelica ModelicaML UML Profile
SysML/UML to Modelica OMG Standardization
tank-height is 0.6m
16
vVDR Method
virtual Verification of Designs vs Requirements
Actor Task Created Artifact
Formalize RMM
Requirement
Requirements Monitor Models
Designs
Formalize Designs DAM
Alternative
Models
Formalize SM Scenario
Scenarios Models
Analyze Results
17
OpenModelica Environment Architecture
Interactive
OMOptim session handler Textual
Optimization Model Editor
DrModelica
OMNoteBook Execution Modelica
Model Editor Compiler
Modelica
Debugger
Parse
Client: Graphic
Model Editor
Server: Main Program
Corba
Including Compiler,
Interpreter, etc. Client: OMShell
Interactive
Session Handler
SCode Interactive
Client: Eclipse
Untyped API
Plugin MDT
Inst
Typed Checked Command API
system
plot
Ceval
etc.
18
Translation of Models to Simulation Code
Modelica
Graphical Editor Modelica Modelica
Modelica Model Source code
Textual Editor Modelica Model
Translator
Flat model
Analyzer
Sorted equations
Optimizer
Optimized sorted
equations
Code generator
C Code
C Compiler
Executable
Simulation
Example Calls:
Calls fulfill the normal Modelica function call syntax.:
saveModel("MyResistorFile.mo",MyResistor)
19
Some of the Corba API functions
saveModel(A1<string>,A2<cref>) 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>) Deletes the class from the symbol table.
addComponent(A1<ident>,A2<cref>, Adds a component with name (A1), type (A2), and class (A3) as arguments. Optional annotations
A3<cref>,annotate=<expr>) are given with the named argument annotate.
deleteComponent(A1<ident>, Deletes a component (A1) within a class (A2).
A2<cref>)
updateComponent(A1<ident>, Updates an already existing component with name (A1), type (A2), and class (A3) as arguments.
A2<cref>, Optional annotations are given with the named argument annotate.
A3<cref>,annotate=<expr>)
addClassAnnotation(A1<cref>, Adds annotation given by A2( in the form annotate= classmod(...)) to the model definition
annotate=<expr>) referenced by A1. Should be used to add Icon Diagram and Documentation annotations.
getComponents(A1<cref>) Returns a list of the component declarations within class A1:
{{Atype,varidA,commentA},{Btype,varidB,commentB}, {...}}
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( Returns the flattened annotation record of the nth component (A2) (the first is has no 1) within
A1<cref>,A2<int>) 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( Returns the modification of the nth component (A2) where the first has no 1) of class/component
A1<cref>,A2<int>)?? A1.
39getInheritanceCount(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.
Platforms
20
Main Events March 2011 October 2012
OSMC expanded from 32 to 45 organizational members
OpenModelica 1.7 release (April 2011)
OpenModelica 1.8 release (Nov 2011)
Support for FMI Export and Import
Flattening of the whole MSL 3.1 Media library, and about half of the Fluid library.
Improved index reduction with dynamic state selection
Beta release of new efficient debugger for algorithmic Modelica/MetaModelica
OpenModelica 1.8.1 release (April 2012)
Operator Overloading support
Dramatically improved flattening speed for some models
Improved simulation run-time
ModelicaML with Modelica library import (MSL) and value-bindings
OpenModelica 1.9.0 beta release (October 2012)
MSL 3.1 simulation improved, from 36 to 74 to 100 example models
Improved simulation of other libraries, e.g. ThermoSysPro, PlanarMechanics, etc.
Improved algorithms for tearing, matching, dynamic state selection, index reduction
Full version of OMPython, updated ModelicaML for requirements verification
21
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
der(x) = y; // This is the 1st diff equation //
der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */
end VanDerPol;
simulate(VanDerPol,stopTime = 25)
1
plotParametric(x,y)
-2 -1 1 2
-1
-2
Start OMNotebook
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
Section 2.1), using OMNotebook!
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
thrust
mass massLossRate abs thrust
apollo13
mg altitude velocity
velocity acceleration
declaration
new model class Rocket "rocket class" comment
parameters (changeable parameter String name;
before the simulation) Real mass(start=1038.358);
Real altitude(start= 59404);
floating point Real velocity(start= -2003); start value
type Real acceleration;
Real thrust; // Thrust force on rocket
Real gravity; // Gravity forcefield
parameter Real massLossRate=0.000277; name + default value
equation
(thrust-mass*gravity)/mass = acceleration; mathematical
der(mass) = -massLossRate * abs(thrust); equation (acausal)
der(altitude) = velocity;
differentiation with der(velocity) = acceleration;
regards to time end Rocket;
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
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
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; 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
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 =moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
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 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
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.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
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
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.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
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 plot the example. Do a slight change 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-Mechanical)
A DC motor can be thought of as an electrical circuit
which also contains an electromechanical component.
model DCMotor
Resistor R(R=100);
Inductor L(L=100);
VsourceDC DC(f=10);
Ground G;
EMF emf(k=10,J=10, b=2);
Inertia load;
equation R L
connect(DC.p,R.n); emf
connect(R.p,L.n); DC
connect(L.p, emf.n);
connect(emf.p, DC.n); load
connect(DC.n,G.p);
connect(emf.flange,load.flange);
G
end DCMotor;
9
Graphical Modeling - Using Drag and Drop
Composition
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
11
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
12
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 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
13
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.
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;
14
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;
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.
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.
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.
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
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.
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");
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.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
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 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 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)
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;
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> Each then-, elseif-, and else-branch must have 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
<equations>
when-equations are used to express
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; 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
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
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
Exercise03-classes-textual-circuit.onb
11
Arrays, Algorithms, and Functions
1
Two forms of Array Variable Declarations
Flexible array sizes can only be used in functions and partial models
2
Modifiers for Array Variables
Array variables can be initialized or given start values using modifiers
Real A3[2,2]; // Array variable
Real A4[2,2](start={{1,0},{0,1}}); // Array with modifier
Real A5[2,2](unit={{"Voltage","Voltage"},{"Voltage","Voltage"}});
3
Set Formers Array Constructors with Iterators
Mathematical notation for creation of a set of expressions, e.g. A = {1, 3, 4, 6...}
{ expri | i A} equivalent to { expr1 , expr3 , expr4 , expr6, ... }
General array concatenation can be done through the array concatenation operator
cat(k,A,B,C,...) that concatenates the arrays A,B,C,... along the kth dimension
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
4
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, ...]
5
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 // Elementwise mult: {2,4,6}
3 * {1,2,3} // Elementwise mult: {3,6,9}
{1,2,3} * {1,2,2} // Scalar product: 11
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 // Result: {2,4,6}
2 .* {1,2,3} // Result: {2,4,6}
{2,4,6} .* {1,2,2} // Result: {2,8,12}
{1,2,3} .* {1,2} // Not allowed, different array sizes!
6
Array Reduction Functions and Operators
An array reduction function reduces an array to a scalar value, i.e.,
computes a scalar value from the array. The following are defined:
Modelica functions with one scalar return value can be applied to arrays
elementwise, e.g. if v is a vector of reals, then sin(v) is a vector where each
element is the result of applying the function sin to the corresponding element in v
7
Algorithms and Statements
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;
8
Iteration Using for-statements
in Algorithm Sections
for <iteration-variable> in <iteration-set-expression> loop
<statement1> The general structure of a for-
<statement2> statement with a single iterator
...
end for
class SumZ
parameter Integer n = 5;
Real[n] z(start = {10,20,30,40,50});
A simple for-loop
Real sum; summing the five
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;
9
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);
used in the class algorithm
sum := 0;
SumVector perform for i in 1:n loop
a combined if v[i]>0 then
sum := sum + v[i];
summation and elseif v[i] > -1 then
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 certain conditions become true
when x > 2 then
There are situations where several y1 := sin(x);
assignment statements within the y3 := 2*x + y1 + y2;
same when-statement is convenient end when;
10
Functions
Function Declaration
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
12
Functions with Multiple Results
function PointOnCircle"Computes cartesian coordinates of point"
input Real angle "angle in radians";
input Real radius;
output Real x; // 1:st result formal parameter
output Real y; // 2:nd result formal parameter
algorithm
x := radius * cos(phi);
y := radius * sin(phi);
end PointOnCircle;
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
External Functions
It is possible to call functions defined outside the Modelica
language, implemented in C or FORTRAN 77
function polynomialMultiply The body of an
input Real a[:], b[:]; external function is
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external marked with the
end polynomialMultiply; keyword
external
If no language is specified, the implementation language for the external
function is assumed to be C. The external function polynomialMultiply
can also be specified, e.g. via a mapping to a FORTRAN 77 function:
function polynomialMultiply
input Real a[:], b[:];
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external FORTRAN 77
end polynomialMultiply;
13
Exercise04-equations-algorithms-functions.onb
14
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 end Complex;
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 Complex x,y; The type Complex 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 z,w;
equation instead of into an enclosing
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 b(x=1.0, 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
\Mechanics ...
Rotational
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
Package containing basic mathematical functions:
sin(u) sine
cos(u) cosine
tan(u) tangent (u shall not be: ,-/2, /2, 3/2, )
asin(u) inverse sine (-1 u 1)
acos(u) inverse cosine (-1 u 1)
atan(u) inverse tangent
atan2(u1, u2) four quadrant inverse tangent
sinh(u) hyperbolic sine
cosh(u) hyperbolic cosine
tanh(u) hyperbolic tangent
exp(u) exponential, base e
log(u) natural (base e) logarithm (u 0)
log10(u) base 10 logarithm (u 0)
4
Modelica.Mechanics
Modelica.SIunits
5
Modelica.Stategraph
Modelica.Thermal
Example:
6
ModelicaAdditions Library (OLD)
ModelicaAdditions.Multibody (OLD)
7
MultiBody (MBS) - Example Kinematic Loop
8
ModelicaAdditions.PetriNets (OLD)
Transition
Place
9
PNLib Cont
10
Power System Stability - SPOT
11
Vehicle Dynamics Library VehicleDynamics
There is a Greatly Extended Commercial Version
Powertrain
SmartElectricDrives
VehicleDynamics
AirConditioning
HyLib
PneuLib
CombiPlant
HydroPlant
12
Hydraulics Library HyLib
Licensed Modelica package developed
originally by Peter Beater
More than 90 models for Pumps
Pumps
HyLib - Example
13
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
14
Powertrain Library - Powertrain
15
Example Fighter Aircraft Library
Simple PID
Controls alpha and height
16
Example Aircraft Animation
Power output
Air Exhaust
Compressor Turbine
17
Example Gas Turbine
Load rejection
18
Example Gas Turbine Load Rejection
19
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
An event condition so that the event can take place
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
if-equations, if-statements, and if-expressions
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,
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
terminal()
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 time>=2 then // When A: Increase x by 1.5 at time=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()
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;
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 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
Synchronous features in Modelica 3.3
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 Copyright Open Source Modelica Consortium 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
m*der(v) = f - k*x MassWithSpringDamper;
- 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;
14
Biological Models
Population Dynamics
Predator-Prey
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.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
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;
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-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;
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
2
Difficulties in State Space Approach
Modeling Approach 2
3
Physical Modeling Style (e.g Modelica) vs
signal flow 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-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
6
Object-Oriented Component-Based
Approaches in General
7
Approach 3: Top-Down 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
10
Example: OO Modeling of a Tank System
source
levelSensor controller
maxLevel out in
level h tank valve
Object-Oriented Modeling
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,unit="m") "Tank 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
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);
Tank tank(area=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, 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;
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-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
Example:
Exchange the PI controller component for a PID
controller component
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);
Tank tank(area=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 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;
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 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
21
Library Design
Influenza Model
1
Spreading of Influenza Epidemic
2
Influenza Model Parameters
Average weekly contacts of a person with others, CWk=15
Contraction rate per contact, RateC=0.25
Governing Equations
_ _
_
_
_
_
_
_
_
3
Block Oriented Approach
4
Object Oriented Approach #1
Immune
Non Infected
Sick
Less
Components Infected
Base class
Non Infected
Sick
Infected
5
Simulation
Immune
Non Infected
Sick
Infected
Coclusions
6
Goal
7
Short Version of Exercises Using OpenModelica
Version 2012-02-07
Peter Fritzson
The complete exercises can be found under the Modelica course in the OpenModelica.org home page.
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.
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.