Introduction to Object-Oriented Modeling, /OpenModelica Tutorial Plan for the Simulation, Debugging and Dynamic Optimization MOSES 2016 Workshop with Modelica using OpenModelica • Wednesday slot 24. The Modelica language part 1. MOSES 2016 Workshop Introductory hands-on Modelica modeling. Tutorial, Version May 18, 2016 Peter Fritzson Slides 8 – 49 Linköping University, [email protected] Director of the Open Source Modelica Consortium • Thursday slot 28. The OpenModelica tool. (slides Vice Chairman of Modelica Association Bernhard Thiele, Ph.D., [email protected] 50 – 78) The Modelica language part 2. (slides 95- Researcher at PELAB, Linköping University 115)

Slides • Thursday slot 29. Hands-on with Modelica textual Based on book and lecture notes by Peter Fritzson Contributions 2004-2005 by Emma Larsdotter Nilsson, Peter Bunus equation-based modeling (slides 95-115) Contributions 2006-2008 by Adrian Pop and Peter Fritzson Contributions 2009 by David Broman, Peter Fritzson, Jan Brugård, and Mohsen Torabzadeh-Tari Contributions 2010 by Peter Fritzson Contributions 2011 by Peter F., Mohsen T,. Adeel Asghar, Contributions 2012, 2013, 2014, 2015, 2016 by Peter Fritzson, Lena Buffoni, Mahder Gebremedhin, Bernhard Thiele

2016-05-16 2 Copyright © Open Source Modelica Consortium

Tutorial Based on Book, Decembr 2014 Introductory Download OpenModelica Software Modelica Book Peter Fritzson September 2011 232 pages Principles of Object Oriented Modeling and Simulation with 2015 –Translations Modelica 3.3 available in A Cyber-Physical Approach Chinese, Japanese, Can be ordered from Wiley or Amazon Spanish

Wiley-IEEE Press, 2014, 1250 pages Wiley IEEE Press • OpenModelica For Introductory • www..org Short Courses on • Modelica Association Object Oriented • www.modelica.org Mathematical Modeling

3 Copyright © Open Source Modelica Consortium 4 Copyright © Open Source Modelica Consortium

Acknowledgements, Usage, Copyrights Outline

• If you want to use the Powerpoint version of these slides in your own course, send an email to: [email protected] Part I Part II • Thanks to Emma Larsdotter Nilsson, Peter Bunus, David Introduction to Modelica and a Modelica environments Broman, Jan Brugård, Mohsen-Torabzadeh-Tari, Adeel demo example Asghar, Lena Buffoni, for contributions to 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”, copyright Wiley-IEEE Press • Some examples and figures reproduced with permission Part III Part IV and Part V from Modelica Association, Martin Otter, Hilding Elmqvist, Modelica language concepts Graphical modeling and the Wolfram MathCore, Siemens and textual modeling Modelica standard library • Modelica Association: www.modelica.org Dynamic Optimization • OpenModelica: www.openmodelica.org

5 Copyright © Open Source Modelica Consortium 6 Copyright © Open Source Modelica Consortium

1 Detailed Schedule (morning version) 09.00-12.30 Software Installation - Windows

09:00 - Introduction to Modeling and Simulation • Start installation of OpenModelica including OMEdit graphic editor 09:10 - Modelica – The Next Generation 09:25 - Exercises Part I (15 minutes) • Start the software installation • Short hands-on exercise on graphical modeling using OMEdit– RL Circuit 09:50 – Part II: Modelica Environments and the OpenModelica Environment 10:10 – Part III: Modelica Textual Modeling • Install OpenModelica-1.9.4beta.exe from the USB 10:15 - Exercises Part IIIa (10 minutes) • Hands-on exerciseson textual modeling using the OpenModelica environment Stick 10:25 – Coffee Break 10:40 - Modelica Discrete Events, Hybrid, Clocked Properties (Bernhard Thiele) 11:00- Exercises Part IIIb (15 minutes) • Hands-on exercises on textual modeling using the OpenModelica environment 11:20– Part IV: Components, Connectors and Connections - Modelica Libraries 11:30 –Part V Dynamic Optimization (Bernhard Thiele) • Hands-on exercise on dynamic optimization using OpenModelica 12:00 – Exercise Graphical Modeling DCMotor using OpenModelica

7 Copyright © Open Source Modelica Consortium 8 Copyright © Open Source Modelica Consortium

Software Installation – (requires internet connection) Software Installation – MAC (requires internet connection)

•Go to •Go to https://openmodelica.org/index.php/download/down https://openmodelica.org/index.php/download/down load-mac and follow the instructions or follow the load-linux and follow the instructions. instructions written below. • The installation uses MacPorts. After setting up a MacPorts installation, run the following commands on the terminal (as root): • echo rsync://build.openmodelica.org/macports/ >> /opt/local/etc/macports/sources.conf # assuming you installed into /opt/local • port selfupdate • port install openmodelica-devel

9 Copyright © Open Source Modelica Consortium 10 Copyright © Open Source Modelica Consortium

Modelica Background: Stored Knowledge

Model knowledge is stored in books and human Part I minds which computers cannot access

Introduction to Modelica and a demo example “The change of motion is proportional to the motive force impressed “ –Newton

11 Copyright © Open Source Modelica Consortium 12 Copyright © Open Source Modelica Consortium

2 Modelica Background: The Form – Equations What is Modelica?

• Equations were used in the third millennium B.. A language for modeling of complex cyber-physical systems • Equality sign was introduced by Robert Recorde in 1557 • Robotics • Automotive Newton still wrote text (Principia, vol. 1, 1686) • Aircrafts “The change of motion is proportional to the motive force • Satellites impressed ” • Power plants CSSL (1967) introduced a special form of “equation”: variable = expression • Systems biology v = INTEG(F)/m

Programming languages usually do not allow equations!

13 Copyright © Open Source Modelica Consortium 14 Copyright © Open Source Modelica Consortium

What is Modelica? What is Modelica?

A language for modeling of complex cyber-physical systems A language for modeling of complex cyber-physical systems i.e., Modelica is not a tool Free, open language There exist several free and commercial specification: tools, for example: • OpenModelica from OSMC • from Dassault systems • Wolfram System Modeler fr Wolfram MathCore • SimulationX from ITI • MapleSim from MapleSoft • AMESIM from LMS • JModelica.org from Modelon Primary designed for simulation, but there are also other Available at: www.modelica.org • MWORKS from Tongyang Sw & Control usages of models, e.g. optimization. Developed and standardized • IDA Simulation Env, from Equa by Modelica Association • ESI Group Modeling tool, ESI Group

15 Copyright © Open Source Modelica Consortium 16 Copyright © Open Source Modelica Consortium

Modelica – The Next Generation Modeling Language Modelica Acausal Modeling

Declarative language What is acausal modeling/design? Equations and mathematical functions allow acausal modeling, high level specification, increased correctness Why does it increase reuse? Multi-domain modeling The acausality makes Modelica library classes more Combine electrical, mechanical, thermodynamic, hydraulic, reusable than traditional classes containing assignment biological, control, event, real-time, etc... statements where the input-output causality is fixed. Everything is a class Example: a resistor equation: Strongly typed object-oriented language with a general class concept, Java & MATLAB-like syntax R*i = v; Visual component programming can be used in three ways: Hierarchical system architecture capabilities i := v/R; Efficient, non-proprietary v := R*i; Efficiency comparable to C; advanced equation compilation, e.g. 300 000 equations, ~150 000 lines on standard PC R := v/i;

17 Copyright © Open Source Modelica Consortium 18 Copyright © Open Source Modelica Consortium

3 What is Special about Modelica? What is Special about Modelica?

Cyber-Physical Modeling Multi-Domain 3 domains Modeling • Multi-Domain Modeling -electric Physical - mechanics • Visual acausal hierarchical component modeling - control • Typed declarative equation-based textual language • Hybrid modeling and simulation

Cyber

19 Copyright © Open Source Modelica Consortium 20 Copyright © Open Source Modelica Consortium

What is Special about Modelica? What is Special about Modelica?

Multi-Domain Visual Acausal Multi-Domain Hierarchical system Visual Acausal Modeling Keeps the physical Hierarchical Modeling modeling Hierarchical structure Component k2 Component i axis6 qddRef cut joint Modeling qdRef qRef k1 r3Control Modeling r3Motor r3Drive1 tn 1 1 i 1 S S qd axis5

Acausal model l

qdRef Kd (Modelica) S 0.03 rel

joint=0 Jmotor=J spring=c axis4 S pSum Kv sum wSum rate2 rate3 qRef iRef gear=i +1 b(s) 340.8 0.3 - +1 - a(s) S fric=Rv0 axis3

rate1 tacho2 tacho1

