Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views173 pages

Modelica Lectures

The document outlines the principles of object-oriented modeling and simulation using Modelica, highlighting its applications in various fields such as robotics, automotive, and aerospace. It provides an overview of the Modelica language, its features, and the importance of modeling and simulation in understanding complex systems. Additionally, it discusses the structure of the course and acknowledges contributions from various individuals and institutions.

Uploaded by

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

Modelica Lectures

The document outlines the principles of object-oriented modeling and simulation using Modelica, highlighting its applications in various fields such as robotics, automotive, and aerospace. It provides an overview of the Modelica language, its features, and the importance of modeling and simulation in understanding complex systems. Additionally, it discusses the structure of the course and acknowledges contributions from various individuals and institutions.

Uploaded by

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

Principles of Object

Object--Oriented
Modeling and Simulation
with Modelica
Peter Fritzson
Linköping University, [email protected]

Mohsen Torabzadeh-
Torabzadeh-Tari
Linköping University, [email protected]

Martin Sjölund
Linköping University, [email protected]

Slides
Based on book and lecture notes by Peter Fritzson
Contributions 2004-2005 by Emma Larsdotter Nilsson, Peter Bunus
Contributions 2007-2008 by Adrian Pop, Peter Fritzson
Contributions 2009 by David Broman, Jan Brugård, Mohsen
Torabzadeh-Tari, Peter Fritzson
Contributions 2010 by Mohsen Torabzadeh-Tari, Peter Fritzson

2010-10-13 Course at Linköping University

Course Based on Book, 2004

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

Wiley-IEEE Press

940 pages

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Outline Day 1

Part I Part II
Introduction to Modelica and a Modelica environments
demo example

Part III Part IV


Modelica language concepts Graphical modeling and the
and textual modeling Modelica standard library

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Acknowledgements, Usage, Copyrights


• If you want to use the Powerpoint version of these slides in
your own course, send an email to: [email protected]
• Thanks to Emma Larsdotter Nilsson for contributions to the
layout of these slides
slides, to Peter Bunus
Bunus, Adrian Pop
Pop, David
Broman, Jan Brugård, Mohsen Torabzadeh-Tari for
contributions.
• Most examples, figures and much text in this course are
adapted with permission from Peter Fritzson’s book
”Principles of Object Oriented Modeling and Simulation with
Modelica 2.1”, copyright Wiley-IEEE Press
• Some examplesp and figures
g reproduced
p with p
permission from
Modelica Association, Martin Otter, Hilding Elmqvist, and
MathCore
• Modelica Association: www.modelica.org
• OpenModelica: www.openmodelica.org

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
Software Installation

• Start the software installation

• Install OpenModelica-1.5.msi and simForge (e.g.


SimForge-0.9.RC2.jar) from the USB Stick

• (If
( you
y have a Mac or Linux computer,
p install
OpenModelica-1.5.0)

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Outline
• Introduction to Modeling and Simulation
• Modelica - The next generation modeling and
g g
Simulation Language
• Modeling and Simulation Environments and
OpenModelica
• Classes
• Components, Connectors and Connections
q
• Equations
• Discrete Events and Hybrid Systems
• Algorithms and Functions
• Demonstrations
6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Why Modeling & Simulation ?

• Increase understanding of complex systems


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

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

What is a system?

• A system is an object or collection of


objects whose properties we want to study
• Natural
N t l and d artificial
tifi i l systems
t
• Reasons to study: curiosity, to build it

Collector

Storage tank
Hot water
Heater

Electricity

Cold water Pump

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

9 Peter Fritzson Copyright © Open Source Modelica Consortium 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

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
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:
• Mental model – statement like “a person is reliable”
• Verbal model – model expressed in words
• Physical model – a physical object that mimics the system
• Mathematical model – a description of a system where
the relationships
p are expressed
p in mathematical form – a
virtual prototype
• Physical modeling – also used for mathematical models
built/structured in the same way as physical models

11 Peter Fritzson Copyright © Open Source Modelica Consortium 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

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Reasons for Simulation

• Suppression of second-order effects


• Experiments are too expensive, too dangerous, or
the system to be investigated does not yet exist
• The time scale is not compatible with experimenter
(Universe, million years, …)
• Variables may be inaccessible.
• Easy manipulation of models
• Suppression of disturbances

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Dangers of Simulation

Falling in love with a model


The Pygmalion effect (forgetting that model is not the real
world,, e.g.
g introduction of foxes to hunt rabbits in Australia))

Forcing reality into the constraints of a model


The Procrustes effect (e.g. economic theories)

Forgetting the model’s level of accuracy


Simplifying assumptions

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

7
Building Models Based on Knowledge

System knowledge
• The collected general experience in relevant domains
• The system itself

Specific or generic knowledge


• E.g. software engineering knowledge

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Kinds of Mathematical Models

• Dynamic vs. Static models


y
• Continuous-time vs. Discrete-time dynamic models
• Quantitative vs. Qualitative models

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Dynamic vs. Static Models

A dynamic model includes time in the model


A static model can be defined without involving time

Resistor voltage – static system

Input current
pulse
Capacitor voltage - dynamic

time

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Continuous-Time vs.
Continuous-
Discrete--Time Dynamic Models
Discrete
Continuous-time models may evolve their variable values
continuously during a time period
Discrete-time variables changeg values a finite number of times
during a time period

Continuous

Discrete

time

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
Quantitative vs. Qualitative Models

Results in qualitative data


Variable values cannot be represented numerically
Mediocre = 1, Good = 2, Tasty = 3, Superb = 4

Superb
Tasty
Good
Mediocre
time

Quality of food in a restaurant according


to inspections at irregular points in time

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Using Modeling and Simulation


within the Product Design-
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
erification

Realization

Documentation, Version and Configuration Management

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

10
Principles of Graphical Equation-
Equation-Based Modeling

• Each icon represents a physical component


i.e. Resistor, mechanical Gear Box, Pump
• Composition lines represent the actual
physical connections i.e. electrical line,
mechanical connection, heat flow
• Variables at the interfaces describe Component 1 Component 2

interaction with other component Connection

Component 3
• Physical behavior of a component is
described by equations
• Hierarchical decomposition of components

21 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Application Example – Industry Robot


k2

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

qdRef Kd
S
0.03 rel

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

+1 b(s) 340.8
0.3
- +1 - a(s) S

axis3

rate1 tacho2 tacho1


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

q
qd
Rp2=50

Ra=250 La=(250/(2**D*w m))

Rd1=100
C=0.004*D/w m Rp1=200 axis1

Rd2=100
Ri=10
- -
-
+ +
diff + pow er
OpI
Vs

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

x
g3
wrela = n*qd; inertial
zrela = n*qdd; g1

Sb = Sa*transpose(Srel);
hall2

r0b = r0a; hall1 w r


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

Courtesy of Martin Otter

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

11
GTX Gas Turbine Power Cutoff Mechanism

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

23 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica in Automotive Industry

24 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

12
Modelica in Avionics

25 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica in Biomechanics

26 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

13
Modelica –
The Next Generation
Modeling Language

27 Peter Fritzson Copyright © Open Source Modelica Consortium 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

28 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

14
The Form – Equations
• Equations were used in the third millennium B.C.
• Equality sign was introduced by Robert Recorde in 1557

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


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

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


variable
i bl = expression i
v = INTEG(F)/m

Programming languages usually do not allow equations!

29 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

What is Modelica?

A language for modeling of complex physical systems

• Robotics
R b ti
• Automotive
• Aircrafts
• Satellites
• Power plants
• Systems biology

30 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

15
What is Modelica?

A language for modeling of complex physical systems

Primary designed for simulation, but there are also other


usages of models, e.g. optimization.

31 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

What is Modelica?

A language for modeling of complex 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
• MathModelica by MathCore
• Dymola by Dassault systems / Dynasim
• SimulationX by ITI
• MapleSim by MapleSoft

Available at: www.modelica.org

32 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

33 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica – The Next Generation Modeling


Language
High level language
MATLAB-style array operations; Functional style; iterators,
constructors, object orientation, equations, etc.

MATLAB similarities
MATLAB-like array and scalar arithmetic, but strongly typed and
efficiency comparable to C.

Non-Proprietary
• Open Language Standard
• Both
B th Open-Source
O S and
dCCommercial
i l iimplementations
l t ti

Flexible and powerful external function facility


• LAPACK interface effort started

34 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

17
Modelica Language Properties

• Declarative and Object-Oriented


• Equation-based; continuous and discrete equations
• Parallel process modeling of real-time applications,
according to synchronous data flow principle
• Functions with algorithms without global side-effects
(but local data updates allowed)
• Type system inspired by Abadi/Cardelli
• Everything is a class – Real, Integer, models,
functions, packages, parameterized classes....
35 Peter Fritzson Copyright © Open Source Modelica Consortium 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
36 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

18
Brief Modelica History
• First Modelica design group meeting in fall 1996
• International group of people with expert knowledge
in both language design and physical modeling
• Industry and academia

• Modelica Versions
• 1.0 released September 1997
• 2.0 released March 2002
• 2.2 released March 2005
• 3 0 released
3.0 l dSSeptember
t b 2007
• 3.1 released May 2009

• Modelica Association established 2000


• Open, non-profit organization

37 Peter Fritzson Copyright © Open Source Modelica Consortium 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


Linköping, Sweden

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


Germany
• The 5th International Modelica conference September 4-5, 2006 in
Vienna, Austria
• The 6th International Modelica conference March 3-4, 2008 in Bielefeld,
Germany
• The 7th International Modelica conference Sept 21-22, 2009 in Como,
Italy

38 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

19
Exercises Part I
Hands--on graphical modeling
Hands
(20 minutes)

39 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Graphical Modeling
Using Drag and Drop Composition

Courtesy
MathCore
Engineering AB

40 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

20
Exercises Part I – Basic Graphical Modeling
• (See instructions on next two pages)
• Start the simForge editor
• Draw the RL-Circuit
• Simulate
R1 L

R=10
R=100 L=1
L=0.1
A
C

The RL-Circuit Simulation


G

41 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Exercises Part I – simForge Instructions Page 1


• Start simForge, (e.g. SimForge-0.9.RC2.jar).
• Go to File menu and choose New Project.
• Write RL_Circuit and click on the Browse button for choosing the
destination folder.
• Press OK.
• In the navigation bar in the left, there should be three items,
Modelica, IEC61131-3 and Simulation result. Double-click on the
Modelica.
• Under the Modelica :
• The standard Modelica library components are listed
in the Used external package.
• The Modelica classes and Modelica files are the
places where your models will end up under. The first
folder is for the graphical models and the latter is for the
texual form.

42 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

21
Exercises Part I – simForge Instructions Page 2
• Go to File menu and choose New File. Write RL_circuit and press OK.
• In the Add Class pop-up dialog box change the Type from package to
class and press OK.
• Double click on the RL_circuit under the Modelica classes and the
graphical window will appear.
• Drag and Drop components from the standard Modelica library to your
model.
• For connecting components, move the cursor to the target pin and press
shift+click once and just move the cursor with the mouse to the
destination pin and press again shift+click.
• Under the Edit menu ->
Advanced properties you can
• Start the simulation with simulation button. tick
i k the
h visible
i ibl legend
l d bar.
b
• In the simulation pop-up you can leave out
some fields like the Stop time, which will result
in a default value of 1 sec. will be used.

• The result will appear under the Simulation result.

43 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

22
Modelica Environments and OpenModelica
p

1 Peter Fritzson Copyright © Open Source Modelica Consortium

Dymola

• Dynasim (Dassault Systemes)


• Sweden
• First Modelica tool on the market
• Main focus on automotive
industry
• www.dynasim.com

2 Peter Fritzson Copyright © Open Source Modelica Consortium

1
Simulation X

