You are on page 1of 116

Principles of Object-Oriented Modeling and Simulation with Modelica

Mini-Tutorial for MODPROD Workshop 2009 Peter Fritzson
Linköping University, Dept. of Comp. & Inform. Science SE 581-83, Linköping, Sweden petfr@ida.liu.se

Reference

Disturbance

Controller

Actuator

System

Output

2009-02-03 MODPROD’2009

Tutorial Aim This tutorial aims to give the participant an • introduction to object-oriented modeling and simulation • introduction to the Modelica language • hands-on experience in textual modeling • (Probably not enough time: hands-on experience in graphical modeling) After the course participants should be able to develop basic models on their own.

2

Copyright © Peter Fritzson

Software Installation

• Start the software installation • Install OpenModelica-1.4.5.msi from the OpenModelica USB Stick (Windows) • If you have Mac, install OpenModelica-1.4.5.dmg

3

Copyright © Peter Fritzson

2004 Peter Fritzson Principles of Object Oriented Modeling and Simulation with Modelica 2.1 Wiley-IEEE Press 940 pages 4 Copyright © Peter Fritzson .Tutorial Based on Recent Book.

Martin Otter. copyright Wiley-IEEE Press • Some examples and figures reproduced with permission from Modelica Association.modelica. Copyrights • If you want to use the Powerpoint version of these slides in your own course. and MathCore • Modelica Association: www.se • Thanks to Emma Larsdotter Nilsson for contributions to the layout of these slides • Most examples and figures in this tutorial are adapted with permission from Peter Fritzson’s book ”Principles of Object Oriented Modeling and Simulation with Modelica 2.1”. Hilding Elmqvist.se/projects/OpenModelica 5 Copyright © Peter Fritzson . Usage. send an email to: peter.ida.liu.Acknowledgements.org • OpenModelica: www.fritzson@ida.liu.

Why Modeling & Simulation? • • • • Increase understanding of complex systems Design and optimization Virtual prototyping Verification Build more complex systems 6 Copyright © Peter Fritzson .

Examples of Complex Systems • • • • • • • Robotics Automotive Aircrafts Satellites Biomechanics Power plants Hardware-in-the-loop. real-time simulation 7 Copyright © Peter Fritzson .

Qualitative models 8 Copyright © Peter Fritzson .Kinds of Mathematical Models • Dynamic vs. Discrete-time dynamic models • Quantitative vs. Static models • Continuous-time vs.

Dynamic vs.dynamic time 9 Copyright © Peter Fritzson . 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 .

Discrete-Time Dynamic Models Continuous-time models may evolve their variable values continuously during a time period Discrete-time variables change values a finite number of times during a time period Continuous Discrete time 10 Copyright © Peter Fritzson .Continuous vs.

Resistor. heat flow Component 1 Component 2 • Connection Component 3 • • • Variables at the interfaces describe interaction with other component Physical behavior of a component is described by equations Hierarchical decomposition of components 11 Copyright © Peter Fritzson . Pump Composition lines represent the actual physical connections i.e. mechanical Gear Box. mechanical connection. electrical line.e.Principles of Graphical Equation-Based Modeling • Each icon represents a physical component i.