b(s) b(s) g5 PT1 a(s) a(s) Causal axis2 Ra=250 q qd Rp2=50 C=0.004*D/w m Rd1=100 Rp1=200 block-based m)) La=(250/(2*D*w Srel = n*transpose(n)+(identity(3)-Rd2=100 n*transpose(n))*cos(q)- axis1 Ri=10 skew(n)*sin(q); - - - + + model wrela = n*qd; diff + pow er zrela = n*qdd; OpI Vs Sb = Sa*transpose(Srel); Rd4=100 () r0b = r0a; emf

vb = Srel*va; g3 y wb = Srel*(wa + wrela); Rd3=100 g1 x ab = Srel*aa; inertial zb = Srel*(za + zrela + cross(wa,hall2 wrela)); hall1 w r Courtesy of Martin Otter g4 g2 qd q 21 Copyright © Open Source Modelica Consortium 22 Copyright © Open Source Modelica Consortium

What is Special about Modelica? What is Special about Modelica?

Visual Acausal Multi-Domain Multi-Domain Visual Acausal Hierarchical Modeling A textual class-based language Modeling Component Component OO primary used for as a structuring concept Modeling Modeling Behaviour described declaratively using Hybrid modeling = • Differential algebraic equations (DAE) (continuous-time) continuous-time + discrete-time modeling • Event triggers (discrete-time) Continuous-time Variable class VanDerPol "Van der Pol oscillator model" Discrete-time declarations Real x(start = 1) "Descriptive string for x”; Real y(start = 1) "y coordinate”; parameter Real lambda = 0.3; Clocked discrete-time equation Typed der(x) = y; Typed der(y) = -x + lambda*(1 - x*x)*y; time Declarative end VanDerPol; Declarative Hybrid Equation-based Equation-based Modeling Textual Language Differential equations Textual Language

23 Copyright © Open Source Modelica Consortium 24 Copyright © Open Source Modelica Consortium

4 Modelica – Faster Development, Lower Maintenance Modelica vs Simulink Block Oriented Modeling than with Traditional Tools Simple Electrical Model

Modelica: Keeps the Simulink: physical Block Diagram (e.g. Simulink, ...) or Physical model – Signal-flow model – hard to structure Proprietary Code (e.g. Ada, Fortran, C,...) easy to understand understand vs Modelica

Res2 sum3 Ind l2 p p -1 1 R2 1/L 1 s R1=10 R2=100

Causality sum2 Systems p Derivation n n +1 Definition Modeling of +1 (manual derivation of System Subsystems AC=220 input/output relations) Implementation Simulation Decomposition p p sinln sum1 Res1 Cap l1 n +1 1 Proprietary 1/R1 1/C -1 s Code C=0.01 L=0.1

Block Diagram n n

p Modelica G

25 Copyright © Open Source Modelica Consortium 26 Copyright © Open Source Modelica Consortium

Graphical Modeling - Using Drag and Drop Composition 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); Inductor L(L=100); VsourceDC DC(f=10); Ground G; ElectroMechanicalElement EM(k=10,J=10, b=2); Inertia load; equation R L connect(DC.p,R.n); EM connect(R.p,L.n); DC connect(L.p, EM.n); connect(EM.p, DC.n); load connect(DC.n,G.p); connect(EM.flange,load.flange); G end DCMotor

27 Copyright © Open Source Modelica Consortium 28 Copyright © Open Source Modelica Consortium

Corresponding DCMotor Model Equations Model Translation Process to Hybrid DAE to Code

The following equations are automatically derived from the Modelica model: Modelica Graphical Editor Modelica Modelica Modelica Model Source code Textual Editor Modelica Model Frontend Translator Modeling Flat model Hybrid DAE Environment Analyzer "Middle-end" Sorted equations Optimizer Optimized sorted equations (load component not included) Backend Code generator C Code Automatic transformation to ODE or DAE for simulation: C Compiler Executable Simulation

29 Copyright © Open Source Modelica Consortium 30 Copyright © Open Source Modelica Consortium

5 Modelica in Power Generation GTX Gas Turbine Power Cutoff Mechanism Modelica in Automotive Industry

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

31 Copyright © Open Source Modelica Consortium 32 Copyright © Open Source Modelica Consortium

Modelica in Avionics Modelica in Biomechanics

33 Copyright © Open Source Modelica Consortium 34 Copyright © Open Source Modelica Consortium

Application of Modelica in Robotics Models Combined-Cycle Power Plant Real-time Training Simulator for Flight, Driving Plant model – system level

• Using Modelica models • GT unit, ST unit, Drum boilers unit and HRSG units, generating real-time connected by thermo-fluid code ports and by signal buses • Different simulation • Low-temperature parts environments (e.g. (condenser, feedwater Flight, Car Driving, system, LP circuits) are Helicopter) represented by trivial • Developed at DLR boundary conditions. Munich, Germany • GT model: simple law • Dymola Modelica tool relating the electrical load request with the exhaust gas temperature and flow rate.

Courtesy Francesco Casella, Politecnico di Milano – Italy and Francesco Pretolani, CESI SpA - Italy

Courtesy of Tobias Bellmann, DLR, Oberphaffenhofen, Germany

35 Copyright © Open Source Modelica Consortium 36 Copyright © Open Source Modelica Consortium

6 System Dynamics – World Society Simulation Modelica Spacecraft Dynamics Library Limits to Material Growth; Population, Energy and Material flows

Formation flying on elliptical orbits Left. World3 simulation with OpenModelica Control the relative motion of two or more • 2 collapse scenarios spacecraft (close to current developments) • 1 sustainable scenario (green).

CO2 Emissions per person: • USA 17 ton/yr • Sweden 7 ton/yr • India 1.4 ton/yr Attitude control for satellites • Bangladesh 0.3 ton/yr using magnetic coils as actuators • System Dynamics Modelica library by Francois Cellier (ETH), et al in OM distribution. Torque generation mechanism: interaction between coils and • Warming converts many agriculture areas to deserts (USA, Europe, India, Amazonas) geomagnetic field • Ecological breakdown around 2080-2100, drastic reduction of world population

Courtesy of Francesco Casella, Politecnico di Milano, Italy •To avoid this: Need for massive investments in sustainable technology and renewable energy sources

37 Copyright © Open Source Modelica Consortium 38 Copyright © Open Source Modelica Consortium

What Can You Do? Need Global Sustainability Mass Movement

• Book: Current catastrophic scenarios: Mark Lynas: ”6 Degrees” Book: How to address the problems: Tim Jackson ”Prosperity without Growth” • Promote sustainable lifestyle and technology • Install electric solar PV panels • Buy shares in cooperative wind power

Expanded to 93 sqm, 12 kW, March 2013 20 sqm solar panels on garage roof, Nov 2012 House produced 11600 kwh, used 9500 kwh Generated 2700 W at noon March 10, 2013 Avoids 10 ton CO2 emission per year

39 Copyright © Open Source Modelica Consortium 40 Copyright © Open Source Modelica Consortium

Example Electric Cars Can be charged by electricity from own solar panels

Renault ZOE; 5 seat; Range: Small rectangles – surface needed • EU-drive cycle 210 km for 100% solar energy for humanity • Realistic Swedish drive cycle: • Summer: 165 km • Winter: 100 – 110 km Cheap fast supercharger

Good News Year 2013 –China installed 12Gw, production 14 Twh/yr DLR ROboMObil More than doubling capacity. Germany installed 3.3 Gw • experimental electric car Tesla model S • Modelica models range 480 km

41 Copyright © Open Source Modelica Consortium 42 Copyright © Open Source Modelica Consortium

7 Sustainable Society Necessary for Human Survival Brief Modelica History

Almost Sustainable • First Modelica design group meeting in fall 1996 • India, 1.4 ton C02/person/year • International group of people with expert knowledge in both language design and physical modeling • Healthy vegetarian food • Industry and academia • Small-scale agriculture • Modelica Versions • Small-scale shops • 1.0 released September 1997 • Simpler life-style (Mahatma Gandhi) • 2.0 released March 2002 Non-sustainable • 2.2 released March 2005 • 3.0 released September 2007 • USA 17 ton CO2, Sweden 7 ton CO2/yr • 3.1 released May 2009 • High meat consumption (1 kg beef uses ca • 3.2 released March 2010 4000 L water for production) • 3.3 released May 2012 • Hamburgers, unhealthy , includes beef • 3.2 rev 2 released November 2013 • Energy-consuming mechanized agriculture Gandhi – role model for • 3.3 rev 1 released July 2014 • Transport dependent shopping centres future less materialistic life style • Modelica Association established 2000 in Linköping • Stressful materialistic lifestyle • Open, non-profit organization

43 Copyright © Open Source Modelica Consortium 44 Copyright © Open Source Modelica Consortium

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 Exercises Part I • The 6th International Modelica conference March 3-4, 2008 in Bielefeld, Germany • The 7th International Modelica conference Sept 21-22, 2009 in Como, Italy Hands-on graphical modeling • The 8th International Modelica conference March 20-22, 2011 in Dresden, Germany (15 minutes) • The 9th International Modelica conference Sept 3-5, 2012 in Munich, Germany • The 10th International Modelica conference March 10-12, 2014 in Lund, Sweden • The 11th International Modelica conference Sept 21-23, 2015 in Versailles, Paris

45 Copyright © Open Source Modelica Consortium 46 Copyright © Open Source Modelica Consortium

Exercises Part I – Basic Graphical Modeling Exercises Part I – OMEdit Instructions (Part I)

•(See instructions on next two pages) • Start OMEdit from the Program menu under OpenModelica • Start the OMEdit editor (part of OpenModelica) •Go to File menu and choose New, and then select Model. • Draw the RLCircuit • Simulate • E.g. write RLCircuit as the model name. • For more information on how to use OMEdit, go to Help and choose R1 L User Manual or press F1.

R=10R=100 L=0.1L=1 A C • Under the Modelica Library: • Contains The standard Modelica library components The RLCircuit Simulation • The Modelica files contains the list of models you have created. G

47 Copyright © Open Source Modelica Consortium 48 Copyright © Open Source Modelica Consortium

8 Exercises Part I – OMEdit Instructions (Part II)

• For the RLCircuit model, browse the Modelica standard library and add the following component models: Part II • Add Ground, Inductor and Resistor component models from Modelica.Electrical.Analog.Basic package. • Add SineVoltage component model from Modelica.Electrical.Analog.Sources Modelica environments and OpenModelica package. • Make the corresponding connections between the component models as shown in slide 38. • Simulate the model • Go to Simulation menu and choose simulate or click on the simulate button in the toolbar. • Plot the instance variables • Once the simulation is completed, a plot variables list will appear on the right side. Select the variable that you want to plot.

49 Copyright © Open Source Modelica Consortium 50 Copyright © Open Source Modelica Consortium

Wolfram System Modeler – Wolfram MathCore Dymola

• Dassault Systemes Sweden • USA, Sweden • Sweden • General purpose • First Modelica tool on the market • Mathematica integration • Initial main focus on automotive • www.wolfram.com industry • www.mathcore.com • www.dymola.com

Mathematica

Simulation and analysis Courtesy Car model graphical view Wolfram Research

51 Copyright © Open Source Modelica Consortium 52 Copyright © Open Source Modelica Consortium

Simulation X MapleSim

• ITI Gmbh (Just bought by ESI • Maplesoft Group) • Canada • Germany • Recent Modelica tool on the • Mechatronic systems market • www..com • Integrated with Maple • www.maplesoft.com

53 Copyright © Open Source Modelica Consortium 54 Copyright © Open Source Modelica Consortium

9 The OpenModelica Open Source Environment The OpenModelica Environment www.openmodelica.org

www.OpenModelica.org • Advanced Interactive Modelica compiler (OMC) • OMEdit graphic Editor • Supports most of the Modelica Language • OMDebugger for equations • Modelica and Python scripting • OMOptim optimization tool • OM Dynamic optimizer collocation • Basic environment for creating models • ModelicaML UML Profile • OMShell – an interactive command handler • MetaModelica extension • OMNotebook – a literate programming notebook • ParModelica extension • MDT – an advanced textual environment in

55 Copyright © Open Source Modelica Consortium 56 Copyright © Open Source Modelica Consortium 56

OSMC – International Consortium for Open Source Model-based Development Tools, 48 members Jan 2016 OMNotebook Electronic Notebook with DrModelica

Founded Dec 4, 2007 Industrial members • Primarily for teaching • ABB AB, Sweden • ISID Dentsu, Tokyo, Japan • Interactive electronic book Open-source community services • Bosch Rexroth AG, Germany • Maplesoft, Canada • Siemens Turbo, Sweden • Ricardo Inc., USA • Platform independent • Website and Support Forum • CDAC Centre, Kerala, India • RTE France, Paris, France • Creative Connections, Prague • Saab AB, Linköping, Sweden • Version-controlled source base • DHI, Aarhus, Denmark • Enterprises, France • Bug database • Dynamica s.r.l., Cremona, Italy • SKF, Göteborg, Sweden Commands: • EDF, Paris, France • TLK Thermo, Germany • Development courses • Equa Simulation AB, Sweden • Sozhou Tongyuan, China • Shift-return (evaluates a cell) • Fraunhofer IWES, Bremerhaven • VTI, Linköping, Sweden • www.openmodelica.org • IFPEN, Paris, France • VTT, Finland • File Menu (open, close, etc.) • Wolfram MathCore, Sweden Code Statistics • Text Cursor (vertical), Cell University members cursor (horizontal) • Austrian Inst. of Tech, Austria • Heidelberg University, Germany • TU Berlin, Inst. UEBB, Germany • Linköping University, Sweden • Cell types: text cells & • FH Bielefeld, Bielefeld, Germany • TU Hamburg/Harburg Germany • TU Braunschweig, Germany • IIT Bombay, Mumbai, India executable code cells • University of Calabria, Italy • KTH, Stockholm, Sweden • Univ California, Berkeley, USA • Univ of Maryland, Syst Eng USA • Copy, paste, group cells • Chalmers Univ Techn, Sweden • Univ of Maryland, CEEE, USA • TU Dortmund, Germany • Politecnico di Milano, Italy • Copy, paste, group text • TU Dresden, Germany • Ecoles des Mines, CEP, France • Université Laval, Canada • Mälardalen University, Sweden • Command Completion (shift- • Ghent University, Belgium • Univ Pisa, Italy • Halmstad University, Sweden • StellenBosch Univ, South Africa tab) • Telemark Univ College, Norway

57 Copyright © Open Source Modelica Consortium 58 Copyright © Open Source Modelica Consortium

OMnotebook Interactive Electronic Notebook OM Web Notebook Generated from OMNotebook Here Used for Teaching Control Theory Edit, Simulate, and Plot Models on a Web Page

OMweb OMNote book book

59 Copyright © Open Source Modelica Consortium 60 Copyright © Open Source Modelica Consortium

10 OpenModelica Environment Demo OpenModelica MDT – Eclipse Plugin

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

61 Copyright © Open Source Modelica Consortium 62 Copyright © Open Source Modelica Consortium

OpenModelica MDT: Code Outline and Hovering Info OpenModelica Simulation in Web Browser Client

MultiBody RobotR3.FullRobot

Identifier Info on Hovering OpenModelica compiles to efficient Code Outline for Java Script code which is executed in web browser easy navigation within Modelica files 63 Copyright © Open Source Modelica Consortium 63 64 Copyright © Open Source Modelica Consortium

Interactive Simulation OMPython – Python Scripting with OpenModelica

• Interpretation of Modelica commands and expressions • Interactive Session handling Examples of Simulation Visualization • Library / Tool Simulation Control • Optimized Parser results • Helper functions Plot View • Deployable, Extensible and Distributable

Requirements Evaluation View in ModelicaML

MaxLevel

Liquid Level h Source Domain-Specific Level h Visualization View

Tank 1 Tank 2

65 Copyright © Open Source Modelica Consortium 66 Copyright © Open Source Modelica Consortium

11 PySimulator Package Modelica3D Library

• PySimulator, a • Modelica 3D simulation and Graphics Library analysis package by Fraunhofer developed by DLR FIRST, Berlin • Free, downloadable • Part of • Uses OMPython to OpenModelica simulate Modelica distribution models by • Can be used for OpenModelica 3D graphics in OpenModelica

67 Copyright © Open Source Modelica Consortium 68 Copyright © Open Source Modelica Consortium

Extending Modelica with PDEs for 2D, 3D flow problems – Research Failure Mode and Effects Analysis (FMEA) in OM

Insulated boundary: • Modelica models augmented with reliability properties can be used to generate class PDEModel reliability models in Figaro, which in turn can be used for static reliability analysis HeatNeumann h_iso; Dirichlet h_heated(g=50); Poorly insulated boundary: • Prototype in OpenModelica integrated with Figaro tool (which is becoming open- HeatRobin h_glass(h_heat=30000); T 20 source) HeatTransfer ht; inf Rectangle2D dom; Application Modelica Library Modelica model equation Simulation dom.eq=ht; dom.left.bc=h_glass; dom.top.bc=h_iso; Conducting boundary: dom.right.bc=h_iso; u60 Automated dom.bottom.bc=h_heated; generation end PDEModel;

Figaro Reliability Reliability model FT generation FT processing Library in Figaro Prototype in OpenModelica 2005 PhD Thesis by Levon Saldamli www.openmodelica.org Currently not operational

69 Copyright © Open Source Modelica Consortium 70 Copyright © Open Source Modelica Consortium

OMOptim – Optimization (1) Optimized Problems OMOptim – Optimization (2) parameters Model structure Model Variables Optimized Solved problems Result plot Export result data .csv Objectives

71 Copyright © Open Source Modelica Consortium 72 Copyright © Open Source Modelica Consortium

12 Multiple-Shooting and Collocation Dynamic Trajectory Optimization OpenModelica Dynamic Optimization Collocation

• Minimize a goal function subject to model equation constraints, useful e.g. for NMPC • Multiple Shooting/Collocation • Solve sub-problem in each sub-interval

Example speedup, 16 cores:

MULTIPLE_COLLOCATION 16.0 14.0 12.0 10.0 8.0 6.0 4.0 2.0 0.0 124816

ipopt [scaled] jac_g [scaled]

73 Copyright © Open Source Modelica Consortium 74 Copyright © Open Source Modelica Consortium

General Tool Interoperability & Model Exchange Functional Mock-up Interface (FMI) Functional Mockup Units • Import and export of input/output blocks – etc. Functional Mock-Up Units – FMUs, described by • differential-, algebraic-, discrete equations,

Engine Gearbox Thermal Automated Chassis components, • with time-, state, and step-events with ECU with ECU systems cargo door roadway, ECU (e.g. ESP) • An FMU can be large (e.g. 100 000 variables) functional mockup interface for model exchange and tool coupling • An FMU can be used in an embedded system (small overhead) courtesy Daimler • FMUs can be connected together • FMI development was started by ITEA2 MODELISAR project. FMI is a Modelica Association Project now • Version 1.0 • FMI for Model Exchange (released Jan 26,2010) • FMI for Co-Simulation (released Oct 12,2010) • Version 2.0 • FMI for Model Exchange and Co-Simulation (released July 25,2014) • > 60 tools supporting it (https://www.fmi-standard.org/tools)

75 Copyright © Open Source Modelica Consortium 76 Copyright © Open Source Modelica Consortium

OpenModelica Functional Mockup Interface (FMI) FMI in OpenModelica

• Model Exchange implemented (FMI 1.0 and FMI 2.0) • FMI 2.0 Co-simulation available • The FMI interface is accessible via the OpenModelica scripting environment and the OpenModelica connection editor

77 Copyright © Open Source Modelica Consortium 78 Copyright © Open Source Modelica Consortium

13 OPENPROD – Large 28-partner European Project, 2009-2012 OPENPROD Model-Based Development Environment Vision of Cyber-Physical Model-Based Product Development Covers Product-Design V Feedback SystemSystem SimulationSimulation BusinessBusiness Model-Driven- Compilation RequirementsRequirements ModelDriven Compilation ProcessProcess Design & Code Gen CaptureCapture Design & Code Gen Feedback ControlControl (PIM) (PSM) SystemSystem SoftwareSoftware & & SystemSyst Product Product SimulationSimulation ProcessProcess RequirementsRequirements ProductProduct PlatformPlatform BusinessBusiness Compilation modelsmodels modelsmodels modelsmodels modelsmodels RequirementsRequirements ModelModel-Driven-Driven Compilation ProcessProcess & Code Gen Unified Modeling: Meta--modeling&Modelica&modeling&Modelica& UML &OWL CaptureCapture DesignDesign & Code Gen ControlControl (PIM) (PSM) SoftwareSoftware & & Level of Abstraction SystemSyst Product Product Experience Feedback ProcessProcess RequirementsRequirements ProductProduct PlatformPlatform models System Maintenance modelsmodels modelsmodels modelsmodels models requirements Product verification and Calibration Unified Modeling: MetaMeta-modeling&-modeling&Modelica& Modelica& UML &OWL Specification deployment Preliminary feature design Subsystem level integration test Design Integration calibration and verification Architectural design and OPENPROD Vision of unified modeling framework for model-based Subsystem level integration and system functional design Design Verification Refinement verification product development. Detailed feature design and implementation Component verification Open Standards – Modelica (HW, SW) and UML (SW) Realization

79 Copyright © Open Source Modelica Consortium 80 Copyright © Open Source Modelica Consortium Documentation, Version and Configuration Management

Business Process Control and Modeling Requirement Capture

Feedback Feedback SystemSystem SystemSystem SimulationSimulation VTT Simantics SimulationSimulation BusinessBusiness Model-Driven- Compilation BusinessBusiness Model-Driven- Compilation RequirementsRequirements ModelDriven Compilation Business process modeler RequirementsRequirements ModelDriven Compilation ProcessProcess Design & Code Gen ProcessProcess Design & Code Gen CaptureCapture Design & Code Gen CaptureCapture Design & Code Gen ControlControl (PIM) (PSM) ControlControl (PIM) (PSM) vVDR (virtual Verification of SoftwareSoftware & & SoftwareSoftware & & SystemSyst Product Product SystemSyst Product Product Designs against Requirements) ProcessProcess RequirementsRequirements ProductProduct PlatformPlatform ProcessProcess RequirementsRequirements ProductProduct PlatformPlatform modelsmodels modelsmodels modelsmodels modelsmodels modelsmodels modelsmodels modelsmodels modelsmodels OpenModelica in ModelicaML UML/Modelica Unified Modeling: MetaMeta-modeling&-modeling& Modelica& UML &OWL Unified Modeling: MetaMeta-modeling&-modeling& Modelica& UML &OWL compiler & simulator Profile, part of OpenModelica OpenModelica based simulation OpenModelica based simulation Metso Business model & simulation VTT Simantics Graphic Modeling To Simulation of 3 strategies with outcomes Verification Model Provider from Design Model design model

Scenario Model Binding

Requirement Models Client from requirement model

81 Copyright © Open Source Modelica Consortium 82 Copyright © Open Source Modelica Consortium

OpenModelica – ModelicaML UML Profile Example: Simulation and Requirements Evaluation SysML/UML to Modelica OMG Standardization

• ModelicaML is a UML Profile for SW/HW modeling • Applicable to “pure” UML or to other UML profiles, e.g. SysML • Standardized Mapping UML/SysML to Modelica • Defines transformation/mapping for executable models • Being standardized by OMG • ModelicaML • Defines graphical concrete syntax (graphical notation for diagram) for Req. 001 is instantiated 2 times (there are 2 tanks in representing Modelica constructs integrated with UML the system) • Includes graphical formalisms (e.g. State Machines, Activities, Requirements) tank-height is 0.6m • Which do not exist in Modelica language Req. 001 for the tank2 is violated • Which are translated into executable Modelica code • Is defined towards generation of executable Modelica code Req. 001 for the tank1 is not violated • Current implementation based on the Papyrus UML tool + OpenModelica

83 Copyright © Open Source Modelica Consortium 84 Copyright © Open Source Modelica Consortium

14 vVDR Method – virtual Verification of Designs vs Requirements Industrial Product with OEM Usage of OpenModelica

Actor Task Created Artifact • The Wolfram SystemModeler modeling and

Formalize RMM Requirement simulation product by Wolfram, www.wolfram.com Requirements Monitor Models • Includes a large part of the OpenModelica compiler using the OSMC OEM license. Designs Formalize Designs DAM Alternative • Images show a house heating application and an Models excavator dynamics simulation.

Formalize SM Scenario Scenarios Models Goal: Enable on-demand Create Verification* VM Verification Models AUTOMATED verification of designs Models against requirements using automated model Reports composition at any time AUTOMATED Execute and Create Report during development.

Analyze Results

85 Copyright © Open Source Modelica Consortium 86 Copyright © Open Source Modelica Consortium

ABB Industry Use of OpenModelica FMI 2.0 and Debugger Performance Profiling (Below: Profiling all equations in MSL 3.2.1 DoublePendulum)

• ABB OPTIMAX® provides advanced model based control products for power generation and water utilities

• ABB: “ABB uses several compatible Modelica tools, including OpenModelica, depending on specific application needs.”

• ABB: “OpenModelica provides outstanding debugging features that help to save a lot of time during model development.”

87 Copyright © Open Source Modelica Consortium 88 Copyright © Open Source Modelica Consortium

The OpenModelica MDT Debugger (Eclipse-based) OpenModelica MDT Algorithmic Code Debugger Using Japanese Characters

89 Copyright © Open Source Modelica Consortium 90 Copyright © Open Source Modelica Consortium

15 Debugging Example – Detecting Source of Chattering OpenModelica Equation Model Debugger (excessive event switching) causing bad performance

• Lkjlkjlj

Showing • Lkjlkj equation • lkjklj transformations of a model:

0 = y + der(x * time * z); z = 1.0;

(1) substitution: y + der(x * (time * z)) => y + der(x * (time * 1.0))

(2) simplify: y + der(x * (time * 1.0)) => equation y + der(x * time)

(3) expand derivative (symbolic z = if x > 0 then -1 else 1; diff): y + der(x * time) y = 2 * z; =>y + (x + der(x) * time) … (4) solve: 0.0 = y + (x + der(x) * time) => der(x) = ((-y) - x) / time Mapping run-time error to source model position time <> 0

91 Copyright © Open Source Modelica Consortium 92 Copyright © Open Source Modelica Consortium

Error Indication – Simulation Slows Down Exercise 1.2 – Equation-based Model Debugger

In the model ChatteringEvents1, chattering takes place after t = 0.5, due to the discontinuity in the right hand side of the first equation. Chattering can be detected because lots of tightly spaced events are generated. The debugger allows to identify the (faulty) equation that gives rise to all the zero crossing events.

model ChatteringEvents1 Real x(start=1, fixed=true); Real y; Uses 25% CPU Real z; equation z = noEvent(if x > 0 then -1 else 1); y = 2*z; der(x) = y; end ChatteringNoEvents1;

• Switch to OMEdit text view (click on text button upper left) • Open the Debugging.mo package file using OMEdit • Open subpackage Chattering, then open model ChatteringEvents1 • Simulate in debug mode • Click on the button Debug more (see prev. slide) • Possibly start task manager and look at CPU. Then click stop simulation button

93 Copyright © Open Source Modelica Consortium 94 Copyright © Open Source Modelica Consortium

Acausal Modeling

The order of computations is not decided at modeling time Part III Acausal Causal

Modelica language concepts Visual Component and textual modeling Level

Equation A resistor equation: Causal possibilities: Level R*i = v; i := v/R; Typed v := R*i; Declarative Hybrid R := v/i; Equation-based Modeling Textual Language

95 Copyright © Open Source Modelica Consortium 96 Copyright © Open Source Modelica Consortium

16 Typical Simulation Process Simple model - Hello World!

Name of model Initial condition Equation: x’ = - x Initial condition: x(0) = 1 model HelloWorld "A simple equation" Continuous-time Real x(start=1); variable parameter Real a = -1; equation Parameter, constant der(x)= a*x; during simulation end HelloWorld; Simulation in OpenModelica environment Differential equation

1

0.8 simulate(HelloWorld, stopTime = 2) 0.6 plot(x) 0.4

0.2

0.5 1 1.5 2

97 Copyright © Open Source Modelica Consortium 98 Copyright © Open Source Modelica Consortium

Modelica Variables and Constants A Simple Rocket Model

thrust mass gravity • Built-in primitive data types acceleration  Rocket mass Boolean true or false apollo13 thrust mass  massLossRate abs thrust Integer Integer value, e.g. 42 or –3 mg altitude  velocity Real Floating point value, e.g. 2.4e-6 velocity  acceleration String String, e.g. “Hello world” Enumeration Enumeration literal e.g. ShirtSize.Medium 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 • Parameters are constant during simulation type Real acceleration; Real thrust; // Thrust force on rocket Real gravity; // Gravity forcefield • Two types of constants in Modelica parameter Real massLossRate=0.000277; name + default value • constant equation constant Real PI=3.141592653589793; (thrust-mass*gravity)/mass = acceleration; mathematical • parameter constant String redcolor = "red"; der(mass) = -massLossRate * abs(thrust); equation (acausal) constant Integer one = 1; der(altitude) = velocity; differentiation with der(velocity) = acceleration; parameter Real mass = 22.5; regards to time end Rocket;

99 Copyright © Open Source Modelica Consortium 100 Copyright © Open Source Modelica Consortium

Celestial Body Class Moon Landing

Rocket apollo13 A class declaration creates a type name in Modelica thrust moon.g  moon .mass apollo.gravity  class CelestialBody apollo .altitude  moon.radius 2 mg  constant Real g = 6.672e-11; parameter Real radius; altitude parameter String name; CelestialBody parameter Real mass; end CelestialBody; class MoonLanding parameter Real force1 = 36350; An instance of the class can be parameter Real force2 = 1308; only access protected ... inside the class parameter Real thrustEndTime = 210; declared by prefixing the type CelestialBody moon; parameter Real thrustDecreaseTime = 43.2; ... access by dot public name to a variable name notation outside Rocket apollo(name="apollo13"); the class CelestialBody moon(name="moon",mass=7.382e22,radius=1.738e6); equation apollo.thrust = if (time < thrustDecreaseTime) then force1 The declaration states that moon is a variable else if (time < thrustEndTime) then force2 else 0; containing an object of type CelestialBody apollo.gravity=moon.g*moon.mass/(apollo.altitude+moon.radius)^2; end MoonLanding;

101 Copyright © Open Source Modelica Consortium 102 Copyright © Open Source Modelica Consortium

17 Simulation of Moon Landing Specialized Class Keywords

simulate(MoonLanding, stopTime=230) • Classes can also be declared with other keywords, e.g.: model, record, plot(apollo.altitude, xrange={0,208}) block, connector, function, ... plot(apollo.velocity, xrange={0,208}) • Classes declared with such keywords have specialized properties

30000 • Restrictions and enhancements apply to contents of specialized classes 50 100 150 200 25000 • After Modelica 3.0 the keyword means the same as -100 class model 20000 -200 15000 • Example: (Modelica 2.2). A model is a class that cannot be used as a 10000 -300 connector class 5000 -400 •Example: A record is a class that only contains data, with no equations

50 100 150 200 •Example: A block is a class with fixed input-output causality

It starts at an altitude of 59404 The rocket initially has a high model CelestialBody (not shown in the diagram) at negative velocity when approaching constant Real g = 6.672e-11; time zero, gradually reducing it the lunar surface. This is reduced to parameter Real radius; parameter String name; until touchdown at the lunar zero at touchdown, giving a smooth parameter Real mass; surface when the altitude is zero landing end CelestialBody;

103 Copyright © Open Source Modelica Consortium 104 Copyright © Open Source Modelica Consortium

Modelica Functions Function Call – Example Function with for-loop

• Modelica Functions can be viewed as a specialized Example Modelica function call: {1,2,3,4} becomes class with some restrictions and extensions ... the value of the p = polynomialEvaluator({1,2,3,4},21) coefficient vector A, and • A function can be called with arguments, and is 21 becomes the value of the formal parameter x. instantiated dynamically when called function PolynomialEvaluator input Real A[:]; // array, size defined // at function call time function sum input Real x := 1.0;// default value 1.0 for x The function output Real sum; input Real arg1; PolynomialEvaluator input Real arg2; protected Real xpower; // local variable xpower computes the value of a output Real result; algorithm polynomial given two algorithm sum := 0; result := arg1+arg2; xpower := 1; arguments: end sum; 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;

105 Copyright © Open Source Modelica Consortium 106 Copyright © Open Source Modelica Consortium

Extra slide Inheritance Multiple Inheritance

parent class to Color Multiple Inheritance is fine – inheriting both geometry and color restricted kind record ColorData of class without parameter Real red = 0.2; equations class Point parameter Real blue = 0.6; Real x; class ExpandedColor class Color Real green; Real y,z; end ColorData; parameter Real red=0.2; parameter Real red=0.2; child class or parameter Real blue=0.6; parameter Real blue=0.6; end Point; subclass Real green; Real green; class ColoredPoint class Color equation equation extends Point; keyword extends ColorData; red + blue + green = 1; red + blue + green = 1; extends Color; denoting equation multiple inheritance end ExpandedColor; end Color; end ColoredPoint; inheritance red + blue + green = 1; end Color; class ColoredPointWithoutInheritance Real x; Real y, z; Data and behavior: field declarations, equations, and parameter Real red = 0.2; Equivalent to parameter Real blue = 0.6; certain other contents are copied into the subclass Real green; equation red + blue + green = 1; end ColoredPointWithoutInheritance;

107 Copyright © Open Source Modelica Consortium 108 Copyright © Open Source Modelica Consortium

18 Extra slide Multiple Inheritance cont’ Simple Class Definition

Only one copy of multiply inherited class Point is kept • Simple Class Definition • Often used for • Shorthand Case of Inheritance class Point introducing new Real x; Real y; •Example: names of types: end Point; class SameColor = Color;

type Resistor = Real; Equivalent to: class VerticalLine class HorizontalLine extends Point; extends Point; connector MyPin = Pin; Real vlength; Diamond Inheritance Real hlength; end VerticalLine; end HorizontalLine; class SameColor inheritance extends Color; end SameColor;

class Rectangle extends VerticalLine; extends HorizontalLine; end Rectangle;

109 Copyright © Open Source Modelica Consortium 110 Copyright © Open Source Modelica Consortium

Extra slide Inheritance Through Modification The Moon Landing - Example Using Inheritance (I)

• Modification is a concise way of combining inheritance Rocket apollo13 thrust with declaration of classes or instances mg model Rocket "generic rocket class" •A modifier modifies a declaration equation in the extends Body; altitude CelestialBody parameter Real massLossRate=0.000277; Real altitude(start= 59404); inherited class Real velocity(start= -2003); Real acceleration; • Example: The class Real is inherited, modified with a Real thrust; model Body "generic body" Real gravity; different start value equation, and instantiated as an Real mass; equation String name; thrust-mass*gravity= mass*acceleration; altitude variable: end Body; der(mass)= -massLossRate*abs(thrust); der(altitude)= velocity; der(velocity)= acceleration; model CelestialBody end Rocket; extends Body; ... constant Real g = 6.672e-11; Real altitude(start= 59404); parameter Real radius; ... end CelestialBody;

111 Copyright © Open Source Modelica Consortium 112 Copyright © Open Source Modelica Consortium

Extra slide Extra slide The Moon Landing - Example using Inheritance (II) Inheritance of Protected Elements

If an extends-clause is preceded by the protected keyword, inherited parameters all inherited elements from the superclass become protected elements of the subclass model MoonLanding class ColoredPoint parameter Real force1 = 36350; class Point protected parameter Real force2 = 1308; Real x; extends Color; parameter Real thrustEndTime = 210; class Color Real y,z; public parameter Real thrustDecreaseTime = 43.2; Real red; end Point; extends Point; Rocket apollo(name="apollo13", mass(start=1038.358) ); Real blue; end ColoredPoint; CelestialBody moon(mass=7.382e22,radius=1.738e6,name="moon"); Real green; equation equation apollo.thrust = if (time

113 Copyright © Open Source Modelica Consortium 114 Copyright © Open Source Modelica Consortium

19 Exercises Part III a

• Start OMNotebook (part of OpenModelica) • Start->Programs->OpenModelica->OMNotebook Exercises Part III a • Open File: Exercises-ModelicaTutorial.onb from the directory you copied (15 minutes) your tutorial files to. • Note: The DrModelica electronic book has been automatically opened when you started OMNotebook.

• Open Exercises-ModelicaTutorial.pdf (also available in printed handouts)

115 Copyright © Open Source Modelica Consortium 116 Copyright © Open Source Modelica Consortium

Exercises 2.1 and 2.2 (See also next two pages) Exercise 2.1 – Hello World!

• Open the Exercises-ModelicaTutorial.onb found in the A Modelica “Hello World” model Tutorial directory you copied at installation. Equation: x’ = - x class HelloWorld "A simple equation” • Exercise 2.1. Simulate and plot the HelloWorld example. Do Initial condition: x(0) = 1 parameter Real a=-1; a slight change in the model, re-simulate and re-plot. Try Real x(start=1); equation command-completion, val( ), etc. der(x)= a*x; end HelloWorld; class HelloWorld "A simple equation" Real x(start=1); equation simulate(HelloWorld, stopTime = 2) Simulation in OpenModelica environment

der(x)= -x; plot(x) 1 end HelloWorld; 0.8 simulate(HelloWorld, stopTime = 2) plot(x) • Locate the VanDerPol model in DrModelica (link from 0.6

Section 2.1), using OMNotebook! 0.4

• (extra) Exercise 2.2: Simulate and plot VanDerPol. Do a 0.2 slight change in the model, re-simulate and re-plot. 0.5 1 1.5 2

117 Copyright © Open Source Modelica Consortium 118 Copyright © Open Source Modelica Consortium

(extra) Exercise 2.2 – Van der Pol Oscillator (extra) Exercise 2.3 – DAE Example

class VanDerPol "Van der Pol oscillator model" class DAEexample Real x(start = 1) "Descriptive string for x"; // x starts at 1 Include algebraic equation Real y(start = 1) "y coordinate"; // y starts at 1 Real x(start=0.9); parameter Real lambda = 0.3; Algebraic equations contain Real y; equation no derivatives equation der(x) = y; // This is the 1st diff equation // der(y)+(1+0.5*sin(y))*der(x) der(y) = -x + lambda*(1 - x*x)*y; /* This is the 2nd diff equation */ Exercise: Locate in DrModelica. = sin(time); end VanDerPol; Simulate and plot. Change x - y = exp(-0.9*x)*cos(y); the model, simulate+plot. end DAEexample;

2 Simulation in OpenModelica environment simulate(VanDerPol,stopTime = 25) 1.20 plotParametric(x,y) 1 1.15 simulate(DAEexample, stopTime = 1) plot(x) -2 -1 1 2 1.10 1.05 -1 1.0 time 0.2 0.4 0.6 0.8 1 0.95 -2 0.90

119 Copyright © Open Source Modelica Consortium 120 Copyright © Open Source Modelica Consortium

20 Exercise 2.4 – Model the system below (extra) Exercise 2.5 – Functions

• Model this Simple System of Equations in Modelica • a) Write a function, sum2, which calculates the sum of Real numbers, for a vector of arbitrary size.

• b) Write a function, average, which calculates the average of Real numbers, in a vector of arbitrary size. The function average should make use of a function call to sum2.

121 Copyright © Open Source Modelica Consortium 122 Copyright © Open Source Modelica Consortium

Hybrid Modeling

Hybrid modeling = continuous-time + discrete-time modeling

Part III b Continuous-time Real x; Voltage v; Discrete Events and Hybrid Systems Current i; Discrete-time discrete Real x; Integer i; Boolean b; time Events •A point in time that is instantaneous, i.e., has zero duration •An event condition so that the event can take place • A set of variables that are associated with the event • Some behavior associated with the event, e.g. conditional equations that become active or are deactivated at Picture: Courtesy Hilding Elmqvist the event

123 Copyright © Open Source Modelica Consortium 124 Copyright © Open Source Modelica Consortium

Event Creation – if Event Creation – when

if-equations, if-statements, and if-expressions when-equations when then if then model Diode "Ideal diode" extends TwoPin; time false if s<0 end when; elseif then Real s; event 1 event 2 event 3 Boolean off; else equation If-equation choosing off = s < 0; equation for v end if; if off then Equations only active at event times v=s else v=0; If-expression Time event State event end if; when time >= 10.0 then i = if off then 0 else s; when sin(x) > 0.5 then end Diode; ...... end when; end when;

Only dependent on time, can be Related to a state. Check for scheduled in advance zero-crossing

125 Copyright © Open Source Modelica Consortium 126 Copyright © Open Source Modelica Consortium

21 Generating Repeated Events Reinit - Discontinuous Changes

The value of a continuous-time state variable can be instantaneously The call sample(t0,d) returns sample(t0,d) changed by a reinit-equation within a when-equation true and triggers events at times true , where , … t0+i*d i=0,1 model BouncingBall "the bouncing ball model" false time parameter Real g=9.81; //gravitational acc. t0 t0+d t0+2d t0+3d t0+4d parameter Real c=0.90; //elasticity constant Variables need to be Real height(start=10),velocity(start=0); discrete equation der(height) = velocity; model SamplingClock Creates an event der(velocity)=-g; Integer i; after 2 s, then when height<0 then discrete Real r; reinit(velocity, -c*velocity); equation each 0.5 s end when; when sample(2,0.5) then end BouncingBall; i = pre(i)+1; r = pre(r)+0.3; Initial conditions end when; pre(...) takes the end SamplingClock; Reinit ”assigns” previous value continuous-time variable before the event. velocity a new value

127 Copyright © Open Source Modelica Consortium 128 Copyright © Open Source Modelica Consortium

Application: Digital Control Systems Sampled Data-Systems in Modelica

// time-discrete controller when {initial(),sample(3,3)} then E*xd = A*pre(xd)+ B*y; ud = C*pre(xd) + D*y; end when; y ud

// plant (continuous-time process) 0 = f(der(x), x, ud); y = g(x);

• Discrete-time controller + continuous-time plant = • y is automatically sampled at t = 3, 6, 9,…; hybrid system or sampled-data system •xd, u are piecewise-constant variables that change values at • Typically periodic sampling, can be modeled with sampling events (implicit zero-order hold) • initial() triggers event at initialization (t=0) “when sample(t0,td) then …”

129 Copyright © Open Source Modelica Consortium 130 Copyright © Open Source Modelica Consortium

Exercise 2.6 – BouncingBall

• Locate the BouncingBall model in one of the hybrid modeling sections of DrModelica (the When- Equations link in Section 2.9), run it, change it slightly, and re-run it. Part IIIc “Technology Preview”

Clocked Synchronous Models and State Machines

131 Copyright © Open Source Modelica Consortium 132 Copyright © Open Source Modelica Consortium

22 Clocked Synchronous Extension in Modelica 3.3 State Machines in Modelica 3.3: Simple Example

• Equations are active if corresponding clock ticks. Defaults to periodic clock with 1.0 s sampling period • “i” is a shared variable, “j” is a local variable. Transitions are “delayed” and enter states by “reset”

133 Copyright © Open Source Modelica Consortium 134 Copyright © Open Source Modelica Consortium

Simple Example: Modelica Code Hierarchical and Parallel Composition model Simple_NoAnnotations "Simple state machine" inner Integer i(start=0); block State1 outer output Integer i; output Integer j(start=10); equation i = previous(i) + 2; j = previous(j) - 1; end State1; State1 state1; block State2 outer output Integer i; equation i = previous(i) - 1; end State2; State2 state2; equation transition(state1,state2,i > 10,immediate=false); transition(state2,state1,i < 1,immediate=false); Semantics of Modelica state machines (and example above) initialState(state1); end Simple_NoAnnotations; inspired by Florence Maraninchi & Yann Rémond’s “Mode- Automata” and by Marc Pouzet’s Lucid Synchrone 3.0.

135 Copyright © Open Source Modelica Consortium 136 Copyright © Open Source Modelica Consortium

Technology Preview Preview Clocked Synchronous and State Machines

• The clocked synchronous language extension not yet ready in • The OMNotebook ebook OpenModelica (under development) “SynchronousAndStateMachinePreview.onb” • However some simple models can be simulated. provides one example featuring clocked • No graphical editing support for state machine in OMEdit, yet. synchronous language elements and two state machine examples. • Full state machine extension requires that clocked synchronous support is available • Open this and simulate. (If there is time) • However, many state machines can already be simulated • By using a workaround that restricts the sampling period of a state machine to a fixed default value of 1s.

137 Copyright © Open Source Modelica Consortium 138 Copyright © Open Source Modelica Consortium

23 Software Component Model

Interface Acausal coupling Connector

Part IV Component Connection Component Causal coupling Components, Connectors and Connections – A component class should be defined independently of the Modelica Libraries and Graphical Modeling environment, very essential for reusability A component may internally consist of other components, i.e. hierarchical modeling Complex systems usually consist of large numbers of connected components

139 Copyright © Open Source Modelica Consortium 140 Copyright © Open Source Modelica Consortium

Connectors and Connector Classes The flow prefix

Connectors are instances of connector classes Two kinds of variables in connectors: electrical connector • Non-flow variables potential or energy level connector class connector Pin • Flow variables represent some kind of flow Voltage v; v + keyword flow flow Current i; pin indicates that currents end Pin; Coupling of connected pins i sum to zero. • Equality coupling, for non- variables Pin pin; flow an instance pin • Sum-to-zero coupling,forflow variables of class Pin mechanical connector connector class connector Flange The value of a flow variable is positive when the current Position s; flow Force f; s or the flow is into the component end Flange; flange v f pin an instance flange Flange flange; positive flow direction: of class Flange i +

141 Copyright © Open Source Modelica Consortium 142 Copyright © Open Source Modelica Consortium

Physical Connector connect-equations

• Classes Based on Energy Flow Connections between connectors are realized as equations in Modelica

Domain Potential Flow Carrier Modelica connect(connector1,connector2) Type Library Electrical. The two arguments of a connect-equation must be references to Electrical Voltage Current Charge Analog connectors, either to be declared directly within the same class or be Mechanical. Translational Position Force Linear momentum members of one of the declared variables in that class Translational Angular Mechanical. Rotational Angle Torque momentum Rotational + v v + Magnetic Magnetic pin1 pin2 Magnetic Magnetic flux potential flux rate i i Hydraulic Pressure Volume flow Volume HyLibLight Heat Temperature Heat flow Heat HeatFlow1D Pin pin1,pin2; Chemical Under Chemical Particle flow Particles //A connect equation potential construction //in Modelica: Corresponds to pin1.v = pin2.v; connect(pin1,pin2); Pneumatic Pressure Mass flow Air PneuLibLight pin1.i + pin2.i =0;

143 Copyright © Open Source Modelica Consortium 144 Copyright © Open Source Modelica Consortium

24 Connection Equations Common Component Structure

Pin pin1,pin2; The base class TwoPin has //A connect equation i //in Modelica two connectors p and n for p.v + TwoPin - i n.v Corresponds to pin1.v = pin2.v; p n connect(pin1,pin2); pin1.i + pin2.i =0; positive and negative pins p.i n.i Multiple connections are possible: respectively i connect(pin1,pin2); connect(pin1,pin3); ... connect(pin1,pinN); partial class partial model TwoPin (cannot be Voltage v electrical connector class Each primitive connection set of nonflow variables is instantiated) connector Pin Current i Voltage v; used to generate equations of the form: positive pin Pin p; flow Current i; negative pin Pin n; end Pin; equation vvv123 vn v = p.v - n.v; 0 = p.i + n.i; Each primitive connection set of flow variables is used to generate i = p.i; end TwoPin; sum-to-zero equations of the form: // TwoPin is same as OnePort in // Modelica.Electrical.Analog.Interfaces ii12()  ikn  i  0

145 Copyright © Open Source Modelica Consortium 146 Copyright © Open Source Modelica Consortium

Electrical Components Electrical Components cont’

model Resistor ”Ideal electrical resistor” extends TwoPin; p.i n.i parameter Real R; + model Source equation extends TwoPin; v(t) p.v n.v p.i n.i parameter Real A,w; R*i = v; v + end Resistor; equation v = A*sin(w*time); p.v n.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 Ground

Pin p; This image cannot currently be equation displayed. model Capacitor ”Ideal electrical capacitor” p.v = 0; extends TwoPin; p.i n.i end Ground; parameter Real C ; + equation p.v n.v i=C*der(v); v end Capacitor;

147 Copyright © Open Source Modelica Consortium 148 Copyright © Open Source Modelica Consortium

Resistor Circuit Modelica Standard Library - Graphical Modeling

• Modelica Standard Library (called Modelica) is a

i1 i 2 n R1 p p R2 n v 1 v 2 standardized predefined package developed by

v 3 p R3 n Modelica Association i 3

• It can be used freely for both commercial and model ResistorCircuit noncommercial purposes under the conditions of Resistor R1(R=100); Resistor R2(R=200); The Modelica License. Resistor R3(R=300); equation Corresponds to R1.p.v = R2.p.v; connect(R1.p, R2.p); R1.p.v = R3.p.v; connect(R1.p, R3.p); R1.p.i + R2.p.i + R3.p.i = 0; • Modelica libraries are available online including end ResistorCircuit; documentation and source code from http://www.modelica.org/library/library.html

149 Copyright © Open Source Modelica Consortium 150 Copyright © Open Source Modelica Consortium

25 Modelica Standard Library cont’ Modelica.Blocks

The Modelica Standard Library contains components from Continuous, discrete, and logical input/output blocks various application areas, including the following sublibraries: to build block diagrams. • Blocks Library for basic input/output control blocks

• Constants Mathematical constants and constants of nature Library • Electrical Library for electrical models Continuous • Icons Icon definitions • Fluid 1-dim Flow in networks of vessels, pipes, fluid machines, valves, etc. • Math Mathematical functions Examples: • 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

151 Copyright © Open Source Modelica Consortium 152 Copyright © Open Source Modelica Consortium

Modelica.Electrical Modelica.Mechanics

Electrical components for building analog, digital, and Package containing components for mechanical systems multiphase circuits Subpackages:

Library Library Library Library • Rotational 1-dimensional rotational mechanical components

Analog Digital Machines MultiPhase • Translational 1-dimensional translational mechanical components • MultiBody 3-dimensional mechanical components Examples:

V2

R2 R4

Gnd9

C2 Gnd3 Gnd6 C4 R1 Transistor1 Transistor2 R3

V1 C1 I1 C5 C3 Gnd4

Gnd1 Gnd2 Gnd7 Gnd8 Gnd5

153 Copyright © Open Source Modelica Consortium 154 Copyright © Open Source Modelica Consortium

Modelica.Stategraph Other Free Libraries

Hierarchical state machines (similar to Statecharts) • WasteWater Wastewater treatment plants, 2003 • ATPlus Building simulation and control (fuzzy control included), 2005 • MotorCycleDymanics Dynamics and control of motorcycles, 2009 • NeuralNetwork Neural network mathematical models, 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, 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 • ...

155 Copyright © Open Source Modelica Consortium 156 Copyright © Open Source Modelica Consortium

26 Some Commercial Libraries Connecting Components from Multiple Domains

• Block domain 1 R1 • Powertrain ind • Mechanical domain R2 • SmartElectricDrives emf ex ac iner vsen

• VehicleDynamics 2 • Electrical domain Block Mechanical Electrical • AirConditioning domain domain G domain model Generator •HyLib Modelica.Mechanics.Rotational.Accelerate ac; • PneuLib Modelica.Mechanics.Rotational.Inertia iner; Modelica.Electrical.Analog.Basic.EMF emf(k=-1); • CombiPlant Modelica.Electrical.Analog.Basic.Inductor ind(L=0.1); Modelica.Electrical.Analog.Basic.Resistor R1,R2; • HydroPlant 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;

157 Copyright © Open Source Modelica Consortium 158 Copyright © Open Source Modelica Consortium

DCMotor Model Multi-Domain (Electro-Mechanical)

A DC motor can be thought of as an electrical circuit which also contains an electromechanical component. Part V Dynamic Optimization model DCMotor Resistor R(R=100); Theory and Exercises Inductor L(L=100); VsourceDC DC(f=10); Ground G; EMF emf(k=10,J=10, b=2); Inertia load; using equation R L connect(DC.p,R.n); emf OpenModelica connect(R.p,L.n); DC connect(L.p, emf.n); connect(emf.p, DC.n); load connect(DC.n,G.p); connect(emf.flange,load.flange); G end DCMotor;

159 Copyright © Open Source Modelica Consortium 160 Copyright © Open Source Modelica Consortium

Optimization of Dynamic Trajectories Using Built-in Dynamic Optimization - Motivation Multiple-Shooting and Collocation

• Minimize a goal function subject to model This approach uses a single Simulation equation constraints, useful e.g. for NMPC optimization run and is different from classical parameter • Multiple Shooting/Collocation Inputs Output sweep optimization typically using Simulation • Solve sub-problem in each sub-interval (known) (result) a large number of simulations

Example speedup, 16 cores:

MULTIPLE_COLLOCATION Optimization – Try to find the inputs that result in a desired output 16.0 14.0 12.0 10.0 Inputs Output 8.0 Simulation 6.0 (result) (desired) 4.0 2.0 0.0 124816

ipopt [scaled] jac_g [scaled]

161 Copyright © Open Source Modelica Consortium 162 Copyright © Open Source Modelica Consortium

27 Optimal Control Problem (OCP) OCP Formulation in OpenModelica

Cost The path constraints ,,0can be split into box min ,, , , ,, function 1 MayerTerm LagrangeTerm constraints Subject to min max Initial conditions 2 min max Nonlinear dynamic model ,, 3 Path constraints ,, 0 4 Variable attributes min and max are reused for describing Terminal constraints constraints, annotations are used for specifying the OCP 0 5 where Annotation ,…, is the state vector and Mayer-Term Real costM annotation(isMayer=true); ,…, is the control variable vector for Lagrange-Term Real costL annotation(isLagrange=true); ∈, respectively. Constraints Real x(max=0) annotation(isConstraint=true); Final constraints Real y(min=0) annotation(isFinalConstraint=true);

163 Copyright © Open Source Modelica Consortium 164 Copyright © Open Source Modelica Consortium

Predator-Prey Example – The Forest Model Predator-Prey Example – Modelica model

Dynamic model of a forest with foxes , rabbits , fox hunters and rabbit hunters (adapted from Vitalij Ruge, “Native Optimization model Forest "Predator-prey model" Features in OpenModelica”, part of the OpenModelica documentation) parameter Real g_r = 4e-2 "Natural growth rate for rabbits"; parameter Real g_fr = 1e-1 "Efficiency in growing foxes from rabbits"; parameter Real d_rf = 5e-3 "Death rate of rabbits due to foxes"; parameter Real d_rh = 5e-2 "Death rate of rabbits due to hunters"; ∙ ∙ ∙ ∙ parameter Real d_f = 9e-2 "Natural deathrate for foxes"; ∙ ∙ ∙ ∙ ∙ parameter Real d_fh = 9e-2 "Death rate of foxes due to hunters"; Real x_r(start=700,fixed=true) "Rabbits with start population of 700"; IC: 700, 10 Real x_f(start=10,fixed=true) "Foxes with start population of 10"; input Real u_hr "Rabbit hunters"; input Real u_hf "Fox hunters"; Control where equation variables 4∙10, Natural growth rate 5∙10, Death rate of der(x_r) = g_r*x_r - d_rf*x_r*x_f - d_rh*u_hr; der(x_f) = g_fr*d_rf*x_r*x_f - d_f*x_f - d_fh*u_hf; for rabbits rabbits due to hunters end Forest; 1∙10 , Efficiency in growing 9∙10 , Natural death rate foxes from rabbits for foxes 5∙10 , Death rate of rabbits 9∙10 , Death rate of due to foxes foxes due to hunters

165 Copyright © Open Source Modelica Consortium 166 Copyright © Open Source Modelica Consortium

Predator-Prey Example – Optimal Control Problem Predator-Prey Example – Using OMNotebook

Objective: Regulate the population in the forest to a desired Start the optimization from OMNotebook using a time interval level (5 foxes, 500 rabbits) at the end of the simulation () , 0,400 seconds 0.1 ∙ 5 0.01∙ 500 (desired population at ) setCommandLineOptions("+gDynOpt"); Constraints: 0, 0, x 0, x 0 optimize(ForestOCP, stopTime=400, tolerance=1e-8, numberOfIntervals=50, simflags="-s optimization"); Modelica model: Important for scaling, needs to be > 0 to make Cost function Extension of the constraint optimizer converge! Mayer-term Option Example value Description system model numberOfIntervals 50 collocation intervals model ForestOCP; extends Forest( startTime, stopTime 0, 400 time horizon in seconds u_hr(min=0, nominal=1e-4),u_hf(min=0, nominal=1e-4), x_r(min=0),x_f(min=0)); tolerance 1e-8 solver/optimizer tolerance Real J_Mayer = simflags … see documentation for details 0.1*(x_r- 5)^2 + 0.01*(x_r - 500)^2 annotation(isMayer=true); end ForestOCP;

167 Copyright © Open Source Modelica Consortium 168 Copyright © Open Source Modelica Consortium

28 Predator-Prey Example – Using OMEdit Predator-Prey Example – Plots

Tools→Options→Simulation Simulation→Simulation Setup

Simulation of the forest model with Simulation of the forest model using the control variables control variables 0 computed by the optimization. +gDynOpt Notice (not well visible in the plot) that optimization 500, 5

169 Copyright © Open Source Modelica Consortium 170 Copyright © Open Source Modelica Consortium

Exercise – Optimal Control

Load the OPCExample.onb ebook into OMNotebook and Part Vb modify the optimization problem in the following ways: More 1. Constrain the maximal number of rabbit hunters and fox hunters to five, respectively. Graphical Modeling Exercises 2. Change the Mayer-term of the cost function to a Lagrange-term. using 3. Penalize the number of employed hunters by a OpenModelica suitable modification of the cost function and observe how the solution changes for different modifications.

171 Copyright © Open Source Modelica Consortium 172 Copyright © Open Source Modelica Consortium

Graphical Modeling Animation – DCMotor Graphical Modeling - Using Drag and Drop Composition

173 Copyright © Open Source Modelica Consortium 174 Copyright © Open Source Modelica Consortium

29 Multi-Domain (Electro-Mechanical) Modelica Model Corresponding DCMotor Model Equations

• A DC motor can be thought of as an electrical circuit which The following equations are automatically derived from the Modelica model: also contains an electromechanical component model DCMotor Resistor R(R=100); Inductor L(L=100); VsourceDC DC(f=10); Ground G; ElectroMechanicalElement EM(k=10,J=10, b=2); Inertia load; equation R L connect(DC.p,R.n); EM connect(R.p,L.n); DC (load component not included) connect(L.p, EM.n); load connect(EM.p, DC.n); Automatic transformation to ODE or DAE for simulation: connect(DC.n,G.p); connect(EM.flange,load.flange); G end DCMotor

175 Copyright © Open Source Modelica Consortium 176 Copyright © Open Source Modelica Consortium

Exercise 3.1 Exercise 3.2

• Draw the DCMotor model using the graphic connection • If there is enough time: Add a torsional spring to the editor using models from the following Modelica outgoing shaft and another inertia element. Simulate again and see the results. Adjust some parameters to libraries: make a rather stiff spring. Mechanics.Rotational.Components, Electrical.Analog.Basic, Electrical.Analog.Sources

• Simulate it for 15s and plot the R L emf variables for the outgoing u rotational speed on the inertia J axis and the voltage on the

voltage source (denoted u in the G figure) in the same plot.

177 Copyright © Open Source Modelica Consortium 178 Copyright © Open Source Modelica Consortium

Exercise 3.3 Exercise 3.4 – DrControl

• If there is enough time: Add a PI controller to the system • If there is enough time: Open the DrControl electronic book and try to control the rotational speed of the outgoing shaft. about control theory with Modelica and do some exercises. Verify the result using a step signal for input. Tune the PI • Open File: C:OpenModelica1.9.3\share\omnotebook\drcontrol\DrControl.onb controller by changing its parameters in OMEdit.

179 Copyright © Open Source Modelica Consortium 180 Copyright © Open Source Modelica Consortium

30 Learn more… Summary

Multi-Domain Visual Acausal • OpenModelica Modeling Component • www.openmodelica.org Modeling • Modelica Association • www.modelica.org • Books • Principles of Object Oriented Modeling and Simulation with Modelica 3.3: A Cyber-Physical Approach, Peter Fritzson 2015.

• Modeling and Simulation of Technical and Physical Systems with Modelica. Peter Fritzson., 2011 Typed http://eu.wiley.com/WileyCDA/WileyTitle/productCd- 111801068X.html Declarative Hybrid • Introduction to Modelica, Michael Tiller Textual Language Thanks for listening! Modeling

181 Copyright © Open Source Modelica Consortium 182 Copyright © Open Source Modelica Consortium

31