• ITI
• Germany
• Mechatronic systems
y
• www.simulationx.com

3 Peter Fritzson Copyright © Open Source Modelica Consortium

MapleSim

• Maplesoft
• Canada
• Recent Modelica tool on the
market
• Integrated with Maple
• www.maplesoft.com

4 Peter Fritzson Copyright © Open Source Modelica Consortium

2
MathModelica

• MathCore
• Sweden
• Released 2006
• General purpose
• Mathematica connection
• www.mathcore.com

5 Peter Fritzson Copyright © Open Source Modelica Consortium

The OpenModelica Environment


www.OpenModelica.org

6 Peter Fritzson Copyright © Open Source Modelica Consortium

3
OpenModelica and simForge
• OpenModelica
• Open Source Modelica
Consortium (OSMC)
• Sweden and other countries
• Open source
• www.openmodelica.org

• Graphical editor simForge


• Politecnico di Milano, Italy
• Runs together with OpenModelica
• Open source
7 Peter Fritzson Copyright © Open Source Modelica Consortium

OpenModelica
• Advanced Interactive Modelica compiler (OMC)
• Supports most of the Modelica Language
• Basic environment for creating models
• OMShell – an interactive command handler • ModelicaML UML Profile
• OMNotebook – a literate programming notebook • MetaModelica extension
• MDT – an advanced textual environment in Eclipse

8 Peter Fritzson Copyright © Open Source Modelica Consortium 8

4
Open Source Modelica Consortium
Open-source community services Founded Dec 4, 2007
• Website and Support Forum Industrial members (12)
• Version-controlled source base •ABB Corporate Research
•Bosch-Rexroth AG, Germany
• Bug database
•Siemens Turbo Machinery y AB
• Development courses •Creative Connections, Prague
• www.openmodelica.org •Equa Simulation AB, Sweden
•IFP, Paris, France
•MostforWater, Belgium
•MathCore Engineering AB
Code Statistics •MapleSoft, Canada
•TLK Thermo, Germany
•VTT, Finland
•XRG Simulation AB, Germany
University members (9)
•Linköping University, Sweden
Hamburg University of Technology/TuTech, Institute of
•Hamburg
Thermo-Fluid Dynamics, Germany
•Technical University of Braunschweig, the Institut of
Thermodynamik, Germany
•Université Laval, the modelEAU group, Canada
•Griffith University, Australia
•University of Queensland, Australia
•Politecnico di Milano, Italy
•Mälardalen University, Sweden
•Technical University Dresden, Germany

9 Peter Fritzson Copyright © Open Source Modelica Consortium

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)

10 Peter Fritzson Copyright © Open Source Modelica Consortium

5
Interactive Session Handler – on dcmotor Example
(Session handler called OMShell – OpenModelica Shell)

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

11 Peter Fritzson Copyright © Open Source Modelica Consortium

Event Handling by OpenModelica – BouncingBall


model BouncingBall
parameter Real e=0.7 "coefficient of restitution";
>>simulate(BouncingBall, parameter Real g=9.81 "gravity acceleration";
stopTime=3.0); Real h(start=1) "height of ball";
Real v "velocity of ball";
>>plot({h,flying});
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;

12 Peter Fritzson Copyright © Open Source Modelica Consortium

6
Run Scripts in OpenModelica

• RunScript command interprets a .mos file


• .mos means MOdelica Script file
• Example:
>> runScript("sim_BouncingBall.mos")

The file sim_BouncingBall.mos :


loadFile( BouncingBall.mo );
loadFile("BouncingBall.mo");
simulate(BouncingBall, stopTime=3.0);
plot({h,flying});

13 Peter Fritzson Copyright © Open Source Modelica Consortium

OpenModelica MDT – Eclipse Plugin


• Browsing of packages, classes, functions
• Automatic building of executables;
separate compilation
• Syntax
S t highlighting
hi hli hti
• Code completion,
Code query support for developers
• Automatic Indentation
• Debugger
(Prel. version for algorithmic subset)

14 Peter Fritzson Copyright © Open Source Modelica Consortium

7
OpenModelica MDT – Usage Example

Code Assistance on
function calling.

15 Peter Fritzson Copyright © Open Source Modelica Consortium

OpenModelica Environment Architecture

Eclipse Plugin Graphical Model


Editor/Browser Editor/Browser

Interactive
Emacs session handler Textual
Editor/Browser Model Editor

DrModelica
OMNoteBook Execution Modelica
Model Editor Compiler

Modelica
Debugger

16 Peter Fritzson Copyright © Open Source Modelica Consortium

8
OpenModelica Client
Client--Server Architecture

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

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

17 Peter Fritzson Copyright © Open Source Modelica Consortium

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
C d generator
Code t
C Code
C Compiler
Executable
Simulation

18 Peter Fritzson Copyright © Open Source Modelica Consortium

9
Corba Client
Client--Server API
• Simple text-based (string) communication in
Modelica Syntax
• API supporting model structure query and update

Example Calls:
Calls fulfill the normal Modelica function call syntax.:

saveModel("MyResistorFile.mo",MyResistor)

will save the model MyResistor into the file “MyResistorFile.mo”.

For creating new models it is most practical to send a model, e.g.:

model Foo end Foo;


or, e.g.,
connector Port end Port;

19 Peter Fritzson Copyright © Open Source Modelica Consortium

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.
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,
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.

20getInheritanceCount(A1<cref>)
Peter Fritzson Copyright © Open SourceReturns the number
Modelica (as a string) of inherited classes of a class.
Consortium
getNthInheritedClass(A1<cref>, Returns the type name of the nth inherited class of a class. The first class has number 1.

10
Platforms

• All OpenModelica GUI tools (OMShell,


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

• Windows – currently main development and release


platform
l tf
• Linux – available. Also used for development
• Mac – available

21 Peter Fritzson Copyright © Open Source Modelica Consortium

OpenModelica – Recent Developments

• Dec 2008. OSMC Board decides to focus on


improving the OpenModelica compiler for Modelica
libraries during 2009
• Dec 2008. MathCore contributes 1 man-year worth
of source code for the flattening frontend.
• Jan-Sept 2009. Development mostly on the
compiler frontend
• Sept
S t 2009.
2009 O OpenModelica
M d li release
l 1
1.5,
5 containing
t i i
approx 2 man-years development compared to
version 1.4.5. (Beta release available today).

22 Peter Fritzson Copyright © Open Source Modelica Consortium

11
Modelica Language Concepts
and Textual Modeling
Classes and Inheritance

Typed
Declarative Hybrid
Equation-based Modeling
Textual Language

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Acausal Modeling

The order of computations is not decided at modeling time


Acausal Causal

Visual
Component
Level

Equation A resistor equation: Causall possibilities:


C ibiliti
Level R*i = v; i := v/R;
v := R*i;
R := v/i;

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Typical Simulation Process

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

What is Special about Modelica?

• Multi-Domain Modeling
• Visual acausal hierarchical component modeling
• Typed declarative equation-based textual
language
• Hybrid modeling and simulation

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
What is Special about Modelica?
Multi-Domain
Modeling

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

What is Special about Modelica?


Multi-Domain Visual Acausal
Keeps the physical Hierarchical
Modeling
structure Component
Modeling

Acausal model
(Modelica)

Causal
block-based
model
(Simulink)

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

rate1 tacho2 tacho1


b(s) b(s) g5
PT1
a(s) a(s)
axis2
2=50
Rp2

Ra=250 La=(250/(2*D*w m))


qd
C=0.004*D/w m Rp1=200
Rd1=100

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

Courtesy of Martin Otter hall1 w r

g2 qd
g4
q

7CourtesyPeter Fritzson
of Martin Otter Copyright © Open Source Modelica Consortium pelab

What is Special about Modelica?


Multi-Domain Visual Acausal
Modeling Hierarchical
A textual class-based language
Component
OO primary used for as a structuring concept
Modeling
Behaviour described declaratively using
• Differential algebraic equations (DAE) (continuous-time)
• Event triggers (discrete-time)

Variable class VanDerPol "Van der Pol oscillator model"


declarations Real x(start = 1) "Descriptive string for x”;
Real y(start = 1) "y coordinate”;
parameter Real lambda = 0.3;
p
equation
Typed der(x) = y;
der(y) = -x + lambda*(1 - x*x)*y;
Declarative end VanDerPol;
Equation-based
Differential equations
Textual Language

8 Peter Fritzson 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

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica Classes and


Inheritance

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Simplest Model – Hello World!

A Modelica “Hello World” model


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

Simulation in OpenModelica environment


1

0.8 simulate(HelloWorld, stopTime = 2)


0.6
plot(x)

0.4

0.2

0.5 1 1.5 2

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Model Including Algebraic Equations

Include algebraic equation class DAEexample


Real x(start=0.9);
Algebraic equations contain Real y;
no derivatives equation
der(y)+(1+0.5*sin(y))*der(x)
= sin(time);
x - y = exp(-0.9*x)*cos(y);
end DAEexample;

Simulation in OpenModelica environment


1.20

1.15 simulate(DAEexample, stopTime = 1)


1.10
plot(x)
1.05

1.0 time
0.2 0.4 0.6 0.8 1
0.95

0.90

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Example class: Van der Pol Oscillator
class VanDerPol "Van der Pol oscillator model"
Real x(start = 1) "Descriptive string for x"; // x starts at 1
Real y(start = 1) "y coordinate"; // y starts at 1
parameter Real lambda = 0.3;
equation
d ( ) = y;
der(x) // This
hi iis the
h 1st diff equation
i //
der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */
end VanDerPol;

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

-2 -1 1 2

-1

-2

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Exercises – Simple Textual Modeling

• Start
S OMNotebook
O
• Start->Programs->OpenModelica->OMNotebook
• Open File: Exercise01-classes-simple-textual.onb

• Open Exercise01-classes-simple-textual.pdf

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

7
Exercises 2.1 and 2.2
• Open the Exercise01-classes-simple-textual.onb
found in the Tutorial directory.
• Locate the VanDerPol model in DrModelica (link from
S ti 2
Section 2.1),
1) using
i OMN
OMNotebook!
t b k!
• Exercise 2.1: Simulate and plot VanDerPol. Do a slight
change in the model, re-simulate and re-plot.
• Exercise 2.2. Simulate and plot the HelloWorld example.
Do a slight change in the model, re-simulate and re-plot.
Try command-completion, val( ), etc.
class HelloWorld "A simple equation"
Real x(start=1);
equation simulate(HelloWorld, stopTime = 2)
der(x)= -x; plot(x)
end HelloWorld;

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Variables and Constants

Built-in primitive data types


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

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Variables and Constants cont’

• Names indicate meaning of constant


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

17 Peter Fritzson Copyright © Open Source Modelica Consortium 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 x ; //
Descriptive string for x”; x starts at 1
Real y(start = 1) "y coordinate”; // y starts at 1
parameter Real lambda = 0.3;
equation
der(x) = y; // This is the 1st diff equation //
der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */
end VanDerPol;

2) Source code comments, disregarded by compiler


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

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
A Simple Rocket Model
thrust − mass ⋅ gravity
Rocket acceleration =
mass
apollo13 thrust
mass ′ = − massLossRate ⋅ abs ( thrust )
mg altitude′ = velocity
velocity ′ = acceleration

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

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Celestial Body Class

A class declaration creates a type name in Modelica


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

An instance of the class can be


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

The declaration states that moon is a variable


containing an object of type CelestialBody

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

altitude
CelestialBody

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

21 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Simulation of Moon Landing


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

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

10000 -300

5000 -400

50 100 150 200

It starts at an altitude of 59404 The rocket initially has a high


(not shown in the diagram) at negative velocity when approaching
time zero, gradually reducing it the lunar surface. This is reduced to
until touchdown at the lunar zero at touchdown, giving a smooth
surface when the altitude is zero landing

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