Application Example – Industry Robot k2 i qddRef qdRef 1 S qRef 1 S k1 i r3Control r3Motor cut joint r3Drive1 1 axis6 tn qd axis5 l qdRef Kd S 0. ab = Srel*aa. qd q R d3=100 hall2 g2 x inertial y Courtesy of Martin Otter 12 Copyright © Peter Fritzson . g4 zb = Srel*(za + zrela + cross(wa. wrela)).03 Jmotor=J rel joint=0 spring=c axis4 - 0. g3 zrela = n*qdd.8 S - a(s) fric=R v0 qRef pSum Kv sum w Sum rate2 rate3 iRef S gear=i axis3 rate1 b(s) a(s) tacho2 b(s) a(s) tacho1 PT1 g5 axis2 R p2=50 q qd Rd1=100 R a=250 La=(250/(2*D *wm )) C=0.3 +1 +1 b(s) 340. r0b = r0a. hall1 w r wb = Srel*(wa + wrela).n*transpose(n))*cos(q).skew(n)*sin(q). vb = Srel*va.004*D/w m Rp1=200 axis1 Rd2=100 + dif f Ri=10 + OpI Vs Rd4=100 + pow er Srel = n*transpose(n)+(identity(3). g1 Sb = Sa*transpose(Srel). emf wrela = n*qd.

GTX Gas Turbine Power Cutoff Mechanism Hello Courtesy of Siemens Industrial Turbomachinery AB Developed by MathCore for Siemens 13 Copyright © Peter Fritzson .

Modelica – The Next Generation Modeling Language 14 Copyright © Peter Fritzson .

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 15 Copyright © Peter Fritzson .

vol. 1686) “The change of motion is proportional to the motive force impressed ” CSSL (1967) introduced a special form of “equation”: variable = expression v = INTEG(F)/m Programming languages usually do not allow equations! 16 Copyright © Peter Fritzson . • Equality sign was introduced by Robert Recorde in 1557 Newton still wrote text (Principia. 1.The Form – Equations • Equations were used in the third millennium B.C.

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

Object Oriented Mathematical Modeling • 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 18 Copyright © Peter Fritzson .

19 Copyright © Peter Fritzson .Modelica Acausal Modeling What is acausal modeling/design? Why does it increase reuse? The acausality makes Modelica library classes more reusable than traditional classes containing assignment statements where the input-output causality is fixed. Example: a resistor equation: R*i = v. can be used in three ways: i := v/R. v := R*i. R := v/i.

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. non-profit organization 20 Copyright © Peter Fritzson .0 released September 1997 2.0 released March 2002 2.2 released March 2005 3.0 released September 2007 • Modelica Association established 2000 • Open.

2000 • The 2nd International Modelica conference March 18-19. 2006 in Vienna. 2008 in Bielefeld. Austria • The 6th International Modelica conference March 3-4. 2003 in Linköping. 2002 • The 3rd International Modelica conference November 5-6.Modelica Conferences • The 1st International Modelica conference October. Sweden • The 4th International Modelica conference March 6-7. 2005 in Hamburg. Germany 21 Copyright © Peter Fritzson . Germany • The 5th International Modelica conference September 4-5.

Demo – Basic Graphical Modeling • Demo (Can use the SimForge Graphical Editor) 22 Copyright © Peter Fritzson .

Using Drag and Drop Composition 23 Copyright © Peter Fritzson .Graphical Modeling .

Completed DCMotor using Graphical Composition Courtesy MathCore Engineering AB 24 Copyright © Peter Fritzson .

p.p.p. DC.n. VsourceDC DC(f=10). EM. connect(EM.n). Inductor L(L=100). connect(EM.Multi-Domain (Electro-Mechanical) Modelica Model • A DC motor can be thought of as an electrical circuit which also contains an electromechanical component model DCMotor Resistor R(R=100).R.flange).load.n).J=10.p. connect(R. equation R connect(DC.p). connect(DC. DC connect(L.flange. ElectroMechanicalElement EM(k=10. Inertia load.n). b=2). Ground G.n).G. G end DCMotor 25 Copyright © Peter Fritzson L EM load .L.

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: 26 Copyright © Peter Fritzson .

org 27 Copyright © Peter Fritzson .The OpenModelica Environment www.OpenModelica.

teaching. and industrial usage • Free.OpenModelica • Goal: comprehensive modeling and simulation environment for research. open-source for academic use • Commercial users have to be members of Open Source Modelica Consortium (OSMC) • Available under OSMC-PL license • The OpenModelica compiler (OMC) implemented in MetaModelica. and applications 28 Copyright © Peter Fritzson . a slightly extended Modelica • Invitation for open-source cooperation around OpenModelica. tools.

OpenModelica Environment Architecture Eclipse Plugin Editor/Browser Emacs Editor/Browser Interactive session handler Graphical Model Editor/Browser Textual Model Editor DrModelica OMNoteBook Model Editor Execution Modelica Compiler Modelica Debugger 29 Copyright © Peter Fritzson .

OpenModelica Client-Server Architecture Parse Server: Main Program Including Compiler. etc. 30 Copyright © Peter Fritzson . Client: Graphic Model Editor Corba Client: OMShell Interactive Session Handler Client: Eclipse Plugin MDT SCode Interactive Untyped API Inst system Ceval Typed Checked Command API plot etc. Interpreter.

Translation of Models to Simulation Code Modelica Graphical Editor Modelica Textual Editor Modelica Model Modelica Source code Modelica Model Translator Flat model Analyzer Sorted equations Optimizer Code generator Optimized sorted equations C Code C Compiler Executable Simulation 31 Copyright © Peter Fritzson .

Released in OpenModelica 1.5 • • • • Compiler/interpreter – OMC Interactive session handler – OMShell Notebook with DrModelica – OMNotebook Eclipse plugin Modelica Development Tooling (MDT) • Also available: SimForge graphical editor 32 Copyright © Peter Fritzson .4.

portable between Windows. MMC) are portable between the three platforms • Windows – main development and release platform • Linux – available • Mac –available 33 Copyright © Peter Fritzson . MDT.Platforms • All OpenModelica GUI tools (OMShell. Mac • Both compilers (OMC. OMNotebook) are developed on the Qt4 GUI library. Linux.

Basic.Interactive Session Handler – dcmotor Example • OMShell – OpenModelica Shell >>simulate(dcmotor.g. connect(r1. equation connect(v.flange_b.Electrical.Analog. end dcmotor. Modelica.Resistor r1(R=10).n.Electrical.n.Analog.stopTime=10. Modelica.0.n.load.flange_a).p).Electrical.p).ConstantVoltage v.i1.0) >>plot({load.w.Inertia load. connect(i1. 34 Copyright © Peter Fritzson .Inductor i1.startTime=0. connect(emf1.Analog.EMF emf1.r1. Modelica.Sources.Mechanics.load.p.Analog.p).p).Basic.Analog.Rotational. Modelica. connect(v.emf1.g. Modelica.n.Ground g.Basic. connect(emf1.Electrical.p).Basic.phi}) model dcmotor Modelica.Electrical.

Code query support for developers • Automatic Indentation • Debugger (Prel. separate compilation • Syntax highlighting • Code completion. version for algorithmic subset) 35 Copyright © Peter Fritzson . classes.OpenModelica MDT – Eclipse Plugin • Browsing of packages. functions • Automatic building of executables.

OpenModelica MDT – Usage Example Code Assistance on function calling. 36 Copyright © Peter Fritzson .

The Modelica Language – Modelica Classes and Inheritance 37 Copyright © Peter Fritzson .

Variables and Constants Built-in primitive data types Boolean true or false Integer Integer value.4e-6 String String. 2. e. ShirtSize.g. 42 or –3 Real Floating point value.g. “Hello world” Enumeration Enumeration literal e.g. e.g. e.Medium 38 Copyright © Peter Fritzson .

5. one = 1. mass = 22.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 constant constant parameter Real String Integer Real PI=3. 39 Copyright © Peter Fritzson . redcolor = "red".141592653589793.

g. class VanDerPol "Van der Pol oscillator model" Real x(start = 1) "Descriptive string for x”. disregarded by compiler 2a) C style. /* This is the end VanDerPol.g. Real x "state variable". /* This is a C style comment */ 2b) C++ style. e. x starts at 1 y starts at 1 1st diff equation // 2nd diff equation */ 2) Source code comments.3. e. e. equation der(x) = y.g. // Comment to the end of the line… 40 Copyright © Peter Fritzson .x*x)*y. // parameter Real lambda = 0.Comments in Modelica 1) Declaration comments. // Real y(start = 1) "y coordinate”. // This is the der(y) = -x + lambda*(1 .

358). end Rocket. der(mass) = -massLossRate * abs(thrust). Real velocity(start= -2003). equation (thrust-mass*gravity)/mass = acceleration. Real altitude(start= 59404).A Simple Rocket Model Rocket apollo13 thrust mg thrust − m ass ⋅ gravity m ass m ass ′ = − m assLossRate ⋅ abs ( thrust ) acceleration = altitude ′ = velocity velocity ′ = acceleration declaration comment new model parameters (changeable before the simulation) floating point type differentiation with regards to time class Rocket "rocket class" parameter String name. der(velocity) = acceleration. Real mass(start=1038.000277. // Gravity forcefield parameter Real massLossRate=0. start value name + default value mathematical equation (acausal) 41 Copyright © Peter Fritzson . // Thrust force on rocket Real gravity. Real acceleration. der(altitude) = velocity. Real thrust.

declared by prefixing the type name to CelestialBody . name..672e-11.Celestial Body Class A class declaration creates a type name in Modelica class CelestialBody constant Real parameter Real parameter String parameter Real end CelestialBody. The declaration states that moon is a variable containing an object of type CelestialBody 42 Copyright © Peter Fritzson . mass. a variable name moon... An instance of the class can be .. radius. g = 6.

radius)^2.altitude+moon. equation apollo. apollo. protected parameter Real thrustEndTime = 210. CelestialBody moon(name="moon".gravity=moon.mass (apollo .radius=1. end MoonLanding.2. radius )2 CelestialBody class MoonLanding parameter Real force1 = 36350. parameter Real force2 = 1308.thrust = if (time < thrustDecreaseTime) then force1 else if (time < thrustEndTime) then force2 else 0. only access inside the class access by dot notation outside the class 43 Copyright © Peter Fritzson .382e22. g ⋅ moon .Moon Landing Rocket apollo13 thrust mg altitude apollo . public Rocket apollo(name="apollo13").altitude + moon .738e6). parameter Real thrustDecreaseTime = 43.mass/(apollo.g*moon.mass=7. gravity = moon .

xrange={0. gradually reducing it until touchdown at the lunar surface when the altitude is zero 44 Copyright © Peter Fritzson The rocket initially has a high negative velocity when approaching the lunar surface.400 100 150 200 It starts at an altitude of 59404 (not shown in the diagram) at time zero. stopTime=230) plot(apollo.208}) plot(apollo. giving a smooth landing . This is reduced to zero at touchdown.Simulation of Moon Landing simulate(MoonLanding.100 20000 .velocity.altitude.208}) 30000 50 25000 .300 . xrange={0.200 15000 10000 5000 50 100 150 200 .

. . record. with no equations Example: A block is a class with fixed input-output causality model CelestialBody constant Real parameter Real parameter String parameter Real end CelestialBody.: model. 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.Restricted Class Keywords • • • • • • The class keyword can be replaced by other keywords.. mass.. 45 Copyright © Peter Fritzson g = 6. connector.672e-11. name. e. radius. function.g. block.

input Real arg2. output Real result. and is instantiated dynamically when called • More on functions and algorithms later function sum input Real arg1.Modelica Functions • Modelica Functions can be viewed as a special kind of restricted class with some extensions • A function can be called with arguments. end sum. algorithm result := arg1+arg2. 46 Copyright © Peter Fritzson .

end Color. Data and behavior: field declarations. equation red + blue + green = 1. end ExpandedColor.6. parameter Real blue=0. equation red + blue + green = 1. class Color extends ColorData. parameter Real blue = 0.2. equations. and certain other contents are copied into the subclass 47 Copyright © Peter Fritzson .Inheritance parent class to Color restricted kind of class without equations child class or subclass keyword denoting inheritance record ColorData parameter Real red = 0. class ExpandedColor parameter Real red=0.2. Real green. Real green.6. end ColorData.

end ColoredPointWithoutInheritance. equation red + blue + green = 1. Real y. end ColoredPoint. equation red + blue + green = 1. class Point Real x. z. end Color. parameter Real red = 0.2.6. extends Color. Equivalent to 48 Copyright © Peter Fritzson . Real y.6. Real green. class ColoredPoint extends Point. Real green. parameter Real blue = 0.2. multiple inheritance class ColoredPointWithoutInheritance Real x.z. end Point.Multiple Inheritance Multiple Inheritance is fine – inheriting both geometry and color class Color parameter Real red=0. parameter Real blue=0.

Equivalent to: connector MyPin = Pin. end SameColor. 49 Copyright © Peter Fritzson .Simple Class Definition • Simple Class Definition • Shorthand Case of Inheritance • Example: class SameColor = Color. • Often used for introducing new names of types: type Resistor = Real. inheritance class SameColor extends Color.

modified with a different start value equation...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. and instantiated as an altitude variable: .. 50 Copyright © Peter Fritzson . . Real altitude(start= 59404)..

model CelestialBody extends Body. constant Real g = 6. der(mass)= -massLossRate*abs(thrust).Example Using Inheritance (I) Rocket apollo13 thrust mg model Rocket "generic rocket class" extends Body. Real gravity. Real thrust.The Moon Landing . Real acceleration. Real altitude(start= 59404). 51 Copyright © Peter Fritzson . end CelestialBody. altitude CelestialBody model Body "generic body" Real mass. String name. parameter Real massLossRate=0. end Rocket. der(velocity)= acceleration. der(altitude)= velocity.672e-11. parameter Real radius. Real velocity(start= -2003).000277. end Body. equation thrust-mass*gravity= mass*acceleration.

2. parameter Real force2 = 1308. mass(start=1038. 52 Copyright © Peter Fritzson . parameter Real thrustEndTime = 210. Rocket apollo(name="apollo13". end Landing.radius)^2.radius=1.Example using Inheritance (II) inherited parameters model MoonLanding parameter Real force1 = 36350. parameter Real thrustDecreaseTime = 43.name="moon").The Moon Landing . apollo. CelestialBody moon(mass=7.thrust = if (time<thrustDecreaseTime) then force1 else if (time<thrustEndTime) then force2 else 0.382e22.738e6.g*moon.altitude+moon.358) ).mass/(apollo.gravity =moon. equation apollo.

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

Exercises Part II (30 minutes) 54 Copyright © Peter Fritzson .

pdf 55 Copyright © Peter Fritzson .onb • Open Exercises-ModelicaTutorial.Exercises Part II • Start OMNotebook • Start->Programs->OpenModelica->OMNotebook • Open File: Exercises-ModelicaTutorial.

stopTime = 2) equation plot(x) der(x)= -x.2: Simulate and plot VanDerPol. • Exercise 2. class HelloWorld "A simple equation" Real x(start=1). etc. end HelloWorld.1). re-simulate and re-plot.1.1 and 2.2 • Open the Exercises-ModelicaTutorial. 56 Copyright © Peter Fritzson . Do a slight change in the model. • Locate the VanDerPol model in DrModelica (link from Section 2. Simulate and plot the HelloWorld example. val( ).onb found in the Tutorial directory. Try commandcompletion. using OMNotebook! • Exercise 2.Exercises 2. Do a slight change in the model. re-simulate and re-plot. simulate(HelloWorld.

Exercise 2.1 – Hello World! A Modelica “Hello World” model
Equation: x’ = - x Initial condition: x(0) = 1
class HelloWorld "A simple equation” parameter Real a=-1; Real x(start=1); equation der(x)= a*x; end HelloWorld;

Simulation in OpenModelica environment
1 0.8 0.6 0.4 0.2

simulate(HelloWorld, stopTime = 2) plot(x)

0.5

1

1.5

2

57

Copyright © Peter Fritzson

Exercise 2.2 – Van der Pol Oscillator
class VanDerPol "Van der Pol oscillator model" Real x(start = 1) "Descriptive string for x"; // Real y(start = 1) "y coordinate"; // parameter Real lambda = 0.3; equation der(x) = y; // This is the der(y) = -x + lambda*(1 - x*x)*y; /* This is the end VanDerPol; x starts at 1 y starts at 1

1st diff equation // 2nd diff equation */

2

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

1

1 -1

2

-2

58

Copyright © Peter Fritzson

Exercise 2.5 – Model the system below • Model this Simple System of Equations in Modelica

59

Copyright © Peter Fritzson

OMNotebook Electronic Notebook with DrModelica • Primarily for teaching • Interactive electronic book • Platform independent 60 Copyright © Peter Fritzson .

Cells with both Text and Graphics • Text Cells • Input Cells • Graphic Cells 61 Copyright © Peter Fritzson .

Exercises and Answers in OMNotebook DrModelica Easy to follow Exercises with solutions hidden in collapsed cells 62 Copyright © Peter Fritzson .

Some OMNotebook 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)

• (see also OpenModelica Users Guide or OMNotebook help)

63

Copyright © Peter Fritzson

OMNotebook Cell Editing Exercises (optional) • Select and copy a cell (tree to the right) • Position the horizontal cell cursor: first click between cells; then click once more on top of the horizontal line • Paste the cell

• Note: You can find most Users Guide examples in the UsersGuideExamples.onb in the testmodels directory of the OpenModelica installation.

64

Copyright © Peter Fritzson

Components, Connectors and Connections – Modelica Libraries and Graphical Modeling

65

Copyright © Peter Fritzson

i.Software Component Model Interface Connector Acausal coupling Component Connection Component Causal coupling A component class should be defined independently of the environment. hierarchical modeling Complex systems usually consist of large numbers of connected components 66 Copyright © Peter Fritzson . very essential for reusability A component may internally consist of other components.e.

Pin pin. end Flange. an instance pin of class Pin mechanical connector connector class connector Pin Voltage flow Current end Pin. Flange flange. s flange f an instance flange of class Flange 67 Copyright © Peter Fritzson .Connectors and Connector Classes Connectors are instances of connector classes electrical connector connector class keyword flow indicates that currents of connected pins sum to zero. v. flow Force f. v i + pin connector Flange Position s. i.

The flow prefix Two kinds of variables in connectors: • Non-flow variables potential or energy level • Flow variables represent some kind of flow Coupling • Equality coupling. for non-flow variables • Sum-to-zero coupling. for flow variables The value of a flow variable is positive when the current or the flow is into the component v positive flow direction: pin i + 68 Copyright © Peter Fritzson .

Rotational Magnetic flux Volume Heat Particles Air HyLibLight HeatFlow1D Under construction PneuLibLight Pressure 69 Copyright © Peter Fritzson . Analog Mechanical.Physical Connector • Classes Based on Energy Flow Domain Type Electrical Translational Rotational Magnetic Hydraulic Heat Chemical Pneumatic Potential Voltage Position Angle Magnetic potential Pressure Temperature Chemical potential Flow Current Force Torque Magnetic flux rate Volume flow Heat flow Particle flow Mass flow Carrier Charge Linear momentum Angular momentum Modelica Library Electrical. Translational Mechanical.

pin1 v i + pin2 Corresponds to pin1. pin1. //A connect equation //in Modelica: connect(pin1. 70 Copyright © Peter Fritzson .connect-equations Connections between connectors are realized as equations in Modelica connect(connector1. either to be declared directly within the same class or be members of one of the declared variables in that class + v i Pin pin1.v.i + pin2.i =0.connector2) The two arguments of a connect-equation must be references to connectors.v = pin2.pin2).pin2.

Corresponds to pin1.i =0.i + pin2. .pin2). Multiple connections are possible: connect(pin1. //A connect equation //in Modelica connect(pin1.pinN). connect(pin1.pin2).Connection Equations Pin pin1. pin1.v = pin2.pin3).v. connect(pin1.. Each primitive connection set of nonflow variables is used to generate equations of the form: v1 = v 2 = v 3 = … v n Each primitive connection set of flow variables is used to generate sumto-zero equations of the form: i1 + i 2 + … ( − i k ) + … i n = 0 71 Copyright © Peter Fritzson .pin2..

and Composite Connections Two basic and one composite kind of connection in Modelica • Acausal connections • Causal connections.Acausal. end OutPort 72 Copyright © Peter Fritzson . composed of basic or composite connections connector class fixed causality connector OutPort output Real signal. also called signal connections • Composite connections. Causal. also called structured connections.

i i partial model TwoPin Voltage v connector Pin Current i Voltage v. flow Current i.Interfaces electrical connector class 73 Copyright © Peter Fritzson .Electrical.v . Pin p.Analog.v.v p. end Pin. equation v = p. 0 = p.v n. Pin n.i.i i + p Tw oP in n - i n.n.Common Component Structure The base class TwoPin has two connectors p and n for positive and negative pins respectively partial class (cannot be instantiated) positive pin negative pin p.i + n. i = p. // TwoPin is same as OnePort in // Modelica.i. end TwoPin.

i + n.v v p. p.i n. parameter Real L ”Inductance”. end Resistor.i n.i n. end Capacitor. parameter Real C .i + n. equation i=C*der(v). equation R*i = v.v p. p.v model Inductor ”Ideal electrical inductor” extends TwoPin. end Inductor. equation L*der(i) = v.v v model Capacitor ”Ideal electrical capacitor” extends TwoPin.v p.i + n. p.v v 74 Copyright © Peter Fritzson . parameter Real R.Electrical Components model Resistor ”Ideal electrical resistor” extends TwoPin.

Electrical Components cont’ model Source extends TwoPin. equation v = A*sin(w*time).i n.v model Ground Pin p.i + v(t) n.i 75 Copyright © Peter Fritzson . p. end Ground. equation p.v p. parameter Real A.v p.w. p. end Resistor.v = 0.

v.v. equation connect(R1. end ResistorCircuit.p.p. Corresponds to R1.i + R2.p.p.i + R3.p. connect(R1.v = R2.v = R3. Resistor R2(R=200).i = 0.p.p.p. Resistor R3(R=300).p. R1.p). R2. 76 Copyright © Peter Fritzson . R3. R1.Resistor Circuit i1 i2 n R1 p v1 v2 v3 i3 p R2 n p R3 n model ResistorCircuit Resistor R1(R=100).p).

html 77 Copyright © Peter Fritzson .modelica.org/library/library. • Modelica libraries are available online including documentation and source code from http://www.Graphical Modeling • 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 Standard Library .

with the following sublibraries: • • • • • • • • • • • 78 Blocks Constants Electrical Icons Math Mechanics Media SIunits Stategraph Thermal Utilities Library for basic input/output control blocks Mathematical constants and constants of nature Library for electrical models Icon definitions Mathematical functions Library for mechanical systems Media models for liquids and gases Type definitions based on SI units according to ISO 31-1992 Hierarchical state machines (analogous to Statecharts) Components for thermal systems Utility functions especially for scripting Copyright © Peter Fritzson .Modelica Standard Library cont’ Modelica Standard Library contains components from various application areas.

Library Library Library Library Library Library Continuous Sources Math Interfaces NonLinear D iscrete Example: 79 Copyright © Peter Fritzson .Modelica.Blocks This library contains input/output blocks to build up block diagrams.

digital.Electrical Electrical components for building analog.Modelica. and multiphase circuits Library Library Library Library Analog Digital Machines MultiPhase Examples: V2 R2 R4 Gnd9 C2 Gnd3 R1 Transistor1 Gnd6 C4 Transistor2 R3 V1 C1 I1 C5 C3 Gnd4 Gnd1 Gnd2 Gnd7 Gnd8 Gnd5 80 Copyright © Peter Fritzson .

Modelica.Mechanics Package containing components for mechanical systems Subpackages: • • • Rotational Translational MultiBody 1-dimensional rotational mechanical components 1-dimensional translational mechanical components 3-dimensional mechanical components 81 Copyright © Peter Fritzson .

Modelica.Ground G.Electrical.Basic.Rotational.n). iner. R2. connect(emf.Resistor R1.Analog.Electrical.flange_b.Electrical.flange_b.n.Inertia iner.Connecting Components from Multiple Domains • Block domain ind 1 R1 • Mechanical domain ex ac iner emf R2 vsen • Electrical domain Block domain Mechanical domain G Electrical domain 2 model Generator Modelica.Analog.Rotational. R2.p).flange_a).n. emf. connect(emf. Modelica.riseTimeConst={1}). R1.Exponentials ex(riseTime={2}.Sensors.1).p).EMF emf(k=-1).n).n.Accelerate ac. G. connect(iner. connect(ind. connect(emf. connect(ex.p).p.flange_b). Modelica.Analog. Modelica.n.R2.outPort.inPort).Basic.p).Blocks.p).Mechanics. vsens. ind. connect(R2. connect(R1. Modelica.Basic.Analog.Mechanics.Electrical.VoltageSensor vsens. ac. Modelica.Inductor ind(L=0.Basic.Analog. Modelica. end Generator.n. connect(R2.p. equation connect(ac.Electrical. 82 Copyright © Peter Fritzson . vsens.Sources.

p.p. connect(emf. b=2).n). Inertia load.G.R. Ground G. Inductor L(L=100).L. emf. EMF emf(k=10.n).DCMotor Model Multi-Domain (Electro-Mechanical) A DC motor can be thought of as an electrical circuit which also contains an electromechanical component.n). VsourceDC DC(f=10).p).p. connect(L.n).flange). end DCMotor. connect(R. R DC L emf load G 83 Copyright © Peter Fritzson .J=10. connect(emf.flange.p.load.n. model DCMotor Resistor R(R=100). equation connect(DC. connect(DC. DC.

Graphical Modeling 84 Copyright © Peter Fritzson .

Exercises Part III Graphical Modeling Exercises (Probably not enough time Need to install simForge) 85 Copyright © Peter Fritzson .

Sources • Simulate it for 15s and plot the variables for the outgoing rotational speed on the inertia axis and the voltage on the voltage source (denoted u in the figure) in the same plot. Electrical. R u L emf J G 86 Copyright © Peter Fritzson .Analog.Basic.Rotational. Electrical.Exercise 3.Analog.1 • Draw the DCMotor model using the graphic connection editor using models from the following Modelica libraries: Mechanics.

Simulate again and see the results.2 • If there is enough time: Add a torsional spring to the outgoing shaft and another inertia element. Adjust some parameters to make a rather stiff spring.Exercise 3. 87 Copyright © Peter Fritzson .

3 • If there is enough time: Add a PI controller to the system and try to control the rotational speed of the outgoing shaft. 88 Copyright © Peter Fritzson . Tune the PI controller by changing its parameters in MathModelica.Exercise 3. Verify the result using a step signal for input.

Live example – Graphical Modeling • Building a component with icon 89 Copyright © Peter Fritzson .

3. Replace with component 90 Copyright © Peter Fritzson .Exercise 3.4 • Make a component of the model in Exercise 2.2. and use it when building the model in exercise 2.

org 91 Copyright © Peter Fritzson .openmodelica.The End OpenModelica: www.

Additional non-covered slides for Algorithms and Functions and Discrete Events and Hybrid Systems 92 Copyright © Peter Fritzson .

Algorithms and Functions 93 Copyright © Peter Fritzson .

. Algorithm sections can be embedded among equation sections 94 Copyright © Peter Fritzson .. x2 := y-5.. algorithm x1 := z+x. also called statements algorithm . z = w.Algorithm Sections Whereas equations are very well suited for physical modeling. ... <statements> .. i. equation u = x1+x2. x1 := x2+y.. sequences of instructions. <some keyword> equation x = y*2.e. there are situations where computations are more conveniently expressed as algorithms.

30. 7 // r takes the values 1. end for class SumZ parameter Integer n = 5. 6..7} loop for r in 1.6.2. end SumZ. 3..5 loop // k takes the values 1..3.12 // i takes the values 1. algorithm sum := 0.4.Iteration using for-statements in Algorithm sections for <iteration-variable> in <iteration-set-expression> loop <statement1> <statement2> .2. for i in 1:n loop // 1:5 is {1. 5. end for. 4.50})..0 : 1.0.5} sum := sum + z[i]. within the class SumZ Examples of for-loop headers with different range expressions for k in 1:10+2 loop for i in {1.40.3.5.0. The general structure of a forstatement with a single iterator A simple for-loop summing the five elements of the vector z.5 : 5.5 95 Copyright © Peter Fritzson . Real sum. 2.20.. Real[n] z(start = {10.3..

Iterations using while-stmts in Algorithm Sections while <conditions> loop <statements> end while. 96 Copyright © Peter Fritzson . end SumSeries. The example class SumSeries shows the while-loop construct used for summing a series of exponential terms until the loop condition is violated .. Integer i.E-6.01*i). end while.e. delta := exp(-0. i := i+1. The general structure of a whileloop with a single iterator. delta := exp(-0. i. Real delta.01*i). the terms become smaller than eps. algorithm i := 1. class SumSeries parameter Real eps = 1. Real sum. while delta>=eps loop sum := sum + delta.

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

Function Declaration The structure of a typical function declaration is as follows: function <functionname> input TypeI1 in1. protected <local variables> . <statements> .... All internal parts of a function are optional.. input TypeI3 in3. the following is also a legal function: function <functionname> end <functionname>..... . output TypeO2 out2. . input TypeI2 in2. Modelica functions are declarative mathematical functions: • Always return the same result(s) given the same input argument values 98 Copyright © Peter Fritzson . algorithm . output TypeO1 out1... end <functionname>.

end PolynomialEvaluator. // array.1) loop sum := sum + A[i]*xpower. // local variable xpower algorithm sum := 0. protected Real xpower. xpower := 1.// default value 1.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[:]. 99 Copyright © Peter Fritzson . size defined // at function call time input Real x := 1.0. The function PolynomialEvaluator computes the value of a polynomial given two arguments: a coefficient vector A and a value of x. end for.0 for x output Real sum. xpower := xpower*x. for i in 1:size(A.

.3.2.x=21) 100 Copyright © Peter Fritzson . p:= polynomialEvaluator({1..21) The same call to the function polynomialEvaluator can instead be made using named association of actual parameters to formal parameters..3.2.Positional and Named Argument Association Using positional association.2. in the call below the actual argument {1.4} becomes the value of the coefficient vector A. . p:= polynomialEvaluator(A={1..3.. algorithm . .4}.. algorithm .4}.. and 21 becomes the value of the formal parameter x..

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

If enough time. Do Exercise 2.6 on Functions and algorithms 102 Copyright © Peter Fritzson .

Discrete Events and Hybrid Systems Picture: Courtesy Hilding Elmqvist 103 Copyright © Peter Fritzson .

i. Instantaneous equations is a special case of conditional equations that are only active at events.e.. 104 Copyright © Peter Fritzson . are referenced or explicitly changed by equations associated with the event Some behavior associated with the event.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. expressed as conditional equations that become active or are deactivated at the event.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.

initial and terminal events Initialization actions are triggered by initial() initial() true false event at start time Actions at the end of a simulation are triggered by terminal() terminal() true false event at end time 105 Copyright © Peter Fritzson .

when clock then .Generating Repeated Events The call sample(t0.interval.Time Boolean clock.. first. … sample(t0. end when..1. 106 Copyright © Peter Fritzson .d) returns true and triggers events at times t0+i*d.d) true false t0 t0+d t0+2d t0+3d t0+4d time class SamplingClock parameter Modelica.interval). end SamplingClock. where i=0. equation clock = sample(first.SIunits.

model Diode "Ideal diode" extends TwoPin. when-equations become active at events when <conditions> then <equations> end when.start then . and if-expressions express different behavior in different operating regions if <condition> then <equations> elseif <condition> then <equations> else <equations> end if. if off then v=s else v=0. Real s.. equation when x > y. Boolean off. end if.Expressing Event Behavior in Modelica if-equations. i = if off then 0 else s. 107 Copyright © Peter Fritzson . end Diode.. if-statements. equation off = s < 0.

or enumeration. pre(y) gives the previous value of y immediately before the event. Integer. a subtype of those. Real. except for event iteration of multiple events at the same point in time when the value is from the previous iteration y pre(y) y time event • • • 108 The variable y has one of the basic types Boolean. String. 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 Copyright © Peter Fritzson .Obtaining Predecessor Values using pre() At an event.

1 change(v) true false event event true time The expression change(v) is true at instants when v changes value 109 Copyright © Peter Fritzson .2 4.Detecting Changes using edge()and change() Detecting changes of boolean variables using edge() true false b edge(b) true false event event time The expression edge(b) is true at events when b switches from false to true Detecting changes of discrete-time variables using change() v 4.5 3.

1 delay(v.5 3.d) time start+d t1 t1+d t2 t2+d In the expression delay(v.5 3.d) v is delayed by a delay time d 110 Copyright © Peter Fritzson .2 4.Creating Time-Delayed Expressions Creating time-delayed expressions using delay() v 4.2 4.1 4.

y}) 5 4 3 2 1 2 4 6 8 10 t 111 Copyright © Peter Fritzson . Real x(start=5). end when. startTime = 0.A Sampler Model model Sampler parameter Real sample_interval = 0. simulate(Sampler. plot({x. equation der(x) = -x. sample_interval) then y = x. Real y.1. when sample(0. stopTime = 10) end Sampler.

//elasticity constant Real height(start=0).90. 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.Discontinuous Changes to Variables at Events via When-Equations/Statements 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. when height<0 then reinit(velocity. end when. -c*velocity).18. equation der(height) = velocity. t 112 Copyright © Peter Fritzson . parameter Real c=0.velocity(start=10). end BouncingBall. der(velocity)=-g. //gravitational acc.

b/2 b/2 ground phi_dev < -b/2 phi_dev <= b/2 A finite state automaton SimpleElastoBacklash model Backward tau < 0 phi_dev >= -b/2 Slack tau = 0 phi_dev > b/2 Forward tau > 0 113 Copyright © Peter Fritzson .A Mode Switching Model Example Elastic transmission with slack tau DC motor transmission with elastic backlash resistor inductor M otor side Load side inertia1 signalV oltage em f elastoB acklash inertia2 step phi_dev .

Flange_b flange_b "(right) driven flange .connector". // Forward angle gives torque tau>0 slack = not (backward or forward). Flange_a flange_a "(left) driving flange . // Backward angle gives torque tau<0 forward = phi_rel > b/2.phi.e5 "Spring constant (c>0). phi_dev = phi_rel . // 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). backward = phi_rel < -b/2. parameter Real c = 1. Real tau "Torque between flanges". Real phi_dev "Angle deviation from zero-torque pos".A Mode Switching Model Example cont’ partial model SimpleElastoBacklash Boolean backward. // Mode variables parameter Real b "Size of backlash region".connector". Real phi_rel "Relative rotation angle betw.m/rad". N. // zero torque end SimpleElastoBacklash 114 Copyright © Peter Fritzson . equation phi_rel = flange_b.phi_rel0. parameter Real phi_rel0 = 0 "Angle when spring exerts no torque". slack.flange_a.phi . forward. flanges".

A Mode Switching Model Example cont’ 1 0.8 -1 -1.75 0.2 We define a model with less mass in inertia2(J=1).5 10 15 20 25 t elastoBacklash.4 -0.25 -0. and weaker string constant c=1e-5.w -0.w_rel Relative rotational speed between the flanges of the Elastobacklash transmission t 5 -0.2 -0. to show even more dramatic backlash phenomena The figure depicts the rotational speeds for the two flanges of the transmission with elastic backlash 115 Copyright © Peter Fritzson .w inertia2.6 10 15 20 25 inertia1.25 5 -0. no damping d=0.5 0.

change it slightly.3 – BouncingBall • Locate the BouncingBall model in one of the hybrid modeling sections of DrModelica (the When-Equations link in Section 2. run it.Exercise 2.9). 116 Copyright © Peter Fritzson . and re-run it.