11
Restricted Class Keywords

• The class keyword can be replaced by other keywords, e.g.: model,


record, block, connector, function, ...
• Classes declared with such keywords have restrictions
• Restrictions apply to the contents of restricted classes

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


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

23 Peter Fritzson Copyright © Open Source Modelica Consortium 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
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 Copyright © Open Source Modelica Consortium pelab

12
Inheritance
parent class to Color

restricted kind record ColorData


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

Data and behavior: field declarations, equations, and


certain other contents are copied into the subclass

25 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Inheriting definitions

Legal!
Identical to the
Inheriting multiple
record ColorData
inherited field blue identical
parameter Real red = 0.2;
0 2; definitions results
parameter Real blue = 0.6; in only one
Real green; definition
end ColorData;

class ErrorColor
extends ColorData;
parameter Real blue = 0.6;
parameter Real red = 0.3;
equation
q
red + blue + green = 1; Inheriting
Illegal!
end ErrorColor; Same name, but multiple different
different value definitions of the
same item is an
error

26 Peter Fritzson Copyright © Open Source Modelica Consortium 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;

Color is identical to Color2


class Color2 // OK!
extends Color; Same equation twice leaves
equation one copy when inheriting
red + blue + green = 1;
end Color2;

class Color3 // Error! Color3 is overdetermined


extends Color;
equation Different equations means
red + blue + green = 1.0; two equations!
// also inherited: red + blue + green = 1;
end Color3;

27 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Multiple Inheritance

Multiple Inheritance is fine – inheriting both geometry and color


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

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

28 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

14
Multiple Inheritance cont’

Only one copy of multiply inherited class Point is kept


class Point
Real x;
Real
l y;
end Point;

class VerticalLine class HorizontalLine


extends Point; extends Point;
Real vlength; Diamond Inheritance Real hlength;
end VerticalLine; end HorizontalLine;

class Rectangle
extends VerticalLine;
extends HorizontalLine;
end Rectangle;

29 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Simple Class Definition –


Shorthand Case of Inheritance

• Example: • Often used for


class SameColor = Color; introducing new
names off types:
Equivalent to: type Resistor = Real;

class SameColor
inheritance extends Color; connector MyPin = Pin;
end SameColor;

30 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

15
Inheritance Through Modification

• Modification is a concise way of combining


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

31 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

The Moon Landing


Example Using Inheritance
Rocket
apollo13 thrust

mg model Rocket "generic rocket class"


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

32 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

16
The Moon Landing
Example using Inheritance cont’

inherited
parameters

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

33 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Inheritance of Protected Elements


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

17
Advanced Topic

• Class parameterization

35 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Generic Classes with Type Parameters


class C
Formal class parameters are replaceable class ColoredClass = GreenClass;
replaceable variable or type ColoredClass obj1(p1=5);
declarations within the class (usually)
marked with the prefix replaceable replaceable YellowClass obj2;
ColoredClass obj3;
R dCl
RedClass obj4;
bj4
equation
Actual arguments to classes are end C;
modifiers, which when containing
whole variable declarations or
types are preceded by the prefix class C2 =
redeclare C(redeclare class ColoredClass = BlueClass);

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;

36 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

18
Class Parameterization when Class Parameters
are Components
R1

The class ElectricalCircuit has been


converted into a parameterized generic
class GenericElectricalCircuit with
AC R2 L1 2 R3
three formal class parameters R1, R2, R3,
marked by the keyword replaceable

Class
class ElectricalCircuit class GenericElectricalCircuit
Resistor R1(R=100);
parameterization replaceable Resistor R1(R=100);
Resistor R2(R=200); replaceable Resistor R2(R=200);
Resistor R3(R=300); replaceable Resistor R3(R=300);
Inductor L1; Inductor L1;
SineVoltage AC; SineVoltage AC;
Groung G; Groung G;
equation
ti equation
connect(R1.n,R2.n); connect(R1.n,R2.n);
connect(R1.n,L1.n); connect(R1.n,L1.n);
connect(R1.n,R3.n); connect(R1.n,R3.n);
connect(R1.p,AC.p); connect(R1.p,AC.p);
..... .....
end ElectricalCircuit; end GenericElectricalCircuit;

37 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Class Parameterization when Class Parameters


are Components - cont’
R1
A more specialized class TemperatureElectricalCircuit is
created by changing the types of R1, R3, to TempResistor

AC R2 L1 2 R3

class TemperatureElectricalCircuit =
G GenericElectricalCircuit (redeclare TempResistor R1
redeclare TempResistor R3);

class TemperatureElectricalCircuit We add a temperature variable Temp for


parameter Real Temp=20; the temperature of the resistor circuit
and modifiers for R1 and R3 which are
extends GenericElectricalCircuit( now TempResistors.
redeclare TempResistor R1(RT=0.1, Temp=Temp),
redeclare TempResistor R3(R=300));
end TemperatureElectricalCircuit class ExpandedTemperatureElectricalCircuit
parameter Real Temp;
TempResistor R1(R=200, RT=0.1, Temp=Temp),
replaceable Resistor R2;
TempResistor R3(R=300);
equivalent to equation
....
end ExpandedTemperatureElectricalCircuit

38 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

19
Exercises 1 Simple Textual Continued

• C
Continue exercises in Exercise01-classes-
simple-textual.onb

• Do Exercises 1.3, 1.4, 1.5 and 2

39 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Exercise 1.3 – Model the System Below

• Model this Simple System of Equations in


Modelica

40 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

20
Components, Connectors
and Connections

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Software Component Model


Interface Acausal coupling
Connector

Component Connection Component


Causal coupling

A component class should be defined independently of the


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

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Connectors and Connector Classes
Connectors are instances of connector classes
electrical connector

connector class connector Pin


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

connector class connector Flange


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

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

The flow prefix

Two kinds of variables in connectors:


• Non-flow variables effort, potential or energy level
• Flow
Fl variables
i bl representt some kind
ki d off flow
fl
Coupling
• Equality coupling, for effort(non-flow) variables
• Sum-to-zero coupling, for flow variables

The value of a flow variable is positive when the current


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

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

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


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

+ v v +
pin1 pin2
i i

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

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

Multiple connections are possible:


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

Each primitive connection set of effort (nonflow) Across


variables is used to generate equations of the form: variable

v1 = v2 = v3 =  vn
Each primitive connection set of flow variables is used to generate
sum-to-zero equations of the form: Through
variable
i1 + i2 +  (−ik ) +  in = 0

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Acausal, Causal, and Composite


Connections
Two basic and one composite kind of connection in Modelica
• Acausal connections
• Causal connections
connections, also called signal connections
• Composite connections, also called structured connections,
composed of basic or composite connections

connector class connector OutPort


fixed causality output Real signal;
d OutPort
end O tP t

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
Common Component Structure

The base class TwoPin has


p.v i + TwoPin - i n.v
two connectors p and n for p n

positive and negative pins p.i n.i


respectively i

partial class partial model TwoPin


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

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

model Inductor ”Ideal electrical inductor”


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

model Capacitor ”Ideal electrical capacitor”


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

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Electrical Components cont’

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

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

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Resistor Circuit
i1 i2
n R1 p p R2 n
v1 v2

v3
p R3 n
i3

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

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

mass1 srel -0.5

L -1

s -1.5
-mg
mg
t
0.1 0.2 0.3 0.4 0.5

-2.5

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Extra Exercise
• Locate the Oscillator model in DrModelica using
OMNotebook!
• Simulate and pplot the example.
p Do a slight
g change g in the
model e.g. different elasticity c, re-simulate and re-plot.
fixed1
• Draw the Oscillator model using
the graphic connection editor e.g.
using the library Modelica. b

Mechanical.Translational spring1
a
• Including components SlidingMass,
Force, Blocks.Sources.Constant mass1

• Simulate and plot!

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

connector OutPort "Connector with output signals of type Real"


parameter Integer n=1 "Dimension of signal vector";
fixed causality output Real signal[n] "Real output signals";
end OutPort;

inPort outPort

multiple input partial block MISO


single output "Multiple Input Single Output continuous control block"
bl k
block parameter Integer nin=1 "Number of inputs";
InPort inPort(n=nin) "Connector of Real input signals";
OutPort outPort(n=1) "Connector of Real output signal";
protected
Real u[:] = inPort.signal "Input signals";
Real y = outPort.signal[1] "Output signal";
end MISO; // From Modelica.Blocks.Interfaces

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Connecting Components
from Multiple Domains
• Block domain ind R1
1

• Mechanical domain emf


R2

ex ac iner vsen

• Electrical domain Block Mechanical Electrical


2

domain domain G domain

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

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Simple Modelica DCMotor Model
Multi--Domain (Electro
Multi (Electro--Mechanical)
A DC motor can be thought of as an electrical circuit
which also contains an electromechanical component.

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

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Corresponding DCMotor Model Equations


The following equations are automatically derived from the Modelica model:

(load component not included)

Automatic transformation to ODE or DAE for simulation:

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
Graphical Modeling
Using Drag and Drop Composition

Courtesy
MathCore
Engineering AB

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Completed DCMotor using Graphical


Composition

Courtesy MathCore
Engineering AB

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

• Simulate it for 15s and plot the R L


emf
variables for the outgoing u
rotational
t ti l speed
d on th
the iinertia
ti
J
axis and the voltage on the
voltage source (denoted u in the G
figure) in the same plot.

21 Peter Fritzson Copyright © Open Source Modelica Consortium 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
spring.

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

23 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Hierarchically Structured Components


An inside connector is a connector belonging to an internal component of a
structured component class.
An outside connector is a connector that is part of the external interface of
a structured
t t d componentt class,
l is
i declared
d l d directly
di tl within
ithi th
thatt class
l
partial model PartialDCMotor
InPort inPort; // Outside signal connector
RotFlange_b rotFlange_b; // Outside rotational flange connector
Inductor inductor1;
Resistor resistor1;
PartialDCMotor
Ground ground1;
EMF emf1;
p n p n
SignalVoltage signalVoltage1; resistor1 inductor1
n
equation p
rotFlange_b
( , g g );
connect(inPort,signalVoltage1.inPort); inPort inPort signalVoltage1 emf1
rotFlange_b
connect(signalVoltage1.n, resistor1.p); p
n
connect(resistor1.n, inductor1.p);
connect(signalVoltage1.p, ground1.p);
connect(ground1.p, emf1.n); p
ground1
connect(inductor1.n, emf1.p);
connect(emf1.rotFlange_b, rotFlange_b);
end PartialDCMotor;

24 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

12
Hierarchically
Structured Components cont’

partialDCMotor1

step1 inertia1

model DCMotorCircuit2
Step step1;
PartialDCMotor partialDCMotor1;
Inertia inertia1;
equation
connect(step1.outPort, partialDCMotor1.inPort);
connect(partialDCMotor1.rotFlange_b, inertia1.rotFlange_a);
end DCMotorCircuit2;

25 Peter Fritzson Copyright © Open Source Modelica Consortium 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

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

26 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

13
Connector Restrictions cont’
connector RealInput
input Real signal; class C
end RealInput; RealInput u; // input connector
RealOutput y; // output connector
connector RealOutput end C;
output Real signal;
end RealOutput;

class CInst
C C1, C2, C3, C4; // Instances of C
A circuit consisting of four
equation connected components
connect(C1.outPort, C2.inPort); C1, C2, C3, and C4
connect(C2.outPort, C3.inPort);
connect(C3.outPort, C4.inPort); which are instances of the
end CInst; class
l C

C1 C2 C3 C4
input output input output input output input output

27 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Connector Restrictions cont’


class M "Structured class M" A circuit in which the middle
RealInput u; // Outside input connector components C2 and C3 are placed
RealOutput y; // Outside output connector inside a structured component M1 to
C C2;
C C3;; which two outside connectors M1.u
end M; and M1.y have been attached.

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

28 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

14
Parameterization and Extension of Interfaces
connector Stream External interfaces to
Real pressure; component classes are
flow Real volumeFlowRate;
inlet end Stream; defined primarily through the
use of connectors
connectors.
Tank
model Tank
parameter Real Area=1;
replaceable connector TankStream = Stream;
outlet TankStream inlet, outlet; // The connectors
Real level;
Parameterization
equation
of interfaces // Mass balance
Area*der(level) = inlet.volumeFlowRate +
outlet.volumeFlowRate;
outlet.pressure = inlet.pressure;
The Tank model has an end Tank;
connector Stream // Connector class
external interface in terms of Real pressure;
the connectors inlet and flow Real volumeFlowRate;
outlet end Stream

29 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Parameterization and Extension of Interfaces –


cont’
We would like to extend the Tank model to include
temperature-dependent effects, analogous to how
inlet we extended a resistor to a temperature-dependent
resistor
Tank
model HeatTank
extends Tank(redeclare connector TankStream = HeatStream);
Real temp;
outlet equation
// Energy balance for temperature effects
Area*level*der(temp) = inlet.volumeFlowRate*inlet.temp +
outlet.volumeFlowRate*outlet.temp;
outlet.temp = temp; // Perfect mixing assumed.
end HeatTank;

connector HeatStream
extends Stream;
Real temp;
end HeatStream;

30 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

15
Arrays of Connectors
Part built up with a for-equation (see Lecture 4)

InertialSystem1 Spherical1 BoxBody1 Spherical2 BoxBody2 SphericalN BoxBodyN

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;

31 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

16
Equations

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Usage of Equations
In Modelica equations are used for many tasks
• The main usage of equations is to represent relations in
mathematical models
models.
• Assignment statements in conventional languages are
usually represented as equations in Modelica
• Attribute assignments are represented as equations
• Connections between objects generate equations

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Equation Categories
Equations in Modelica can informally be classified
into three different categories
• N
Normall equations
ti (
(e.g., expr1
1 = expr2)
2) occurring
i iin
equation sections, including connect equations and other
equation types of special syntactic form
• Declaration equations, (e.g., Real x = 2.0) which are part of
variable, parameter, or constant declarations
• Modifier equations, (e.g. x(unit="V")
x(unit V ) )which are commonly
used to modify attributes of classes.

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Constraining Rules for Equations


Single Assignment Rule
The total number of “equations” is identical to the total number of
“unknown” variables to be solved for

Synchronous Data Flow Principle


• All variables keep their actual values until these values are explicitly
changed
• At every point in time, during “continuous integration” and at event
instants, the active equations express relations between variables which
have to be fulfilled concurrentlyy
Equations are not active if the corresponding if-branch or when-equation
in which the equation is present is not active because the corresponding
branch condition currently evaluates to false
• Computation and communication at an event instant does not take time

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
Declaration Equations
Declaration equations: It is also possible to specify a declaration
constant Integer one = 1;
equation for a normal non-constant variable:
parameter Real mass = 22.5; Real speed = 72.4;

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

5 Peter Fritzson Copyright © Open Source Modelica Consortium 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
speed(start=72.4);
4);
Modifier equations also occur in type definitions:
type Voltage = Real(unit="V", min=-220.0, max=220.0);

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

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Kinds of Normal Equations in Equation
Sections
Kinds of equations that can be present in equation sections:
• equality equations • repetitive equation structures with for-equations
• connect equations • conditional equations with if-equations
• assert and terminate • conditional equations with when-equations
when equations
• reinit model MoonLanding
parameter Real force1 = 36350;
parameter Real force2 = 1308;
parameter Real thrustEndTime = 210;
parameter Real thrustDecreaseTime = 43.2;
Rocket apollo(name="apollo13", mass(start=1038.358) );
CelestialBody moon(mass=7.382e22,radius=1.738e6,name="moon");
equation
conditional if (time<thrustDecreaseTime) then
if-equation
q apollo.thrust = force1;
elseif (time<thrustEndTime) then
apollo.thrust = force2;
else
apollo.thrust = 0;
end if;
equality apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
equation
end Landing;

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Equality Equations

expr1 = expr2:
(out1, out2, out3,...) = function_name(in_expr1, in_expr2, ...);

class EqualityEquations
Real x,y,z;
equation
simple equality (x, y, z) = f(1.0, 2.0); // Correct!
equation (x+1, 3.0, z/y) = f(1.0, 2.0); // Illegal!
// Not a list of variables
// on the left-hand
left hand side
end EqualityEquations;

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

Consider the following simple example with a for-equation:


class FiveEquations class FiveEquationsUnrolled
Real[5] x; Real[5] x;
equation Both classes have equation
for i in 1:5 loop equivalent
q behavior! x[1] = 2;
x[i] = i+1; x[2] = 3;
end for; x[3] = 4;
end FiveEquations; x[4] = 5;
x[5] = 6;
end FiveEquationsUnrolled;
In the class on the right the for-equation
has been unrolled into five simple equations

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

connect-equations
In Modelica connect-equations are used to establish
connections between components via connectors
connect(connector1 connector2)
connect(connector1,connector2)

Repetitive connect-equations
class RegComponent
Component components[n];
equation
for i in 1:n-1 loop
connect(components[i] o tlet components[i+1] inlet)
connect(components[i].outlet,components[i+1].inlet);
end for;
end RegComponent;

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Conditional Equations: if-equations
if <condition> then if-equations for which the conditions have higher
<equations> variability than constant or parameter must include an
elseif <condition> then else-part
<equations>
else
<equations> E h then-, elseif-,
Each i and d else-branch
b h mustt h
have th
the
end if; same number of equations
model MoonLanding
parameter Real force1 = 36350;
...
Rocket apollo(name="apollo13", mass(start=1038.358) );
CelestialBody moon(mass=7.382e22,radius=1.738e6,name="moon");
equation
if (time<thrustDecreaseTime) then
apollo.thrust = force1;
elseif (time<thrustEndTime) then
apollo.thrust = force2;
else
apollo.thrust = 0;
end if;
apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2;
end Landing;

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Conditional Equations: when-equations


when <conditions> then when x > 2 then
<equations> y1 = sin(x);
end when; y3 = 2*x + y1+y2;
end when;

<equations> in when-equations are instantaneous equations that are


active at events when <conditions> become true

Events are ordered in time and form an event history:

time
event 1 event 2 event 3

• An event is a point in time that is instantaneous, i.e., has zero duration


• An event condition switches from false to true in order for the event to
take place

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Conditional Equations: when-equations cont'
when <conditions> then when-equations are used to express
<equations>
end when; instantaneous equations that are only
valid (become active) at events, e.g. at
discontinuities or when certain conditions
become true
when x > 2 then when {x > 2, sample(0,2), x < 5} then
y1 = sin(x); y1 = sin(x);
y3 = 2*x + y1+y2; y3 = 2*x + y1+y2;
end when; end when;

when initial() then


... // Equations to be activated at the beginning of a simulation
end when;
...
when terminal() then
... // Equations to be activated at the end of a simulation
end when;

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Restrictions on when-equations
Form restriction Modelica restricts the allowed equations
model WhenNotValid
within a when-equation to: variable =
Real x, y; expression, if-equations, for-equations,...
equation
x + y = 5
5; In the WhenNotValid model when the
when sample(0,2) then equations within the when-equation are
2*x + y = 7;
not active it is not clear which variable,
// Error: not valid Modelica
end when; either x or y, that is a “result” from the
end WhenNotValid;
when-equation to keep constant outside
the when-equation.
A corrected version appears in the class WhenValidResult below
model WhenValidResult
Real x,y;
equation
x + y = 5; // Equation to be used to compute x.
when sample(0,2) then
y = 7 - 2*x; // Correct, y is a result variable from the when!
end when;
end WhenValidResult;

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

when-equations cannot be nested!

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Restrictions on when-equations cont’

Single assignment rule: same variable may not be


defined in several when-equations.
A conflict
fli t b
between
t th
the equations
ti will
ill occur if b
both
th
conditions would become true at the same time instant
model DoubleWhenConflict
Boolean close; // Error: close defined by two equations!
equation
...
when condition1 then
close = true; // First equation
end
d when;
h
...
when condition2 then
close = false; //Second equation
end when;
end DoubleWhenConflict

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Restrictions on when-equations cont’
Solution to assignment conflict between equations in
independent when-equations:
• Use elsewhen to give higher priority to the first when-equation
when equation

model DoubleWhenConflictResolved
Boolean close;
equation
...
when condition1 then
close = true; // First equation has higher priority!
elsewhen
l h condition2
di i 2 then
th
close = false; //Second equation
end when;
end DoubleWhenConflictResolved

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Restrictions on when-equations cont’


Vector expressions
The equations within a when-equation are activated when
any of the elements of the vector expression becomes true

model VectorWhen
Boolean close;
equation
...
when {condition1,condition2} then
close = true;
end when;
end DoubleWhenConflict

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
assert-equations
assert(assert-expression, message-string)

assert is a predefined function for giving error messages


taking a Boolean condition and a string as an argument

The intention behind assert is to provide a convenient


means for specifying checks on model validity within a model

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;

19 Peter Fritzson Copyright © Open Source Modelica Consortium 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 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

10
Algorithms and Functions

1 Peter Fritzson Copyright © Open Source Modelica Consortium 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>
equation
x = y*2;
z = w;
Algorithm sections can be embedded algorithm
among equation sections x1 := z+x;
x2 := y-5;
x1 := x2+y;
equation
u = x1+x2;
...

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

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

Examples of for-loop headers with different range expressions


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

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Iterations Using while


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

class SumSeries
parameter Real eps = 1.E-6;
The example class SumSeries
Integer i; shows the while-loop construct
Real sum; used for summing a series of
Real delta;
algorithm exponential terms until the loop
i := 1; condition is violated , i.e., the
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;

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

when-statements
when <conditions> then when-statements are used to express
<statements>
elsewhen <conditions> then actions (statements) that are only
<statements>
end when;
executed at events, e.g. at discontinuities
or when
h certaini conditions
di i b
become true
when x > 2 then
There are situations where several y1 := sin(x);
assignment statements within the y3 := 2*x + y1 + y2;
end when;
same when-statement is convenient
algorithm when {x > 2, sample(0,2), x < 5} then
when x > 2 then y1 := sin(x);
y1 := sin(x); y3 := 2*x + y
y y1 + y
y2;
;
end when; end when;
equation
y2 = sin(y1);
algorithm Algorithm and equation sections can
when x > 2 then
y3 := 2*x + y1 + y2; be interleaved.
end when;

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Function Declaration

The structure of a typical function declaration is as follows:


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

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Function Call
Two basic forms of arguments in Modelica function calls:
• Positional association of actual arguments to formal parameters
• Named association of actual arguments to formal parameters

Example function called on next page:


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

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

The same call to the function polynomialEvaluator can instead be


made using named association of actual parameters to formal
parameters.
...
algorithm
...
p:= polynomialEvaluator(A={1,2,3,4},x=21)

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

Any kind of variable of compatible type is allowed in the parenthesized list


on the left hand side, e.g. even array elements:
(arr[1],arr[2]) := PointOnCircle(1.2, 2);

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
External Functions
It is possible to call functions defined outside the Modelica
language, implemented in C or FORTRAN 77
function polynomialMultiply The body of an
input Real a[:], b[:]; external
t l function
f ti isi
output Real c[:] := zeros(size(a,1)+size(b, 1) - 1);
external marked with the
end polynomialMultiply; keyword
external
If no language is specified, the implementation language for the external
function is assumed to be C. The external function polynomialMultiply
can also be specified, e.g. via a mapping to a FORTRAN 77 function:

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

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Packages

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Packages for Avoiding Name Collisions


• Modelica provide a safe and systematic way of avoiding
name collisions through the package concept
• Ap package
g is simply
p y a container or name space
p for
names of classes, functions, constants and other
allowed definitions

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Packages as Abstract Data Type:
Data and Operations in the Same Place
Keywords
encapsulated package ComplexNumber
denoting a Usage of the
package
record Complex ComplexNumber
Real re;
encapsulated Real im;
package
makes
k end
d Complex;
C l
package class ComplexUser
dependencies function add ComplexNumbers.Complex a(re=1.0, im=2.0);
(i.e., imports) input Complex x,y; ComplexNumbers.Complex b(re=1.0, im=2.0);
explicit output Complex z; ComplexNumbers.Complex z,w;
algorithm equation
z.re := x.re + y.re; z = ComplexNumbers.multiply(a,b);
z.im := x.im + y.im w = ComplexNumbers.add(a,b);
end add; end ComplexUser

function multiply
input
p Complex
p x,y;
y The type
yp Complex
p and the
output Complex z;
Declarations of algorithm operations multiply and add
substract,
divide,
z.re := x.re*y.re – x.im*y.im; are referenced by prefixing
z.im := x.re*y.im + x.im*y.re;
realPart,
imaginaryPart,
end multiply; them with the package name
etc are not shown ………………………………………………………. ComplexNumber
here end ComplexMumbers

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Accessing Definitions in Packages


• Access reference by prefixing the package name to definition names
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

• Shorter access names (e.g. Complex, multiply) can be used if


definitions are first imported from a package (see next page).

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
Importing Definitions from Packages
• Qualified import import <packagename>
• Single definition import import <packagename> . <definitionname>
• Unqualified import import <packagename> . *
• Renaming import import <shortpackagename> = <packagename>

The four forms of import are exemplified below assuming


that we want to access the addition operation (add) of the
package Modelica.Math.ComplexNumbers

import Modelica.Math.ComplexNumbers; //Access as ComplexNumbers.add


import Modelica.Math.ComplexNumbers.add; //Access as add
import Modelica.Math.ComplexNumbers.* //Access as add
import Co = Modelica.Math.ComplexNumbers //Access as Co.add

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Qualified Import
Qualified import import <packagename>

The qualified import statement


import <packagename>;
imports all definitions in a package,
package which subsequently can be
referred to by (usually shorter) names
simplepackagename . definitionname, where the simple
package name is the packagename without its prefix.

encapsulated package ComplexUser1


import Modelica.Math.ComplexNumbers;
class User
This is the most common
ComplexNumbers.Complex a(x=1.0, y=2.0); form of import that
ComplexNumbers Complex b(x=1
ComplexNumbers.Complex b(x=1.0,
0 y=2
y=2.0);
0);
ComplexNumbers.Complex z,w;
eliminates
li i t th the risk
i k ffor
equation name collisions when
z = ComplexNumbers.multiply(a,b);
w = ComplexNumbers.add(a,b); importing from several
end User; packages
end ComplexUser1;

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Single Definition Import
Single definition import import <packagename> . <definitionname>

The single definition import of the form


import
p <packagename>.<definitionname>;
p g
allows us to import a single specific definition (a constant or class but
not a subpackage) from a package and use that definition referred to
by its definitionname without the package prefix
encapsulated package ComplexUser2
import ComplexNumbers.Complex;
import ComplexNumbers.multiply;
import ComplexNumbers.add;
class User There is no risk for name
Complex a(x=1.0, y=2.0); collision as long
g as we
Complex b(x=1.0, y=2.0);
Complex z,w; do not try to import two
equation definitions with the same
z = multiply(a,b);
w = add(a,b); short name
end User;
end ComplexUser2;

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Unqualified Import
Unqualified import import <packagename> . *

The unqualified import statement of the form


import packagename.
packagename.*; ;
imports all definitions from the package using their short names without
qualification prefixes.
Danger: Can give rise to name collisions if imported package is changed.

class ComplexUser3
import ComplexNumbers.*;
Complex a(x=1.0, y=2.0);
This example also shows
Complex b(x=1.0, y=2.0); direct import into a class
Complex zz,w;
w;
equation i t d off into
instead i t an enclosing
l i
z = multiply(a,b); package
w = add(a,b);
end ComplexUser3;

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
Renaming Import
Renaming import import <shortpackagename> = <packagename>

The renaming import statement of the form:


import <shortpackagename> = <packagename>;
imports a package and renames it locally to shortpackagename.
One can refer to imported definitions using shortpackagename as
a presumably shorter package prefix.

class ComplexUser4
import Co = ComplexNumbers;
Co.Complex a(x=1.0, y=2.0); This is as safe as qualified
Co.Complex
p b(x=1.0, y
y=2.0); import but gives more
Co.Complex z,w;
equation concise code
z = Co.multiply(a,b);
w = Co.add(a,b);
end ComplexUser4;

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Package and Library Structuring


A well-designed package structure is one of the most
important aspects that influences the complexity,
understandability, and maintainability of large software
systems.
t There
Th are many factors
f t to
t consider
id when
h
designing a package, e.g.:

• The name of the package.

• Structuring of the package into subpackages.

• Reusability and encapsulation of the package.

• Dependencies on other packages.

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Subpackages and Hierarchical Libraries

The main use for Modelica packages and subpackages is to structure


hierarchical model libraries, of which the standard Modelica library is a
good example.

encapsulated package Modelica // Modelica


encapsulated package Mechanics // Modelica.Mechanics
encapsulated package Rotational // Modelica.Mechanics.Rotational
model Inertia // Modelica.Mechanics.Rotational.Inertia
...
end Inertia;
model Torque // Modelica.Mechanics.Rotational.Torque
...
end Torque;
...
end Rotational;
...
end Mechanics;
...
end Modelica;

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Ecapsulated Packages and Classes


An encapsulated package or class prevents direct reference to public
definitions outside itself, but as usual allows access to public subpackages
and classes inside itself.

• Dependencies on other packages become explicit


– more readable and understandable models!
• Used packages from outside must be imported.

encapsulated model TorqueUserExample1


import Modelica.Mechanics.Rotational; // Import package Rotational
Rotational.Torque t2; // Use Torque, OK!
Modelica.Mechanics.Rotational.Inertia w2;
//Error! No direct reference to the top-level
top level Modelica package
... // to outside an encapsulated class
end TorqueUserExample1;

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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.

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Mapping a Package Hierachy into a Directory


Hirarchy

A Modelica package hierarchy can be mapped into a


corresponding directory hierarchy in the file system

C:\library Modelica
\Modelica
package.mo
\Blocks
package.mo
Continuous.mo Mechanics
Blocks
Interfaces.mo
\Examples
package.mo
Example1.mo
\M h i
\Mechanics ...
Rotational
i l
package.mo
Rotational.mo Examples
... Continuous Interfaces
Example1

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Modelica Libraries

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica Standard Library

Modelica Standard Library (called Modelica) is a


standardized predefined package developed by Modelica
Association

It can be used freely for both commercial and noncommercial


purposes under the conditions of The Modelica License.

Modelica libraries are available online including documentation


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

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica.Blocks

Continuous, discrete, and logical input/output blocks


to build block diagrams.

Library

Continuous

Examples:

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
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 g
gravitation";
;

constant Real h(final unit="J.s") = 6.62606876e-34 "Planck constant";

constant Modelica.SIunits.CelsiusTemperature T_zero=-273.15 "Absolute


zero temperature”;

5 Peter Fritzson Copyright © Open Source Modelica Consortium 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 Gnd6 C4
R1 Transistor1 Transistor2 R3

V1 C1 I1 C5 C3 Gnd4

Gnd1 Gnd2 Gnd7 Gnd8 Gnd5

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Modelica.Icons

Package with icons that can be reused in other libraries

Examples:

Library

Info Library Example

Info Library1 Library2 Example

RotationalSensor TranslationalSensor GearIcon MotorIcon

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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)
h( ) h
hyperbolic
b li cosine
i
tanh(u) hyperbolic tangent
exp(u) exponential, base e
log(u) natural (base e) logarithm (u  0)
log10(u) base 10 logarithm (u  0)

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
Modelica.Mechanics

Package containing components for mechanical systems


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

9 Peter Fritzson Copyright © Open Source Modelica Consortium 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”.

A subpackage called NonSIunits is available containing non


SI units such as Pressure_bar, Angle_deg, etc

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Modelica.Stategraph

Hierarchical state machines (similar to Statecharts)

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modelica.Thermal

Subpackage FluidHeatFlow with components for heat flow


modeling.

Sub
S b package
k HeatTransfer f with ith components
t to
t model
d l11-
dimensional heat transfer with lumped elements

Example:

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
ModelicaAdditions Library (OLD)

ModelicaAdditions library contains additional Modelica


libraries from DLR. This has been largely replaced by the new
release of the Modelica 33.1
1 libraries
libraries.
Sublibraries:
• Blocks Input/output block sublibrary
• HeatFlow1D 1-dimensional heat flow (replaced by Modelica.Thermal)
• Multibody Modelica library to model 3D mechanical systems
• PetriNets Libraryy to model Petri nets and state transition diagrams
g
• Tables Components to interpolate linearly in tables

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

ModelicaAdditions.Multibody (OLD)

This is a Modelica library to model 3D Mechanical systems


including visualization
New version
N i hhas b
been released
l d ((march
h 2004) th
thatt iis called
ll d
Modelica.Mechanics.MultiBody in the standard library
Improvements:
• Easier to use
• Automatic handling of kinematic loops.
• Built-in animation properties for all components

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

7
MultiBody (MBS) - Example Kinematic Loop

Old library New library


(cutjoint needed) (no cutjoint needed)

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

MultiBody (MBS) - Example Animations

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
ModelicaAdditions.PetriNets

This package contains components to model Petri nets


Used for modeling of computer hardware, software, assembly
li
lines, etc
t

Transition

Place

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Other Free Libraries

• WasteWater Wastewater treatment plants, 2003


• ATPlus Building simulation and control (fuzzy control included), 2005
• MotorCycleDymanics Dynamics and control of motorcycles, 2009
• N
NeuralNetwork
lN k N
Neural l network
k mathematical
h i l models,
d l 2006
• VehicleDynamics Dynamics of vehicle chassis (obsolete), 2003
• SPICElib Some capabilities of electric circuit simulator PSPICE, 2003
• SystemDynamics System dynamics modeling a la J. Forrester, 2007
• BondLib Bond graph modeling of physical systems, 2007
• MultiBondLib Multi bond graph modeling of physical systems, 2007
• ModelicaDEVS DEVS discrete event modeling, 2006
• ExtendedPetriNets Petri net modeling
modeling, 2002
• External.Media Library External fluid property computation, 2008
• VirtualLabBuilder Implementation of virtual labs, 2007
• SPOT Power systems in transient and steady-state mode, 2007
• ...

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
Power System Stability - SPOT

The SPOT package is a Modelica Library for Power Systems


Voltage and Transient stability simulations

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Thermo-hydraulics Library – ThermoFluid


Thermo-
Replaced by the New Fluid/Media Library

ThermoFluid is a Modelica base library for thermo-hydraulic


models
• IIncludes
l d models
d l th
thatt d
describe
ib th
the b
basic
i physics
h i off flflows off flfluid
id and
d
heat, medium property models for water, gases and some
refrigerants, and also simple components for system modeling.

• Handles static and dynamic momentum balances

• Robust against backwards and


zero flow

• The discretization method is


a first-order, finite volume
method (staggered grid).

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

10
Vehicle Dynamics Library – VehicleDynamics
There is a Greatly Extended Commercial Version

This library is used to model vehicle chassis

21 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Some Commercial Libraries

• Powertrain
• SmartElectricDrives
• VehicleDynamics
• AirConditioning
• HyLib
• PneuLib
• CombiPlant
• HydroPlant
• …

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

11
Hydraulics Library HyLib
• Licensed Modelica package developed
originally by Peter Beater
• More than 90 models for Pumps

• Pumps

• Motors and cylinders


• Restrictions and valves
• Hydraulic lines Cylinders
• Lumped volumes and sensors
• Models can be connected in an
arbitrary way, e.g. in series or in parallel.
•HyLibLight is a free subset of Valves
HyLib
• More info: www.hylib.com
23 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

HyLib - Example

Hydraulic drive system with closed circuit

24 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

12
Pneumatics Library PneuLib
•Licensed Modelica package
developed by Peter Beater
Directional valves
•More than 80 models for
• Cylinders

• Motors
• Valves and nozzles
Flow control valves
• Lumped volumes
• Lines and sensors
• Models can be connected in an arbitrary
way, e.g. in series or in parallel.
•PneuLibLight is a free subset of Cylinders
HyLib.
• More info: www.pneulib.com

25 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

PneuLib - Example

Pneumatic circuit with multi-position cylinder, booster and


different valves

26 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

13
Powertrain Library - Powertrain

• Licensed Modelica package


developed by DLR
• Speed and torque dependent
friction
• Bus concept
• Control units
• Animation

27 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Some Modelica Applications

28 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

14
Example Fighter Aircraft Library

Custom made library, Aircraft*, for fighter aircraft


applications

• Six degrees of freedom (6 DOF)


• Dynamic calculation of center of
gravity (CoG)
• Use of Aerodynamic tables or
mechanical rudders

*Property of FOI (The Swedish


Defence Institute)

29 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Aircraft with Controller

• Simple PID
• Controls alpha and height

30 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

15
Example Aircraft Animation

Animation of fighter aircraft with controller

31 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Example Gas Turbine

42 MW gas turbine (GTX 100) from Siemens Industrial


Turbomachinery AB, Finspång, Sweden
Fuel

Compressed air Combustion Exhaust gas


chamber

Power output

Air Exhaust
C
Compressor T bi
Turbine

Courtesy Siemens Industrial Turbines AB

32 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

16
Example Gas Turbine

33 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Example Gas Turbine – Load Rejection


Rotational speed (rpm) of the compressor shaft

Load rejection

Generator Switch pilot


to main fuel

34 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

17
Example Gas Turbine – Load Rejection

Percentage of fuel valve opening Generated power to the simulated


(red = pilot, blue = main) electrical grid

35 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

18
Discrete Events and Hybrid Systems

Picture: Courtesy Hilding Elmqvist

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Events

Events are ordered in time and form an event history

time
event 1 event 2 event 3

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


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

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Hybrid Modeling
Hybrid modeling = continuous-time + discrete-time modeling

Continuous-time Real x;
Voltage v;
Current i;

Discrete-time
discrete Real x;
Integer i;
Boolean b;
time
Events
• A point in time that is instantaneous, i.e., has zero duration
• A eventt condition
An diti so that
th t the
th eventt can take
t k place
l
• A set of variables that are associated with the event
• Some behavior associated with the event,
e.g. conditional equations that become active or are deactivated at
the event

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Event creation – if

if-equations, if-statements, and if-expressions

if <condition> then model Diode "Ideal diode"


<equations> extends TwoPin;
R l s;
Real
False
a se if s
s<0
0
elseif <condition> then
<equations> Boolean off;
else equation If-equation choosing
<equations> off = s < 0;
if off then
equation for v
end if;
v=s
else
v=0; If-expression
end if;
i = if off then 0 else s;
end Diode;

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
Event creation – when

when-equations
when <conditions> then
<equations> time
end when; event 1 event 2 event 3

Equations only active at event times

Time event State event


when time >= 10.0 then
when sin(x) > 0.5 then
...
...
end when;
end when;

Only dependent on time, can be Related to a state. Check for


scheduled in advance zero-crossing

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Generating Repeated Events

sample(t0,d)
The call sample(t0,d) returns
true and triggers events at times true
t0+i*d where i=0,1,
t0+i*d, i 0 1 …
false time
t0 t0+d t0+2d t0+3d t0+4d
Variables need to be
discrete
model SamplingClock Creates an event
Integer i;
discrete Real r;
after 2 s, then
equation each 0.5 s
when sample(2,0.5) then
i = pre(i)+1;
r = pre(r)+0.3;
end when;
end SamplingClock; pre(...) takes the
previous value
before the event.

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Reinit – Discontinuous Changes
The value of a continuous-time state variable can be instantaneously
changed by a reinit-equation within a when-equation

model BouncingBall "the bouncing ball model"


parameter Real g=9.81; //gravitational acc.
parameter Real c=0.90; //elasticity constant
Real height(start=10),velocity(start=0);
equation
der(height) = velocity;
der(velocity)=-g;
when height<0 then
reinit(velocity, -c*velocity);
end when;
end BouncingBall;

Initial conditions
Reinit ”assigns”
continuous-time variable
velocity a new value

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

initial and terminal events


Initialization actions are triggered by initial()

initial()

true

false time
event at start

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

t
terminal()
i l()

true

false time
event at end

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
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; Simulation ends before
terminate when y >5 then reaching time 10
terminate("The time has elapsed 5s");
end when;
end terminationMode;

simulate(terminationModel, startTime = 0, stopTime = 10)

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Expressing Event Behavior in Modelica

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


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

when-equations become active at events


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

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Event Priority
Erroneous multiple definitions, single assignment rule violated
model WhenConflictX // Erroneous model: two equations define x
discrete Real x;
equation
when
hen time>=2
ti > 2 then // Wh
When A
A: I
Increase x b
by 1
1.5
5 at
t ti
time=2
2
x = pre(x)+1.5;
end when;
when time>=1 then // When B: Increase x by 1 at time=1
x = pre(x)+1;
end when;
end WhenConflictX;

model WhenPriorityX
discrete Real x;
Using event priority equation
when time>=2 then // Higher priority
to avoid erroneous x = pre(x)+1.5;
elsewhen time>=1 then // Lower priority
multiple definitions x = pre(x)+1;
end when;
end WhenPriorityX;

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Obtaining Predecessor Values


of a Variable Using pre()
At an event, pre(y) gives the previous value of y immediately
before the event, except for event iteration of multiple events at
the same ppoint in time when the value is from the pprevious
iteration y y

pre(y)

time
event

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

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Detecting Changes of Boolean
Variables Using edge()and change()

Detecting changes of boolean variables using edge()


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

Detecting changes of discrete-time variables using change()


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

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Creating Time
Time--Delayed Expressions

Creating time-delayed expressions using delay()

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

start+d t1 t1+d t2 t2+d

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

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

t
2 4 6 8 10

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Discontinuous Changes to Variables at Events via


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

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

phi_dev step elastoBacklash


- b/2 b/2

ground

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

A finite state automaton


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

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

A Mode Switching Model Example cont’

partial model SimpleElastoBacklash


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

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
A Mode Switching Model Example cont’

1 elastoBacklash.w_rel

0.75 Relative rotational speed between


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

-0.5

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

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Water Tank System with PI Controller


model TankPI
TankPI LiquidSource source(flowLevel=0.02);
qIn qOut Tank tank(area=1);
source
tank PIcontinuousController piContinuous(ref=0.25);
equation
tSensor tActuator
connect(source qOut, tank
connect(source.qOut, tank.qIn);
qIn);
connect(tank.tActuator, piContinuous.cOut);
piContinuous connect(tank.tSensor, piContinuous.cIn);
cIn cOut
end TankPI;

maxLevel levelSensor model Tank


out in
ReadSignal tOut; // Connector, reading tank level
level
tank ActSignal tInp; // Connector, actuator controlling input flow
pump
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;

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

model PIDcontinuousController model PIdiscreteController


extends BaseController(K = 2, T = 10); extends BaseController(K = 2, T = 10);
Real x; discrete Real x;
Real y; equation
equation when sample(0, Ts) then
der(x) = error/T; x = pre(x) + error * Ts / T;
y = T*der(error); outCtr = K * (x+error);
outCtr = K*(error + x + y); end when;
end PIDcontinuousController; end PIdiscreteController;

21 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Concurrency and Resource Sharing

Dining Philosophers Example

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

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

11
Biological Models
Population Dynamics
Predator--Prey
Predator

1 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Some Well-
Well-known Population Dynamics
Applications

• Population Dynamics of Single Population

• Predator-Prey Models (e.g. Foxes and Rabbits)

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Population Dynamics of Single Population
• P – population size = number of individuals in a population
• P – population change rate, change per time unit
• g – growth factor of population (e
(e.g.
g % births per year)
• d – death factor of population (e.g. % deaths per year)

growthrate  g  P
Exponentially increasing
deathrate  d  P population if (g-d)>0

P  growthrate  deathrate Exponentially decreasing


population if (g-d)<0
P  ( g  d )  P

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Population Dynamics Model


• g – growth rate of population
• d – death rate of population
• P – population size

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;

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Population Growth Exercise!!


• Locate the PopulationGrowth model in DrModelica
• Change the initial population size and growth and
death factors to g
get an exponentially
p y decreasing
g
population
simulate(PopulationGrowth, stopTime=100) Exponentially decreasing
plot(P)
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;

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Population Dynamics with both Predators
and Prey Populations

• Predator-Prey models

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Predator--Prey (Foxes and Rabbits) Model


Predator
• R = rabbits = size of rabbit population
• F = foxes = size of fox population
• R = der(rabbits) = change rate of rabbit population
• F = der(foxes) = change rate of fox population
• gr = g_r = growth factor of rabbits
• df = d_f = death factor of foxes
• drf = d_rf = death factor of rabbits due to foxes
• gfr = g_rf
g rf = growth factor of foxes due to rabbits and foxes
R  g r  R  d rf  F  R F  g fr  d rf  R  F  d f  F
der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes;
der(foxes) = g_fr*d_rf*rabbits*foxes - d_f*foxes;

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
Predator--Prey (Foxes and Rabbits) Model
Predator

class LotkaVolterra
parameter Real g_r =0.04 "Natural growth rate for rabbits";
parameter Real d_rf=0.0005 "Death rate of rabbits due to foxes";
parameter Real d_f =0.09 "Natural deathrate for foxes";
parameter Real g_fr=0.1 "Efficency in growing foxes from rabbits";
Real rabbits(start=700) "Rabbits,(R) with start population 700";
Real foxes(start=10) "Foxes,(F) with start population 10";
equation
der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes;
der(foxes) = g
g_fr*d_rf*rabbits*foxes
fr*d rf*rabbits*foxes - d_f*foxes;
d f*foxes;
end LotkaVolterra;

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Simulation of Predator-
Predator-Prey (LotkaVolterra)

simulate(LotkaVolterra, stopTime=3000)
plot({rabbits, foxes}, xrange={0,1000})

rabbits

foxes

5000

4000

3000

2000

1000

t
200 400 600 800 1000

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Exercise of Predator-
Predator-Prey
• Locate the LotkaVolterra model in DrModelica
• Change the death and growth rates for foxes and
rabbits, simulate, and observe the effects
simulate(LotkaVolterra, stopTime=3000)
plot({rabbits, foxes}, xrange={0,1000})

class LotkaVolterra
parameter Real g_r =0.04 "Natural growth rate for rabbits";
parameter Real d_rf=0.0005 "Death rate of rabbits due to foxes";
parameter Real d_f =0.09 "Natural deathrate for foxes";
parameter Real g
g_fr
fr=0
0.1
1 "Efficency
Efficency in growing foxes from rabbits";
rabbits ;
Real rabbits(start=700) "Rabbits,(R) with start population 700";
Real foxes(start=10) "Foxes,(F) with start population 10";
equation
der(rabbits) = g_r*rabbits - d_rf*rabbits*foxes;
der(foxes) = g_fr*d_rf*rabbits*foxes - d_f*foxes;
end LotkaVolterra;

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Model Design

1 Peter Fritzson Copyright © Open Source Modelica Consortium 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

2 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

1
Modeling Approach 1

T diti
Traditional
l state
t t space approach
h

3 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Traditional State Space Approach

• Basic structuring in terms of subsystems and


variables

• Stating equations and formulas

• Converting the model to state space form:


x (t )  f ( x (t ), u (t ))
y (t )  g ( x (t ), u (t ))

4 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

2
Difficulties in State Space Approach

• The system decomposition does not


correspond
p to the "natural" p
physical
y system
y
structure

• Breaking down into subsystems is difficult if


the connections are not of input/output type.

• Two connected state-space subsystems do


not usually give a state-space system
automatically.

5 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modeling Approach 2

Traditional signal-style block-oriented approach

6 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

3
Physical Modeling Style (e.g Modelica) vs
signal flow Block-
Block-Oriented Style (e.g. Simulink)

Modelica: Block-oriented:
Physical model – easy to Signal-flow model – hard to
understand understand for physical systems

Res2 sum3 Ind l2


p p -1 1
R2 1/L
1 s

R1=10 R2=100
sum2
p
n n +1
+1
AC=220

p p sinln sum1 Res1 Cap l1


n +1 1
1/R1 1/C
-1 s
C=0 01
C=0.01 L=0 1
L=0.1

n n

p
G

7 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Traditional Block Diagram Modeling


• Special case of model components:
the causality of each interface variable
has been fixed to either input or output

Typical Block diagram model components:


x
+
 -
y
f(x,y)

Integrator Adder Multiplier Function


Branch Point

Simulink is a common block diagram tool

8 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

4
Physical Modeling Style (e.g Modelica) vs
signal flow Block-
Block-Oriented Style (e.g. Simulink)

Modelica: Block-oriented:
Physical model – easy to Signal-flow model – hard to
understand understand for physical systems

Res2 sum3 Ind l2


p p -1 1
R2 1/L
1 s

R1=10 R2=100
sum2
p
n n +1
+1
AC=220

p p sinln sum1 Res1 Cap l1


n +1 1
1/R1 1/C
-1 s
C=0 01
C=0.01 L=0 1
L=0.1

n n

p
G

9 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Example Block Diagram Models


Electric
k1 / k 2 - i
+
-
1/ L 

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

10 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

5
Properties of Block Diagram Modeling

• - The system decomposition topology does not


correspond to the "natural" physical system structure
• - Hard work of manual conversion of equations into
signal-flow representation
• - Physical models become hard to understand in signal
representation
• - Small model changes (e.g. compute positions from
force instead of force from positions) requires redesign of
whole model
• + Block diagram modeling works well for control systems
since they are signal-oriented rather than "physical"

11 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Object--Oriented Modeling Variants


Object

• Approach 3: Object
Object-oriented
oriented approach based on
finished library component models
• Approach 4: Object-oriented flat model approach
• Approach 5: Object-oriented approach with
design of library model components

12 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

6
Object-Oriented Component
Object- Component--Based
Approaches in General

• Define the system briefly


• What kind of system is it?
• What does it do?

• Decompose the system into its most important


components
• Define communication, i.e., determine interactions
• Define interfaces, i.e., determine the external ports/connectors
• Recursivelyy decompose
p model components
p of “high
g complexity”
p y

• Formulate new model classes when needed


• Declare new model classes.
• Declare possible base classes for increased reuse and maintainability

13 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Top--Down versus Bottom


Top Bottom--up Modeling

• Top Down: Start designing the overall view.


Determine what components are needed.
needed

• Bottom-Up: Start designing the components


and try to fit them together later.

14 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

7
Approach 3: Top-
Top-Down Object
Object--oriented
approach using library model components

• Decompose into subsystems


• Sketch communication
• Design subsystems models by connecting
library component models
• Simulate!

15 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Decompose into Subsystems and Sketch


Communication – DC
DC--Motor Servo Example

Electrical Rotational
Controller Circuit Mechanics

The DC-Motor servo subsystems and their connections

16 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

8
Modeling the Controller Subsystem

Electrical Rotational
Controller Circuit Mechanics

feedback1

- PI
step1 PI1

Modeling the controller

17 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Modeling the Electrical Subsystem

Electrical Rotational
Controller Circuit Mechanics

resistor1 inductor1

EMF1
signalVoltage1

ground1

Modeling the electric circuit

18 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

9
Modeling the Mechanical Subsystem
Electrical Rotational
Controller Circuit Mechanics

inertia1 idealGear1 inertia2 spring1 inertia3

speedSensor1

Modeling the mechanical subsystem including the speed sensor.

19 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Object--Oriented Modeling from Scratch


Object

• Approach 4: Object
Object-oriented
oriented flat model approach
• Approach 5: Object-oriented approach with
design of library model components

20 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

10
Example: OO Modeling of a Tank System

source
levelSensor controller
maxLevel out in
level h tank valve

• The system is naturally


decomposed into components

21 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Object--Oriented Modeling
Object

Approach 4: Object-oriented flat model design

22 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

11
Tank System Model FlatTank – No Graphical
Structure
model FlatTank
• No component // Tank related variables and parameters
structure parameter Real flowLevel(unit="m3/s")=0.02;
parameter Real area(unit="m2") =1;
parameter Real flowGain(unit="m2/s") =0.05;
• Just flat set of Real h(start=0
h(start=0,unit=
unit="m")
m ) "Tank
Tank level";
level ;
equations Real qInflow(unit="m3/s") "Flow through input valve";
Real qOutflow(unit="m3/s") "Flow through output valve";
// Controller related variables and parameters
• Straight- parameter Real K=2 "Gain";
parameter Real T(unit="s")= 10 "Time constant";
forward but parameter Real minV=0, maxV=10; // Limits for flow output
less flexible, Real ref = 0.25 "Reference level for control";
no graphical Real error "Deviation from reference level";
structure Real outCtr "Control signal without limiter";
Real x; "State variable for controller";
equation
assert(minV>=0,"minV must be greater or equal to zero");//
der(h) = (qInflow-qOutflow)/area; // Mass balance equation
qInflow = if time>150 then 3*flowLevel else flowLevel;
qOutflow = LimitValue(minV,maxV,-flowGain*outCtr);
error = ref-h;
der(x) = error/T;
outCtr = K*(error+x);
end FlatTank;

23 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Simulation of FlatTank System


• Flow increase to flowLevel at time 0
• Flow increase to 3*flowLevel at time 150
simulate(FlatTank, stopTime=250)
plot(h, stopTime=250)

0.4

0.3

0.2

0.1

time
50 100 150 200 250

24 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

12
Object--Oriented Modeling
Object

• Approach 5:
Object-oriented approach with design of
library model components

25 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Object Oriented Component-


Component-Based Approach
Tank System with Three Components
• Liquid source TankPI
qIn qOut
• Continuous PI source
tank
controller tS
tSensor tA t t
tActuator

• Tank cIn
piContinuous
cOut

model TankPI
LiquidSource source(flowLevel=0.02);
PIcontinuousController piContinuous(ref=0.25);
T k
Tank t
tank(area=1);
k( 1)
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, piContinuous.cOut);
connect(tank.tSensor, piContinuous.cIn);
end TankPI;

26 Peter Fritzson Copyright © Open Source Modelica Consortium 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
Connector, sensor reading tank level (m)";
(m) ;
ActSignal tActuator "Connector, actuator controlling input flow";
LiquidFlow qIn "Connector, flow (m3/s) through input valve";
LiquidFlow qOut "Connector, flow (m3/s) through output valve";
parameter Real area(unit="m2") = 0.5;
parameter Real flowGain(unit="m2/s") = 0.05;
parameter Real minV=0, maxV=10; // Limits for output valve flow
Real h(start=0.0, unit="m") "Tank level";
equation
assert(minV>=0,"minV
( , – minimum Valve level must be >= 0 ");//
)
der(h) = (qIn.lflow-qOut.lflow)/area; // Mass balance
equation
qOut.lflow = LimitValue(minV,maxV,-flowGain*tActuator.act);
tSensor.val = h;
end Tank;

27 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Connector Classes and Liquid Source Model


for Tank System
connector ReadSignal "Reading fluid level"
Real val(unit="m"); TankPI
end ReadSignal; qIn qOut
source
tank
connector ActSignal "Signal to actuator tSensor tActuator

for setting valve position"


piContinuous
Real act; cIn cOut

end ActSignal;

connector LiquidFlow "Liquid flow at inlets or outlets"


Real lflow(unit="m3/s");
end LiquidFlow;

model LiquidSource
LiquidFlow qOut;
parameter flowLevel = 0.02;
equation
qOut.lflow = if time>150 then 3*flowLevel else flowLevel;
end LiquidSource;

28 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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;

29 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

The Base Controller – A Partial Model


partial model BaseController
parameter Real Ts(unit="s")=0.1
"Ts - Time period between discrete samples – discrete sampled";
parameter Real K=2
K 2 "Gain";
Gain ;
parameter Real T=10(unit="s") "Time constant - continuous";
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; TankPI
end BaseController; qIn qOut
source
tank
tSensor tActuator

error = difference betwen reference level and


piContinuous
actual tank level from cIn connector cIn cOut

30 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

15
Simulate Component-
Component-Based Tank System
• As expected (same equations), TankPI gives the
same result as the flat model FlatTank

simulate(TankPI, stopTime=250)
plot(h, stopTime=250)

0.4

0.3

0.2

0.1

time
50 100 150 200 250

31 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Flexibility of Component
Component--Based Models

g of components
• Exchange p p
possible in a
component-based model

• Example:
Exchange the PI controller component for a PID
controller component
p

32 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

16
Tank System with Continuous PID Controller
Instead of Continuous PI Controller
• Liquid source TankPID

• Continuous PID source


qIn
tank
qOut

controller tSensor tActuator

• Tank cIn
pidContinuous
cOut

model TankPID
LiquidSource source(flowLevel=0.02);
PIDcontinuousController pidContinuous(ref=0.25);
T k
Tank t
tank(area=1);
k( 1)
equation
connect(source.qOut, tank.qIn);
connect(tank.tActuator, pidContinuous.cOut);
connect(tank.tSensor, pidContinuous.cIn);
end TankPID;

33 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Continuous PID Controller


dx error
• error = (reference level – 
dt T
actual tank level) y T
d error
dt
• T is a time constant C  K * (error  x  y )
outCtr
• x, y are controller state Integrating equations gives Proportional
variables & Integrative & Derivative(PID)

 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;

34 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

35 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Two Tanks Connected Together


• Flexibility of component-based models allows connecting models together
TanksConnectedPI
qIn
q qOut
q qIn
q qOut
q
so rce
source
tank1 tank2
tSensor tActuator tSensor tActuator

piContinuous piContinuous
cIn cOut cIn cOut

model TanksConnectedPI
LiquidSource source(flowLevel=0.02);
Tank tank1(area=1), tank2(area=1.3);;
PIcontinuousController p
piContinuous1(ref=0.25),
( ), p
piContinuous2(ref=0.4);
( );
equation
connect(source.qOut,tank1.qIn);
connect(tank1.tActuator,piContinuous1.cOut);
connect(tank1.tSensor,piContinuous1.cIn);
connect(tank1.qOut,tank2.qIn);
connect(tank2.tActuator,piContinuous2.cOut);
connect(tank2.tSensor,piContinuous2.cIn);
end TanksConnectedPI;

36 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

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

37 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Exchange: Either PI Continous or PI Discrete


Controller
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;

model PIDcontinuousController model PIdiscreteController


extends BaseController(K = 2, T = 10); extends BaseController(K = 2, T = 10);
Real x; discrete Real x;
Real y; equation
equation when sample(0, Ts) then
der(x) = error/T; x = pre(x) + error * Ts / T;
y = T*der(error); outCtr = K * (x+error);
outCtr = K*(error + x + y); end when;
end PIDcontinuousController; end PIdiscreteController;

38 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

19
Exercises

• Replace the PIcontinuous controller by the


PIdiscrete controller and simulate. (see also the
book page 461)
book,
• Create a tank system of 3 connected tanks and
simulate.

39 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

Principles for Designing Interfaces – i.e.,


Connector Classes
• Should be easy and natural to connect components
• For interfaces to models of physical components it must be physically
possible to connect those components
• Component interfaces to facilitate reuse of existing
model components in class libraries
• Identify kind of interaction
• If there is interaction between two physical components involving energy
flow, a combination of one potential and one flow variable in the appropriate
domain should be used for the connector class
• If information or signals are exchanged between components,
components input/output
signal variables should be used in the connector class
• Use composite connector classes if several
variables are needed

40 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

20
Simplification of Models

• When need to simplify models?


• When parts of the model are too complex
• Too time-consuming g simulations
• Numerical instabilities
• Difficulties in interpreting results due to too many low-level model details

• Simplification approaches
• Neglect small effects that are not important for the phenomena to be
modeled
• Aggregate state variables into fewer variables
• Approximate
A i t subsystems
b t with
ith very slow
l d
dynamics
i withith constants
t t
• Approximate subsystems with very fast dynamics with static
relationships, i.e. not involving time derivatives of those rapidly changing
state variables

41 Peter Fritzson Copyright © Open Source Modelica Consortium pelab

21
2010-10-19

An Introduction to Shakespeare
The Dynamics of Shakespearian Characters

Peter Bunus
Department of Computer and Information Science
SE 584-32 Linköping University, Sweden
{[email protected]}

Problem formulation

Romeo is in love with Julia

How to model such


complicated systems?

1
2010-10-19

A Mathematical Description of Romeo

dx
 ax  by where x is the Romeo love for Julia
dt
x>0

x = 0 Romeo doesn’t care about Julia

x < 0 Romeo hates Julia

a and b describes Romeo romantic style

Romeo’s Romantic Styles

 a=0 (out of touch with own feelings)


dx  b=0 (oblivious to other’s feelings)
 ax  by  a>0, b>0 (eager beaver)
dt  a>0, b<0 (narcissistic nerd)
 a<0, b>0 (cautious lover)
 a<0, b<0 (hermit)

2
2010-10-19

What about Julia?

She has her own style

ddy y>0
 cy  dx
dt y = 0 Julia doesn’t care about Romeo

y < 0 Julia hates Romeo

c and d describes Julia romantic style

Putting Romeo and Julia Together

3
2010-10-19

Putting Romeo and Julia Together – cont’

 dx
 dt  ax  by
The mathematician’s remark:

 dy  cx  dy
 dt
William Shakespeare needed 25 674
words and 1938 paragraphs to explain
this

4 parameters with 3 choices for each


gives 81 different romantic pairings

Love needs initial conditions

 dx
 dt  ax  by x[0]  0; y[0]  0

 dy  cx  dy
 dt
@
D
@
D
x t

y t

0.5

t
2 4 6 8 10

-0.5

-1

4
2010-10-19

Love Affair #1

Do opposites attract?
 Take c = -b and d = -a 1

 dx
0.5

 dt  ax  by 2 4 6 8 10


 dy  bx  ay
-0.5

 dt -1

• Romeo’s’ feelings
f li show
h thath he
h really
ll likes
lik Julia
li but
b as soon as
his affections are not met, he gets discouraged and cools down
• In the true spirit of a woman, Julia starts to like him as soon as
his attention fades

Love Affair #1 – Parametric Plot

0.5

-1 -0.5 0.5 1

-0.5

-1

5
2010-10-19

Love Affair #1 – cont’

Love Affair #2 - Romeo the Robot

 Take a = 0 , b = 0 x[0]=0
20000

 dx
 dt  0
15000


10000

 dy  cx  dy 5000

 dt 2 4 6 8 10

• Can
C beb either
i h love
l or hate
h depending
d di on the
h sign
i off y, c andd d.
d
• Romeo’s indifference drives Julia insane with passion
• Her feelings never dies

6
2010-10-19

Love Affair #3

 a = 0 , b = -1 1

 c = 1, d = 0 0.5

 dx 2 4 6 8 10

 dt  by -0.5


 dy  x
-1

 dt
• The same never ending cycle from Love affair #1
• At t=0 Julia likes Romeo and Romeo dislikes Julia
• Again their feelings oscillate, neither sure they love each other

Love Affair #4

 a = 2 , b = -2
8
6´10

 c = -1, d = 1 4´10 8

8
2´10

 dx
 dt  2 x  2 y
2 4 6 8 10
8
-2 ´10

 -4 ´10 8

 dy   x  y
8
-6 ´10

 dt
• During the first 7 years of knowledge R&J feel indifference to
each other
• At the same time R realizes his love for J, J realizes that he is
repulsed of him

7
2010-10-19

Love Affair #5

 a = 0 , b = -2 0.4

0.3
 c = 1, d = -1
0.2

 dx 0.1

 dt  2 y 2 4 6 8 10

 -0.1

 dy  x  y -0.2

 dt
-0.3

• Julia’s love for Romeo is out of control. We tried to help her by


damping her reactions with negative values of y. Unfortunately
the damping was contagious and sadly their feelings for each
other died.

Love Affair #6

Tybalt the damper

8
2010-10-19

Love Affair #5 -cont’

Love Affair #6

 dx
 dt  0.2( y  2)
3


2

 dy  0.8( x  2)
1

 dt 10 20 30 40 50

• Julia responds to Romeo’s love but when she becomes too


affectionate his love decreases

9
2010-10-19

Which Version was Chosen by Shakespeare?

 a=1,b=1

 c = 1, d = 1
7
1.75 ´10

1.5 ´10 7

 dx
1.25 ´10 7

 dt  ax  by
1´10 7

7.5 ´10 6

 5´10
6

 dy  cx  dy 2.5 ´10 6

 dt 2 4 6 8 10

Shakespeare’s Version

10
2010-10-19

Exchanging the Model

7
1.75 ´10

1.5 ´10 7 In this situation we need


1.25 ´10 7

1´10 7
to find another model
7.5 ´10 6

6
5´10

2.5 ´10 6

2 4 6 8 10
200
p
k=0.3

150

The Rabbit Population k=0.25

Growth Model 100

k=0.2

ddp 50

 kp
dt
t
2 4 6 8 10

p = number of individuals in a population at a time t


k = reproduction coefficient

What if ?

 Romeo has a mistress, Rowena

 Rowena and Julia don’t know about one


another
 Romeo responds to each with the same
romantic style (same a and b)

 Rowena’s hate has the same effect on his


feelings for Julia as does Julia’s love, and vice
versa

11
2010-10-19

Love Triangle Equations ?

dxJuliet
 axJuliet  b( y  z )
dt
dy
 cxJuliet  dy
dt
dxRowena
 axRowena  b( z  y )
dt
dz
 exRowena  fz
dt

 System is 4D (4 variables)
 There are 6 parameters
 System is linear (no chaos)

Romeo’s fate ?

 Averaged over all romantic styles (64 combinations of


parameters)) andd 64 initial
i i i l conditions:
di i
37% loves Julia & hates Rowena
37% loves Rowena & hates Julia
6% loves both (2% everyone in love)
6% hates both (2% everyone in hate)
14% apathy (10% everyone apathetic)
 Anything can happen!

12
2010-10-19

How about me ?

Since I’m happily married the previous model entered into a


stable state.
Step Response
1.6

1.4

num=1; 1.2
den=[1 5 10];
1
Kp=200;

Amplitude
0.8

[numCL,denCL]=cloop(Kp*num,den, -1); 0.6

t=0:0.01:6; 0.4
step(numCL,
t ( CL denCL,t)
d CL t)
0.2

0
-8 -6 -4 -2 0 2 4 6
Time (sec)

Let’s analyze my happiness instead

Happiness model ?

d2x dx
2
    2 x  F (t )
dt dt

Damping Oscillation External Force

dx
Happiness H 
dt

13
2010-10-19

What is x ?

d2x dx
2
    2
x  F (t )
d
dt d
dt

 x = integral of H
 x is what others perceive
 In the love model x is what the other feels
 H (your happiness) must average to zero (with positive
damping)
 x does not average to zero

Winning the lottery ?

14
2010-10-19

Drug or Other Addiction ?

Random Events ?

15
2010-10-19

Real Life ?

Some implications

 Constant
C t t happiness
h i is
i an unrealistic
li ti goal.
l
 Others see less volatility in you and often
wrongly conclude how you feel.
 Rome and Julia might not be so happy as it
looks.
 Individuals can be categorized by their values
of  and  .
 Long prison terms may be ineffective.

16
2010-10-19

Conclusions

William Shakespeare’s drama is complex

but

simple models might suffice

References and Acknowledgements

Thanks to J.C Sprott Department of Physics University of


Wisconsin - Madison
Strogatz,
St t S.S H.
H 1988.
1988 Love
L affairs
ff i andd differential
diff ti l
equations. Mathematics Magazine 61:35.
Steven H. Strogatz, Nonlinear Dynamics and Chaos (Addison-
Wesley, 1994)
Sergio Rinaldi. Laura and Petrarch: An Intriguing Case of Cyclical
Love Dynamics.
Dynamics SIAM Journal of Applied Mathematics.
Mathematics Vol 58
58,
No. 4, pp 1205-1221, August 1998

17
Library Design
Influenza Model

1 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Spreading of Influenza Epidemic

• Four state variables.


• Initial population of 10 000 non-infected
i di id l
individuals.
• Stem of influenza is introduced into the system.
• Infections occur spontaneously
• Virus spread in infected individuals and after
some time, the individuals fall sick.

2 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

1
Spreading of Influenza Epidemic

• Contagious people = sick + infected, spread the


disease further
• The
Th sicki k people
l eventually
t ll gett cured,
d iimmune
people
• Immune period is temporary due to mutation of
virus.
• Immune people turn into non-infected people
again who are again susceptible to infection.

3 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Influenza Model Parameters


• Time to breakdown, 4 weeks
• Actual sickness period, 2 weeks
• Immune period
period, 26 weeks

4 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

2
Influenza Model Parameters
• Average weekly contacts of a person with others, CWk=15
• Contraction rate per contact, RateC=0.25

Infection_rate min floor Non_infected_population*


CWk*Perc_infected*RateC
Initial , Non_infected_population

5 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Governing Equations

_ _
_

_
_

_
_

_
_

6 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

3
Block Oriented Approach

7 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Object Oriented Approach #1


Immune
Constants
Non Infected
Sick

Less
Components
Infected

8 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

4
Object Oriented Approach #2
Immune

Constants
C

Non Infected
Sick
Base class

Infected

9 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Object Oriented Approach #3, multiple


conncectors or connect several comp.
comp.
Immune

Constants
C
Non Infected
Sick

Base class

Infected

10 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

5
Simulation

Immune
Non Infected

Sick
Infected

11 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

Coclusions

• The influenza epidemic spreads rapidly


• Within 4 weeks, the percentage of sick people
reaches
h it its maximum
i off roughly
hl 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 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

6
Excersize

• Make the influenza library with the suggested


packages, components, interface, and example
• Tip:
Ti ThThe iinner and
d outer
t operators
t can bbe useful
f l ((what
h t hhappens with
ith the
th
encapsulation rule?)
Define the constants in the package level

13 Mohsen Torabzadeh-
Torabzadeh-Tari pelab

You might also like