OpenModelicaUsersGuide-1 21 PDF
OpenModelicaUsersGuide-1 21 PDF
OpenModelicaUsersGuide-1 21 PDF
Release v1.21.0-1-g4ef5d27bdd
2023
CONTENTS
1 Introduction 3
1.1 System Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Interactive Session with Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Summary of Commands for the Interactive Session Handler . . . . . . . . . . . . . . . . . . . . 24
1.4 Running the compiler from command line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2 Package Management 27
2.1 Overview of Basic Modelica Package Management Concepts . . . . . . . . . . . . . . . . . . . 27
2.2 The Package Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3 How the package index works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
i
3.33 Temporary Directory, Log Files and Working Directory . . . . . . . . . . . . . . . . . . . . . . 74
3.34 High DPI Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4 2D Plotting 81
4.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.2 Plot Command Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
6 Debugging 95
6.1 The Equation-based Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.2 The Algorithmic Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
10 OMSimulator 131
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.2 OMSimulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.3 OMSimulatorLib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
10.4 OMSimulatorLua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
10.5 OMSimulatorPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.6 OpenModelicaScripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
10.7 Graphical Modelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
10.8 SSP Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
ii
14 Optimization with OpenModelica 251
14.1 Built-in Dynamic Optimization using Annotations . . . . . . . . . . . . . . . . . . . . . . . . . 251
14.2 Built-in Dynamic Optimization using Optimica language extensions . . . . . . . . . . . . . . . . 261
14.3 Dynamic Optimization with OpenModelica and CasADi . . . . . . . . . . . . . . . . . . . . . . 263
14.4 Parameter Sweep Optimization using OMOptim . . . . . . . . . . . . . . . . . . . . . . . . . . 268
16 PDEModelica1 291
16.1 PDEModelica1 language elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
16.2 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
16.3 Viewing results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
iii
24.7 Standard set methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
24.8 Usage of setMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
24.9 Advanced Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
24.10 Linearization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
24.11 Usage of Linearization methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
24.12 Sensitivity Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
24.13 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
25 Jupyter-OpenModelica 355
iv
32.20 Release Notes for OpenModelica 1.9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
32.21 Release Notes for OpenModelica 1.9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
32.22 Release Notes for OpenModelica 1.9.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
32.23 Release Notes for OpenModelica 1.8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
32.24 OpenModelica 1.8.0, November 2011 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
32.25 OpenModelica 1.7.0, April 2011 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
32.26 OpenModelica 1.6.0, November 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
32.27 OpenModelica 1.5.0, July 2010 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
32.28 OpenModelica 1.4.5, January 2009 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
32.29 OpenModelica 1.4.4, Feb 2008 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
32.30 OpenModelica 1.4.3, June 2007 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
32.31 OpenModelica 1.4.2, October 2006 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
32.32 OpenModelica 1.4.1, June 2006 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
32.33 OpenModelica 1.4.0, May 2006 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
32.34 OpenModelica 1.3.1, November 2005 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Bibliography 539
Index 541
v
vi
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
This work is licensed under a Creative Commons Attribution 4.0 International License.
This document is part of OpenModelica: https://www.openmodelica.org Contact: [email protected]
Modelica® is a registered trademark of the Modelica Association, https://www.Modelica.org
Mathematica® is a registered trademark of Wolfram Research Inc, http://www.wolfram.com
This users guide provides documentation and examples on how to use the OpenModelica system, both for the
Modelica beginners and advanced users.
CONTENTS 1
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
The OpenModelica system described in this document has both short-term and long-term goals:
• The short-term goal is to develop an efficient interactive computational environment for the Modelica lan-
guage, as well as a rather complete implementation of the language. It turns out that with support of
appropriate tools and libraries, Modelica is very well suited as a computational language for development
and execution of both low level and high level numerical algorithms, e.g. for control system design, solving
nonlinear equation systems, or to develop optimization algorithms that are applied to complex applications.
• The long-term goal is to have a complete reference implementation of the Modelica language, including
simulation of equation based models and additional facilities in the programming environment, as well
as convenient facilities for research and experimentation in language design or other research activities.
However, our goal is not to reach the level of performance and quality provided by current commercial
Modelica environments that can handle large models requiring advanced analysis and optimization by the
Modelica compiler.
The long-term research related goals and issues of the OpenModelica open source implementation of a Modelica
environment include but are not limited to the following:
• Development of a complete formal specification of Modelica, including both static and dynamic semantics.
Such a specification can be used to assist current and future Modelica implementers by providing a semantic
reference, as a kind of reference implementation.
• Language design, e.g. to further extend the scope of the language, e.g. for use in diagnosis, structural
analysis, system identification, etc., as well as modeling problems that require extensions such as partial
differential equations, enlarged scope for discrete modeling and simulation, etc.
• Language design to improve abstract properties such as expressiveness, orthogonality, declarativity, reuse,
configurability, architectural properties, etc.
• Improved implementation techniques, e.g. to enhance the performance of compiled Modelica code by gen-
erating code for parallel hardware.
• Improved debugging support for equation based languages such as Modelica, to make them even easier to
use.
• Easy-to-use specialized high-level (graphical) user interfaces for certain application domains.
• Visualization and animation techniques for interpretation and presentation of results.
• Application usage and model library development by researchers in various application areas.
The OpenModelica environment provides a test bench for language design ideas that, if successful, can be submit-
ted to the Modelica Association for consideration regarding possible inclusion in the official Modelica standard.
The current version of the OpenModelica environment allows most of the expression, algorithm, and function
parts of Modelica to be executed interactively, as well as equation models and Modelica functions to be compiled
into efficient C code. The generated C code is combined with a library of utility functions, a run-time library, and
a numerical DAE solver.
3
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Interactive
OMOptim sessionhandler Textual
Optimization
Model Editor
Subsystem
OMNotebook
DrModelica Execution Modelica
Model Editor Compiler
Modelica
Debugger
Figure 1.1: The architecture of the OpenModelica environment. Arrows denote data and control flow. The inter-
active session handler receives commands and shows results from evaluating commands and expressions that are
translated and executed. Several subsystems provide different forms of browsing and textual editing of Modelica
code. The debugger currently provides debugging of an extended algorithmic subset of Modelica.
4 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Optimization subsystem OMOptim. This is an optimization subsystem for OpenModelica, currently for
design optimization choosing an optimal set of design parameters for a model. The current version has a
graphical user interface, provides genetic optimization algorithms and Pareto front optimization, works in-
tegrated with the simulators and automatically accesses variables and design parameters from the Modelica
model.
• Dynamic Optimization subsystem. This is dynamic optimization using collocation methods, for Model-
ica models extended with optimization specifications with goal functions and additional constraints. This
subsystem is integrated with in the OpenModelica compiler.
• Modelica equation model debugger. The equation model debugger shows the location of an error in the
model equation source code. It keeps track of the symbolic transformations done by the compiler on the
way from equations to low-level generated C code, and also explains which transformations have been done.
• Modelica algorithmic code debugger. The algorithmic code Modelica debugger provides debugging for an
extended algorithmic subset of Modelica, excluding equation-based models and some other features, but in-
cluding some meta-programming and model transformation extensions to Modelica. This is a conventional
full-feature debugger, using Eclipse for displaying the source code during stepping, setting breakpoints, etc.
Various back-trace and inspection commands are available. The debugger also includes a data-view browser
for browsing hierarchical data such as tree- or list structures in extended Modelica.
>>> getVersion()
"OMCompiler v1.21.0-v1.21.0.1+g4ef5d27bdd"
>>> x := 1:12
{1,2,3,4,5,6,7,8,9,10,11,12}
Example Session 1
>>> model A Integer t = 1.5; end A; //The type is Integer but 1.5 is of Real Type
{A}
>>> instantiateModel(A)
""
"[<interactive>:1:9-1:23:writable] Error: Type mismatch in binding t = 1.5,
˓→expected subtype of Integer, got type Real.
"
Example Session 2
If you do not see the error-message when running the example, use the command getErrorString().
model C
Integer a;
Real b;
equation
der(a) = b; // der(a) is illegal since a is not a Real number
der(b) = 12.0;
end C;
>>> instantiateModel(C)
""
Error:
[<interactive>:5:3-5:13:writable] Error: Argument ‘a‘ of der is not differentiable.
true
The function bubblesort is called below to sort the vector x in descending order. The sorted result is returned to-
gether with its type. Note that the result vector is of type Real[:], instantiated as Real[12], since this is the declared
type of the function result. The input Integer vector was automatically converted to a Real vector according to
the Modelica type coercion rules. The function is automatically compiled when called if this has not been done
before.
>>> bubblesort(x)
{12.0,11.0,10.0,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0}
Another call:
>>> bubblesort({4,6,2,5,8})
{8.0,6.0,5.0,4.0,2.0}
6 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
function bubblesort
input Real[:] x;
output Real[size(x,1)] y;
protected
Real t;
algorithm
y := x;
for i in 1:size(x,1) loop
for j in 1:size(x,1) loop
if y[i] > y[j] then
t := y[i];
y[i] := y[j];
y[j] := t;
end if;
end for;
end for;
end bubblesort;
Note: The output emitted into stdout by system commands is put into log-files when running the CORBA-based
clients, not into the visible GUI windows. Thus the text emitted by the above cat command would not be returned,
which is why it is redirected to another file.
A better way to read the content of files would be the readFile command:
>>> readFile("bubblesort.mo")
function bubblesort
input Real[:] x;
output Real[size(x,1)] y;
protected
Real t;
algorithm
y := x;
for i in 1:size(x,1) loop
for j in 1:size(x,1) loop
if y[i] > y[j] then
t := y[i];
y[i] := y[j];
y[j] := t;
end if;
end for;
end for;
end bubblesort;
>>> system("dir")
0
>>> system("Non-existing command")
127
Another built-in command is cd, the change current directory command. The resulting current directory is returned
as a string.
>>> dir:=cd()
"«DOCHOME»"
>>> cd("source")
"«DOCHOME»/source"
>>> cd(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/")
"/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/share/doc/omc/testmodels
˓→"
>>> cd(dir)
"«DOCHOME»"
true
Note:
Notification: dcmotor requested package Modelica of version 3.2.2. Modelica 3.2.3 is used instead which states
that it is fully compatible without conversion script needed.
It is simulated:
Note:
Notification: dcmotor requested package Modelica of version 3.2.2. Modelica 3.2.3 is used instead which states
that it is fully compatible without conversion script needed.
8 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
>>> list(dcmotor)
model dcmotor
import Modelica.Electrical.Analog.Basic;
Basic.Resistor resistor1(R = 10);
Basic.Inductor inductor1(L = 0.2, i.fixed = true);
Basic.Ground ground1;
Modelica.Mechanics.Rotational.Components.Inertia load(J = 1, phi.fixed = true, w.
˓→fixed = true);
˓→"Reference temperature";
˓→heatPort - T_ref))";
˓→of heatPort";
˓→der(phi))";
10 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
equation
emf1.internalSupport.flange.phi = emf1.fixed.flange.phi;
step1.y = signalVoltage1.v;
signalVoltage1.p.v = resistor1.p.v;
resistor1.n.v = inductor1.p.v;
inductor1.n.v = emf1.p.v;
emf1.flange.phi = load.flange_a.phi;
ground1.p.v = emf1.n.v;
ground1.p.v = signalVoltage1.n.v;
inductor1.p.i + resistor1.n.i = 0.0;
emf1.p.i + inductor1.n.i = 0.0;
load.flange_b.tau = 0.0;
emf1.flange.tau + load.flange_a.tau = 0.0;
emf1.internalSupport.flange.tau + emf1.fixed.flange.tau = 0.0;
signalVoltage1.p.i + resistor1.p.i = 0.0;
signalVoltage1.n.i + emf1.n.i + ground1.p.i = 0.0;
assert(1.0 + resistor1.alpha * (resistor1.T_heatPort - resistor1.T_ref) >= 1e-15,
˓→ "Temperature outside scope of model!");
Note:
Notification: dcmotor requested package Modelica of version 3.2.2. Modelica 3.2.3 is used instead which states
that it is fully compatible without conversion script needed.
4
load.w
load.phi
3.5
2.5
1.5
0.5
0
0 2 4 6 8 10
12 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
true
>>> list(BouncingBall)
model BouncingBall
parameter Real e = 0.7 "coefficient of restitution";
parameter Real g = 9.81 "gravity acceleration";
Real h(fixed = true, start = 1) "height of ball";
Real v(fixed = true) "velocity of ball";
Boolean flying(fixed = true, start = true) "true, if ball is flying";
Boolean impact;
Real v_new(fixed = true);
Integer foo;
equation
impact = h <= 0.0;
foo = if impact then 1 else 2;
der(v) = if flying then -g else 0;
der(h) = v;
when {h <= 0.0 and v <= 0.0, impact} then
v_new = if edge(impact) then -e*pre(v) else 0;
flying = v_new > 0;
reinit(v, v_new);
end when;
end BouncingBall;
Instead of just giving a simulate and plot command, we perform a runScript command on a .mos (Modelica script)
file sim_BouncingBall.mos that contains these commands:
>>> writeFile("sim_BouncingBall.mos", "
loadFile(getInstallationDirectoryPath() + \"/share/doc/omc/testmodels/
˓→BouncingBall.mo\");
simulate(BouncingBall, stopTime=3.0);
/* plot({h,flying}); */
")
true
>>> runScript("sim_BouncingBall.mos")
"true
record SimulationResult
resultFile = \"«DOCHOME»/BouncingBall_res.mat\",
simulationOptions = \"startTime = 0.0, stopTime = 3.0, numberOfIntervals = 500,
˓→ tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'BouncingBall', options =
model Switch
Real v;
Real i;
Real i1;
Real itot;
Boolean open;
equation
itot = i + i1;
if open then
v = 0;
else
i = 0;
end if;
1 - i1 = 0;
1 - v - i = 0;
open = time >= 0.5;
end Switch;
Retrieve the value of itot at time=0 using the val(variableName, time) function:
>>> val(itot,0)
1.0
14 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
2
itot
open
1.5
0.5
0
0 0.2 0.4 0.6 0.8 1
>>> clear()
true
>>> list()
""
true
It is simulated:
It is plotted:
>>> plotParametric("x","y")
2.5
1.5
0.5
0
y
-0.5
-1
-1.5
-2
-2.5
-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
x
>>> instantiateModel(VanDerPol)
class VanDerPol "Van der Pol oscillator model"
Real x(start = 1.0, fixed = true);
Real y(start = 1.0, fixed = true);
parameter Real lambda = 0.3;
equation
der(x) = y;
der(y) = (-x) + lambda * (1.0 - x * x) * y;
end VanDerPol;
16 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
>>> k := 0;
>>> for i in 1:1000 loop
k := k + i;
end for;
>>> k
500500
>>> g := 0.0;
>>> h := 5;
>>> for i in {23.0,77.12,88.23} loop
for j in i:0.5:(i+1) loop
g := g + j;
g := g + h / 2;
end for;
h := h + g;
end for;
By putting two (or more) variables or assignment statements separated by semicolon(s), ending with a variable,
one can observe more than one variable value:
>>> h; g
1997.45
1479.09
>>> i:="";
>>> lst := {"Here ", "are ","some ","strings."};
>>> s := "";
>>> for i in lst loop
(continues on next page)
>>> s:="";
>>> i:=1;
>>> while i<=10 loop
s:="abc "+s;
i:=i+1;
end while;
>>> s
"abc abc abc abc abc abc abc abc abc abc "
A simple if-statement. By putting the variable last, after the semicolon, its value is returned after evaluation:
>>> a;b
100
"test"
>>> a:=1:5
{1,2,3,4,5}
Type in a function:
function mySqr
input Real x;
output Real y;
algorithm
y:=x*x;
end mySqr;
>>> b:=mySqr(2)
4.0
18 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
>>> a
{1,2,3,4,5}
>>> typeOf(a)
"Integer[5]"
>>> typeOf(b)
"Real"
>>> typeOf(mySqr)
>>> listVariables()
{b,a,s,lst,i,h,g,k,currentSimulationResult}
Clear again:
>>> clear()
true
>>> getErrorString()
""
It is also possible to specify which variables should be present in the result-file. This is done by using POSIX
Extended Regular Expressions. The given expression must match the full variable name (^ and $ symbols are
automatically added to the given regular expression).
// Default, match everything
// match indices of variable myVar that only contain the numbers using combinations
// of the letters 1 through 3
// match x or y or z
package Modelica
annotation(uses(Complex(version="1.0"),
ModelicaServices(version="1.1")));
end Modelica;
>>> clear()
true
model M
annotation(uses(Modelica(version="3.2.1")));
end M;
>>> instantiateModel(M)
class M
end M;
20 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Note:
Notification: Automatically loaded package Modelica 3.2.1 due to uses annotation from M.
Notification: Automatically loaded package Complex 3.2.1 due to uses annotation from Modelica.
Notification: Automatically loaded package ModelicaServices 3.2.1 due to uses annotation from Modelica.
Packages will also be loaded by looking at the first identifier in the path:
>>> instantiateModel(Modelica.Electrical.Analog.Basic.Ground)
class Modelica.Electrical.Analog.Basic.Ground "Ground node"
Real p.v(quantity = "ElectricPotential", unit = "V") "Potential at the pin";
Real p.i(quantity = "ElectricCurrent", unit = "A") "Current flowing into the pin
˓→";
equation
p.i = 0.0;
p.v = 0.0;
end Modelica.Electrical.Analog.Basic.Ground;
Note:
Notification: Automatically loaded package Complex 4.0.0 due to uses annotation from Modelica.
Notification: Automatically loaded package ModelicaServices 4.0.0 due to uses annotation from Modelica.
Notification: Automatically loaded package Modelica default due to usage.
>>> list(BouncingBall)
model BouncingBall
parameter Real e = 0.7 "coefficient of restitution";
parameter Real g = 9.81 "gravity acceleration";
Real h(fixed = true, start = 1) "height of ball";
Real v(fixed = true) "velocity of ball";
Boolean flying(fixed = true, start = true) "true, if ball is flying";
Boolean impact;
Real v_new(fixed = true);
Integer foo;
equation
impact = h <= 0.0;
foo = if impact then 1 else 2;
der(v) = if flying then -g else 0;
der(h) = v;
when {h <= 0.0 and v <= 0.0, impact} then
(continues on next page)
>>> getClassRestriction(BouncingBall)
"model"
>>> getClassInformation(BouncingBall)
("model","",false,false,false,"/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/
˓→build/share/doc/omc/testmodels/BouncingBall.mo",false,1,1,23,17,{},false,false,"
˓→","",false,"","","","","")
>>> isFunction(BouncingBall)
false
>>> existClass(BouncingBall)
true
>>> getComponents(BouncingBall)
{{Real, e, "coefficient of restitution", "public", false, false, false, false,
˓→"parameter", "none", "unspecified", {}},{Real, g, "gravity acceleration", "public
>>> getConnectionCount(BouncingBall)
0
>>> getInheritanceCount(BouncingBall)
0
>>> getComponentModifierValue(BouncingBall,e)
"0.7"
>>> getComponentModifierNames(BouncingBall,"e")
{}
>>> getClassRestriction(BouncingBall)
"model"
>>> getVersion() // Version of the currently running OMC
"OMCompiler v1.21.0-v1.21.0.1+g4ef5d27bdd"
>>> quit()
22 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
true
>>> exportDAEtoMatlab(BouncingBall)
"The equation system was dumped to Matlab file:BouncingBall_imatrix.m"
% Adjacency Matrix
% ====================================
% number of rows: 6
IM={{3,6},{1,{'if', 'true','==' {3},{},}},{{'if', 'true','==' {4},{},}},{5},{2,{'if
˓→', 'edge(impact)' {3},{5},}},{4,2}};
VL = {'foo','v_new','impact','flying','v','h'};
˓→new = if edge(impact) then (-e) * pre(v) else 0.0; end when;','when {h <= 0.0
˓→and v <= 0.0, impact} then flying = v_new > 0.0; end when;'};
simulate(modelname[,startTime=<Real>][,stopTime=<Real>][,numberOfIntervals
=<Integer>][,outputInterval=<Real>][,method=<String>]
[,tolerance=<Real>][,fixedStepSize=<Real>]
[,outputFormat=<String>]) Translate and simulate a model, with optional start time, stop time, and optional
number of simulation intervals or steps for which the simulation results will be computed. More intervals will
give higher time resolution, but occupy more space and take longer to compute. The default number of intervals
is 500. It is possible to choose solving method, default is “dassl”, “euler” and “rungekutta” are also available.
Output format “mat” is default. “plt” and “mat” (MATLAB) are the only ones that work with the val() command,
“csv” (comma separated values) and “empty” (no output) are also available (see section Alternative Simulation
Output Formats).
plot(vars) Plot the variables given as a vector or a scalar, e.g. plot({x1,x2}) or plot(x1).
plotParametric(var1, var2) Plot var2 relative to var1 from the most recently simulated model, e.g. plotParamet-
ric(x,y).
cd() Return the current directory.
cd(dir) Change directory to the directory given as string.
clear() Clear all loaded definitions.
clearVariables() Clear all defined variables.
dumpXMLDAE(modelname, ...) Dumps an XML representation of a model, according to several optional param-
eters.
exportDAEtoMatlab(name) Dumps a Matlab representation of a model.
instantiateModel(modelname)Performs code instantiation of a model/class and return a string containing the flat
class definition.
list() Return a string containing all loaded class definitions.
list(modelname) Return a string containing the class definition of the named class.
listVariables() Return a vector of the names of the currently defined variables.
loadModel(classname) Load model or package of name classname from the path indicated by the environment
variable OPENMODELICALIBRARY.
loadFile(str) Load Modelica file (.mo) with name given as string argument str.
readFile(str) Load file given as string str and return a string containing the file content.
runScript(str) Execute script file with file name given as string argument str.
system(str) Execute str as a system(shell) command in the operating system; return integer success value. Output
into stdout from a shell command is put into the console window.
timing(expr) Evaluate expression expr and return the number of seconds (elapsed time) the evaluation took.
typeOf(variable) Return the type of the variable as a string.
saveModel(str,modelname) Save the model/class with name modelname in the file given by the string argument
str.
val(variable,timePoint) Return the (interpolated) value of the variable at time timePoint.
help() Print this helptext (returned as a string).
quit() Leave and quit the OpenModelica environment
24 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
$ omc --help
OpenModelica Compiler OMCompiler v1.21.0-v1.21.0.1+g4ef5d27bdd
Copyright © 2019 Open Source Modelica Consortium (OSMC)
Distributed under OMSC-PL and GPL, see www.openmodelica.org
...
Documentation is available in the built-in package OpenModelica.Scripting or
online <https://build.openmodelica.org/Documentation/OpenModelica.Scripting.html>.
model TestModel
parameter Real x = 1;
end TestModel;
$ omc TestModel.mo
class TestModel
parameter Real x = 1.0;
end TestModel;
loadModel(Modelica);
getErrorString();
simulate(Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum);
getErrorString();
$ omc TestScript.mos
false
"Error: Failed to open file for writing: //.openmodelica/libraries/index.json.tmp1
Error: Failed to download package index https://libraries.openmodelica.org/index/
˓→v1/index.json to file //.openmodelica/libraries/index.json.
"
record SimulationResult
resultFile = "",
simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'Modelica.Mechanics.
timeFrontend = 0.0,
timeBackend = 0.0,
timeSimCode = 0.0,
timeTemplates = 0.0,
timeCompile = 0.0,
timeSimulation = 0.0,
timeTotal = 0.0
end SimulationResult;
""
In order to obtain more information from the compiler one can use the command line options --
showErrorMessages -d=failtrace when running the compiler:
...
timeSimulation = 0.0,
timeTotal = 0.0
end SimulationResult;
""
26 Chapter 1. Introduction
CHAPTER
TWO
PACKAGE MANAGEMENT
27
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
THREE
OMEdit – OpenModelica Connection Editor is the new Graphical User Interface for graphical model editing in
OpenModelica. It is implemented in C++ using the Qt graphical user interface library and supports the Modelica
Standard Library that is included in the latest OpenModelica installation. This chapter gives a brief introduction
to OMEdit and also demonstrates how to create a DCMotor model using the editor.
OMEdit provides several user friendly features for creating, browsing, editing, and simulating models:
• Modeling – Easy model creation for Modelica models.
• Pre-defined models – Browsing the Modelica Standard library to access the provided models.
• User defined models – Users can create their own models for immediate usage and later reuse.
• Component interfaces – Smart connection editing for drawing and editing connections between model in-
terfaces.
• Simulation – Subsystem for running simulations and specifying simulation parameters start and stop time,
etc.
• Plotting – Interface to plot variables from simulated models.
3.1.2 Linux
Start OMEdit by either selecting the corresponding menu application item or typing “OMEdit” at the shell or
command prompt.
31
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
3.1.3 Mac OS X
The default installation is /Application/MacPorts/OMEdit.app.
3.3 Perspectives
The perspective tabs are loacted at the bottom right of the MainWindow:
• Welcome Perspective
• Modeling Perspective
• Plotting Perspective
• Debugging Perspective
3.3. Perspectives 37
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
3.3. Perspectives 39
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
In order to connect one component model to another the user first needs to enable the connect mode ( ) from
the toolbar.
Move the mouse over the connector. The mouse cursor will change from arrow cursor to cross cursor. To start
the connection press left button and move while keeping the button pressed. Now release the left button. Move
towards the end connector and click when cursor changes to cross cursor.
3.15.1 General
• Simulation Interval
• Start Time – the simulation start time.
• Stop Time – the simulation stop time.
• Number of Intervals – the simulation number of intervals.
• Interval – the length of one interval (i.e., stepsize)
• Integration
• Method – the simulation solver. See section Integration Methods for solver details.
• Tolerance – the simulation tolerance.
• Jacobian - the jacobian method to use.
• DASSL/IDA Options
• Root Finding - Activates the internal root finding procedure of dassl.
• Restart After Event - Activates the restart of dassl after an event is performed.
• Initial Step Size
• Maximum Step Size
• Maximum Integration Order
• C/C++ Compiler Flags (Optional) – the optional C/C++ compiler flags.
• Number of Processors – the number of processors used to build the simulation.
• Build Only – only builds the class.
• Launch Transformational Debugger – launches the transformational debugger.
• Launch Algorithmic Debugger – launches the algorithmic debugger.
• Launch Animation – launches the 3d animation window.
3.15.5 Output
• Output Format – the simulation result file output format.
• Single Precision - Output results in single precision (only for mat output format).
• File Name Prefix (Optional) - the name is used as a prefix for the output files.
• Result File (Optional) - the simulation result file name.
• Variable Filter (Optional) - only output variables with names fully matching the regular expression
• *Protected Variables * - adds the protected variables in result file.
• Equidistant Time Grid – output the internal steps given by dassl instead of interpolating results into an
equidistant time grid as given by stepSize or numberOfIntervals
• Store Variables at Events – adds the variables at time events.
• Show Generated File – displays the generated files in a dialog box.
The Variable Filter takes a regular expression input and only saves in the simulation results file those variables
whose names fully match it. Here are some simple examples:
• .* matches any variable (default choice)
• xy.* matches variables starting with xy
• .*yz matches variables ending with yz
• abc\.def.* matches variables starting with abc.def. Note that the . character is a regex metacharac-
ter, so it must be escaped by a \
• .*body\.a_0\[1\] matches variables ending with body.a_0[1]. Note that ., [, and ] must be
escaped
• x\[.*\] matches all elements of array x
• x\[[2-4]\] matches elements 2, 3, and 4 of array x
• abc.*|def.* matches variables starting with abc or def
• .*der\(.*\) matches all derivatives in the model. Note that ( and ) must be escaped
Please note that all the model variables will still be shown in the Variables Browser tree; however, only those for
which results were actually saved will have a checkbox to plot them.
Note that input labels need not be lexicographically ordered, the association between the columns and the inputs
is given by the first row.
The CSV-file provides the values of the top level inputs at the specified points in time; linear interpolation is used
to provide intermediate values between any two subsequent data points. Discontinuous inputs can be obtained
by providing two consecutive rows with the same time value, containing the left limit values and the right limit
values.
Unless an absolute pathname is provided for the CSV-files, OMEdit will load it from the sub-directory of the
working directory which has the same name of the model, where all the other input and output data files are
located.
3.16 2D Plotting
Successful simulation of model produces the result file which contains the instance variables that are candidate for
plotting. Variables Browser will show the list of such instance variables. Each variable has a checkbox, checking
it will plot the variable. See Figure 3.7. To get several plot windows tiled horizontally or vertically use the menu
items Tile Windows Horizontally or Tile Windows Vertically under View Menu.
Time Plot
Plots the variable over the simulation time. You can have multiple Time Plot windows by clicking on New Plot
Window toolbar button ( ).
Plot Parametric
Draws a two-dimensional parametric diagram, between variables x and y, with y as a function of x. You can have
multiple Plot Parametric windows by clicking on the New Plot Parametric toolbar button ( ).
Select the x-axis variable while holding down the shift key, release the shift key and then select y-axis variables.
One or many y-axis variables can be selected against one x-axis variable. To select a new x-axis variable press
and hold the shift key again.
Unchecking the x-axis variable will uncheck all y-axis variables linked to it.
Array Plot
Plots an array variable so that the array elements' indexes are on the x-axis and corresponding elements' values are
on the y-axis. The time is controlled by the slider above the variable tree. When an array is present in the model,
it has a principal array node in the variable tree. To plot this array as an Array Plot, match the principal node. The
principal node may be expanded into particular array elements. To plot a single element in the Time Plot, match
the element. A new Array Plot window is opened using the New Array Plot Window toolbar button ( ).
Plots the first array elements' values on the x-axis versus the second array elements' values on the y-axis. The time
is controlled by the slider above the variable tree. To create a new Array Parametric Plot, press the New Array
Parametric Plot Window toolbar button ( ), then match the principle array node in the variable tree view to be
plotted on the x-axis and match the principle array node to be plotted on the y-axis.
Diagram Window
Shows the active ModelWidget as a read only diagram. You can only have one Diagram Window. To show it click
on Diagram Window toolbar button ( ).
3.16. 2D Plotting 51
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
3.18 3D Visualization
Since OpenModelica 1.11 , OMEdit has built-in 3D visualization, which replaces third-party libraries (such as
Modelica3D) for 3D visualization.
One can also run the visualization via Simulation > Simulate with Animation from the menu.
When simulating a model in animation mode, the flag +d=visxml is set. Hence, the compiler will generate a
scene description file _visual.xml which stores all information on the multibody shapes. This scene description
references all variables which are needed for the animation of the multibody system. When simulating with
+d=visxml, the compiler will always generate results for these variables.
The animation starts with pushing the play button. The animation is played until stopTime or until the pause
button is pushed. By pushing the previous button, the animation jumps to the initial point of time. Points of time
can be selected by moving the time slider or by inserting a simulation time in the Time-box. The speed factor of
animation in relation to realtime can be set in the Speed-dialog. Other animations can be openend by using the
open file button and selecting a result file with a corresping scene description file.
The 3D camera view can be manipulated as follows:
Predefined views (Isometric, Side, Front, Top) can be selected and the scene can be tilted by 90° either clock or
anticlockwise with the rotation buttons.
Menu Description
Change Transparency The shape becomes either transparent or intransparent.
Make Shape Invisible The shape becomes invisible.
Change Color A color dialog pops up and the color of the shape can be set.
Apply Check Texture A checked texture is applied to the shape.
Apply Custom Texture A file selection dialog pops up and an image file can be selected as a texture.
Remove Texture Removes the current texture of the shape.
3.18. 3D Visualization 55
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
model testModel
annotation(Icon(graphics = {Rectangle(rotation = 0, lineColor = {0,0,255},
˓→fillColor = {0,0,255}, pattern = LinePattern.Solid, fillPattern = FillPattern.
end testModel;
In the above code snippet of testModel, the rectangle and a polygon are added to the icon annotation of the model.
Similarly, any user defined shape drawn on a Diagram View of the model will be added to the diagram annotation
of the model.
package P
model M
annotation(Documentation(info="<html>
<a href=\"javascript:HelloWorld()\">Click here</a>
</html>"));
end M;
annotation(Documentation(__OpenModelica_infoHeader="
<script type=\"text/javascript\">
function HelloWorld() {
alert(\"Hello World!\");
}
</script>"));
end P;
In the above example model M does not need to define the javascript function HelloWorld. It is only defined
once at the package level using the __OpenModelica_infoHeader and then all classes contained in the
package can use it.
In addition styles and JavaScript can be added from file locations using Modelica URIs. Example:
package P
model M
annotation(Documentation(info="<html>
<a href=\"javascript:HelloWorld()\">Click here</a>
</html>"));
end M;
annotation(Documentation(__OpenModelica_infoHeader="
<script type=\"text/javascript\">
src=\"modelica://P/Resources/hello.js\">
}
</script>"));
end P;
function HelloWorld() {
alert("Hello World!");
}
3.23 Options
OMEdit allows users to save several options which will be remembered across different sessions of OMEdit. The
Options Dialog can be used for reading and writing the options.
3.23. Options 59
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
3.23. Options 61
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
– Icon/Diagram View
* Extent
* Left – Defines the left extent point for the view.
* Bottom – Defines the bottom extent point for the view.
* Right – Defines the right extent point for the view.
* Top – Defines the top extent point for the view.
* Grid
* Horizontal – Defines the horizontal size of the view grid.
* Vertical – Defines the vertical size of the view grid.
* Component
* Scale factor – Defines the initial scale factor for the component dragged on the view.
* Preserve aspect ratio – If true then the component’s aspect ratio is preserved while scaling.
• Save class before simulation – if true then always saves the class before running the simulation.
• Switch to plotting perspective after simulation – if true then GUI always switches to plotting
perspective after the simulation.
• Close completed simulation output windows before simulation – if true then the completed sim-
ulation output windows are closed before starting a new simulation.
• Delete intermediate compilation files – if true then the files generated during the compilation
are deleted automatically.
• Delete entire simulation directory of the model when OMEdit is closed – if true then the entire
simulation directory is deleted on quit.
• Output
• Structured - Shows the simulation output in the form of tree structure.
• Formatted Text - Shows the simulation output in the form of formatted text.
• Display Limit - Sets the display limit for simulation output. A link to log file is shown once the
limit is reached.
3.23. Options 63
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Legend
3.23. Options 65
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Model Description Filters - Sets the variable filter for model description file see omcflag-
fmifilter
• Include Modelica based resources via loadResource
• Include Source Code - Sets if the exported FMU can contain source code. Model Description
Filter "blackBox" will override this, because black box FMUs do never contain their source
code.
• Generate Debug Symbols - Generates a FMU with debug symbols.
• Import
• Delete FMU directory and generated model when OMEdit is closed - If true then the temporary FMU
directory that is created for importing the FMU will be deleted.
model Test
annotation(__OpenModelica_commandLineOptions = "--matchingAlgorithm=BFSB --
˓→indexReductionMethod=dynamicStateSelection");
end Test;
The annotation is a space separated list of options where each option is either just a command line flag or a flag
with a value.
In OMEdit open the Simulation Setup and set the Translation Flags then in the bottom check Save translation
flags inside model i.e., __OpenModelica_commandLineOptions annotation and click on OK.
If you want to ignore this annotation then use setCommandLineOptions("--
ignoreCommandLineOptionsAnnotation=true"). In OMEdit Tools > Options > Simulation check Ignore
__OpenModelica_commandLineOptions annotation.
model Test
annotation(__OpenModelica_simulationFlags(s = "heun", cpu = "()"));
end Test;
The annotation is a comma separated list of options where each option is a simulation flag with a value. For flags
that doesn't have any value use () (See the above code example).
In OMEdit open the Simulation Setup and set the Simulation Flags then in the bottom check Save simulation flags
inside model i.e., __OpenModelica_simulationFlags annotation and click on OK.
If you want to ignore this annotation then use setCommandLineOptions("--
ignoreSimulationFlagsAnnotation=true"). In OMEdit Tools > Options > Simulation check Ignore __OpenMod-
elica_simulationFlags annotation.
3.27 Debugger
For debugging capability, see Debugging.
In order to make a transition from one state to another the user first needs to enable the transition mode ( ) from
the toolbar.
Move the mouse over the state. The mouse cursor will change from arrow cursor to cross cursor. To start the
transition press left button and move while keeping the button pressed. Now release the left button. Move towards
the end state and click when cursor changes to cross cursor.
A Create Transition dialog box will appear which allows you to set the transition attributes. Cancelling the dialog
will cancel the transition.
Double click the transition or right click and choose Edit Transition to modify the transition attributes.
can switch between different result files by right clicking on the result file and selecting Set Active in the context
menu.
After the directory is opened in the Libraries-browser, the users can expand the directory structure and click the
file which opens in the texteditor.
The users can click the line number or the matched text and it will automatically open the file in the texteditor and
move the cursor to matched line number of the text.
The users can perform multiple searches and go back to old search results using search histroy option.
FOUR
2D PLOTTING
This chapter covers the 2D plotting available in OpenModelica via OMNotebook, OMShell and command line
script. The plotting is based on OMPlot application. See also OMEdit 2D Plotting.
4.1 Example
class HelloWorld
Real x(start = 1, fixed = true);
parameter Real a = 1;
equation
der(x) = - a * x;
end HelloWorld;
To create a simple time plot the above model HelloWorld is simulated. To reduce the amount of simulation data in
this example the number of intervals is limited with the argument numberOfIntervals=5. The simulation is started
with the command below.
record SimulationResult
resultFile = "«DOCHOME»/HelloWorld_res.csv",
simulationOptions = "startTime = 0.0, stopTime = 4.0, numberOfIntervals = 5,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'HelloWorld', options = '',
Warning:
[<interactive>:2:3-2:34:writable] Warning: Components are deprecated in class.
[<interactive>:3:3-3:23:writable] Warning: Components are deprecated in class.
[<interactive>:5:3-5:19:writable] Warning: Equation sections are deprecated in class.
When the simulation is finished the file HelloWorld_res.csv contains the simulation data:
81
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
1
x
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3 3.5 4
By re-simulating and saving results at many more points, for example using the default 500 intervals, a much
smoother plot can be obtained. Note that the default solver method dassl has more internal points than the output
points in the initial plot. The results are identical, except the detailed plot has a smoother curve.
>>> list(OpenModelica.Scripting.plot,interfaceOnly=true)
"function plot
input VariableNames vars \"The variables you want to plot\";
input Boolean externalWindow = false \"Opens the plot in a new plot window\";
input String fileName = \"<default>\" \"The filename containing the variables.
˓→<default> will read the last simulation result\";
input String title = \"\" \"This text will be used as the diagram title.\";
input String grid = \"simple\" \"Sets the grid for the plot i.e simple, detailed,
˓→ none.\";
82 Chapter 4. 2D Plotting
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
1
x
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3 3.5 4
Figure 4.2: Simple 2D plot of the HelloWorld example with a larger number of output points.
input Boolean logY = false \"Determines whether or not the vertical axis is
˓→logarithmically scaled.\";
input String xLabel = \"time\" \"This text will be used as the horizontal label
˓→in the diagram.\";
input String yLabel = \"\" \"This text will be used as the vertical label in the
˓→diagram.\";
input Real xRange[2] = {0.0, 0.0} \"Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.\";
input Real yRange[2] = {0.0, 0.0} \"Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.\";
input String legendPosition = \"top\" \"Sets the POSITION of the legend i.e left,
˓→ right, top, bottom, none.\";
input String footer = \"\" \"This text will be used as the diagram footer.\";
input Boolean autoScale = true \"Use auto scale while plotting.\";
input Boolean forceOMPlot = false \"if true launches OMPlot and doesn't call
˓→callback function even if it is defined.\";
84 Chapter 4. 2D Plotting
CHAPTER
FIVE
5.1.1 DASSL
DASSL is the default solver in OpenModelica, because of a severals reasons. It is an implicit, higher order,
multi-step solver with a step-size control and with these properties it is quite stable for a wide range of models.
Furthermore it has a mature source code, which was originally developed in the eighties an initial description may
be found in [Pet82].
This solver is based on backward differentiation formula (BDF), which is a family of implicit methods for numer-
ical integration. The used implementation is called DASPK2.0 (see1 ) and it is translated automatically to C by f2c
(see2 ).
The following simulation flags can be used to adjust the behavior of the solver for specific simulation problems:
jacobian, noRootFinding, noRestart, initialStepSize, maxStepSize, maxIntegrationOrder, noEquidistantTimeGrid.
5.1.2 IDA
The IDA solver is part of a software family called sundials: SUite of Nonlinear and DIfferential/ALgebraic equa-
tion Solvers [HBG+05]. The implementation is based on DASPK with an extended linear solver interface, which
includes an interface to the high performance sparse linear solver KLU [DN10].
The simulation flags of DASSL are also valid for the IDA solver and furthermore it has the following IDA specific
flags: idaLS, idaMaxNonLinIters, idaMaxConvFails, idaNonLinConvCoef , idaMaxErrorTestFails.
1 DASPK Webpage
2 Cdaskr source
85
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
5.1.3 CVODE
The CVODE solver is part of sundials: SUite of Nonlinear and DIfferential/ALgebraic equation Solvers
[HBG+05]. CVODE solves initial value problems for ordinary differential equation (ODE) systems with variable-
order, variable-step multistep methods.
In OpenModelica, CVODE uses a combination of Backward Differentiation Formulas (varying order 1 to 5) as
linear multi-step method and a modified Newton iteration with fixed Jacobian as non-linear solver per default.
This setting is advised for stiff problems which are very common for Modelica models. For non-stiff problems
an combination of an Adams-Moulton formula (varying order 1 to 12) as linear multi-step method together with a
fixed-point iteration as non-linear solver method can be choosen.
Both non-linear solver methods are internal functions of CVODE and use its internal direct dense linear solver
CVDense. For the Jacobian of the ODE CVODE will use its internal dense difference quotient approximation.
CVODE has the following solver specific flags: cvodeNonlinearSolverIteration, cvodeLinearMultistepMethod.
5.1.4 GBODE
GBODE stands for Generic Bi-rate ordinary differential equation (ODE) solver and is a generic implementation
for any Runge-Kutta (RK) scheme [HNorsettW00]. In GBODE there are already many different implicit and
explicit RK methods (e.g. SDIRK, ESDIRK, Gauss, Radau, Lobatto, Fehlberg, DOPRI45, Merson) with different
approximation order configurable and ready to use. New RK schemes can easily be added, if the corresponding
Butcher tableau is available. By default the solver runs in single-rate mode using the embedded RK scheme
ESDIRK4 [KC19] with variable-step-size control and efficient event handling.
The bi-rate mode can be utilized using the simulation flag gbratio. This flag determines the percentage of fast
states with respect to all states. These states will then be automatically detected during integration based on the
estimated approximation error and afterwards refined using an appropriate inner step-size control and interpolated
values of the slow states.
The solver utilizes by default the sparsity pattern of the ODE Jacobian and solves the corresponding non-linear
system in case of an implicit chosen RK scheme using KINSOL.
GBODE is highly configurable and the following simulation flags can be used to adjust the behavior of the solver
for specific simulation problems: gbratio, gbm, gbctrl, gbnls, gbint, gberr, gbfm, gbfctrl, gbfnls, gbfint, gbferr.
This solver will replace obsolete and no longer maintained solvers providing a lot more using the following
simulation flags:
old: -s=euler
new: -s=gbode -gbm=expl_euler -gbctrl=const
old: -s=heun
new: -s=gbode -gbm=heun -gbctrl=const
old: -s=impeuler
new: -s=gbode -gbm=impl_euler -gbctrl=const
old: -s=trapezoid
new: -s=gbode -gbm=trapezoid -gbctrl=const
old: -s=imprungekutta
new -s=gbode -gbm=(one of the lobatto or radau or gauss RK methods) -gbctrl=const
old: -s=irksco
new: -s=gbode -gbm=trapezoid
old: -s=rungekuttaSsc
new: -s=gbode -gbm=rungekuttaSsc
5.3 Initialization
To simulate an ODE representation of an Modelica model with one of the methods shown in Integration Methods
a valid initial state is needed. Equations from an initial equation or initial algorithm block define a desired initial
system.
model piston
Modelica.Mechanics.MultiBody.Parts.Fixed fixed1 annotation(
Placement(visible = true, transformation(origin = {-80, 70}, extent = {{-10, -
˓→10}, {10, 10}}, rotation = 0)));
Modelica.Mechanics.MultiBody.Joints.RevolutePlanarLoopConstraint revolutePlanar
˓→annotation(
equation
connect(prismatic.frame_b, fixed2.frame_b) annotation(
Line(points = {{40, -60}, {60, -60}, {60, -60}, {60, -60}}, color = {95, 95,
˓→95}));
>>> loadModel(Modelica);
>>> setCommandLineOptions("-d=initialization");
>>> buildModel(piston);
"[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
(continues on next page)
˓→Parameter body2.r_CM[3] has no value, and is fixed during initialization
5.3. Initialization 89
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
˓→type: Real
˓→type: Real
"
Note how OpenModelica will inform the user about relevant and irrelevant start values for this model and for
which variables a fixed default start value is assumed. The model has four joints but only one degree of freedom,
so one of the joints revolutePlanar or prismatic must be initialized.
So, initializing phi and w of revolutePlanar will give a sensible start system.
model pistonInitialize
extends piston(revolute1.phi.fixed = true, revolute1.phi.start = -1.
˓→221730476396031, revolute1.w.fixed = true, revolute1.w.start = 5);
equation
end pistonInitialize;
>>> setCommandLineOptions("-d=initialization");
>>> simulate(pistonInitialize, stopTime=2.0);
"[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
[/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build/lib/omlibrary/Modelica
˓→4.0.0+maint.om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning:
"
1.1
body2.framea.r0[1]
0.9
0.8
0.7
0.6
0.5
0 0.5 1 1.5 2
5.3. Initialization 91
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
initial state and parameter values; the values of algebraic variables in the imported file will be used to initialize
iteration variables in nonlinear implicit equations of the simulation model, or otherwise ignored.
To activate this second option, set Simulation Setup | Simulation Flag | Initialization Method to none in
OMEdit, or set the simulation flag -iim=none. Also in this case, activating the checkbox Save simulation
flags inside model, i.e. __OpenModelica_simulationFlags annotation saves this option in an __OpenModel-
ica_simulationFlags(iim=none) annotation, so it is retained for future simulations of the same model.
The following minimal working example demonstrates the use of the initial value import feature. You can create a
new package ImportInitialValues in OMEdit, copy and paste its code from here, and then run the different models
in it.
model M2 "Imports parameters and initial guesses only, solve initial equations"
extends M;
annotation(__OpenModelica_simulationFlags(iif = "initial.mat"));
end M2;
model M3 "import parameters, initial guesses and initial states, skip initial
˓→equations"
extends M;
annotation(__OpenModelica_simulationFlags(iim = "none", iif = "initial.mat"));
end M3;
end ImportInitialValues;
Running the ResultFileGenerator model creates a .mat file with some initial values in the working directory: p1
= 7, p2 = 10, p3 = 21, v1 = 2.8, v2 = 10, x = 4, der(x) = 0.
When running model M, the simulation process only relies on the initial and guess values provided by the Modelica
source code. Regarding the parameter values, p1 = 1, `p2 = 1, p3 = 3*p1 = 3; regarding v1, the implicit cubic
equation is solved iteratively using the start value 14 as an initial guess, thus converging to the nearest solution v1
= 15. The other variable v2 can be computed explicitly, so there is no need of any guess value for it. Finally, the
initial value of the state variable is set to x = 6 by the initial equations.
When running model M2, the values of the .mat file are imported to provide values for non-final parameters and
guess values for the initial equations, which are solved starting from there. Hence, the imported parameter values
p1 = 7 and p2 = 10 override the model's binding equations, that would set both to 1; on the other hand, the final
parameter p3 is computed based on the final binding equation to p3 = p1*3 = 21. Regarding v1, the iterative solver
converges to the solution closest to the imported start value of 2.8, i.e. v1 = 3, while v2 is computed explicitly, so
it doesn't depend on the imported start value. The initial value of the state x = 6 is obtained by solving the initial
equation, which is explicit and thus ignores the imported guess value x = 4.
Finally, when running model M3, parameters are handled like in the previous case, as well as the algebraic vari-
ables v1 and v2. However, in this case the initial equations are skipped, so the state variable gets its initial value x
= 4 straight from the imported .mat file.
OpenModelica has different solvers available for non-linear systems. Initializing with homotopy on the first try
is default if a homotopy operator is used. It can be switched off with noHomotopyOnFirstTry. For a general
overview see [SCO+11], for details on the implementation in OpenModelica see [OB13].
The homotopy methods distinguish between local and global methods meaning, if 𝜆 affects the entire initialization
system or only local strong connected components. In addition the homotopy methods can use equidistant 𝜆 or
and adaptive 𝜆 in [0,1].
Default order of methods tried to solve initialization system
If there is no homotopy in the model
• Solve without homotopy method.
If there is homotopy in the model or solving without homotopy failed
• Try global homotopy approach with equidistant 𝜆.
The default homotopy method will do three global equidistant steps from 0 to 1 to solve the initialization system.
Several compiler and simulation flags influence initialization with homotopy: --homotopyApproach,
-homAdaptBend, -homBacktraceStrategy, -homHEps, -homMaxLambdaSteps, -homMaxNewtonSteps,
-homMaxTries, -homNegStartDir, -homotopyOnFirstTry, -homTauDecFac, -homTauDecFacPredictor, -
homTauIncFac, -homTauIncThreshold, -homTauMax, -homTauMin, -homTauStart, -ils.
5.4.1 References
SIX
DEBUGGING
There are two main ways to debug Modelica code, the transformations browser, which shows the transformations
OpenModelica performs on the equations. There is also a debugger for debugging of algorithm sections and
functions.
95
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
96 Chapter 6. Debugging
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
98 Chapter 6. Debugging
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
SEVEN
One of the goals of OpenModelica is to provide a full, no-compromise implementation of the latest version of the
Modelica Language Specification, released by the non-profit Modelica Association. This means that a main re-
quirement for a Modelica library to work in OpenModelica is to be fully compliant to the Language Specification.
Libraries and models developed with other Modelica tools may contain some code which is not valid according to
the current language specification, but still accepted by that tool, e.g. to support legacy code of their customers. In
order to use those libraries and models in OpenModelica, one needs to make sure that such code is replaced by a
valid one. Note that getting rid of invalid Modelica code does not make the library only usable in OpenModelica;
to the contrary, doing that is the best guarantee that the library will be usable both with the original tool used for
development and with OpenModelica, as well as with any other present or future Modelica tool that follows the
standard strictly.
The first recommendation is to use any flag or option of the tool that was originally used to develop the library, that
allows to check for strict compliance to the language specification. For example, Dymola features a translation
option 'Pedantic mode for checking Modelica semantics' that issues an error if non-standard constructs are used.
For your convenience, here you can find a list of commonly reported issues.
103
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
parameter Real r = 4;
MyComponent ma[3](p = r);
MyComponent mb[3](p = 20);
In most cases, the problem is solved by simply adding the each keyword where appropriate.
model M
parameter Boolean activateIn1 = true;
parameter Boolean activateIn2 = true;
Modelica.Blocks.Interfaces.RealInput u1_in if activateIn1;
Modelica.Blocks.Interfaces.RealInput u2_in = u2 if activateIn2;
Real u2 "internal variable corresponding to u2_in";
Real y;
protected
Modelica.Blocks.Interfaces.RealInput u1 "internal connector corresponding to u1_
˓→in";
equation
y = u1 + u2;
connect(u1_in, u1) "automatically disabled if u1_in is deactivated";
if not activateIn1 then
u1 = 0 "default value for protected connector value when u1_in is disabled";
end if;
if not activateIn2 then
u2 = 0 "default value for u2 when u2_in is disabled";
end if;
end M;
where conditional components are only used in connect equations. The following patterns instead are not legal:
model M
parameter Boolean activateIn1 = true;
parameter Boolean activateIn2 = true;
Modelica.Blocks.Interfaces.RealInput u1_in if activateIn1;
Modelica.Blocks.Interfaces.RealInput u2_in if activateIn2;
Real u1 "internal variable corresponding to u1_in";
Real u2 "internal variable corresponding to u2_in";
Real y;
equation
if activateIn1 then
u1 = u1_in "invalid: uses conditional u1_in outside connect equations";
end if;
if activateIn2 then
u2 = u2_in "invalid: uses conditional u1_in outside connect equations";
end if;
y = u1 + u2;
end M;
because those components are also used in other equations. The fact that those equations are conditional and are
not activated when the corresponding conditional components are also not activated is irrelevant, according to the
language specification.
package TestPartialPackage
partial package PartialPackage
function f
input Real x;
output Real y;
algorithm
y := 2*x;
end f;
end PartialPackage;
package RegularPackage
extends PartialPackage;
model A
Real x = time;
end A;
end RegularPackage;
model M1
package P = PartialPackage;
Real x = P.f(time);
end M1;
model M2
extends M1(redeclare package P = RegularPackage);
end M2;
model M3
encapsulated package LocalPackage
import TestPartialPackage.PartialPackage;
extends PartialPackage;
end LocalPackage;
package P = LocalPackage;
Real x = P.f(time);
end M3;
end TestPartialPackage;
Model M1 references a class (a function, in this case) from a partial package. This is perfectly fine if one wants
to write a generic model, which is then specialized by redeclaring the package to a non-partial one, as in M2.
However, M1 cannot be compiled for simulation, since, according to Section 5.3.2 of the language specification,
the classes that are looked inside during lookup shall not be partial in a simulation model.
This problem can be fixed by accessing that class (the function f, in this case) from a non-final package that extends
the partial one, either by redeclaring the partial package to a non-partial one, as in M2, or by locally defining a
non-partial package that extends from the partial one, as in M3. The latter option is of course viable only if the
class being accessed is in itself not a partial or somehow incomplete one.
This issue is often encountered in models using Modelica.Media, that sometimes use some class definitions (e.g.
unit types) from partial packages such as Modelica.Media.Interfaces.PartialMedium. The fix in most cases is just
to use the same definition from the actual replaceable Medium package defined in the model, which will eventually
be redeclared to a non-partial one in the simulation model.
function f
input Real x;
input Real y = 0;
output Real z;
algorithm
z = x + y;
end f;
so, the OpenModelica parser does not accept it. The correct code is:
function f
input Real x;
input Real y = 0;
output Real z;
algorithm
z := x + y;
end f;
Some tools automatically and silently apply the correction to the code, please save it in its correct form to make it
usable with OpenModelica.
Also note that binding equations with '=' sign are instead required for default values of function inputs.
function f
input Real x;
output Real y;
Real z;
algorithm
z := 2;
y := x+z;
end f;
function f
input Real x;
output Real y;
protected
Real z;
algorithm
z := 2;
y := x+z;
end f;
model M
Real x[3];
Real y[3];
Real z;
equation
z = (x.*y)[2];
...
end M;
This construct is already accepted by some Modelica tools, but is not yet included in the current Modelica speci-
fication 3.5, nor even in the current working draft of 3.6, so it is not currently supported by OpenModelica.
Note that in the latter case, the start attribute on y is not used directly to set the initial value of that variable,
but only potentially used as initial guess for the solution of the initialization problem, that may require using an
iterative nonlinear solver. Also note that sets of initial equations are often added to the models taken from reusable
component libraries by selecting certain component parameters, such as initOpt or similar.
If the number of initial conditions matches the number of continuous and discrete states, then the initialization
problem is well-defined. Although this is per se not a guarantee that all tools will be able to solve it and find the
same solution, this is for sure a prerequisite for across-tool portability.
Conversely, if the number of initial conditions is less than the number of states, the tool has to add some initial
equations, using some heuristics to change the fixed attribute of some variables from false to true. Consider for
example the following model:
model M
Real x;
Real y(start = 1);
Real z(start = 2);
equation
der(x) = y + z;
y = 2*x;
z = 10*x + 1;
end M;
This model has one state variable x, no variables with fixed = true attributes and no initial equation, so there is
one missing initial condition. One tool could choose to add the fixed = true attribute to the state variable x, fixing
it to the default value of zero of its start attribute. Or, it could decide to give more priority to variables that have
an explicitly modified start attribute, hence fix the initial value of y to 1, or the initial value of z to 2. Three
completely different simulations would ensue.
The Modelica Language Specification, Section 8.6 does not prescribe or recommend any specific choice criterion
in this case. Hence, different tools, or even different versions of the same tool, could add different initial condi-
tions, leading to completely different simulations. In order to avoid any ambiguity and achieve good portability, it
is thus recommended to make sure that the initial conditions of all simulation model are well-specified.
A model with not enough initial conditions causes the OMC to issue the following translation warning: "The initial
conditions are not fully specified". By activating the Tools | Options | Simulation | Show additional information
from the initialization process option, or the -d=initialization compiler flag, one can get an explicit list of the
additional equations that OpenModelica automatically adds to get a fully specified initialization problem, which
may be helpful to figure out which initial conditions are missing. In this case, we recommend to amend the source
code of the model by adding suitable extra initial conditions, until that warning message no longer appears.
EIGHT
The system of equations after symbolic transformation is represented by a graph. OpenModelica can generate
graph representations which can be displayed in the graph tool yed (http://www.yworks.com/products/yed). The
graph generation is activated with the debug flag
+d=graphml
Two different graphml- files are generated in the working directory. TaskGraph_model.graphml, showing the
strongly-connected components of the model and BipartiteGraph_CompleteDAE_model.graphml showing all
variables and equations. When loading the graphs with yEd, all nodes are in one place. Please use the various
layout algorithms to get a better overview.
109
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
NINE
true
>>> translateModelFMU(BouncingBall)
"«DOCHOME»/BouncingBall.fmu"
>>> system("unzip -l BouncingBall.fmu | egrep -v 'sources|files' | tail -n+3 |
˓→grep -o '[A-Za-z._0-9/]*$' > BB.log")
After the command execution is complete you will see that a file BouncingBall.fmu has been created. Its contents
varies depending on the current platform. On the machine generating this documentation, the contents in Listing
9.1 are generated (along with the C source code).
A log file for FMU creation is also generated named ModelName_FMU.log. If there are some errors while creating
FMU they will be shown in the command line window and logged in this log file as well.
111
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
112 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
By default an FMU that can be used for both Model Exchange and Co-Simulation is generated. We support FMI
1.0 & FMI 2.0 for Model Exchange FMUs and FMI 2.0 for Co-Simulation FMUs.
Currently the Co-Simulation FMU uses the forward Euler solver as default with root finding which does an
Euler step of communicationStepSize in fmi2DoStep. Events are checked for before and after the call to
fmi2GetDerivatives.
For FMI 2.0 for Co-Simulation OpenModelica can export an experimental implementation of SUNDIALS
CVODE (see1 ) as internal integrator.
To export a Co-Simulation FMU with CVODE for the bouncing ball example use the following commands:
true
>>> setCommandLineOptions("--fmiFlags=s:cvode")
true
>>> translateModelFMU(BouncingBall, version = "2.0", fmuType="cs")
"«DOCHOME»/BouncingBall.fmu"
>>> system("unzip -cqq BouncingBall.fmu resources/BouncingBall_flags.json >
˓→BouncingBall_flags.json")
The FMU BouncingBall.fmu will have a new file BouncingBall_flags.json in its resources directory. By manualy
changing its contant users can change the solver method without recompiling the FMU.
The BouncingBall_flags.json for this example is displayed in Listing 9.2.
For this to work OpenModelica will export all needed dependencies into the FMU if and only if the flag fmiFlags
was set. To have CVODE in a SourceCode FMU the user needs to add all sources for SUNDIALS manualy and
create a build script as well.
input Boolean fullPath = false "When true the full output path is returned
˓→otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
The command could be used from command line interface, OMShell, OMNotebook or MDT. The importFMU
command is also integrated with OMEdit through the File > Import > FMU dialog: the FMU package is extracted
in the directory specified by workdir, or in the current directory of omc if not specified, see Tools > Open Working
Directory.
The imported FMU is then loaded in the Libraries Browser and can be used as any other regular Modelica block.
114 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Click TLM Co-Simulation setup button ( ) from the toolbar (requires a composite model to be active
in ModelWidget)
• Right click the composite model in the Libraries Browser and choose TLM Co-Simulation setup from
the popup menu (see Figure 9.3)
The TLM Co-Simulation setup appears as shown below in Figure 9.4.
Click Simulate from the Co-simulation setup to confirm the co-simulation. Figure 9.5 will appears in which you
will be able to see the progress information of the running co-simulation.
The editor also provides the means of reading the log files generated by the simulation manager and monitor.
When the simulation ends, click Open Manager Log File or Open Monitor Log File from the co-simulation
progress bar to check the log files.
116 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Figure 9.3: Co-simulating and Fetching Interface Data of a composite model from the Popup Menu .
118 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
120 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
122 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Click Fetch Interface Data button ( ) from the toolbar (requires a composite model to be active in
ModelWidget)
• Right click the composite model in the Library Browser and choose Fetch Interface Data from the popup
menu (see Figure 9.3).
To retrieve list of TLM interface data for a specific sub-model,
• Right click the sub-model inside the composite model and choose Fetch Interface Data from the popup
menu.
Figure 9.11 will appear in which you will be able to see the progress information of fetching the interface data.
Once the TLM interface data of the sub-models are retrieved, the interface points will appear in the diagram view
as shown below in Figure 9.12.
124 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
126 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Click Simulation Parameters button ( t0 t1) from the toolbar (requires a composite model to be active in
ModelWidget)
• Right click an empty location in the Diagram View of the composite model and choose Simulation Param-
eters from the popup menu (see Figure 9.16)
The co-simulation parameter dialog of the composite model appears as shown below in Figure 9.17 in which you
will be able to specify the simulation parameters.
128 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
130 Chapter 9. FMI and TLM-Based Simulation and Co-simulation of External Models
CHAPTER
TEN
OMSIMULATOR
Version: v2.1.1.post188-gaf996ad
10.1 Introduction
The OMSimulator project is a FMI-based co-simulation tool that supports ordinary (i.e., non-delayed) and TLM
connections. It supports large-scale simulation and virtual prototyping using models from multiple sources utiliz-
ing the FMI standard. It is integrated into OpenModelica but also available stand-alone, i.e., without dependencies
to Modelica specific models or technology. OMSimulator provides an industrial-strength open-source FMI-based
modelling and simulation tool. Input/output ports of FMUs can be connected, ports can be grouped to buses, FMUs
can be parameterized and composed, and composite models can be exported according to the (preliminary) SSP
(System Structure and Parameterization) standard. Efficient FMI based simulation is provided for both model-
exchange and co-simulation. TLM-based tool connection is provided for a range of applications, e.g., Adams,
Simulink, Beast, Dymola, and OpenModelica. Moreover, optional TLM (Transmission Line Modelling) domain-
specific connectors are also supported, providing additional numerical stability to co-simulation. An external API
is available for use from other tools and scripting languages such as Python and Lua.
10.2 OMSimulator
OMSimulator is a command line wrapper for the OMSimulatorLib library.
˓→components.
131
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
˓→with 1.0
To use flag logLevel with option debug (--logLevel=1) or debug+trace (--logLevel=2) one needs to
build OMSimulator with debug configuration enabled. Refer to the OMSimulator README on GitHub for further
instructions.
10.2.2 Examples
10.3 OMSimulatorLib
This library is the core of OMSimulator and provides a C interface that can easily be utilized to handle co-
simulation scenarios.
10.3.1 RunFile
Simulates a single FMU or SSP model.
10.3.2 activateVariant
This API provides support to activate a multi-variant modelling from an ssp file [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ] from a ssp file. By default when importing a ssp file the default variant will be "System-
Structure.ssd". The users can be able to switch between other variants by using this API and make changes to that
particular variant and simulate them.
10.3.3 addBus
Adds a bus to a given component.
10.3.4 addConnection
Adds a new connection between connectors A and B. The connectors need to be specified as fully qualified com-
ponent references, e.g., "model.system.component.signal".
The two arguments crefA and crefB get swapped automatically if necessary. The third argument suppressUnitCon-
version is optional and the default value is false which allows automatic unit conversion between connections, if
set to true then automatic unit conversion will be disabled.
10.3.5 addConnector
Adds a connector to a given component.
10.3.6 addConnectorToBus
Adds a connector to a bus.
10.3.7 addConnectorToTLMBus
Adds a connector to a TLM bus.
10.3.8 addExternalModel
Adds an external model to a TLM system.
10.3.9 addResources
Adds an external resources to an existing SSP. The external resources should be a ".ssv" or ".ssm" file
10.3.10 addSignalsToResults
Add all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.3.11 addSubModel
Adds a component to a system.
10.3.12 addSystem
Adds a (sub-)system to a model or system.
10.3.13 addTLMBus
Adds a TLM bus.
10.3.14 addTLMConnection
Connects two TLM connectors.
10.3.15 compareSimulationResults
This function compares a given signal of two result files within absolute and relative tolerances.
Type Description
Integer 1 if the signal is considered as equal, 0 otherwise
10.3.16 copySystem
Copies a system.
10.3.17 delete
Deletes a connector, component, system, or model object.
10.3.18 deleteConnection
Deletes the connection between connectors crefA and crefB.
The two arguments crefA and crefB get swapped automatically if necessary.
10.3.19 deleteConnectorFromBus
Deletes a connector from a given bus.
10.3.20 deleteConnectorFromTLMBus
Deletes a connector from a given TLM bus.
10.3.21 deleteResources
Deletes the reference and resource file in a SSP. Deletion of ".ssv" and ".ssm" files are currently supported. The
API can be used in two ways.
1) deleting only the reference file in ".ssd".
2) deleting both reference and resource files in ".ssp".
To delete only the reference file in ssd, the user should provide the full qualified cref of the ".ssv" file associated
with a system or subsystem or component (e.g) "model.root:root1.ssv".
To delete both the reference and resource file in ssp, it is enough to provide only the model cref of the ".ssv" file
(e.g) "model:root1.ssv".
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file then
the ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as the ssm file is
binded to a ssv file.
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref. (e.g)
":root.ssv"
10.3.22 doStep
Simulates a macro step of the given composite model. The step size will be determined by the master algorithm
and is limited by the definied minimal and maximal step sizes.
10.3.23 duplicateVariant
This API provides support to develop a multi-variant modelling in OMSimulator [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ]. When duplicating a variant, the new variant becomes the current variant and all the changes
made by the users are applied to the new variants only, and all the ssv and ssm resources associated with the
new variant will be given new name based on the variant name provided by the user. This allows the bundling of
multiple variants of a system structure definition referencing a similar set of packaged resources as a single SSP.
However there must still be one SSD file named SystemStructure.ssd at the root of the ZIP archive which will be
considered as default variant.
10.3.24 export
Exports a composite model to a SPP file.
10.3.25 exportDependencyGraphs
Export the dependency graphs of a given model to dot files.
10.3.26 exportSSMTemplate
Exports all signals that have start values of one or multiple FMUs to a SSM file that are read from modelDescrip-
tion.xml with a mapping entry. The mapping entry specifies a single mapping between a parameter in the source
and a parameter of the system or component being parameterized. The mapping entry contains two attributes
namely source and target. The source attribute will be empty and needs to be manually mapped by the users asso-
ciated with the parameter name defined in the SSV file, the target contains the name of parameter in the system or
component to be parameterized. The function can be called for a top level model or a certain FMU component. If
called for a top level model, start values of all FMUs are exported to the SSM file. If called for a component, start
values of just this FMU are exported to the SSM file.
10.3.27 exportSSVTemplate
Exports all signals that have start values of one or multiple FMUs to a SSV file that are read from modelDescrip-
tion.xml. The function can be called for a top level model or a certain FMU component. If called for a top level
model, start values of all FMUs are exported to the SSV file. If called for a component, start values of just this
FMU are exported to the SSV file.
10.3.28 exportSnapshot
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.3.29 extractFMIKind
Extracts the FMI kind of a given FMU from the file system.
10.3.30 faultInjection
Defines a new fault injection block.
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
10.3.31 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
10.3.32 getBoolean
Get boolean value of given signal.
10.3.33 getBus
Gets the bus object.
10.3.34 getComponentType
Gets the type of the given component.
10.3.35 getConnections
Get list of all connections from a given component.
10.3.36 getConnector
Gets the connector object of the given connector cref.
10.3.37 getDirectionalDerivative
This function computes the directional derivatives of an FMU.
10.3.38 getElement
Get element information of a given component reference.
10.3.39 getElements
Get list of all sub-components of a given component reference.
10.3.40 getFMUInfo
Returns FMU specific information.
10.3.41 getFixedStepSize
Gets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.3.42 getInteger
Get integer value of given signal.
10.3.43 getModelState
Gets the model state of the given model cref.
10.3.44 getReal
Get real value.
10.3.45 getResultFile
Gets the result filename and buffer size of the given model cref.
10.3.46 getSolver
Gets the selected solver method of the given system.
10.3.47 getStartTime
Get the start time from the model.
10.3.48 getStopTime
Get the stop time from the model.
10.3.49 getString
Get string value.
Memory is allocated for value. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.3.50 getSubModelPath
Returns the path of a given component.
10.3.51 getSystemType
Gets the type of the given system.
10.3.52 getTLMBus
Gets the TLM bus objects of the given TLM bus cref.
10.3.53 getTLMVariableTypes
Gets the type of an TLM variable.
˓→***descriptions);
10.3.54 getTime
Get the current simulation time from the model.
10.3.55 getTolerance
Gets the tolerance of a given system or component.
10.3.56 getVariableStepSize
Gets the step size parameters.
10.3.57 getVersion
Returns the library's version string.
10.3.58 importFile
Imports a composite model from a SSP file.
10.3.59 importSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.3.60 initialize
Initializes a composite model.
10.3.61 instantiate
Instantiates a given composite model.
10.3.62 list
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.3.63 listUnconnectedConnectors
Lists all unconnected connectors of a given system.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.3.64 listVariants
This API shows the number of variants available [(e.g). SystemStructure.ssd, VarA.ssd, VarB.ssd ] from a ssp file.
10.3.65 loadSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.3.66 newModel
Creates a new and yet empty composite model.
10.3.67 newResources
Adds a new empty resources to the SSP. The resource file is a ".ssv" file where the parameter values set by the users
using "oms_setReal()", "oms_setInteger()" and "oms_setReal()" are writtern to the file. Currently only ".ssv" files
can be created.
The filename of the resource file is provided by the users using colon suffix at the end of cref. (e.g) ":root.ssv"
10.3.68 referenceResources
Switches the references of ".ssv" and ".ssm" in a SSP file. Referencing of ".ssv" and ".ssm" files are currently
supported. The API can be used in two ways.
1) Referencing only the ".ssv" file.
2) Referencing both the ".ssv" along with the ".ssm" file.
This API should be used in combination with "oms_deleteResources".To switch with a new reference, the old
reference must be deleted first using "oms_deleteResources" and then reference with new resources.
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file, then
the reference of ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as
the ssm file is binded to a ssv file. Hence it is not possible to switch the reference of ".ssm" file alone. So inorder
to switch the reference of ".ssm" file, the users need to bind the reference of ".ssm" file along with the ".ssv".
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref (e.g)
":root.ssv", and the ".ssm" file is optional and is provided by the user as the second argument to the API.
10.3.69 removeSignalsFromResults
Removes all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.3.70 rename
Renames a model, system, or component.
10.3.71 replaceSubModel
Replaces an existing fmu component, with a new component provided by the user, When replacing the fmu checks
are made in all ssp concepts like in ssd, ssv and ssm, so that connections and parameter settings are not lost. It is
possible that the namings of inputs and parameters match, but the start values might have been changed, in such
cases new start values will be applied in ssd, ssv and ssm. In case if the Types of inputs and outputs and parameters
differed, then the variables are updated according to the new changes and the connections will be removed with
warning messages to user. In case when replacing a fmu, if the fmu contains parameter mapping associated with
the ssv file, then only the ssm file entries are updated and the start values in the ssv files will not be changed.
10.3.72 reset
Reset the composite model after a simulation run.
The FMUs go into the same state as after instantiation.
10.3.73 setActivationRatio
Experimental feature for setting the activation ratio of FMUs for experimenting with multi-rate master algorithms.
10.3.74 setBoolean
Sets the value of a given boolean signal.
10.3.75 setBusGeometry
10.3.76 setCommandLineOption
Sets special flags.
Available flags:
˓→components.
˓→with 1.0
10.3.77 setConnectionGeometry
10.3.78 setConnectorGeometry
Set geometry information to a given connector.
10.3.79 setElementGeometry
Set geometry information to a given component.
10.3.80 setFixedStepSize
Sets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.3.81 setInteger
Sets the value of a given integer signal.
10.3.82 setLogFile
Redirects logging output to file or std streams. The warning/error counters are reset.
filename="" to redirect to std streams and proper filename to redirect to file.
10.3.83 setLoggingCallback
Sets a callback function for the logging system.
10.3.84 setLoggingInterval
Set the logging interval of the simulation.
10.3.85 setLoggingLevel
Enables/Disables debug logging (logDebug and logTrace).
0 default, 1 default+debug, 2 default+debug+trace
10.3.86 setMaxLogFileSize
Sets maximum log file size in MB. If the file exceeds this limit, the logging will continue on stdout.
10.3.87 setReal
Sets the value of a given real signal.
10.3.88 setRealInputDerivative
Sets the first order derivative of a real input signal.
This can only be used for CS-FMU real input signals.
10.3.89 setResultFile
Set the result file of the simulation.
10.3.90 setSolver
Sets the solver method for the given system.
10.3.91 setStartTime
Set the start time of the simulation.
10.3.92 setStopTime
Set the stop time of the simulation.
10.3.93 setString
Sets the value of a given string signal.
10.3.94 setTLMBusGeometry
10.3.95 setTLMConnectionParameters
Simulates a composite model in its own thread.
10.3.96 setTLMPositionAndOrientation
Sets initial position and orientation for a TLM 3D interface.
10.3.97 setTLMSocketData
Sets data for TLM socket communication.
10.3.98 setTempDirectory
Set new temp directory.
10.3.99 setTolerance
Sets the tolerance for a given model or system.
Default values are 1e-4 for both relative and absolute tolerances.
A tolerance specified for a model is automatically applied to its root system, i.e. both calls do exactly the same:
Component, e.g. FMUs, pick up the tolerances from there system. That means it is not possible to define different
tolerances for FMUs in the same system right now.
In a strongly coupled system (oms_system_sc), the relative tolerance is used for CVODE and the absolute tolerance
is used to solve algebraic loops.
In a weakly coupled system (oms_system_wc), both the relative and absolute tolerances are used for the adaptive
step master algorithms and the absolute tolerance is used to solve algebraic loops.
10.3.100 setUnit
Sets the unit of a given signal.
10.3.101 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
10.3.102 setWorkingDirectory
Set a new working directory.
10.3.103 simulate
Simulates a composite model.
10.3.104 simulate_realtime
Experimental feature for (soft) real-time simulation.
10.3.105 stepUntil
Simulates a composite model until a given time value.
10.3.106 terminate
Terminates a given composite model.
10.4 OMSimulatorLua
This is a shared library that provides a Lua interface for the OMSimulatorLib library.
oms_setTempDirectory("./temp/")
oms_newModel("model")
oms_addSystem("model.root", oms_system_sc)
-- instantiate FMUs
oms_addSubModel("model.root.system1", "FMUs/System1.fmu")
oms_addSubModel("model.root.system2", "FMUs/System2.fmu")
-- add connections
oms_addConnection("model.root.system1.y", "model.root.system2.u")
oms_addConnection("model.root.system2.y", "model.root.system1.u")
(continues on next page)
-- simulation settings
oms_setResultFile("model", "results.mat")
oms_setStopTime("model", 0.1)
oms_setFixedStepSize("model.root", 1e-4)
oms_instantiate("model")
oms_setReal("model.root.system1.x_start", 2.5)
oms_initialize("model")
oms_simulate("model")
oms_terminate("model")
oms_delete("model")
10.4.1 activateVariant
This API provides support to activate a multi-variant modelling from an ssp file [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ] from a ssp file. By default when importing a ssp file the default variant will be "System-
Structure.ssd". The users can be able to switch between other variants by using this API and make changes to that
particular variant and simulate them.
10.4.2 addBus
Adds a bus to a given component.
status = oms_addBus(cref)
10.4.3 addConnection
Adds a new connection between connectors A and B. The connectors need to be specified as fully qualified com-
ponent references, e.g., "model.system.component.signal".
The two arguments crefA and crefB get swapped automatically if necessary. The third argument suppressUnitCon-
version is optional and the default value is false which allows automatic unit conversion between connections, if
set to true then automatic unit conversion will be disabled.
10.4.4 addConnector
Adds a connector to a given component.
oms_causality_input
oms_causality_output
oms_causality_parameter
oms_causality_bidir
oms_causality_undefined
oms_signal_type_real
oms_signal_type_integer
oms_signal_type_boolean
oms_signal_type_string
oms_signal_type_enum
oms_signal_type_bus
10.4.5 addConnectorToBus
Adds a connector to a bus.
10.4.6 addConnectorToTLMBus
Adds a connector to a TLM bus.
10.4.7 addExternalModel
Adds an external model to a TLM system.
10.4.8 addResources
Adds an external resources to an existing SSP. The external resources should be a ".ssv" or ".ssm" file
-- Example
oms_importFile("addExternalResources1.ssp")
-- add list of external resources from filesystem to ssp
oms_addResources("addExternalResources", "../../resources/externalRoot.ssv")
oms_addResources("addExternalResources:externalSystem.ssv", "../../resources/
˓→externalSystem1.ssv")
oms_addResources("addExternalResources", "../../resources/externalGain.ssv")
-- export the ssp with new resources
oms_export("addExternalResources", "addExternalResources1.ssp")
10.4.9 addSignalsToResults
Add all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.4.10 addSubModel
Adds a component to a system.
10.4.11 addSystem
Adds a (sub-)system to a model or system.
10.4.12 addTLMBus
Adds a TLM bus.
oms_tlm_domain_input
oms_tlm_domain_output
oms_tlm_domain_mechanical
oms_tlm_domain_rotational
oms_tlm_domain_hydraulic
oms_tlm_domain_electric
oms_tlm_no_interpolation
oms_tlm_coarse_grained
oms_tlm_fine_grained
10.4.13 addTLMConnection
Connects two TLM connectors.
10.4.14 compareSimulationResults
This function compares a given signal of two result files within absolute and relative tolerances.
Type Description
Integer 1 if the signal is considered as equal, 0 otherwise
10.4.15 copySystem
Copies a system.
10.4.16 delete
Deletes a connector, component, system, or model object.
status = oms_delete(cref)
10.4.17 deleteConnection
Deletes the connection between connectors crefA and crefB.
The two arguments crefA and crefB get swapped automatically if necessary.
10.4.18 deleteConnectorFromBus
Deletes a connector from a given bus.
10.4.19 deleteConnectorFromTLMBus
Deletes a connector from a given TLM bus.
10.4.20 deleteResources
Deletes the reference and resource file in a SSP. Deletion of ".ssv" and ".ssm" files are currently supported. The
API can be used in two ways.
1) deleting only the reference file in ".ssd".
2) deleting both reference and resource files in ".ssp".
To delete only the reference file in ssd, the user should provide the full qualified cref of the ".ssv" file associated
with a system or subsystem or component (e.g) "model.root:root1.ssv".
To delete both the reference and resource file in ssp, it is enough to provide only the model cref of the ".ssv" file
(e.g) "model:root1.ssv".
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file then
the ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as the ssm file is
binded to a ssv file.
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref. (e.g)
":root.ssv"
status = oms_deleteResources(cref)
-- Example
oms_importFile("deleteResources1.ssp")
-- delete only the references in ".ssd" file
oms_deleteResources("deleteResources.root:root.ssv")
-- delete both references and resources
oms_deleteResources("deleteResources:root.ssv")
oms_export("deleteResources1.ssp")
10.4.21 duplicateVariant
This API provides support to develop a multi-variant modelling in OMSimulator [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ]. When duplicating a variant, the new variant becomes the current variant and all the changes
made by the users are applied to the new variants only, and all the ssv and ssm resources associated with the
new variant will be given new name based on the variant name provided by the user. This allows the bundling of
multiple variants of a system structure definition referencing a similar set of packaged resources as a single SSP.
However there must still be one SSD file named SystemStructure.ssd at the root of the ZIP archive which will be
considered as default variant.
10.4.22 export
Exports a composite model to a SPP file.
10.4.23 exportDependencyGraphs
Export the dependency graphs of a given model to dot files.
10.4.24 exportSSMTemplate
Exports all signals that have start values of one or multiple FMUs to a SSM file that are read from modelDescrip-
tion.xml with a mapping entry. The mapping entry specifies a single mapping between a parameter in the source
and a parameter of the system or component being parameterized. The mapping entry contains two attributes
namely source and target. The source attribute will be empty and needs to be manually mapped by the users asso-
ciated with the parameter name defined in the SSV file, the target contains the name of parameter in the system or
component to be parameterized. The function can be called for a top level model or a certain FMU component. If
called for a top level model, start values of all FMUs are exported to the SSM file. If called for a component, start
values of just this FMU are exported to the SSM file.
10.4.25 exportSSVTemplate
Exports all signals that have start values of one or multiple FMUs to a SSV file that are read from modelDescrip-
tion.xml. The function can be called for a top level model or a certain FMU component. If called for a top level
model, start values of all FMUs are exported to the SSV file. If called for a component, start values of just this
FMU are exported to the SSV file.
10.4.26 exportSnapshot
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.4.27 faultInjection
Defines a new fault injection block.
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
10.4.28 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
This function is neither needed nor available from the Lua interface.
10.4.29 getBoolean
Get boolean value of given signal.
10.4.30 getDirectionalDerivative
This function computes the directional derivatives of an FMU.
10.4.31 getFixedStepSize
Gets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.4.32 getInteger
Get integer value of given signal.
10.4.33 getModelState
Gets the model state of the given model cref.
10.4.34 getReal
Get real value.
10.4.35 getSolver
Gets the selected solver method of the given system.
10.4.36 getStartTime
Get the start time from the model.
10.4.37 getStopTime
Get the stop time from the model.
10.4.38 getString
Get string value.
Memory is allocated for value. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.4.39 getSystemType
Gets the type of the given system.
10.4.40 getTime
Get the current simulation time from the model.
10.4.41 getTolerance
Gets the tolerance of a given system or component.
10.4.42 getVariableStepSize
Gets the step size parameters.
10.4.43 getVersion
Returns the library's version string.
version = oms_getVersion()
10.4.44 importFile
Imports a composite model from a SSP file.
10.4.45 importSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.4.46 initialize
Initializes a composite model.
status = oms_initialize(cref)
10.4.47 instantiate
Instantiates a given composite model.
status = oms_instantiate(cref)
10.4.48 list
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.4.49 listUnconnectedConnectors
Lists all unconnected connectors of a given system.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.4.50 listVariants
This API shows the number of variants available [(e.g). SystemStructure.ssd, VarA.ssd, VarB.ssd ] from a ssp file.
status = oms_listVariants(cref)
10.4.51 loadSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.4.52 newModel
Creates a new and yet empty composite model.
status = oms_newModel(cref)
10.4.53 newResources
Adds a new empty resources to the SSP. The resource file is a ".ssv" file where the parameter values set by the users
using "oms_setReal()", "oms_setInteger()" and "oms_setReal()" are writtern to the file. Currently only ".ssv" files
can be created.
The filename of the resource file is provided by the users using colon suffix at the end of cref. (e.g) ":root.ssv"
status = oms_newResources(cref)
-- Example
oms_newModel("newResources")
oms_addSystem("newResources.root", oms_system_wc)
oms_addConnector("newResources.root.Input1", oms_causality_input, oms_signal_type_
˓→real)
-- add Top level new resources, the filename is provided using the colon suffix
˓→":root.ssv"
oms_newResources("newResources.root:root.ssv")
oms_setReal("newResources.root.Input1", 10)
-- export the ssp with new resources
oms_export("newResources", "newResources.ssp")
10.4.54 referenceResources
Switches the references of ".ssv" and ".ssm" in a SSP file. Referencing of ".ssv" and ".ssm" files are currently
supported. The API can be used in two ways.
1) Referencing only the ".ssv" file.
2) Referencing both the ".ssv" along with the ".ssm" file.
This API should be used in combination with "oms_deleteResources".To switch with a new reference, the old
reference must be deleted first using "oms_deleteResources" and then reference with new resources.
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file, then
the reference of ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as
the ssm file is binded to a ssv file. Hence it is not possible to switch the reference of ".ssm" file alone. So inorder
to switch the reference of ".ssm" file, the users need to bind the reference of ".ssm" file along with the ".ssv".
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref (e.g)
":root.ssv", and the ".ssm" file is optional and is provided by the user as the second argument to the API.
-- Example
oms_importFile("referenceResources1.ssp")
-- delete only the references in ".ssd" file
oms_deleteResources("referenceResources1.root:root.ssv")
-- usage-1 switch with new references, only ssv file
oms_referenceResources("referenceResources1.root:Config1.ssv")
-- usage-2 switch with new references, both ssv and ssm file
oms_referenceResources("referenceResources1.root:Config1.ssv", "Config1.ssm")
oms_export("referenceResources1.ssp")
10.4.55 removeSignalsFromResults
Removes all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.4.56 rename
Renames a model, system, or component.
10.4.57 replaceSubModel
Replaces an existing fmu component, with a new component provided by the user, When replacing the fmu checks
are made in all ssp concepts like in ssd, ssv and ssm, so that connections and parameter settings are not lost. It is
possible that the namings of inputs and parameters match, but the start values might have been changed, in such
cases new start values will be applied in ssd, ssv and ssm. In case if the Types of inputs and outputs and parameters
differed, then the variables are updated according to the new changes and the connections will be removed with
warning messages to user. In case when replacing a fmu, if the fmu contains parameter mapping associated with
the ssv file, then only the ssm file entries are updated and the start values in the ssv files will not be changed.
10.4.58 reset
Reset the composite model after a simulation run.
The FMUs go into the same state as after instantiation.
status = oms_reset(cref)
10.4.59 setActivationRatio
Experimental feature for setting the activation ratio of FMUs for experimenting with multi-rate master algorithms.
status = experimental_setActivationRatio(cref, k)
10.4.60 setBoolean
Sets the value of a given boolean signal.
10.4.61 setCommandLineOption
Sets special flags.
status = oms_setCommandLineOption(cmd)
Available flags:
˓→components.
˓→with 1.0
10.4.62 setFixedStepSize
Sets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.4.63 setInteger
Sets the value of a given integer signal.
10.4.64 setLogFile
Redirects logging output to file or std streams. The warning/error counters are reset.
filename="" to redirect to std streams and proper filename to redirect to file.
status = oms_setLogFile(filename)
10.4.65 setLoggingInterval
Set the logging interval of the simulation.
10.4.66 setLoggingLevel
Enables/Disables debug logging (logDebug and logTrace).
0 default, 1 default+debug, 2 default+debug+trace
oms_setLoggingLevel(logLevel)
10.4.67 setMaxLogFileSize
Sets maximum log file size in MB. If the file exceeds this limit, the logging will continue on stdout.
oms_setMaxLogFileSize(size)
10.4.68 setReal
Sets the value of a given real signal.
10.4.69 setRealInputDerivative
Sets the first order derivative of a real input signal.
This can only be used for CS-FMU real input signals.
10.4.70 setResultFile
Set the result file of the simulation.
10.4.71 setSolver
Sets the solver method for the given system.
10.4.72 setStartTime
Set the start time of the simulation.
10.4.73 setStopTime
Set the stop time of the simulation.
10.4.74 setString
Sets the value of a given string signal.
10.4.75 setTLMPositionAndOrientation
Sets initial position and orientation for a TLM 3D interface.
10.4.76 setTLMSocketData
Sets data for TLM socket communication.
10.4.77 setTempDirectory
Set new temp directory.
status = oms_setTempDirectory(newTempDir)
10.4.78 setTolerance
Sets the tolerance for a given model or system.
Default values are 1e-4 for both relative and absolute tolerances.
A tolerance specified for a model is automatically applied to its root system, i.e. both calls do exactly the same:
Component, e.g. FMUs, pick up the tolerances from there system. That means it is not possible to define different
tolerances for FMUs in the same system right now.
In a strongly coupled system (oms_system_sc), the relative tolerance is used for CVODE and the absolute tolerance
is used to solve algebraic loops.
In a weakly coupled system (oms_system_wc), both the relative and absolute tolerances are used for the adaptive
step master algorithms and the absolute tolerance is used to solve algebraic loops.
10.4.79 setUnit
Sets the unit of a given signal.
10.4.80 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
10.4.81 setWorkingDirectory
Set a new working directory.
status = oms_setWorkingDirectory(newWorkingDir)
10.4.82 simulate
Simulates a composite model.
status = oms_simulate(cref)
10.4.83 simulate_realtime
Experimental feature for (soft) real-time simulation.
status = experimental_simulate_realtime(ident)
10.4.84 stepUntil
Simulates a composite model until a given time value.
10.4.85 terminate
Terminates a given composite model.
status = oms_terminate(cref)
10.5 OMSimulatorPython
This is a shared library that provides a Python interface for the OMSimulatorLib library.
Installation using pip is recommended:
oms = OMSimulator()
oms.setTempDirectory("./temp/")
oms.newModel("model")
oms.addSystem("model.root", oms.system_sc)
# instantiate FMUs
oms.addSubModel("model.root.system1", "FMUs/System1.fmu")
oms.addSubModel("model.root.system2", "FMUs/System2.fmu")
# add connections
oms.addConnection("model.root.system1.y", "model.root.system2.u")
oms.addConnection("model.root.system2.y", "model.root.system1.u")
# simulation settings
oms.setResultFile("model", "results.mat")
oms.setStopTime("model", 0.1)
oms.setFixedStepSize("model.root", 1e-4)
oms.instantiate("model")
oms.setReal("model.root.system1.x_start", 2.5)
oms.initialize("model")
oms.simulate("model")
oms.terminate("model")
oms.delete("model")
The python package also provides a more object oriented API. The following example is equivalent to the previous
one:
oms.setTempDirectory('./temp/')
model = oms.newModel("model")
root = model.addSystem('root', oms.Types.System.SC)
# instantiate FMUs
root.addSubModel('system1', 'FMUs/System1.fmu')
root.addSubModel('system2', 'FMUs/System2.fmu')
# add connections
root.addConnection('system1.y', 'system2.u')
root.addConnection('system2.y', 'system1.u')
# simulation settings
(continues on next page)
model.instantiate()
model.setReal('root.system1.x_start', 2.5)
#or system.setReal('system1.x_start', 2.5)
model.initialize()
model.simulate()
model.terminate()
model.delete()
10.5.1 activateVariant
This API provides support to activate a multi-variant modelling from an ssp file [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ] from a ssp file. By default when importing a ssp file the default variant will be "System-
Structure.ssd". The users can be able to switch between other variants by using this API and make changes to that
particular variant and simulate them.
10.5.2 addBus
Adds a bus to a given component.
status = oms.addBus(cref)
10.5.3 addConnection
Adds a new connection between connectors A and B. The connectors need to be specified as fully qualified com-
ponent references, e.g., "model.system.component.signal".
The two arguments crefA and crefB get swapped automatically if necessary. The third argument suppressUnitCon-
version is optional and the default value is false which allows automatic unit conversion between connections, if
set to true then automatic unit conversion will be disabled.
10.5.4 addConnector
Adds a connector to a given component.
oms.input
oms.output
oms.parameter
oms.bidir
oms.undefined
oms.signal_type_real
oms.signal_type_integer
oms.signal_type_boolean
oms.signal_type_string
oms.signal_type_enum
oms.signal_type_bus
10.5.5 addConnectorToBus
Adds a connector to a bus.
10.5.6 addConnectorToTLMBus
Adds a connector to a TLM bus.
10.5.7 addExternalModel
Adds an external model to a TLM system.
10.5.8 addResources
Adds an external resources to an existing SSP. The external resources should be a ".ssv" or ".ssm" file
## Example
from OMSimulator import OMSimulator
oms = OMSimulator()
oms.importFile("addExternalResources1.ssp")
## add list of external resources from filesystem to ssp
oms.addResources("addExternalResources", "../../resources/externalRoot.ssv")
oms.addResources("addExternalResources:externalSystem.ssv", "../../resources/
˓→externalSystem1.ssv")
oms.addResources("addExternalResources", "../../resources/externalGain.ssv")
(continues on next page)
10.5.9 addSignalsToResults
Add all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.5.10 addSubModel
Adds a component to a system.
10.5.11 addSystem
Adds a (sub-)system to a model or system.
10.5.12 addTLMBus
Adds a TLM bus.
oms.tlm_domain_input
oms.tlm_domain_output
oms.tlm_domain_mechanical
oms.tlm_domain_rotational
oms.tlm_domain_hydraulic
oms.tlm_domain_electric
oms.default
oms.coarsegrained
oms.finegrained
10.5.13 addTLMConnection
Connects two TLM connectors.
10.5.14 compareSimulationResults
This function compares a given signal of two result files within absolute and relative tolerances.
Type Description
Integer 1 if the signal is considered as equal, 0 otherwise
10.5.15 copySystem
Copies a system.
10.5.16 delete
Deletes a connector, component, system, or model object.
status = oms.delete(cref)
10.5.17 deleteConnection
Deletes the connection between connectors crefA and crefB.
The two arguments crefA and crefB get swapped automatically if necessary.
10.5.18 deleteConnectorFromBus
Deletes a connector from a given bus.
10.5.19 deleteConnectorFromTLMBus
Deletes a connector from a given TLM bus.
10.5.20 deleteResources
Deletes the reference and resource file in a SSP. Deletion of ".ssv" and ".ssm" files are currently supported. The
API can be used in two ways.
1) deleting only the reference file in ".ssd".
2) deleting both reference and resource files in ".ssp".
To delete only the reference file in ssd, the user should provide the full qualified cref of the ".ssv" file associated
with a system or subsystem or component (e.g) "model.root:root1.ssv".
To delete both the reference and resource file in ssp, it is enough to provide only the model cref of the ".ssv" file
(e.g) "model:root1.ssv".
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file then
the ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as the ssm file is
binded to a ssv file.
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref. (e.g)
":root.ssv"
status = oms.deleteResources(cref))
## Example
from OMSimulator import OMSimulator
oms = OMSimulator()
oms.importFile("deleteResources1.ssp")
## delete only the references in ".ssd" file
oms.deleteResources("deleteResources.root:root.ssv")
## delete both references and resources
oms.deleteResources("deleteResources:root.ssv")
oms.export("deleteResources1.ssp")
10.5.21 doStep
Simulates a macro step of the given composite model. The step size will be determined by the master algorithm
and is limited by the definied minimal and maximal step sizes.
status = oms.doStep(cref)
10.5.22 duplicateVariant
This API provides support to develop a multi-variant modelling in OMSimulator [(e.g). SystemStructure.ssd,
VarA.ssd, VarB.ssd ]. When duplicating a variant, the new variant becomes the current variant and all the changes
made by the users are applied to the new variants only, and all the ssv and ssm resources associated with the
new variant will be given new name based on the variant name provided by the user. This allows the bundling of
multiple variants of a system structure definition referencing a similar set of packaged resources as a single SSP.
However there must still be one SSD file named SystemStructure.ssd at the root of the ZIP archive which will be
considered as default variant.
10.5.23 export
Exports a composite model to a SPP file.
10.5.24 exportDependencyGraphs
Export the dependency graphs of a given model to dot files.
10.5.25 exportSSMTemplate
Exports all signals that have start values of one or multiple FMUs to a SSM file that are read from modelDescrip-
tion.xml with a mapping entry. The mapping entry specifies a single mapping between a parameter in the source
and a parameter of the system or component being parameterized. The mapping entry contains two attributes
namely source and target. The source attribute will be empty and needs to be manually mapped by the users asso-
ciated with the parameter name defined in the SSV file, the target contains the name of parameter in the system or
component to be parameterized. The function can be called for a top level model or a certain FMU component. If
called for a top level model, start values of all FMUs are exported to the SSM file. If called for a component, start
values of just this FMU are exported to the SSM file.
10.5.26 exportSSVTemplate
Exports all signals that have start values of one or multiple FMUs to a SSV file that are read from modelDescrip-
tion.xml. The function can be called for a top level model or a certain FMU component. If called for a top level
model, start values of all FMUs are exported to the SSV file. If called for a component, start values of just this
FMU are exported to the SSV file.
10.5.27 exportSnapshot
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.5.28 faultInjection
Defines a new fault injection block.
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
10.5.29 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
oms.freeMemory(obj)
10.5.30 getBoolean
Get boolean value of given signal.
10.5.31 getDirectionalDerivative
This function computes the directional derivatives of an FMU.
10.5.32 getFixedStepSize
Gets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.5.33 getInteger
Get integer value of given signal.
10.5.34 getReal
Get real value.
10.5.35 getResultFile
Gets the result filename and buffer size of the given model cref.
10.5.36 getSolver
Gets the selected solver method of the given system.
10.5.37 getStartTime
Get the start time from the model.
10.5.38 getStopTime
Get the stop time from the model.
10.5.39 getString
Get string value.
Memory is allocated for value. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.5.40 getSubModelPath
Returns the path of a given component.
10.5.41 getSystemType
Gets the type of the given system.
10.5.42 getTime
Get the current simulation time from the model.
10.5.43 getTolerance
Gets the tolerance of a given system or component.
10.5.44 getVariableStepSize
Gets the step size parameters.
10.5.45 getVersion
Returns the library's version string.
oms = OMSimulator()
oms.getVersion()
10.5.46 importFile
Imports a composite model from a SSP file.
10.5.47 importSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.5.48 initialize
Initializes a composite model.
status = oms.initialize(cref)
10.5.49 instantiate
Instantiates a given composite model.
status = oms.instantiate(cref)
10.5.50 list
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.5.51 listUnconnectedConnectors
Lists all unconnected connectors of a given system.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.5.52 listVariants
This API shows the number of variants available [(e.g). SystemStructure.ssd, VarA.ssd, VarB.ssd ] from a ssp file.
status = oms.listVariants(cref)
oms_listVariants("varB")
The API will list the available variants like below <oms:Variants>
<oms:variant name="model" /> <oms:variant name="varB" /> <oms:variant name="varA"
/>
</oms:Variants>
10.5.53 loadSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.5.54 newModel
Creates a new and yet empty composite model.
status = oms.newModel(cref)
10.5.55 newResources
Adds a new empty resources to the SSP. The resource file is a ".ssv" file where the parameter values set by the users
using "oms_setReal()", "oms_setInteger()" and "oms_setReal()" are writtern to the file. Currently only ".ssv" files
can be created.
The filename of the resource file is provided by the users using colon suffix at the end of cref. (e.g) ":root.ssv"
status = oms.newResources(cref)
## Example
from OMSimulator import OMSimulator
oms = OMSimulator()
oms.newModel("newResources")
oms.addSystem("newResources.root", oms_system_wc)
oms.addConnector("newResources.root.Input1", oms.input, oms_signal_type_real)
oms.addConnector("newResources.root.Input2", oms.input, oms_signal_type_real)
## add Top level resources, the filename is provided using the colon suffix ":root.
˓→ssv"
oms.newResources("newResources.root:root.ssv")
oms.setReal("newResources.root.Input1", 10)
## export the ssp with new resources
oms.export("newResources", "newResources.ssp")
10.5.56 referenceResources
Switches the references of ".ssv" and ".ssm" in a SSP file. Referencing of ".ssv" and ".ssm" files are currently
supported. The API can be used in two ways.
1) Referencing only the ".ssv" file.
2) Referencing both the ".ssv" along with the ".ssm" file.
This API should be used in combination with "oms_deleteResources".To switch with a new reference, the old
reference must be deleted first using "oms_deleteResources" and then reference with new resources.
When deleting only the references of a ".ssv" file, if a parameter mapping file ".ssm" is binded to a ".ssv" file, then
the reference of ".ssm" file will also be deleted. It is not possible to delete the references of ".ssm" seperately as
the ssm file is binded to a ssv file. Hence it is not possible to switch the reference of ".ssm" file alone. So inorder
to switch the reference of ".ssm" file, the users need to bind the reference of ".ssm" file along with the ".ssv".
The filename of the reference or resource file is provided by the users using colon suffix at the end of cref (e.g)
":root.ssv", and the ".ssm" file is optional and is provided by the user as the second argument to the API.
## Example
from OMSimulator import OMSimulator
oms = OMSimulator()
oms.importFile("referenceResources1.ssp")
## delete only the references in ".ssd" file
oms.deleteResources("referenceResources1.root:root.ssv")
## usage-1 switch with new references, only ssv file
oms.referenceResources("referenceResources1.root:Config1.ssv")
## usage-2 switch with new references, both ssv and ssm file
oms.referenceResources("referenceResources1.root:Config1.ssv", "Config1.ssm")
10.5.57 removeSignalsFromResults
Removes all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.5.58 rename
Renames a model, system, or component.
10.5.59 replaceSubModel
Replaces an existing fmu component, with a new component provided by the user, When replacing the fmu checks
are made in all ssp concepts like in ssd, ssv and ssm, so that connections and parameter settings are not lost. It is
possible that the namings of inputs and parameters match, but the start values might have been changed, in such
cases new start values will be applied in ssd, ssv and ssm. In case if the Types of inputs and outputs and parameters
differed, then the variables are updated according to the new changes and the connections will be removed with
warning messages to user. In case when replacing a fmu, if the fmu contains parameter mapping associated with
the ssv file, then only the ssm file entries are updated and the start values in the ssv files will not be changed.
10.5.60 reset
Reset the composite model after a simulation run.
The FMUs go into the same state as after instantiation.
status = oms.reset(cref)
10.5.61 setBoolean
Sets the value of a given boolean signal.
status = oms.setBoolean(cref, value)
10.5.62 setCommandLineOption
Sets special flags.
status = oms.setCommandLineOption(cmd)
Available flags:
info: Usage: OMSimulator [Options] [Lua script] [FMU] [SSP file]
Options:
--addParametersToCSV=<arg> Export parameters to .csv file (true,
˓→[false])
˓→components.
˓→with 1.0
10.5.63 setFixedStepSize
Sets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.5.64 setInteger
Sets the value of a given integer signal.
10.5.65 setLogFile
Redirects logging output to file or std streams. The warning/error counters are reset.
filename="" to redirect to std streams and proper filename to redirect to file.
status = oms.setLogFile(filename)
10.5.66 setLoggingInterval
Set the logging interval of the simulation.
10.5.67 setLoggingLevel
Enables/Disables debug logging (logDebug and logTrace).
0 default, 1 default+debug, 2 default+debug+trace
oms.setLoggingLevel(logLevel)
10.5.68 setMaxLogFileSize
Sets maximum log file size in MB. If the file exceeds this limit, the logging will continue on stdout.
oms.setMaxLogFileSize(size)
10.5.69 setReal
Sets the value of a given real signal.
10.5.70 setRealInputDerivative
Sets the first order derivative of a real input signal.
This can only be used for CS-FMU real input signals.
10.5.71 setResultFile
Set the result file of the simulation.
10.5.72 setSolver
Sets the solver method for the given system.
10.5.73 setStartTime
Set the start time of the simulation.
10.5.74 setStopTime
Set the stop time of the simulation.
10.5.75 setString
Sets the value of a given string signal.
10.5.76 setTempDirectory
Set new temp directory.
status = oms.setTempDirectory(newTempDir)
10.5.77 setTolerance
Sets the tolerance for a given model or system.
Default values are 1e-4 for both relative and absolute tolerances.
A tolerance specified for a model is automatically applied to its root system, i.e. both calls do exactly the same:
Component, e.g. FMUs, pick up the tolerances from there system. That means it is not possible to define different
tolerances for FMUs in the same system right now.
In a strongly coupled system (oms_system_sc), the relative tolerance is used for CVODE and the absolute tolerance
is used to solve algebraic loops.
In a weakly coupled system (oms_system_wc), both the relative and absolute tolerances are used for the adaptive
step master algorithms and the absolute tolerance is used to solve algebraic loops.
10.5.78 setUnit
Sets the unit of a given signal.
10.5.79 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
10.5.80 setWorkingDirectory
Set a new working directory.
status = oms.setWorkingDirectory(newWorkingDir)
10.5.81 simulate
Simulates a composite model.
status = oms.simulate(cref)
10.5.82 stepUntil
Simulates a composite model until a given time value.
10.5.83 terminate
Terminates a given composite model.
status = oms.terminate(cref)
Example: Pi
This example uses a simple Modelica model and FMI-based batch simulation to approximate the value of pi.
A Modelica model is used to calculate two uniform distributed pseudo-random numbers between 0 and 1 based
on a seed value and evaluates if the resulting coordinate is inside the unit circle or not.
model Circle
parameter Integer globalSeed = 30020 "global seed to initialize random number
˓→generator";
Real x;
Real y;
Boolean inside = x*x + y*y < 1.0;
protected
Integer state128[4];
algorithm
when initial() then
state128 := Modelica.Math.Random.Generators.Xorshift128plus.
˓→initialState(localSeed, globalSeed);
end when;
annotation(uses(Modelica(version="4.0.0")));
end Circle;
The model is then exported using the FMI interface and the generated FMU can then be used to run a million
simulations in just a few seconds.
Listing 10.1: Batch simulation of the simple Cirlce model with differ-
ent seed values. All OMSimulator-related comands are highlighted for
convenience.
1 import math
2 import matplotlib.pyplot as plt
3 import OMSimulator as oms
4
8 model = oms.newModel('pi')
9 root = model.addSystem('root', oms.Types.System.SC)
10 root.addSubModel('circle', 'Circle.fmu')
11
15 results = list()
16 inside = 0
17
18 MIN = 100
19 MAX = 1000000
20 for i in range(0, MAX+1):
21 if i > 0:
22 model.reset()
23 model.setInteger('root.circle.globalSeed', i)
24 model.initialize()
25 if model.getBoolean("root.circle.inside"):
26 inside = inside + 1
27 if i >= MIN:
(continues on next page)
The following figure shows the approximation of pi in relation to the number of samples.
Figure 10.1: Results of the above batch simulation which approximates the value of pi
10.6 OpenModelicaScripting
This is a shared library that provides a OpenModelica Scripting interface for the OMSimulatorLib library.
loadOMSimulator();
oms_setTempDirectory("./temp/");
oms_newModel("model");
oms_addSystem("model.root", OpenModelica.Scripting.oms_system.oms_system_sc);
// instantiate FMUs
oms_addSubModel("model.root.system1", "FMUs/System1.fmu");
oms_addSubModel("model.root.system2", "FMUs/System2.fmu");
// add connections
(continues on next page)
// simulation settings
oms_setResultFile("model", "results.mat");
oms_setStopTime("model", 0.1);
oms_setFixedStepSize("model.root", 1e-4);
oms_instantiate("model");
oms_setReal("model.root.system1.x_start", 2.5);
oms_initialize("model");
oms_simulate("model");
oms_terminate("model");
oms_delete("model");
unloadOMSimulator();
10.6.1 addBus
Adds a bus to a given component.
status := oms_addBus(cref);
10.6.2 addConnection
Adds a new connection between connectors A and B. The connectors need to be specified as fully qualified com-
ponent references, e.g., "model.system.component.signal".
The two arguments crefA and crefB get swapped automatically if necessary. The third argument suppressUnitCon-
version is optional and the default value is false which allows automatic unit conversion between connections, if
set to true then automatic unit conversion will be disabled.
10.6.3 addConnector
Adds a connector to a given component.
"OpenModelica.Scripting.oms_causality.oms_causality_input"
"OpenModelica.Scripting.oms_causality.oms_causality_output"
"OpenModelica.Scripting.oms_causality.oms_causality_parameter"
"OpenModelica.Scripting.oms_causality.oms_causality_bidir"
"OpenModelica.Scripting.oms_causality.oms_causality_undefined"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_real"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_integer"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_boolean"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_string"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_enum"
"OpenModelica.Scripting.oms_signal_type.oms_signal_type_bus"
10.6.4 addConnectorToBus
Adds a connector to a bus.
10.6.5 addConnectorToTLMBus
Adds a connector to a TLM bus.
10.6.6 addExternalModel
Adds an external model to a TLM system.
10.6.7 addSignalsToResults
Add all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.6.8 addSubModel
Adds a component to a system.
10.6.9 addSystem
Adds a (sub-)system to a model or system.
"OpenModelica.Scripting.oms_system.oms_system_none"
"OpenModelica.Scripting.oms_system.oms_system_tlm"
"OpenModelica.Scripting.oms_system.oms_system_sc"
"OpenModelica.Scripting.oms_system.oms_system_wc"
10.6.10 addTLMBus
Adds a TLM bus.
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_input"
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_output"
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_mechanical"
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_rotational"
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_hydraulic"
"OpenModelica.Scripting.oms_tlm_domain.oms_tlm_domain_electric"
"OpenModelica.Scripting.oms_tlm_interpolation.oms_tlm_no_interpolation"
"OpenModelica.Scripting.oms_tlm_interpolation.oms_tlm_coarse_grained"
"OpenModelica.Scripting.oms_tlm_interpolation.oms_tlm_fine_grained"
10.6.11 addTLMConnection
Connects two TLM connectors.
10.6.12 compareSimulationResults
This function compares a given signal of two result files within absolute and relative tolerances.
Type Description
Integer 1 if the signal is considered as equal, 0 otherwise
10.6.13 copySystem
Copies a system.
10.6.14 delete
Deletes a connector, component, system, or model object.
status := oms_delete(cref);
10.6.15 deleteConnection
Deletes the connection between connectors crefA and crefB.
The two arguments crefA and crefB get swapped automatically if necessary.
10.6.16 deleteConnectorFromBus
Deletes a connector from a given bus.
10.6.17 deleteConnectorFromTLMBus
Deletes a connector from a given TLM bus.
10.6.18 export
Exports a composite model to a SPP file.
10.6.19 exportDependencyGraphs
Export the dependency graphs of a given model to dot files.
10.6.20 exportSnapshot
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.6.21 extractFMIKind
Extracts the FMI kind of a given FMU from the file system.
(kind,status) := oms_extractFMIKind(filename);
10.6.22 faultInjection
Defines a new fault injection block.
"OpenModelica.Scripting.oms_fault_type.oms_fault_type_bias"
"OpenModelica.Scripting.oms_fault_type.oms_fault_type_gain"
"OpenModelica.Scripting.oms_fault_type.oms_fault_type_const"
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
10.6.23 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
This function is not needed for OpenModelicaScripting Interface
10.6.24 getBoolean
Get boolean value of given signal.
10.6.25 getFixedStepSize
Gets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.6.26 getInteger
Get integer value of given signal.
10.6.27 getModelState
Gets the model state of the given model cref.
10.6.28 getReal
Get real value.
10.6.29 getSolver
Gets the selected solver method of the given system.
10.6.30 getStartTime
Get the start time from the model.
10.6.31 getStopTime
Get the stop time from the model.
10.6.32 getSubModelPath
Returns the path of a given component.
10.6.33 getSystemType
Gets the type of the given system.
10.6.34 getTime
Get the current simulation time from the model.
10.6.35 getTolerance
Gets the tolerance of a given system or component.
10.6.36 getVariableStepSize
Gets the step size parameters.
10.6.37 getVersion
Returns the library's version string.
version := oms_getVersion();
10.6.38 importFile
Imports a composite model from a SSP file.
10.6.39 importSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.6.40 initialize
Initializes a composite model.
status := oms_initialize(cref);
10.6.41 instantiate
Instantiates a given composite model.
status := oms_instantiate(cref);
10.6.42 list
Lists the SSD representation of a given model, system, or component.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.6.43 listUnconnectedConnectors
Lists all unconnected connectors of a given system.
Memory is allocated for contents. The caller is responsible to free it using the C-API. The Lua and Python bindings
take care of the memory and the caller doesn't need to call free.
10.6.44 loadSnapshot
Loads a snapshot to restore a previous model state. The model must be in virgin model state, which means it must
not be instantiated.
10.6.45 newModel
Creates a new and yet empty composite model.
status := oms_newModel(cref);
10.6.46 removeSignalsFromResults
Removes all variables that match the given regex to the result file.
The second argument, i.e. regex, is considered as a regular expression (C++11). ".*" and "(.)*" can be used to hit
all variables.
10.6.47 rename
Renames a model, system, or component.
status := oms_rename(cref, newCref);
10.6.48 reset
Reset the composite model after a simulation run.
The FMUs go into the same state as after instantiation.
status := oms_reset(cref);
10.6.49 setBoolean
Sets the value of a given boolean signal.
status := oms_setBoolean(cref, value);
10.6.50 setCommandLineOption
Sets special flags.
status := oms_setCommandLineOption(cmd);
Available flags:
info: Usage: OMSimulator [Options] [Lua script] [FMU] [SSP file]
Options:
--addParametersToCSV=<arg> Export parameters to .csv file (true,
˓→[false])
˓→components.
˓→with 1.0
10.6.51 setFixedStepSize
Sets the fixed step size. Can be used for the communication step size of co-simulation systems and also for the
integrator step size in model exchange systems.
10.6.52 setInteger
Sets the value of a given integer signal.
10.6.53 setLogFile
Redirects logging output to file or std streams. The warning/error counters are reset.
filename="" to redirect to std streams and proper filename to redirect to file.
status := oms_setLogFile(filename);
10.6.54 setLoggingInterval
Set the logging interval of the simulation.
10.6.55 setLoggingLevel
Enables/Disables debug logging (logDebug and logTrace).
0 default, 1 default+debug, 2 default+debug+trace
oms_setLoggingLevel(logLevel);
10.6.56 setReal
Sets the value of a given real signal.
10.6.57 setRealInputDerivative
Sets the first order derivative of a real input signal.
This can only be used for CS-FMU real input signals.
10.6.58 setResultFile
Set the result file of the simulation.
10.6.59 setSolver
Sets the solver method for the given system.
"OpenModelica.Scripting.oms_solver.oms_solver_none"
"OpenModelica.Scripting.oms_solver.oms_solver_sc_min"
"OpenModelica.Scripting.oms_solver.oms_solver_sc_explicit_euler"
"OpenModelica.Scripting.oms_solver.oms_solver_sc_cvode"
"OpenModelica.Scripting.oms_solver.oms_solver_sc_max"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_min"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_ma"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_mav"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_assc"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_mav2"
"OpenModelica.Scripting.oms_solver.oms_solver_wc_max"
10.6.60 setStartTime
Set the start time of the simulation.
10.6.61 setStopTime
Set the stop time of the simulation.
10.6.62 setTLMPositionAndOrientation
Sets initial position and orientation for a TLM 3D interface.
10.6.63 setTLMSocketData
Sets data for TLM socket communication.
10.6.64 setTempDirectory
Set new temp directory.
status := oms_setTempDirectory(newTempDir);
10.6.65 setTolerance
Sets the tolerance for a given model or system.
Default values are 1e-4 for both relative and absolute tolerances.
A tolerance specified for a model is automatically applied to its root system, i.e. both calls do exactly the same:
Component, e.g. FMUs, pick up the tolerances from there system. That means it is not possible to define different
tolerances for FMUs in the same system right now.
In a strongly coupled system (oms_system_sc), the relative tolerance is used for CVODE and the absolute tolerance
is used to solve algebraic loops.
In a weakly coupled system (oms_system_wc), both the relative and absolute tolerances are used for the adaptive
step master algorithms and the absolute tolerance is used to solve algebraic loops.
10.6.66 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
10.6.67 setWorkingDirectory
Set a new working directory.
status := oms_setWorkingDirectory(newWorkingDir);
10.6.68 simulate
Simulates a composite model.
status := oms_simulate(cref);
10.6.69 stepUntil
Simulates a composite model until a given time value.
10.6.70 terminate
Terminates a given composite model.
status := oms_terminate(cref);
That will open a dialog to enter the names of the model and the root system and to choose the root systems type.
There are three types available:
• TLM - Transmission Line Modeling System
• Weakly Coupled - Connected Co-Simulation FMUs System
• Strongly Coupled - Connected Model-Exchange FMUs System
Figure 10.5: OMEdit: Newly created empty root system of SSP model
The file browser will open to select an FMU (.fmu) or result file (.csv) as a subsmodel. Then a dialog opens to
choose the name of the new sub-model.
10.7.4 Simulate
Select the simulate button (symbol with green arrow) or select Simulation->Simulate from the menu in OMEdit
to simulate the SSP model.
Figure 10.11: Dual mass oscillator Modelica model (diagramm view) and FMUs
TLM systems are only allowed on top-level. SSD annotations are used to specify the system type inside the
ssd:SimulationInformation tag, as shown in the example below. Attributes ip, managerport and
monitorport defines the socket communication, used both to exchange data with external tools and with inter-
nal simulation threads.
<?xml version="1.0"?>
<ssd:System name="tlm">
<ssd:SimulationInformation>
<ssd:Annotations>
<ssd:Annotation type="org.openmodelica">
<oms:TlmMaster ip="127.0.1.1" managerport="11111" monitorport="11121"/>
</ssd:Annotation>
</ssd:Annotations>
</ssd:SimulationInformation>
<ssd:Elements>
<ssd:System name="weaklycoupled">
<ssd:SimulationInformation>
<ssd:FixedStepMaster description="oms-ma" stepSize="1e-1" />
</ssd:SimulationInformation>
</ssd:System>
</ssd:Elements>
</ssd:System>
TLM connections are implemented without regular SSD connections. TLM connections are only allowed in TLM
systems. TLM connectors are only allowed in weakly coupled or strongly coupled systems. Both connectors and
<?xml version="1.0"?>
<ssd:System name="tlm">
<ssd:Elements>
<ssd:System name="wc2">
<ssd:Connectors>
<ssd:Connector name="y" kind="input" type="Real" />
</ssd:Connectors>
<ssd:Annotations>
<ssd:Annotation type="org.openmodelica">
<oms:Bus name="bus2" type="tlm" domain="signal"
dimension="1" interpolation="none">
<oms:Signals>
<oms:Signal name="y" tlmType="value" />
</oms:Signals>
</oms:Bus>
</ssd:Annotation>
</ssd:Annotations>
</ssd:System>
<ssd:System name="wc1">
<ssd:Connectors>
<ssd:Connector name="y" kind="output" type="Real" />
<ssd:Connector name="x" kind="output" type="Real" />
<ssd:Connector name="v" kind="output" type="Real" />
<ssd:Connector name="f" kind="input" type="Real" />
</ssd:Connectors>
<ssd:Annotations>
<ssd:Annotation type="org.openmodelica">
<oms:Bus name="bus1" type="tlm" domain="signal"
dimension="1" interpolation="none">
<oms:Signals>
<oms:Signal name="y" tlmType="value" />
</oms:Signals>
</oms:Bus>
<oms:Bus name="bus2" type="tlm" domain="mechanical"
dimension="1" interpolation="none">
<oms:Signals>
<oms:Signal name="x" tlmType="state" />
<oms:Signal name="v" tlmType="flow" />
<oms:Signal name="f" tlmType="effort" />
</oms:Signals>
</oms:Bus>
</ssd:Annotation>
</ssd:Annotations>
</ssd:System>
</ssd:Elements>
<ssd:Annotations>
<ssd:Annotation type="org.openmodelica">
<oms:Connections>
<oms:Connection startElement="wc1" startConnector="bus1"
endElement="wc2" endConnector="bus2"
delay="0.001000" alpha="0.300000"
linearimpedance="100.000000"
angularimpedance="0.000000" />
</oms:Connections>
</ssd:Annotation>
</ssd:Annotations>
</ssd:System>
Depending on the type of TLM bus connector (dimension, domain and interpolation), connectors need to be
assigned to different tlm variable types. Below is the complete list of supported TLM bus types and their respective
connectors.
1D signal
tlmType causality
"value" input/output
tlmType causality
"state" output
"flow" output
"effort" input
tlmType causality
"state" output
"flow" output
"wave" input
"impedance" input
tlmType causality
"state" output
"flow" output
"wave1" input
"wave2" input
"wave3" input
"wave4" input
"wave5" input
"wave6" input
"wave7" input
"wave8" input
"wave9" input
"wave10" input
"time1" input
"time2" input
"time3" input
"time4" input
"time5" input
"time6" input
"time7" input
"time8" input
"time9" input
"time10" input
"impedance" input
tlmType causality
"state1" output
"state2" output
"state3" output
"A11" output
"A12" output
"A13" output
"A21" output
"A22" output
"A23" output
"A31" output
"A32" output
"A33" output
"flow1" output
"flow2" output
"flow3" output
"flow4" output
"flow5" output
"flow6" output
"effort1" input
"effort2" input
"effort3" input
"effort4" input
"effort5" input
"effort6" input
tlmType causality
"state1" output
"state2" output
"state3" output
"A11" output
"A12" output
"A13" output
"A21" output
"A22" output
"A23" output
"A31" output
"A32" output
"A33" output
"flow1" output
"flow2" output
"flow3" output
"flow4" output
"flow5" output
"flow6" output
"wave1" input
"wave2" input
"wave3" input
"wave4" input
"wave5" input
"wave6" input
"linearimpedance" input
"angularimpedance" input
tlmType causality
"state1" output
"state2" output
"state3" output
"A11" output
"A12" output
"A13" output
"A21" output
"A22" output
"A23" output
"A31" output
"A32" output
"A33" output
"flow1" output
"flow2" output
"flow3" output
"flow4" output
"flow5" output
"flow6" output
"wave1_1" input
"wave1_2" input
"wave1_3" input
"wave1_4" input
"wave1_5" input
"wave1_6" input
"wave2_1" input
"wave2_2" input
"wave2_3" input
"wave2_4" input
"wave2_5" input
"wave2_6" input
"wave3_1" input
"wave3_2" input
"wave3_3" input
"wave3_4" input
"wave3_5" input
"wave3_6" input
"wave4_1" input
"wave4_2" input
"wave4_3" input
"wave4_4" input
"wave4_5" input
"wave4_6" input
"wave5_1" input
"wave5_2" input
"wave5_3" input
"wave5_4" input
"wave5_5" input
"wave5_6" input
"wave6_1" input
"wave6_2" input
"wave6_3" input
"wave6_4" input
continues on next page
ELEVEN
SYSTEM IDENTIFICATION
System Identification (OMSysIdent) is part of the OpenModelica tool suite, but not bundled together with the
main OpenModelica distribution and thus must be fetched separately from its project site.
OMSysIdent is a module for the parameter estimation for linear and nonlinear parametric dynamic models
(wrapped as FMUs) on top of the OMSimulator API. It uses the Ceres solver (http://ceres-solver.org/) for the
optimization task. The module provides a Python scripting API as well as an C API.
Note: Notice that this module was previously part of OMSimulator. It has been extracted out of the OMSimulator
project and reorganized as a separate project in September 2020. As of 2020-10-07 the project is working on Linux
but some more efforts are needed for migrating the Windows build and make the build and usage of the module
more convenient.
Version: a65a0ed
11.1 Examples
There are examples in the testsuite which use the scripting API, as well as examples which directly use the C API.
Below is a basic example from the testsuite (HelloWorld_cs_Fit.py) which uses the Python scripting API. It deter-
mines the parameters for the following "hello world" style Modelica model:
model HelloWorld
parameter Real a = -1;
parameter Real x_start = 1;
Real x(start=x_start, fixed=true);
equation
der(x) = a*x;
end HelloWorld;
The goal is to estimate the value of the coefficent a and the initial value x_start of the state variable x. Instead of real
measurements, the script simply uses simulation data generated from the HelloWorld examples as measurement
data. The array data_time contains the time instants at which a sample is taken and the array data_x contains the
value of x that corresponds to the respective time instant.
The estimation parameters are defined by calls to function simodel.addParameter(..) in which the name of the
parameter and a first guess for the parameter's value is stated.
oms = OMSimulator()
oms.setLogFile("HelloWorld_cs_Fit_py.log")
(continues on next page)
215
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
# add FMU
oms.addSubModel("HelloWorld_cs_Fit.root.HelloWorld", "../resources/HelloWorld.fmu")
# Data generated from simulating HelloWorld.mo for 1.0s with Euler and 0.1s step
˓→size
kNumSeries = 1
kNumObservations = 11
data_time = np.array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])
inputvars = []
measurementvars = ["root.HelloWorld.x"]
data_x = np.array([1, 0.9, 0.8100000000000001, 0.7290000000000001, 0.6561, 0.
˓→5904900000000001, 0.5314410000000001, 0.4782969000000001, 0.43046721, 0.
˓→387420489, 0.3486784401])
simodel.addParameter("root.HelloWorld.x_start", 0.5)
simodel.addParameter("root.HelloWorld.a", -0.5)
simodel.addMeasurement(0, "root.HelloWorld.x", data_x)
# simodel.describe()
simodel.setOptions_max_num_iterations(25)
simodel.solve("BriefReport")
# del simodel
oms.terminate("HelloWorld_cs_Fit")
oms.delete("HelloWorld_cs_Fit")
=====================================
Total duration for parameter estimation: 44msec.
Result of parameter estimation (check 'Termination' status above whether solver
˓→converged):
HelloWorld_cs_Fit.root.HelloWorld.a(start=-0.5, *estimate*=-1)
HelloWorld_cs_Fit.root.HelloWorld.x_start(start=0.5, *estimate*=1)
=====================================
HelloWorld.a estimation is OK: True
HelloWorld.x_start estimation is OK: True
info: Logging information has been saved to "HelloWorld_cs_Fit_py.log"
11.2.1 addInput
Add input values for external model inputs.
If there are several measurement series, all series need to be conducted with the same external inputs!
Python
Args:
var (str) Name of variable..
values (np.array) Array of input values for respective time instants in simodel.initialize().
Returns:
status (int) The C-API status code (oms_status_enu_t).
11.2.2 addMeasurement
Add measurement values for a fitting variable.
Python
Args:
iSeries (int) Index of measurement series.
var (str) Name of variable..
values (np.array) Array of measured values for respective time instants in simodel.initialize().
Returns:
status (int) The C-API status code (oms_status_enu_t).
11.2.3 addParameter
Add parameter that should be estimated.
PYTHON
Args:
var (str) Name of parameter.
startvalue (float) Start value of parameter.
Returns:
status (int) The C-API status code (oms_status_enu_t).
11.2.4 describe
Print summary of SysIdent model.
PYTHON
status = simodel.describe()
11.2.5 freeSysIdentModel
Unloads a model.
PYTHON
11.2.6 getParameter
Get parameter that should be estimated.
PYTHON
Args:
var (str) Name of parameter.
Returns:
status (int) The C-API status code (oms_status_enu_t).
startvalue (float) Start value of parameter.
estimatedvalue (float) Estimated value of parameter.
11.2.7 getState
Get state of SysIdent model object.
PYTHON
Returns:
status (int) The C-API status code (oms_status_enu_t).
state (int) State of SysIdent model (omsi_simodelstate_t).
11.2.8 initialize
This function initializes a given composite model. After this call, the model is in simulation mode.
PYTHON
Args:
nSeries (int) Number of measurement series.
time (numpy.array) Array of measurement/input time instants.
inputvars (list of str) List of names of input variables (empty list if none).
measurementvars (list of str) List of names of observed measurement variables.
Returns:
status (int) The C-API status code (oms_status_enu_t).
11.2.9 newSysIdentModel
Creates an empty model for parameter estimation.
PYTHON
simodel = OMSysIdent(ident)
11.2.10 oms_status_str
Mapping of enum C-API status code (oms_status_enu_t) to string.
The C enum is reproduced below for convenience.
typedef enum {
oms_status_ok,
oms_status_warning,
oms_status_discard,
oms_status_error,
oms_status_fatal,
oms_status_pending
} oms_status_enu_t;
PYTHON
Args:
status (int) The C-API status code.
Returns:
status_str (str) String representation of status code.
The range of values of status corresponds to the C enum (by implicit conversion). This is a static Python
method (@staticmethod).
status_str = oms_status_str(status)
Not available.
11.2.11 omsi_simodelstate_str
Mapping of enum C-API state code (omsi_simodelstate_t) to string.
The C enum is reproduced below for convenience.
typedef enum {
omsi_simodelstate_constructed, //!< After omsi_newSysIdentModel
omsi_simodelstate_initialized, //!< After omsi_initialize
omsi_simodelstate_convergence, //!< After omsi_solve if Ceres minimizer
˓→returned with ceres::TerminationType::CONVERGENCE
} omsi_simodelstate_t;
PYTHON
Args:
state (int) State of SysIdent model.
Returns:
simodelstate_str (str) String representation of state code.
The range of values of state corresponds to the C enum (by implicit conversion). This is a static Python method
(@staticmethod).
simodelstate_str = omsi_simodelstate_str(state)
Not available.
11.2.12 setOptions_max_num_iterations
Set Ceres solver option Solver::Options::max_num_iterations.
PYTHON
Args:
max_num_iterations (int) Maximum number of iterations for which the solver should run (de-
fault: 25).
Returns:
status (int) The C-API status code (oms_status_enu_t).
status = simodel.setOptions_max_num_iterations(max_num_iterations)
11.2.13 solve
Solve parameter estimation problem.
PYTHON
Args:
reporttype (str) Print report and progress information after call to Ceres solver. Supported
report types: "", "BriefReport", "FullReport", where "" denotes no output.
Returns:
status (int) The C-API status code (oms_status_enu_t).
status = simodel.solve(reporttype)
TWELVE
OPENMODELICA ENCRYPTION
The encryption module allows the library developers to encrypt their libraries for different platforms. Note that
you need a special version of OpenModelica with encryption support. Contact us if you want one.
12.3 Notes
• There is no license management and obfuscation of the generated code and files. However just a basic
encryption and decryption is supported along with full support for protection access annotation as defined
in Modelica specification 18.9. This means that anyone who has an OpenModelica version with encryption
support can encrypt or decrypt files.
• OpenModelica encryption is based on SEMLA (Standardized Encryption of Modelica Libraries and Arti-
facts) module from Modelon AB.
225
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
THIRTEEN
This chapter covers the OpenModelica electronic notebook subsystem, called OMNotebook, together with the
DrModelica tutoring system for teaching Modelica, and DrControl for teaching control together with Modelica.
Both are using such notebooks.
13.1.2 OMNotebook
The OMNotebook software [Axe05][Fernstrom06] is a new open source free software that gives an interactive
WYSIWYG realization of Literate Programming, a form of programming where programs are integrated with
documentation in the same document.
The OMNotebook facility is actually an interactive WYSIWYG realization of Literate Programming, a form of
programming where programs are integrated with documentation in the same document. OMNotebook is a simple
open-source software tool for an electronic notebook supporting Modelica.
A more advanced electronic notebook tool, also supporting mathematical typesetting and many other facilities, is
provided by Mathematica notebooks in the MathModelica environment, see Figure 13.1.
Figure 13.1: Examples of Mathematica notebooks in the MathModelica modeling and simulation environment.
227
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Traditional documents, e.g. books and reports, essentially always have a hierarchical structure. They are divided
into sections, subsections, paragraphs, etc. Both the document itself and its sections usually have headings as
labels for easier navigation. This kind of structure is also reflected in electronic notebooks. Every notebook
corresponds to one document (one file) and contains a tree structure of cells. A cell can have different kinds of
contents, and can even contain other cells. The notebook hierarchy of cells thus reflects the hierarchy of sections
and subsections in a traditional document such as a book.
Figure 13.2: The front-page notebook of the OMNotebook version of the DrModelica tutoring system.
Figure 13.3: The HelloWorld class simulated and plotted using the OMNotebook version of DrModelica.
Figure 13.4: DrModelica Chapter on Algorithms and Functions in the main page of the OMNotebook version of
DrModelica.
The front-page of DrControl resembles a linked table of content that can be used as a navigation center. The
content list contains topics like:
• Getting started
• The control problem in ordinary life
• Feedback loop
• Mathematical modeling
• Transfer function
• Stability
• Example of controlling a DC-motor
• Feedforward compensation
• State-space form
• State observation
• Closed loop control system.
• Reconstructed system
• Linear quadratic optimization
• Linearization
Each entry in this list leads to a new notebook page where either the theory is explained with Modelica examples
or an exercise with a solution is provided to illustrate the background theory. Below we show a few sections of
DrControl.
𝑚𝑦˙ = 𝑢 − 𝛼𝑦 − 𝑚𝑔 * 𝑠𝑖𝑛(𝜃)
model noFeedback
import SI = Modelica.SIunits;
SI.Velocity y; // output signal without noise,
˓→theta = 0 -> v(t) = 0
By applying a road slope angle different from zero the car velocity is influenced which can be regarded as noise in
this model. The output signal in Figure 13.8 is stable but an overshoot can be observed compared to the reference
signal. Naturally the overshoot is not desired and the student will in the next exercise learn how to get rid of this
undesired behavior of the system.
˓→= '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization. In OMEdit
Tools->Options->Simulation->Show additional information from the initialization process, in OMNotebook
call setCommandLineOptions("-d=initialization").
𝑢 = 𝐾 * (𝑟 − 𝑦)
model withFeedback
import SI = Modelica.SIunits;
SI.Velocity y; // output signal with feedback
˓→link and without noise, theta = 0 -> v(t) = 0
25
y
yNoise
20
15
10
0
0 20 40 60 80 100
By using the information about the current level of the output signal and re-tune the regulator the output quantity
can be controlled towards the reference signal smoothly and without an overshoot, as shown in Figure 13.9.
In the above simple example the flat modeling approach was adopted since it was the fastest one to quickly obtain
a working model. However, one could use the object oriented approach and encapsulate the car and regulator
models in separate classes with the Modelica connector mechanism in between.
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization. In OMEdit
Tools->Options->Simulation->Show additional information from the initialization process, in OMNotebook
call setCommandLineOptions("-d=initialization").
20
y
18 yNoise
16
14
12
10
0
0 2 4 6 8 10
𝑦¨ + 𝑎1 𝑦˙ + 𝑎2 𝑦 = 1
model NegRoots
Real y;
Real der_y;
parameter Real a1 = 3;
parameter Real a2 = 2;
equation
der_y = der(y);
der(der_y) + a1*der_y + a2*y = 1;
end NegRoots;
Choosing different values for a1 and a2 leads to different behavior as shown in Figure 13.11 and Figure 13.12.
In the first example the values of a1 and a2 are chosen in such way that the characteristic equation has negative
real roots and thereby a stable output response, see Figure 13.11.
>>> simulate(NegRoots, stopTime=10)
record SimulationResult
resultFile = "«DOCHOME»/NegRoots_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 10.0, numberOfIntervals = 500,
˓→ tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'NegRoots', options = '',
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization. In OMEdit
Tools->Options->Simulation->Show additional information from the initialization process, in OMNotebook
call setCommandLineOptions("-d=initialization").
0.5
y
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
0
0 2 4 6 8 10
The importance of the sign of the roots in the characteristic equation is illustrated in Figure 13.11 and Figure
13.12, e.g., a stable system with negative real roots and an unstable system with positive imaginary roots resulting
in oscillations.
model ImgPosRoots
Real y;
Real der_y;
parameter Real a1 = -2;
parameter Real a2 = 10;
equation
der_y = der(y);
der(der_y) + a1*der_y + a2*y = 1;
end ImgPosRoots;
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization. In OMEdit
Tools->Options->Simulation->Show additional information from the initialization process, in OMNotebook
call setCommandLineOptions("-d=initialization").
1500
y
1000
500
-500
-1000
-1500
0 2 4 6 8 10
Figure 13.12: Characteristic equation with imaginary roots with positive real part.
The theory and application of Kalman filters is also explained in the interactive course material.
In reality noise is present in almost every physical system under study and therefore the concept of noise is also
introduced in the course material, which is purely Modelica based.
13.4.1 Cells
Everything inside an OMNotebook document is made out of cells. A cell basically contains a chunk of data. That
data can be text, images, or other cells. OMNotebook has four types of cells: headercell, textcell, inputcell, and
groupcell. Cells are ordered in a tree structure, where one cell can be a parent to one or more additional cells. A
tree view is available close to the right border in the notebook window to display the relation between the cells.
• Textcell – This cell type is used to display ordinary text and images. Each textcell has a style that spec-
ifies how text is displayed. The cell´s style can be changed in the menu Format->Styles, example of
different styles are: Text, Title, and Subtitle. The Textcell type also has support for following links to
other notebook documents.
• Inputcell – This cell type has support for syntax highlighting and evaluation. It is intended to be used
for writing program code, e.g. Modelica code. Evaluation is done by pressing the key combina-
tion Shift+Return or Shift+Enter. All the text in the cell is sent to OMC (OpenModelica Com-
piler/interpreter), where the text is evaluated and the result is displayed below the inputcell. By
double-clicking on the cell marker in the tree view, the inputcell can be collapsed causing the result to
be hidden.
• Latexcell – This cell type has support for evaluation of latex scripts. It is intended to be mainly used for
writing mathematical equations and formulas for advanced documentation in OMNotebook. Each La-
texcell supports a maximum of one page document output.To evaluate this cell, latex must be installed
in your system.The users can copy and paste the latex scripts and start the evaluation.Evaluation is
done by pressing the key combination Shift+Return or Shift+Enter or the green color eval button
present in the toolbar. The script in the cell is sent to latex compiler, where it is evaluated and the
output is displayed hiding the latex source. By double-clicking on the cell marker in the tree view,the
latex source is displayed for further modification.
• Groupcell – This cell type is used to group together other cell. A groupcell can be opened or closed.
When a groupcell is opened all the cells inside the groupcell are visible, but when the groupcell is
closed only the first cell inside the groupcell is visible. The state of the groupcell is changed by the
user double-clicking on the cell marker in the tree view. When the groupcell is closed the marker is
changed and the marker has an arrow at the bottom.
13.4.2 Cursors
An OMNotebook document contains cells which in turn contain text. Thus, two kinds of cursors are needed for
positioning, text cursor and cell cursor:
• Textcursor – A cursor between characters in a cell, appearing as a small vertical line. Position the cur-
sor by clicking on the text or using the arrow buttons.
• Cellcursor – This cursor shows which cell currently has the input focus. It consists of two parts. The
main cellcursor is basically just a thin black horizontal line below the cell with input focus. The
cellcursor is positioned by clicking on a cell, clicking between cells, or using the menu item Cell-
>Next Cell or Cell->Previous Cell. The cursor can also be moved with the key combination Ctrl+Up
or Ctrl+Down. The dynamic cellcursor is a short blinking horizontal line. To make this visible, you
must click once more on the main cellcursor (the long horizontal line). NOTE: In order to paste cells
at the cellcursor, the dynamic cellcursor must be made active by clicking on the main cellcursor (the
horizontal line).
level the style should have. This is done in the stylesheet.xml file. Every style can have a <chapter-
Level> tag that specifies the chapter level. Level 0 or no tag at all, means that the style should not have
any chapter numbering.
• Scrollarea – Scrolling through a document can be done by using the mouse wheel. A document can
also be scrolled by moving the cell cursor up or down.
• Syntax highlighter – The syntax highlighter runs in a separated thread which speeds up the loading of
large document that contains many Modelica code cells. The syntax highlighter only highlights when
letters are added, not when they are removed. The color settings for the different types of keywords
are stored in the file modelicacolors.xml. Besides defining the text color and background color of
keywords, whether or not the keywords should be bold or/and italic can be defined.
• Change indicator – A star (*) will appear behind the filename in the title of notebook window if the
document has been changed and needs saving. When the user closes a document that has some un-
saved change, OMNotebook asks the user if he/she wants to save the document before closing. If the
document never has been saved before, the save-as dialog appears so that a filename can be choosen
for the new document.
• Update menus – All menus are constantly updated so that only menu items that are linked to actions
that can be performed on the currently selected cell is enabled. All other menu items will be dis-
abled. When a textcell is selected the Format menu is updated so that it indicates the text settings for
the text, in the current cursor position.
13.5 References
Eric Allen, Robert Cartwright, Brian Stoler. DrJava: A lightweight pedagogic environment for Java. In Proceed-
ings of the 33rd ACM Technical Symposium on Computer Science Education (SIGCSE 2002) (Northern Kentucky
– The Southern Side of Cincinnati, USA, February 27 – March 3, 2002).
Anders Fernström, Ingemar Axelsson, Peter Fritzson, Anders Sandholm, Adrian Pop. OMNotebook – Interactive
WYSIWYG Book Software for Teaching Programming. In Proc. of the Workshop on Developing Computer
Science Education – How Can It Be Done?. Linköping University, Dept. Computer & Inf. Science, Linköping,
Sweden, March 10, 2006.
Eva-Lena Lengquist-Sandelin, Susanna Monemar, Peter Fritzson, and Peter Bunus. DrModelica – A Web-Based
Teaching Environment for Modelica. In Proceedings of the 44th Scandinavian Conference on Simulation and
Modeling (SIMS’2003), available at www.scan-sims.org. Västerås, Sweden. September 18-19, 2003.
FOURTEEN
The following facilities for model-based optimization are provided with OpenModelica:
• Built-in Dynamic Optimization using Annotations using dynamic optimization is the recommended way
of performing dynamic optimization with OpenModelica.
• Dynamic Optimization with OpenModelica and CasADi. Use this if you want to employ the CasADi
tool for dynamic optimization.
• Classical Parameter Sweep Optimization using OMOptim. Use this if you have a static optimization
problem.
14.1.1 Foreword
Dynamic optimization using Annotations is the most user-friendly way to perform Dynamic Optimization(DO) in
OpenModelica, since it allows the OMEdit graphical user interface to be used.
It is also more powerful that the Built-in Dynamic Optimization using Optimica language extensions, since it
allows final constraints.
Where u(t) is the vector of input variables, on which DO works to try to get the desired minimum, and x(t) is the
vector of state variables.
The equations above can be implemented in OpenModelica using the full power of Modelica language, and there-
fore there is a good freedom and flexibility, under the obvious constraint that the system must be regular enough
for the convergence to take place.
However, there are limitations in the possibility operational limits can be set.
251
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The formulation of operational limits in (3) is general, since it allows to use non-boxed constrains. Consider for
instance a battery. The energy the battery can deliver is a function of the power we use to charge or discharge it.
Therefore, the actual limit should be described as:
14.1.3 Syntax
OpenModelica provides specific annotations to allow the optimization problem to be described, as an alternative
to the use of Optimica language. They are listed and commented below.
• Request for an optimization. We must use two simulation flags and a command line option. These can
conveniently be inserted into the code, to avoid selecting them manually all the time, as follows:
__OpenModelica_simulationFlags(s = "optimization", optimizerNP="1"),
__OpenModelica_commandLineOptions = "+g=Optimica",
OptimizerNP gives the number of colloction points and can be only 1 or 3. As already said the RadauIIA
order is 2*OptimizerNP-1.
The user is recommended to use as a first attempt optimizerNP=1. In case of questionable results, they can
try optimizerNP=3.
For the simulation, it is known that the stability ranges are different. At the same time, we lose stability
with higher order (see1 ).
Note that Optimica command-line option is added even if we do not use Optimica specific language con-
structs; this it is required for the use of optimization-related annotations.
• Select optimization parameters. We must specify StartTime, StopTime, Interval, and Tolerance. The first
two have the same meaning as in time simulations. Interval not only defines the output interval (as in time
simulations), but has a more specific meaning: it defines the interval between two successive collocation
points. I.e., optimization is done splitting the whole timespan in sparts having interval as length. There-
fore this value may have a huge effects on the simulation output. For typical runs, number of intervals
values from 100 to 1000-2000 could be adequate. These values are obviously set through the experiment
annotation, e.g.:
experiment(StartTime = 0, StopTime = 20, Tolerance = 1e-07, Interval = 0.02),
the default tolerance is 1e-6. The user is warned that enlarging this value may affect the output quality
adversely by large amounts (an example will be provided later). Going up to 1e-8 may be advisable in some
cases.
• Indicate the minimisation goal. We can indicate whether we must just minimise a quantity, or the integral
of a quantity (see (1)., as follows:
1 Hairer, Ernst and Wanner, Gerhard, Radau Methods, 2015, pp 1213-1216, DOI 10.1007/978-3-540-70529-1_139.
Several isMayer and isLagrange goals can be set. The actual goal will be the sum of all goals (isMayer
goals as they are, isLagrange goals first integrated between t0 and tf ).
Obviously, it is possible in Modelica to use just isMayer=true also for Lagrange terms, integrating the
Laplace integrand inside the model, but the internal numeric treatment will be different.
• Describe the system. This is done in the usual Modelica way. Here we can exploit the huge power of mod-
elica language and tools to automatically convert a system described in physical (and possibly graphical)
terms into DAE equations
• Define path constraints. As we said previously, they must be boxed and time-invariant. They are expressed
using annotations as in the following example (taken from the full example described in the next section):
Here, we see that the constraints are described through min and max values.
• Define initial constraints. These are set using the existing modelica syntax to indicate initial values
• Define final constraints. These are set using a specific annotation, as in the following example (taken from
the full example described in the next section):
annotation(isFinalConstraint = true);
Some special care must be taken when dealing with final constraints. We must be sure that OM front-end
does not do alias elimination of the constrained variable, since in that case it could pass on bounds from final
constraints to the merged variable, and these final constraints would become path constraints. To avoid this
potentially harmful alias elimination we must add to the final constrant an auxiliary parameter, as follows.
˓→energy
The auxiliary parameter can also be used for scaling the constrained variable, so that it is roughly around
one, so easing convergence. This could be done for instance as follows:
˓→storage energy
parameter Real m = 1;
parameter Real p = 1 "needed for final constraints";
Real a;
Real v(start = 0);
Real pos(start = 0);
Real pow(min = -30, max = 30) = f * v annotation(isConstraint = true);
equation
der(pos) = v;
der(v) = a;
f = m * a;
__OpenModelica_simulationFlags(s="optimization", optimizerNP="1"),
__OpenModelica_commandLineOptions="+g=Optimica");
end BangBang2021;
The constraint on power is especially worth considering. Above, we stated that path constraints are 0 ≤
𝑔(x(𝑡), u(𝑡)) here we have box limits on pow, which is indeed a function of state variables as follows:
And a and v are two state variables. So, these are two box constraints of the type 0 ≤ 𝑔 (x(𝑡), u(𝑡)) as follows:
𝑚𝑎𝑣 = 𝑚 x1 x2 ≥ −30 𝑚𝑎𝑣 = 𝑚 x1 x2 ≤ 30.
The results can be expressed in terms of force and power applied to the vehicle. They are as follows:
der(pos) = v;
der(v) = a;
The minimum is 210 g/kWh, and occurs when the ICE power is at the 76.8 % of the nominal power
The system diagram is as follows
The DO algorithm is required to determine the battery power outBatPower (positive when the battery delivers
power) so that to minimise the fuel consumption toGrams. Block toGperkWh is normalised, so that it can be used
for different engines, adapting the horizontal scale through gain, and the vertical’s through gain1.
This diagram defines the system, whose equations will be automatically determined by OpenModelica, through
model flattening. However, some code must be manually written to perform DO.
Here the code is as follows:
//
Real totalCost = toGrams.y "minimize totalCost(tf)" annotation( isMayer=true);
//
A few comments:
• The choice isMayer=true on the objective function totalCost requires its final value to be actually minimised,
not its integral (as would have been in case of the keyword isLaplace=true)
• We have two different constraints on the storage energy: the storage energy must all the time be between 0
and the maximum allowed, and at the end of the simulation must be brought back to its initial value.
• ICE can only deliver power, not absorb; so, we expect all the (regenerative) braking power and energy to be
sent into the storage
We see, as expected that the ICE is switched ON and OFF; and when it is ON it delivers at its 76.8 % of nominal
power, i.e. at 46.1 kW. The battery delivers the difference, and when the load is negative absorbs all the power
from it. The control is such that the energy at the end of the transient is the same as the one at t=0.
This result is good and confirms what we expected.
Effects of tolerance
We mentioned that reduction of tolerance may affect the result adversely by large, especially when the minimum,
as in this case is very flat (since the specific fuel consumption curve used for our example is very flat).
In the following picture we see the result of the previous section as it appears when we release tolerance by
changing it from 1e-7 to and 1e-6. Now the result is badly wrong (and the total cost has changed from to 25.6g
29.9g).
To the DO to be useful, it must obviously go beyond what is exactly expected. Therefore, we repeat the simulation
adding the simulation of some losses inside the battery. According to scientific literature, losses here are modelled
through the following formula:
2
𝑃batt (𝑡)
𝐿(𝑡) = 0.03|𝑃 batt (𝑡)| + 0.04
𝑃𝑏𝑎𝑡𝑡,𝑛𝑜𝑚
Which reflects that they in part are proportional to the absolute value of battery current, partly to its square. The
coefficients are typical for power electronic converters interfacing a battery.
Inside the code, however, the formula introduced is structurally different, since it has been transformed to avoid
the derivative discontinuity of the absolute value of a quantity around zero, using a trick like the one reported in
sect. 1.4.
We see that now the optimiser changes the Ice power when in ON state, to reduce the battery power at its peak,
since the losses formula pushes towards lower powers.
As a last case for example 2, we ass tome limitation on the power that can be exchanged by the battery. This can
be physically due to limitations of either the battery or the inverter connected to it.
To show better the effect, we first rise the ICE power to 100 kW, so that the interval of ICE operation is smaller:
into:
where
giving rise to the following results (with a much longer computation time than in the previous cases):
The upper part contains a vehicle model. The model follows a speed profile defined by the drive cycle driveCyc,
through a simple proportional controller (simulating the driver). The power is applied to a mass; the drag force
dragF sis the force against the movement due to friction (independent on speed) and air resistance (proportional
to the square of vehicle speed).
The lower part contains the management of the storage, and the optimization algorithm, already discussed in
example 2.
The results are shown in the following picture, where the obtained cost (red curve) is compared to what obtainable
in case the ICE is continuously kept ON (blue curve), at a power (blue curve) that allows the battery energy at the
end of the simulation to be equal to the one as t=0, as in the case of the optimised solution.
This example shows that the optimizer can find an ON/OFF strategy that more than halves the hybrid vehicle fuel
consumption.
The following plot shows the ICE power in comparison with total power needed to cover the given trip profile
mass.v. The rest is supplied by the battery.
14.2.1 An Example
In this section, a simple optimal control problem will be solved. When formulating the optimization problems,
models are expressed in the Modelica language and optimization specifications. The optimization language spec-
ification allows users to formulate dynamic optimization problems to be solved by a numerical algorithm. It
includes several constructs including a new specialized class optimization, a constraint section, startTime, final-
Time etc. See the optimal control problem for batch reactor model below.
Create a new file named BatchReactor.mo and save it in you working directory. Notice that this model contains
both the dynamic system to be optimized and the optimization specification.
Once we have formulated the undelying optimal control problems, we can run the optimization by using OMShell,
OMNotebook, MDT, OMEdit using command line terminals similar to the options described below:
>>> setCommandLineOptions("-g=Optimica");
optimization nmpcBatchReactor(objective=-x2)
extends BatchReactor;
end nmpcBatchReactor;
Optimizer Variables
========================================================
State[0]:x1(start = 1, nominal = 1, min = 0, max = 1, init = 1)
State[1]:x2(start = 0, nominal = 1, min = 0, max = 1, init = 0)
Input[2]:u(start = 0, nominal = 5, min = 0, max = 5)
--------------------------------------------------------
number of nonlinear constraints: 0
========================================================
******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
Ipopt is released as open source code under the Eclipse Public License (EPL).
For more information visit https://github.com/coin-or/Ipopt
******************************************************************************
3.5
u
2.5
1.5
0.5
0 0.2 0.4 0.6 0.8 1
Figure 14.1: Optimization results for Batch Reactor model – input variables.
Table 14.1: New meanings of the usual simualtion options for Ipopt.
numberOfIntervals collocation intervals
startTime, stopTime time horizon
tolerance = 1e-8 e.g. 1e-8 solver tolerance
simflags all run/debug options
1
x1
x2
0.8
0.6
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
Figure 14.2: Optimization results for Batch Reactor model – state variables.
In this section, a simple optimal control problem will be solved. When formulating the optimization problems,
models are expressed in the Modelica language and optimization specifications. The optimization language spec-
ification allows users to formulate dynamic optimization problems to be solved by a numerical algorithm. It
includes several constructs including a new specialized class optimization, a constraint section, startTime, final-
Time etc. See the optimal control problem for batch reactor model below.
Create a new file named BatchReactor.mo and save it in you working directory. Notice that this model contains
both the dynamic system to be optimized and the optimization specification.
>>> list(BatchReactor)
model BatchReactor
Real x1(start = 1, fixed = true, min = 0, max = 1);
Real x2(start = 0, fixed = true, min = 0, max = 1);
input Real u(min = 0, max = 5);
equation
der(x1) = -(u + u^2/2)*x1;
der(x2) = u*x1;
end BatchReactor;
One we have formulated the undelying optimal control problems, we can export the XML by using OMShell,
OMNotebook, MDT, OMEdit or command line terminals which are described in Section xml-import-to-casadi.
To export XML, we set the simulation target to XML:
>>> translateModelXML(BatchReactor)
"«DOCHOME»/BatchReactor.xml"
This will generate an XML file named BatchReactor.xml (Listing 14.2) that contains a symbolic representation of
the optimal control problem and can be inspected in a standard XML editor.
xmlns:equ="https://github.com/JModelica/JModelica/tree/master/XML/daeEquations.
˓→xsd"
xmlns:fun="https://github.com/JModelica/JModelica/tree/master/XML/daeFunctions.
˓→xsd"
xmlns:opt="https://github.com/JModelica/JModelica/tree/master/XML/
˓→daeOptimization.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
fmiVersion="1.0"
modelName="BatchReactor"
modelIdentifier="BatchReactor"
guid="{7fba643b-0f12-4b03-a5cd-8c325bd2eaac}"
generationDateAndTime="2023-04-24T08:18:59"
variableNamingConvention="structured"
numberOfContinuousStates="2"
numberOfEventIndicators="0"
>
<VendorAnnotations>
<Tool name="OpenModelica Compiler OMCompiler v1.21.0-v1.21.0.1+g4ef5d27bdd"> </
˓→Tool>
</VendorAnnotations>
<ModelVariables>
<ScalarVariable name="x1" valueReference="0" variability="continuous"
˓→causality="internal" alias="noAlias">
<Real />
<QualifiedName>
<exp:QualifiedNamePart name="x1"/>
</QualifiedName>
<isLinearTimedVariables>
<TimePoint index="0" isLinear="true"/>
</isLinearTimedVariables>
<VariableCategory>derivative</VariableCategory>
</ScalarVariable>
<equ:BindingEquations>
</equ:BindingEquations>
<equ:DynamicEquations>
<equ:Equation>
(continues on next page)
<equ:InitialEquations>
<equ:Equation>
<exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x1"/>
</exp:Identifier>
<exp:RealLiteral>1.0</exp:RealLiteral>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
(continues on next page)
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
<exp:Identifier>
<exp:QualifiedNamePart name="$START"/>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
</exp:Sub>
</equ:Equation>
</equ:InitialEquations>
<fun:Algorithm>
</fun:Algorithm>
<fun:RecordsList>
</fun:RecordsList>
<fun:FunctionsList>
</fun:FunctionsList>
<opt:Optimization>
<opt:TimePoints>
<opt:TimePoint >
</opt:TimePoint>
</opt:TimePoints>
<opt:PathConstraints>
</opt:PathConstraints>
</opt:Optimization>
</OpenModelicaModelDescription>
The symbolic optimal control problem representation (or just model description) contained in BatchReactor.xml
can be imported into CasADi in the form of the SymbolicOCP class via OpenModelica python script.
The SymbolicOCP class contains symbolic representation of the optimal control problem designed to be general
and allow manipulation. For a more detailed description of this class and its functionalities, we refer to the API
documentation of CasADi.
The following step compiles the model to an XML format, imports to CasADi and solves an optimization problem
in windows PowerShell:
1. Create a new file named BatchReactor.mo and save it in you working directory.
E.g. C:\OpenModelica1.9.2\share\casadi\testmodel
2. Perform compilation and generate the XML file
a. Go to your working directory
E.g. cd C:\OpenModelica1.9.2\share\casadi\testmodel
a. Go to omc path from working directory and run the following command
E.g. ..\..\..\bin\omc +s -g=Optimica --simCodeTarget=XML BatchReactor.mo
3. Run defaultStart.py python script from OpenModelica optimization directory
E.g. Python.exe ..\share\casadi\scripts defaultStart.py BatchReactor.xml
The control and state trajectories of the optimization results are shown below:
14.4.1 Constraints
If some constraints should be respected during optimization, they must be defined in the Modelica model itself.
For instance, if mechanical stress must be less than 5 N.m-2 , one should write in the model:
If during simulation, the variable mechanicalStress exceeds 5 N.m-2 , the simulation will stop and be considered
as a failure.
14.4.2 Objectives
As parameters, objectives are picked up from model variables. Objectives’ values are considered by the optimizer
at the final time.
If variables are not displayed, right click on model name in model hierarchy, and select Read variables.
Figure 14.5: Selecting read variables, set parameters, and selecting simulator.
14.4.10 Launch
You can now launch Optimization by clicking Launch button.
Results
The result tab appear when the optimization is finished. It consists of two parts: a table where variables are
displayed and a plot region.
FIFTEEN
This section describes the use of OpenModelica to compute parameter sensitivities using forward sensitivity anal-
ysis together with the Sundials/IDA solver.
15.1.1 Background
Parameter sensitivity analysis aims at analyzing the behavior of the corresponding model states w.r.t. model
parameters.
Formally, consider a Modelica model as a DAE system:
𝐹 (𝑥, 𝑥,
˙ 𝑦, 𝑝, 𝑡) = 0 𝑥(𝑡0 ) = 𝑥0 (𝑝)
𝜕𝑥
𝜕𝑝
are required which quantify, according to their mathematical definition, the impact of parameters 𝑝 on states 𝑥. In
the Sundials/IDA implementation the derivatives are used to evolve the solution over the time by:
𝜕𝑥
𝑠˙ 𝑖 =
𝜕𝑝𝑖
15.1.2 An Example
This section demonstrates the usage of the sensitivities analysis in OpenModelica on an example. This module is
enabled by the following OpenModelica compiler flag:
>>> setCommandLineOptions("--calculateSensitivities")
true
275
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Also for the simulation it is needed to set IDA as solver integration method and add a further simulation flag
-idaSensitivity to calculate the parameter sensitivities during the normal simulation.
˓→idaSensitivity'",
Now all calculated sensitivities are stored into the results mat file under the $Sensitivities block, where all currently
every top-level parameter of the Real type is used to calculate the sensitivities w.r.t. every state.
1.5
$Sensitivities.lambda1.x
1 $Sensitivities.lambda1.y
$Sensitivities.lambda2.x
$Sensitivities.lambda2.y
0.5 $Sensitivities.mu1.x
$Sensitivities.mu1.y
0 $Sensitivities.mu2.x
$Sensitivities.mu2.y
-0.5
-1
-1.5
-2
-2.5
-3
0 0.2 0.4 0.6 0.8 1
5
x
4.5 y
3.5
2.5
1.5
0.5
0
0 0.2 0.4 0.6 0.8 1
15.2.1 Installation
The core files of OMSens are provided as part of the OpenModelica installation. However, you still need to install
python and build OMSens with that python before using it. Follow the build/install instructions described on the
OMSens github page.
15.2.2 Usage
OMSens offers 3 flavors for parameter sensitivity analysis.
• Individual Sensitivity Analysis
• Used to analyze how a parameter affects a variable when perturbed on its own
• Multi-parameter Sweep
• Exploratory experimentation that sweeps the space of a set of parameters
• Vectorial Sensitivity Analysis
• Used to find the combination of parameters that maximizes/minimizes a state variable
As an example, we choose the Lotka-Volterra model that consists of a second-order nonlinear set of ordinary
differential equations. The system models the relationship between the populations of predators and preys in a
closed ecosystem.
model LotkaVolterra "This is the typical equation-oriented model"
parameter Real alpha=0.1 "Reproduction rate of prey";
parameter Real beta=0.02 "Mortality rate of predator per prey";
parameter Real gamma=0.4 "Mortality rate of predator";
parameter Real delta=0.02 "Reproduction rate of predator per prey";
parameter Real prey_pop_init=10 "Initial prey population";
parameter Real pred_pop_init=10 "Initial predator population";
Real prey_pop(start=prey_pop_init) "Prey population";
Real pred_pop(start=pred_pop_init) "Predator population";
initial equation
prey_pop = prey_pop_init;
pred_pop = pred_pop_init;
equation
15.2. Single and Multi-parameter sensitivities with OMSens 277
der(prey_pop) = prey_pop*(alpha-beta*pred_pop);
der(pred_pop) = pred_pop*(delta*prey_pop-gamma);
end LotkaVolterra;
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Select Sensitivity Optimization > Run Sensitivity Analysis and Optimization from the menu. A window like
the one below should appear. Windows users should use the default python executable that comes with
OpenModelica installation i.e., they don't need to change the proposed python executable path. If you want
to use some other python installation then make sure that all the python dependencies are installed for that
python installation.
• Choose Individual Parameter Based Sensitivity Analysis and set up the simulation settings.
• Select variables.
• Select parameters.
• Choose the perturbation percentage and direction. Run the analysis.
• After the analysis a dialog with results is shown. Open the heatmap corresponding to the relative sensitivity
index.
• The heatmap shows the effect of each parameter on each variable in the form of (parameter,variable) cells.
As we can see, pred_pop was affected by the perturbation on every parameter but prey_pop presents a
negligible sensitivity to delta (P.3). Recall that this heatmap shows the effect on the variables at time 40 for
each perturbation imposed at time 0.
Multi-parameter Sweep
Now we would like to see what happens to pred_pop when the top 3 most influencing parameters are perturbed
at the same time. Repeat the first three steps from Individual Sensitivity Analysis but this time select Multi-
parameter Sweep.
• Choose to sweep alpha, gamma and pred_pop_init in a range of ±5% from its default value and with 3
iterations (#iter) distributed equidistantly within that range. Run the sweep analysis.
• The backend is invoked and when it completes the analysis the following results dialog is shown. Open the
plot for pred_pop.
• At time 40 the parameters perturbations with a higher predator population are all blue, but it’s not clear
which one. We need something more precise.
Using the Vectorial optimization-based analysis (see below) we can request OMSens to find a combination of pa-
rameters that perturbs the most (i.e. minimize or maximize) the value of the target variable at a desired simulation
time.
For Vectorial Sensitivity Analysis repeat the first two steps from Individual Sensitivity Analysis but choose Vec-
torial Parameter Based Sensitivity Analysis.
• Choose only alpha, delta and pred_pop_init to perturb.
SIXTEEN
PDEMODELICA1
PDEModelica1 is nonstandardised experimental Modelica language extension for 1-dimensional partial differen-
tial extensions (PDE).
It is enabled using compiler flag --grammar=PDEModelica. Compiler flags may be set e.g. in OMEdit
(Tools->Options->Simulation->OMC Flags) or in the OpenModelica script using command. Note that PDE-
Modelica does now work yet with the current frontend so you need to set -d=newInst in Tools->Options-
>Simulation->OMC Flags or check "Enable old frontend for code generation".
Error:
[<interactive>:4:14-4:14:writable] Error: Missing token: SEMICOLON
The domain omega represents the geometrical domain where the PDE holds. The domain is defined using the
built-in record DomainLineSegment1D. This record contains among others L – the length of the domain, N –
the number of grid points, x – the coordinate variable and the regions left, right and interior, representing
the left and right boundaries and the interior of the domain.
The field variable u is defined using a new keyword field. The domain is a mandatory attribute to specify the
domain of the field.
The indomain operator specifies where the equation containing the field variable holds. It is utilised in the initial
conditions (IC) of the fields, in the PDE and in the boundary conditions (BC). The syntax is
If the region is omitted, interior is the default (e.g. the PDE in the example above).
The IC of the field variable u is written using an expression containing the coordinate variable omega.x.
291
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The PDE contains a partial space derivative written using the pder operator. Also the second derivative is allowed
(not in this example), the syntax is e.g. pder(u,x,x). It is not necessary to specify the domain of coordinate
in pder (to write e.g. pder(u,omega.x), even though x is a member of omega.
16.2 Limitations
BCs may be written only in terms of variables that are spatially differentiated currently.
All fields that are spatially differentiated must have either BC or extrapolation at each boundary. This extrapolation
should be done automatically by the compiler, but this has not been implemented yet. The current workaround is
the usage of the extrapolateField() operator directly in the model.
If-equations are not spported yet, if-expressions must be used instead.
SEVENTEEN
17.1 Introduction
The Modelica Development Tooling (MDT) Eclipse Plugin as part of OMDev – The OpenModelica Development
Environment integrates the OpenModelica compiler with Eclipse. MDT, together with the OpenModelica com-
piler, provides an environment for working with Modelica and MetaModelica development projects. This plugin
is primarily intended for tool developers rather than application Modelica modelers.
The following features are available:
• Browsing support for Modelica projects, packages, and classes
• Wizards for creating Modelica projects, packages, and classes
• Syntax color highlighting
• Syntax checking
• Browsing of the Modelica Standard Library or other libraries
• Code completion for class names and function argument lists
• Goto definition for classes, types, and functions
• Displaying type information when hovering the mouse over an identifier.
17.2 Installation
The installation of MDT is accomplished by following the below installation instructions. These instructions
assume that you have successfully downloaded and installed Eclipse (http://www.eclipse.org).
The latest installation instructions are available through the OpenModelica Trac.
1. Start Eclipse
2. Select Help->Software Updates->Find and Install... from the menu
3. Select ‘Search for new features to install’ and click ‘Next’
4. Select ‘New Remote Site...’
5. Enter ‘MDT’ as name and http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/MDT as URL and click
‘OK’
6. Make sure ‘MDT’ is selected and click ‘Finish’
7. In the updates dialog select the ‘MDT’ feature and click ‘Next’
8. Read through the license agreement, select ‘I accept...’ and click ‘Next’
9. Click ‘Finish’ to install MDT
293
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
294 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
296 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Figure 17.3: Eclipse Setup – disable automatic build for the projects.
298 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Figure 17.7: Eclipse – Switching to another perspective – e.g. the Java Perspective.
300 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
302 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The second variant is useful when typing a call to a function. It shows the function signature (formal param-
eter names and types) in a popup when typing the parenthesis after the function name, here the signature Real
sin(SI.Angle u) of the sin function:
Figure 17.12: Code completion at a function call when typing left parenthesis.
304 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Figure 17.14: Code assistance when writing cases with records in MetaModelica.
306 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
308 Chapter 17. MDT – The OpenModelica Development Tooling Eclipse Plugin
CHAPTER
EIGHTEEN
The algorithmic code debugger, used for the algorithmic subset of the Modelica language as well as the Meta-
Modelica language is described in Section The Eclipse-based Debugger for Algorithmic Modelica. Using this
debugger replaces debugging of algorithmic code by primitive means such as print statements or asserts which
is complex, time-consuming and error- prone. The usual debugging functionality found in debuggers for proce-
dural or traditional object-oriented languages is supported, such as setting and removing breakpoints, stepping,
inspecting variables, etc. The debugger is integrated with Eclipse.
309
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
In order to debug Modelica code we need to load the Modelica files into the OpenModelica Compiler. For this we
can write a small script file like this:
function HelloWorld
input Real r;
output Real o;
algorithm
o := 2 * r;
end HelloWorld;
>>> setCommandLineOptions({"-d=rml,noevalfunc","-g=MetaModelica"})
{true,true}
>>> setCFlags(getCFlags() + " -g")
true
>>> HelloWorld(120.0)
So lets say that we want to debug HelloWorld.mo. For that we must load it into the compiler using the script file.
Put all the Modelica files there in the script file to be loaded. We should also initiate the debugger by calling the
starting function, in the above code HelloWorld(120.0);
While the Modelica perspective is activated the user should click on the bug icon on the toolbar and select Debug
in order to access the dialog for building debug configurations.
To create the debug configuration, right click on the classification Modelica Development Tooling (MDT) GDB
and select New as in figure below. Then give a name to the configuration, select the debugging executable to
be executed and give it command line parameters. There are several tabs in which the user can select additional
debug configuration settings like the environment in which the executable should be run.
Note that we require Gnu Debugger (GDB) for debugging session. We must specify the GDB location, also we
must pass our script file as an argument to OMC.
Setting/Deleting Breakpoints
The Eclipse interface allows to add/remove breakpoints. At the moment only line number based breakpoints are
supported. Other alternative to set the breakpoints is; function breakpoints.
Figure 18.6: Eclipse will ask if the user wants to switch to the debugging perspective.
NINETEEN
A common problem when simulating models in an equation-based language like Modelica is that the model may
contain non-linear equation systems. These are solved in each time-step by extrapolating an initial guess and
running a non-linear system solver. If the simulation takes too long to simulate, it is useful to run the performance
analysis tool. The tool has around 5~25% overhead, which is very low compared to instruction-level profilers
(30x-100x overhead). Due to being based on a single simulation run, the report may contain spikes in the charts.
When running a simulation for performance analysis, execution times of user-defined functions as well as linear,
non-linear and mixed equation systems are recorded.
To start a simulation in this mode, turn on profiling with the following command line flag >>>
setCommandLineOptions("--profiling=all")
The generated report is in HTML format (with images in the SVG format), stored in a file modelname_prof.html,
but the XML database and measured times that generated the report and graphs are also available if you want to
customize the report for comparison with other tools.
Below we use the performance profiler on the simple model A:
model ProfilingTest
function f
input Real r;
output Real o = sin(r);
end f;
String s = "abc";
Real x = f(x) "This is x";
Real y(start=1);
Real z1 = cos(z2);
Real z2 = sin(z1);
equation
der(y) = time;
end ProfilingTest;
>>> setCommandLineOptions("--profiling=blocks+html")
true
>>> simulate(ProfilingTest)
record SimulationResult
resultFile = "«DOCHOME»/ProfilingTest_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'ProfilingTest', options =
317
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
˓→details)
",
timeFrontend = 0.003121333,
timeBackend = 0.019096841,
timeSimCode = 0.002281388,
timeTemplates = 0.004429015000000001,
timeCompile = 0.6928681130000001,
timeSimulation = 0.061217587,
timeTotal = 0.783162377
end SimulationResult;
"Warning: There are nonlinear iteration variables with default zero start
˓→attribute found in NLSJac0. For more information set -d=initialization. In
˓→d=initialization\").
Warning: The initial conditions are not fully specified. For more information set -
˓→d=initialization. In OMEdit Tools->Options->Simulation->Show additional
˓→setCommandLineOptions(\"-d=initialization\").
"
19.1.1 Information
All times are measured using a real-time wall clock. This means context switching produces bad worst-case
execution times (max times) for blocks. If you want better results, use a CPU-time clock or run the command
using real-time priviliges (avoiding context switches).
Note that for blocks where the individual execution time is close to the accuracy of the real-time clock, the
maximum measured time may deviate a lot from the average.
For more details, see ProfilingTest_prof.xml.
19.1.2 Settings
Name Value
Integration method dassl
Output format mat
Output name ProfilingTest_res.mat
Output size 24.0 kB
Profiling data ProfilingTest_prof.data
Profiling size 0B
19.1.3 Summary
Equations
Name Variables
eq0
eq1 y
eq2 s
eq3 z1
eq4
eq5 ` <#var0>`__
eq6 ` <#var0>`__
eq7 ` <#var0>`__
eq8 ` <#var0>`__
eq9 z2
eq10
eq11 x
eq12
eq13 z2
eq14
eq15 ` <#var0>`__
eq16 ` <#var0>`__
eq17 ` <#var0>`__
eq18 ` <#var0>`__
eq19 z1
eq20
eq21 x
eq22 der(y)
eq23
Variables
Name Comment
y
der(y)
x This is x
z1
z2
s
When profiling the DoublePendulum example from MSL, the following output in Figure 19.2 is a typical result.
This information clearly shows which system takes longest to simulate (a linear system, where most of the time
overhead probably comes from initializing LAPACK over and over).
Figure 19.2: Profiling results of the Modelica standard library DoublePendulum example, sorted by execution
time.
TWENTY
OpenModelica can simulate in a web browser on a client computer by model code being compiled to efficient
Javacript code.
For more information, see https://github.com/tshort/openmodelica-javascript
Below used on the MSL MultiBody RobotR3.fullRobot example model.
323
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
TWENTYONE
Below is information and examples about the OpenModelica external C interfaces, as well as examples of Python
interoperability.
model ExternalLibraries
function ExternalFunc1
input Real x;
output Real y;
external y=ExternalFunc1_ext(x) annotation(Library="ExternalFunc1.o",
˓→LibraryDirectory="modelica://ExternalLibraries", Include="#include \
˓→"ExternalFunc1.h\"");
end ExternalFunc1;
function ExternalFunc2
input Real x;
output Real y;
external "C" annotation(Library="ExternalFunc2", LibraryDirectory="modelica://
˓→ExternalLibraries");
end ExternalFunc2;
These C (.c) files and header files (.h) are needed (note that the headers are not needed since OpenModelica will
generate the correct definition if it is not present; using the headers it is possible to write C-code directly in the
Modelica source code or declare non-standard calling conventions):
325
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The following script file ExternalLibraries.mos will perform everything that is needed, provided you have gcc
installed in your path:
>>> system(getCompiler() + " -c -o ExternalFunc1.o ExternalFunc1.c")
0
>>> system(getCompiler() + " -c -o ExternalFunc2.o ExternalFunc2.c")
0
>>> system("ar rcs libExternalFunc2.a ExternalFunc2.o")
0
>>> simulate(ExternalLibraries)
record SimulationResult
resultFile = "«DOCHOME»/ExternalLibraries_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'ExternalLibraries',
˓→= ''",
2
x
1.8 y
1.6
1.4
1.2
0.8
0.6
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
function pyRunString
input String s;
external "C" annotation(Include="
#include <Python.h>
model CallExternalPython
algorithm
pyRunString("
print 'Python says: simulation time',"+String(time)+"
");
end CallExternalPython;
˓→= ''",
In the following Python (.py) files the above Modelica model is simulated via the OpenModelica scripting inter-
face:
mos_file.write('simulate(CalledbyPython,stopTime=10);\n')
mos_file.close()
A second option of simulating the above Modelica model is to use the command buildModel instead of the simulate
command and setting the parameter value in the initial parameter file, CalledbyPython_init.txt instead of using the
command setComponentModifierValue. Then the file CalledbyPython.exe is just executed.
The third option is to use the Corba interface for invoking the compiler and then just use the scripting interface to
send commands to the compiler via this interface.
The fourth variant is to use external function calls to directly communicate with the executing simulation process.
TWENTYTWO
331
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
>>> omc.sendExpression("getVersion()")
OMCompiler v1.21.0-v1.21.0.1+g4ef5d27bdd
>>> omc.sendExpression("cd()")
«DOCHOME»
>>> omc.sendExpression("loadModel(Modelica)")
True
>>> omc.sendExpression("loadFile(getInstallationDirectoryPath() + \"/share/doc/omc/
˓→testmodels/BouncingBall.mo\")")
True
>>> omc.sendExpression("instantiateModel(BouncingBall)")
class BouncingBall
parameter Real e = 0.7 "coefficient of restitution";
parameter Real g = 9.81 "gravity acceleration";
Real h(start = 1.0, fixed = true) "height of ball";
Real v(fixed = true) "velocity of ball";
Boolean flying(start = true, fixed = true) "true, if ball is flying";
Boolean impact;
Real v_new(fixed = true);
Integer foo;
equation
impact = h <= 0.0;
foo = if impact then 1 else 2;
der(v) = if flying then -g else 0.0;
der(h) = v;
when {h <= 0.0 and v <= 0.0, impact} then
v_new = if edge(impact) then -e * pre(v) else 0.0;
flying = v_new > 0.0;
reinit(v, v_new);
end when;
end BouncingBall;
˓→False, False, '', '', False, '', '', '', '', '')
>>> omc.sendExpression("getConnectionCount(BouncingBall)")
0
>>> omc.sendExpression("getInheritanceCount(BouncingBall)")
0
>>> omc.sendExpression("getComponentModifierValue(BouncingBall,e)")
0.7
>>> omc.sendExpression("checkSettings()")
{'OPENMODELICAHOME': '«OPENMODELICAHOME»', 'OPENMODELICALIBRARY':
˓→'«OPENMODELICAHOME»/lib/omlibrary', 'OMC_PATH': '«OPENMODELICAHOME»/bin/omc',
˓→'SYSTEM_PATH': '/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/doc/
˓→UsersGuide/../..//build//bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/
˓→Ubuntu SMP Fri Jan 20 14:29:49 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux\n',
˓→ombuilddir=/var/lib/jenkins1/ws/OpenModelica_maintenance_v1.21/build' '--cache-
˓→file=/dev/null' '--srcdir=.'"}
The common combination of a simulation followed by getting a value and doing a plot:
Import As Library
To use the module from within another python program, simply import OMCSessionZMQ from within the using
program.
For example:
# test.py
from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
cmds = [
'loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/
˓→BouncingBall.mo")',
"simulate(BouncingBall)",
(continues on next page)
22.1.3 Implementation
Client Implementation
The OpenModelica Python API Interface – OMPython, attempts to mimic the OMShell's style of operations.
OMPython is designed to,
• Initialize the CORBA/ZeroMQ communication.
• Send commands to the OMC server via the CORBA/ZeroMQ interface.
• Receive the string results.
• Use the Parser module to format the results.
• Return or display the results.
The object constructor requires a minimum of 2 input arguments which are strings, and may need a third string
input argument.
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory of Python, then the file path must also
be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument (optional) is used to specify the list of dependent libraries or dependent Modelica
files e.g.,
• The fourth input argument (optional), is a keyword argument which is used to set the command line options
e.g.,
• By default ModelicaSystem uses OMCSessionZMQ but if you want to use OMCSession then pass the
argument useCorba=True to the constructor.
22.2.1 BuildModel
The buildModel API can be used after ModelicaSystem(), in case the model needs to be updated or additional
simulationflags needs to be set using sendExpression()
>>> mod.buildModel()
(-1.825929609047952, 0.65907039052943617)
>>> mod.getInputs()
{}
>>> mod.getOutputs()
{}
>>> mod.getSolutions(["time","height"],resultfile="c:/tmpbouncingBall.mat") //
˓→return list of array
22.2.6 Simulation
An example of how to get parameter names and change the value of parameters using set methods and finally
simulate the "BouncingBall.mo" model is given below.
>>> mod.getParameters()
{'c': 0.9, 'radius': 0.1}
To check whether new values are updated to model , we can again query the getParameters().
>>> mod.getParameters()
{'c': 0.5, 'radius': 14}
The model can be simulated using the simulate API in the following ways,
1. without any arguments
2. resultfile (keyword argument) - (only filename is allowed and not the location)
3. simflags (keyword argument) - runtime simulationflags supported by OpenModelica
22.2.7 Linearization
The following methods are proposed for linearization.
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> mod.setLinearizationOptions(["stopTime=2.0","tolerance=1e-06"])
22.3 PySimulator
PySimulator provides a graphical user interface for performing analyses and simulating different model types
(currently Functional Mockup Units and Modelica Models are supported), plotting result variables and applying
simulation result analysis tools like Fast Fourier Transform.
Read more about the PySimulator at https://github.com/PySimulator/PySimulator.
TWENTYTHREE
OMMatlab – the OpenModelica Matlab API is a free, open source, highly portable Matlab-based interactive
session handler for Modelica scripting. It provides the modeler with components for creating a complete Modelica
modeling, compilation and simulation environment based on the latest OpenModelica library standard available.
OMMatlab is architectured to combine both the solving strategy and model building. So domain experts (people
writing the models) and computational engineers (people writing the solver code) can work on one unified tool
that is industrially viable for optimization of Modelica models, while offering a flexible platform for algorithm
development and research. OMMatlab is not a standalone package, it depends upon the OpenModelica installation.
OMMatlab is implemented in Matlab and depends on ZeroMQ - high performance asynchronous messaging li-
brary and it supports the Modelica Standard Library version 3.2 that is included in starting with OpenModelica
1.9.2.
To install OMMatlab follow the instructions at https://github.com/OpenModelica/OMMatlab
339
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The object constructor requires a minimum of 2 input arguments which are strings, and third input argument which
is optional .
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory, then the file path must also be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument (optional) is used to specify the list of dependent libraries or dependent Modelica
files The argument can be passed as a string or array of strings e.g.,
>>> omc.ModelicaSystem("BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"])
• The fourth input argument (optional), which is used to set the command line options e.g.,
>>> ModelicaSystem(mod,"BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"],"-d=newInst")
Matlab does not support keyword arguments, and hence inorder to skip an argument, empty list should be used
"[]" e.g.,
>>> ModelicaSystem(mod,"BouncingBall.mo","BouncingBall",[],"-d=newInst")
23.3 WorkDirectory
For each Matlab session a temporary work directory is created and the results are published in that working
directory, Inorder to get the workdirectory the users can use the following API
>>> omc.getWorkDirectory()
'C:/Users/arupa54/AppData/Local/Temp/tp7dd648e5_5de6_4f66_b3d6_90bce1fe1d58'
23.4 BuildModel
The buildModel API can be used after ModelicaSystem(), in case the model needs to be updated or additional
simulationflags needs to be set using sendExpression()
>>> buildModel(mod)
+----------+------------+-------------------------+--------------+------------+----
˓→-------+---------------+-------+
>>> omc.getInputs()
struct with no fields
>>> omc.getOutputs()
struct with no fields
>>> omc.setSimulationOptions(["stopTime=2.0","tolerance=1e-08"])
>>> omc.getParameters()
struct with fields:
e: '0.7'
g: '9.810000000000001'
>>> omc.setParameters(["e=0.9","g=9.83"])
To check whether new values are updated to model , we can again query the getParameters().
>>> omc.getParameters()
struct with fields:
e: "0.9"
g: "9.83"
Similary we can also use setInputs() to set a value for the inputs during various time interval can also be done
using the following.
>>> omc.setInputs("cAi=1")
The model can be simulated using the simulate API in the following ways,
1. without any arguments
2. resultfile names provided by user (only filename is allowed and not the location)
3. simflags - runtime simulationflags supported by OpenModelica
23.10 Linearization
The following methods are available for linearization of a modelica model
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> omc.setLinearizationOptions(["stopTime=2.0","tolerance=1e-08"])
TWENTYFOUR
OMJulia – the OpenModelica Julia API is a free, open source, highly portable Julia based interactive session han-
dler for Julia scripting of OpenModelica API functionality. It provides the modeler with components for creating
a complete Julia-Modelica modeling, compilation and simulation environment based on the latest OpenModelica
implementation and Modelica library standard available. OMJulia is architectured to combine both the solving
strategy and model building. Thus, domain experts (people writing the models) and computational engineers (peo-
ple writing the solver code) can work on one unified tool that is industrially viable for optimization of Modelica
models, while offering a flexible platform for algorithm development and research. OMJulia is not a standalone
package, it depends upon the OpenModelica installation.
OMJulia is implemented in Julia and depends on ZeroMQ - high performance asynchronous messaging library
and it supports the Modelica Standard Library version 3.2 that is included in starting with OpenModelica 1.9.2.
To install OMJulia follow the instructions at https://github.com/OpenModelica/OMJulia.jl
347
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
The object constructor requires a minimum of 2 input arguments which are strings, and third input argument which
is optional .
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory, then the file path must also be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument (optional) is used to specify the list of dependent libraries or dependent Modelica
files The argument can be passed as a string or array of strings e.g.,
>>> ModelicaSystem(mod,"BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"])
• The fourth input argument (optional), is a keyword argument which is used to set the command line options
e.g.,
>>> ModelicaSystem(mod,"BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"],commandLineOptions="-d=newInst")
24.3 WorkDirectory
For each OMJulia session a temporary work directory is created and the results are published in that working
directory, Inorder to get the workdirectory the users can use the following API
>>> getWorkDirectory(mod)
"C:/Users/arupa54/AppData/Local/Temp/jl_5pbewl"
24.4 BuildModel
The buildModel API can be used after ModelicaSystem(), in case the model needs to be updated or additional
simulationflags needs to be set using sendExpression()
>>> buildModel(mod)
["-1.825929609047952", "0.65907039052943617"]
>>> getInputs(mod)
{}
>>> getOutputs(mod)
{}
>>> setSimulationOptions(mod,["stopTime=2.0","tolerance=1e-08"])
>>> setParameters(mod,["radius=14","c=0.5"])
To check whether new values are updated to model , we can again query the getParameters().
>>> getParameters(mod)
{"c": "0.5", "radius": "14"}
Similary we can also use setInputs() to set a value for the inputs during various time interval can also be done
using the following.
>>> setInputs(mod,"cAi=1")
The model can be simulated using the simulate API in the following ways,
1. without any arguments
2. resultfile (keyword argument) - (only filename is allowed and not the location)
3. simflags (keyword argument) - runtime simulationflags supported by OpenModelica
>>> simulate(mod) // method-1 default result file name will be used
>>> simulate(mod,resultfile="tmpbouncingBall.mat") // method-2 resultfile name
˓→provided by users
24.10 Linearization
The following methods are available for linearization of a modelica model
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> setLinearizationOptions(mod,["stopTime=2.0","tolerance=1e-06"])
24.13 Usage
With the above list of API calls implemented, the users can have more control over the result types, returned as
Julia data structures.
TWENTYFIVE
JUPYTER-OPENMODELICA
An OpenModelica Kernel for Jupyter Notebook. All commands are interpreted by OMPython which communi-
cates with OpenModelica Compiler and the results are presented to user.
The project is available at https://github.com/OpenModelica/jupyter-openmodelica.
Follow the Readme file to install and start running modelica models directly in Jupyter Notebook
355
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
TWENTYSIX
SCRIPTING API
The following are short summaries of OpenModelica scripting commands. These commands are useful for loading
and saving classes, reading and storing data, plotting of results, and various other tasks.
The arguments passed to a scripting function should follow syntactic and typing rules for Modelica and for the
scripting function in question. In the following tables we briefly indicate the types or character of the formal
parameters to the functions by the following notation:
• String typed argument, e.g. "hello", "myfile.mo".
• TypeName – class, package or function name, e.g. MyClass, Modelica.Math.
• VariableName – variable name, e.g. v1, v2, vars1[2].x, etc.
• Integer or Real typed argument, e.g. 35, 3.14, xintvariable.
• options – optional parameters with named formal parameter passing.
26.1.1 interactiveDumpAbsynToJL
function interactiveDumpAbsynToJL
output String res;
end interactiveDumpAbsynToJL;
26.1.2 relocateFunctions
function relocateFunctions
input String fileName;
input String names[:, 2];
output Boolean success;
end relocateFunctions;
357
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
26.1.3 toJulia
function toJulia
output String res;
end toJulia;
26.1.4 GC_expand_hp
function GC_expand_hp
input Integer size;
output Boolean success;
end GC_expand_hp;
26.1.5 GC_gcollect_and_unmap
26.1.6 GC_get_prof_stats
function GC_get_prof_stats
output GC_PROFSTATS gcStats;
end GC_get_prof_stats;
26.1.7 GC_set_max_heap_size
function GC_set_max_heap_size
input Integer size;
output Boolean success;
end GC_set_max_heap_size;
26.1.8 addClassAnnotation
function addClassAnnotation
input TypeName class_;
input ExpressionOrModification annotate;
output Boolean bool;
end addClassAnnotation;
26.1.9 addInitialState
function addInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end addInitialState;
26.1.10 addTransition
function addTransition
input TypeName cl;
input String from;
input String to;
input String condition;
input Boolean immediate = true;
input Boolean reset = true;
input Boolean synchronize = false;
input Integer priority = 1;
input ExpressionOrModification annotate;
output Boolean bool;
end addTransition;
26.1.11 alarm
26.1.12 appendEnvironmentVar
function appendEnvironmentVar
input String var;
input String value;
output String result "returns \"error\" if the variable could not be appended";
end appendEnvironmentVar;
26.1.13 basename
function basename
input String path;
output String basename;
end basename;
26.1.14 buildEncryptedPackage
function buildEncryptedPackage
input TypeName className "the class that should encrypted";
input Boolean encrypt = true;
output Boolean success;
end buildEncryptedPackage;
26.1.15 buildLabel
function buildLabel
input TypeName className "the class that should be built";
input Real startTime = 0.0 "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String method = "dassl" "integration method used for simulation. <default>
˓→= dassl";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.16 buildModel
function buildModel
input TypeName className "the class that should be built";
input Real startTime = "<default>" "the start time of the simulation. <default>
˓→= 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.17 buildModelFMU
function buildModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 1.0 or 2.0.";
input String fmuType = "me" "FMU type, me (model exchange), cs (co-simulation),
˓→me_cs (both model exchange and co-simulation)";
˓→"=current platform, statically link everything. Else, use a host triple, e.g. \
(continues on next page)
˓→"x86_64-linux-gnu\" or \"x86_64-w64-mingw32\"";
output String generatedFileName "Returns the full path of the generated FMU.";
end buildModelFMU;
26.1.18 cd
function cd
input String newWorkingDirectory = "";
output String workingDirectory;
end cd;
26.1.19 checkAllModelsRecursive
function checkAllModelsRecursive
input TypeName className;
input Boolean checkProtected = false "Checks also protected classes if true";
output String result;
end checkAllModelsRecursive;
26.1.20 checkCodeGraph
function checkCodeGraph
input String graphfile;
input String codefile;
output String[:] result;
end checkCodeGraph;
26.1.21 checkInterfaceOfPackages
function checkInterfaceOfPackages
input TypeName cl;
input String dependencyMatrix[:, :];
output Boolean success;
end checkInterfaceOfPackages;
26.1.22 checkModel
function checkModel
input TypeName className;
output String result;
end checkModel;
26.1.23 checkSettings
function checkSettings
output CheckSettingsResult result;
end checkSettings;
26.1.24 checkTaskGraph
function checkTaskGraph
input String filename;
input String reffilename;
output String[:] result;
end checkTaskGraph;
26.1.25 classAnnotationExists
function classAnnotationExists
input TypeName className;
input TypeName annotationName;
output Boolean exists;
end classAnnotationExists;
26.1.26 clear
function clear
output Boolean success;
end clear;
26.1.27 clearCommandLineOptions
function clearCommandLineOptions
output Boolean success;
end clearCommandLineOptions;
26.1.28 clearDebugFlags
function clearDebugFlags
output Boolean success;
end clearDebugFlags;
26.1.29 clearMessages
function clearMessages
output Boolean success;
end clearMessages;
26.1.30 clearProgram
function clearProgram
output Boolean success;
end clearProgram;
26.1.31 clearVariables
function clearVariables
output Boolean success;
end clearVariables;
26.1.32 closeSimulationResultFile
function closeSimulationResultFile
output Boolean success;
end closeSimulationResultFile;
26.1.33 codeToString
function codeToString
input $Code className;
output String string;
end codeToString;
26.1.34 compareFiles
26.1.35 compareFilesAndMove
26.1.36 compareSimulationResults
function compareSimulationResults
input String filename;
input String reffilename;
input String logfilename;
input Real relTol = 0.01;
input Real absTol = 0.0001;
input String[:] vars = fill("", 0);
output String[:] result;
end compareSimulationResults;
26.1.37 convertPackageToLibrary
function convertPackageToLibrary
input TypeName packageToConvert;
input TypeName library;
input String libraryVersion;
output Boolean success;
end convertPackageToLibrary;
26.1.38 convertUnits
function convertUnits
input String s1;
input String s2;
output Boolean unitsCompatible;
output Real scaleFactor;
output Real offset;
end convertUnits;
26.1.39 copy
function copy
input String source;
input String destination;
output Boolean success;
end copy;
26.1.40 copyClass
function copyClass
input TypeName className "the class that should be copied";
input String newClassName "the name for new class";
input TypeName withIn = $Code(TopLevel) "the with in path for new class";
output Boolean result;
end copyClass;
26.1.41 countMessages
function countMessages
output Integer numMessages;
output Integer numErrors;
output Integer numWarnings;
end countMessages;
26.1.42 deleteFile
function deleteFile
input String fileName;
output Boolean success;
end deleteFile;
26.1.43 deleteInitialState
function deleteInitialState
input TypeName cl;
input String state;
output Boolean bool;
end deleteInitialState;
26.1.44 deleteTransition
function deleteTransition
input TypeName cl;
input String from;
input String to;
input String condition;
input Boolean immediate;
input Boolean reset;
input Boolean synchronize;
input Integer priority;
output Boolean bool;
end deleteTransition;
26.1.45 deltaSimulationResults
function deltaSimulationResults
input String filename;
input String reffilename;
input String method "method to compute then error. choose 1norm, 2norm, maxerr";
input String[:] vars = fill("", 0);
output Real result;
end deltaSimulationResults;
26.1.46 diffModelicaFileListings
function diffModelicaFileListings
input String before, after;
input DiffFormat diffFormat = DiffFormat.color;
input Boolean failOnSemanticsChange = false "Defaults to returning after instead
˓→of hard fail";
26.1.47 diffSimulationResults
function diffSimulationResults
input String actualFile;
input String expectedFile;
input String diffPrefix;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between
˓→the maximum and minimum of the signal";
26.1.48 diffSimulationResultsHtml
function diffSimulationResultsHtml
input String var;
input String actualFile;
input String expectedFile;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between
˓→the maximum and minimum of the signal";
26.1.49 directoryExists
function directoryExists
input String dirName;
output Boolean exists;
end directoryExists;
26.1.50 dirname
function dirname
input String path;
output String dirname;
end dirname;
26.1.51 disableNewInstantiation
function disableNewInstantiation
output Boolean success;
end disableNewInstantiation;
26.1.52 dumpXMLDAE
function dumpXMLDAE
input TypeName className;
input String translationLevel = "flat" "flat, optimiser, backEnd, or stateSpace";
input Boolean addOriginalAdjacencyMatrix = false;
input Boolean addSolvingInfo = false;
input Boolean addMathMLCode = false;
input Boolean dumpResiduals = false;
input String fileNamePrefix = "<default>" "this is the className in string form
˓→by default";
input String rewriteRulesFile = "" "the file from where the rewiteRules are read,
˓→ default is empty which means no rewrite rules";
26.1.53 echo
function echo
input Boolean setEcho;
output Boolean newEcho;
end echo;
26.1.54 enableNewInstantiation
function enableNewInstantiation
output Boolean success;
end enableNewInstantiation;
26.1.55 escapeXML
function escapeXML
input String inStr;
output String outStr;
end escapeXML;
26.1.56 exit
function exit
input Integer status;
end exit;
26.1.57 exportToFigaro
function exportToFigaro
input TypeName path;
input String directory = cd();
input String database;
input String mode;
input String options;
input String processor;
output Boolean success;
end exportToFigaro;
26.1.58 extendsFrom
function extendsFrom
input TypeName className;
input TypeName baseClassName;
output Boolean res;
end extendsFrom;
26.1.59 filterSimulationResults
function filterSimulationResults
input String inFile;
input String outFile;
input String[:] vars;
input Integer numberOfIntervals = 0 "0=Do not resample";
input Boolean removeDescription = false;
input Boolean hintReadAllVars = true;
output Boolean success;
end filterSimulationResults;
26.1.60 generateCode
function generateCode
input TypeName className;
output Boolean success;
end generateCode;
26.1.61 generateEntryPoint
function generateEntryPoint
input String fileName;
input TypeName entryPoint;
input String url = "https://trac.openmodelica.org/OpenModelica/newticket";
end generateEntryPoint;
26.1.62 generateHeader
function generateHeader
input String fileName;
output Boolean success;
end generateHeader;
26.1.63 generateJuliaHeader
function generateJuliaHeader
input String fileName;
output Boolean success;
end generateJuliaHeader;
26.1.64 generateScriptingAPI
function generateScriptingAPI
input TypeName cl;
input String name;
output Boolean success;
output String moFile;
output String qtFile;
output String qtHeader;
end generateScriptingAPI;
26.1.65 generateSeparateCode
function generateSeparateCode
input TypeName className;
input Boolean cleanCache = false "If true, the cache is reset between each
˓→generated package. This conserves memory at the cost of speed.";
26.1.66 generateSeparateCodeDependencies
function generateSeparateCodeDependencies
input String stampSuffix = ".c" "Suffix to add to dependencies (often .c.stamp)";
output String[:] dependencies;
end generateSeparateCodeDependencies;
26.1.67 generateSeparateCodeDependenciesMakefile
function generateSeparateCodeDependenciesMakefile
input String filename "The file to write the makefile to";
input String directory = "" "The relative path of the generated files";
input String suffix = ".c" "Often .stamp since we do not update all the files";
output Boolean success;
end generateSeparateCodeDependenciesMakefile;
26.1.68 generateVerificationScenarios
function generateVerificationScenarios
input TypeName path;
output Boolean success;
end generateVerificationScenarios;
26.1.69 getAlgorithmCount
function getAlgorithmCount
input TypeName class_;
output Integer count;
end getAlgorithmCount;
26.1.70 getAlgorithmItemsCount
function getAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getAlgorithmItemsCount;
26.1.71 getAllSubtypeOf
function getAllSubtypeOf
input TypeName className;
input TypeName parentClass = $Code(AllLoadedClasses);
input Boolean qualified = false;
input Boolean includePartial = false;
input Boolean sort = false;
output TypeName classNames[:];
end getAllSubtypeOf;
26.1.72 getAnnotationCount
function getAnnotationCount
input TypeName class_;
output Integer count;
end getAnnotationCount;
26.1.73 getAnnotationModifierValue
function getAnnotationModifierValue
input TypeName name;
input String vendorannotation;
input String modifiername;
output String modifiernamevalue;
end getAnnotationModifierValue;
26.1.74 getAnnotationNamedModifiers
function getAnnotationNamedModifiers
input TypeName name;
input String vendorannotation;
output String[:] modifiernamelist;
end getAnnotationNamedModifiers;
26.1.75 getAnnotationVersion
function getAnnotationVersion
output String annotationVersion;
end getAnnotationVersion;
26.1.76 getAstAsCorbaString
function getAstAsCorbaString
input String fileName = "<interactive>";
output String result "returns the string if fileName is interactive; else it
˓→returns ok or error depending on if writing the file succeeded";
end getAstAsCorbaString;
26.1.77 getAvailableIndexReductionMethods
function getAvailableIndexReductionMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableIndexReductionMethods;
26.1.78 getAvailableLibraries
function getAvailableLibraries
output String[:] libraries;
end getAvailableLibraries;
26.1.79 getAvailableLibraryVersions
function getAvailableLibraryVersions
input TypeName libraryName;
output String[:] librariesAndVersions;
end getAvailableLibraryVersions;
26.1.80 getAvailableMatchingAlgorithms
function getAvailableMatchingAlgorithms
output String[:] allChoices;
output String[:] allComments;
end getAvailableMatchingAlgorithms;
26.1.81 getAvailablePackageConversionsFrom
function getAvailablePackageConversionsFrom
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsFrom;
26.1.82 getAvailablePackageConversionsTo
function getAvailablePackageConversionsTo
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsTo;
26.1.83 getAvailablePackageVersions
function getAvailablePackageVersions
input TypeName pkg;
input String version;
output String[:] withoutConversion;
end getAvailablePackageVersions;
26.1.84 getAvailableTearingMethods
function getAvailableTearingMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableTearingMethods;
26.1.85 getBooleanClassAnnotation
function getBooleanClassAnnotation
input TypeName className;
input TypeName annotationName;
output Boolean value;
end getBooleanClassAnnotation;
26.1.86 getBuiltinType
function getBuiltinType
input TypeName cl;
output String name;
end getBuiltinType;
26.1.87 getCFlags
function getCFlags
output String outString;
end getCFlags;
26.1.88 getCXXCompiler
function getCXXCompiler
output String compiler;
end getCXXCompiler;
26.1.89 getClassComment
function getClassComment
input TypeName cl;
output String comment;
end getClassComment;
26.1.90 getClassInformation
function getClassInformation
input TypeName cl;
output String restriction, comment;
output Boolean partialPrefix, finalPrefix, encapsulatedPrefix;
output String fileName;
output Boolean fileReadOnly;
output Integer lineNumberStart, columnNumberStart, lineNumberEnd,
˓→columnNumberEnd;
26.1.91 getClassNames
function getClassNames
input TypeName class_ = $Code(AllLoadedClasses);
input Boolean recursive = false;
input Boolean qualified = false;
input Boolean sort = false;
input Boolean builtin = false "List also builtin classes if true";
input Boolean showProtected = false "List also protected classes if true";
input Boolean includeConstants = false "List also constants in the class if true
˓→";
26.1.92 getClassRestriction
function getClassRestriction
input TypeName cl;
output String restriction;
end getClassRestriction;
26.1.93 getClassesInModelicaPath
function getClassesInModelicaPath
output String classesInModelicaPath;
end getClassesInModelicaPath;
26.1.94 getCommandLineOptions
function getCommandLineOptions
output String[:] flags;
end getCommandLineOptions;
26.1.95 getCompileCommand
function getCompileCommand
output String compileCommand;
end getCompileCommand;
26.1.96 getCompiler
function getCompiler
output String compiler;
end getCompiler;
26.1.97 getComponentModifierNames
function getComponentModifierNames
input TypeName class_;
input String componentName;
output String[:] modifiers;
end getComponentModifierNames;
26.1.98 getComponentModifierValue
function getComponentModifierValue
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValue;
26.1.99 getComponentModifierValues
function getComponentModifierValues
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValues;
26.1.100 getComponentsTest
function getComponentsTest
input TypeName name;
output Component[:] components;
record Component
String className "the type of the component";
String name "the name of the component";
String comment "the comment of the component";
Boolean isProtected "true if component is protected";
Boolean isFinal "true if component is final";
Boolean isFlow "true if component is flow";
Boolean isStream "true if component is stream";
Boolean isReplaceable "true if component is replaceable";
String variability "'constant', 'parameter', 'discrete', ''";
String innerOuter "'inner', 'outer', ''";
String inputOutput "'input', 'output', ''";
String dimensions[:] "array with the dimensions of the component";
end Component;
end getComponentsTest;
26.1.101 getConfigFlagValidOptions
function getConfigFlagValidOptions
input String flag;
output String validOptions[:];
output String mainDescription;
output String descriptions[:];
end getConfigFlagValidOptions;
26.1.102 getConnectionCount
function getConnectionCount
input TypeName className;
output Integer count;
end getConnectionCount;
26.1.103 getConnectionList
function getConnectionList
input TypeName className;
output String[:, :] result;
end getConnectionList;
26.1.104 getConversionsFromVersions
function getConversionsFromVersions
input TypeName pack;
output String[:] withoutConversion;
output String[:] withConversion;
end getConversionsFromVersions;
26.1.105 getDefaultOpenCLDevice
function getDefaultOpenCLDevice
output Integer defdevid;
end getDefaultOpenCLDevice;
26.1.106 getDerivedClassModifierNames
function getDerivedClassModifierNames
input TypeName className;
output String[:] modifierNames;
end getDerivedClassModifierNames;
26.1.107 getDerivedClassModifierValue
function getDerivedClassModifierValue
input TypeName className;
input TypeName modifierName;
output String modifierValue;
end getDerivedClassModifierValue;
26.1.108 getDerivedUnits
function getDerivedUnits
input String baseUnit;
output String[:] derivedUnits;
end getDerivedUnits;
26.1.109 getDocumentationAnnotation
function getDocumentationAnnotation
input TypeName cl;
output String out[3] "{info,revision,infoHeader} TODO: Should be changed to have
˓→2 outputs instead of an array of 2 Strings...";
end getDocumentationAnnotation;
26.1.110 getElementModifierNames
function getElementModifierNames
input TypeName className;
input String elementName;
output String[:] modifiers;
end getElementModifierNames;
26.1.111 getElementModifierValue
function getElementModifierValue
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValue;
26.1.112 getElementModifierValues
function getElementModifierValues
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValues;
26.1.113 getEnvironmentVar
function getEnvironmentVar
input String var;
output String value "returns empty string on failure";
end getEnvironmentVar;
26.1.114 getEquationCount
function getEquationCount
input TypeName class_;
output Integer count;
end getEquationCount;
26.1.115 getEquationItemsCount
function getEquationItemsCount
input TypeName class_;
output Integer count;
end getEquationItemsCount;
26.1.116 getErrorString
26.1.117 getHomeDirectoryPath
function getHomeDirectoryPath
output String homeDirectoryPath;
end getHomeDirectoryPath;
26.1.118 getImportCount
function getImportCount
input TypeName class_;
output Integer count;
end getImportCount;
26.1.119 getImportedNames
function getImportedNames
input TypeName class_;
output String[:] out_public;
output String[:] out_protected;
end getImportedNames;
26.1.120 getIndexReductionMethod
function getIndexReductionMethod
output String selected;
end getIndexReductionMethod;
26.1.121 getInheritedClasses
function getInheritedClasses
input TypeName name;
output TypeName inheritedClasses[:];
end getInheritedClasses;
26.1.122 getInitialAlgorithmCount
function getInitialAlgorithmCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmCount;
26.1.123 getInitialAlgorithmItemsCount
function getInitialAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmItemsCount;
26.1.124 getInitialEquationCount
function getInitialEquationCount
input TypeName class_;
output Integer count;
end getInitialEquationCount;
26.1.125 getInitialEquationItemsCount
function getInitialEquationItemsCount
input TypeName class_;
output Integer count;
end getInitialEquationItemsCount;
26.1.126 getInitialStates
function getInitialStates
input TypeName cl;
output String[:, :] initialStates;
end getInitialStates;
26.1.127 getInstallationDirectoryPath
function getInstallationDirectoryPath
output String installationDirectoryPath;
end getInstallationDirectoryPath;
26.1.128 getInstantiatedParametersAndValues
function getInstantiatedParametersAndValues
input TypeName cls;
output String[:] values;
end getInstantiatedParametersAndValues;
26.1.129 getLanguageStandard
function getLanguageStandard
output String outVersion;
end getLanguageStandard;
26.1.130 getLinker
function getLinker
output String linker;
end getLinker;
26.1.131 getLinkerFlags
function getLinkerFlags
output String linkerFlags;
end getLinkerFlags;
26.1.132 getLoadedLibraries
function getLoadedLibraries
output String[:, 2] libraries;
end getLoadedLibraries;
26.1.133 getMMfileTotalDependencies
function getMMfileTotalDependencies
input String in_package_name;
input String public_imports_dir;
output String[:] total_pub_imports;
end getMMfileTotalDependencies;
26.1.134 getMatchingAlgorithm
function getMatchingAlgorithm
output String selected;
end getMatchingAlgorithm;
26.1.135 getMemorySize
function getMemorySize
output Real memory(unit = "MiB");
end getMemorySize;
26.1.136 getMessagesString
function getMessagesString
output String messagesString;
end getMessagesString;
26.1.137 getModelInstance
function getModelInstance
input TypeName className;
input String modifier = "";
input Boolean prettyPrint = false;
output String result;
end getModelInstance;
26.1.138 getModelInstanceIcon
function getModelInstanceIcon
input TypeName className;
input Boolean prettyPrint = false;
output String result;
end getModelInstanceIcon;
26.1.139 getModelicaPath
function getModelicaPath
output String modelicaPath;
end getModelicaPath;
26.1.140 getNoSimplify
function getNoSimplify
output Boolean noSimplify;
end getNoSimplify;
26.1.141 getNthAlgorithm
function getNthAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithm;
26.1.142 getNthAlgorithmItem
function getNthAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithmItem;
26.1.143 getNthAnnotationString
function getNthAnnotationString
input TypeName class_;
input Integer index;
output String result;
end getNthAnnotationString;
26.1.144 getNthConnection
function getNthConnection
input TypeName className;
input Integer index;
output String[:] result;
end getNthConnection;
26.1.145 getNthEquation
function getNthEquation
input TypeName class_;
input Integer index;
output String result;
end getNthEquation;
26.1.146 getNthEquationItem
function getNthEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthEquationItem;
26.1.147 getNthImport
function getNthImport
input TypeName class_;
input Integer index;
output String out[3] "{\"Path\",\"Id\",\"Kind\"}";
end getNthImport;
26.1.148 getNthInitialAlgorithm
function getNthInitialAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithm;
26.1.149 getNthInitialAlgorithmItem
function getNthInitialAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithmItem;
26.1.150 getNthInitialEquation
function getNthInitialEquation
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquation;
26.1.151 getNthInitialEquationItem
function getNthInitialEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquationItem;
26.1.152 getOrderConnections
function getOrderConnections
output Boolean orderConnections;
end getOrderConnections;
26.1.153 getPackages
function getPackages
input TypeName class_ = $Code(AllLoadedClasses);
output TypeName classNames[:];
end getPackages;
26.1.154 getParameterNames
function getParameterNames
input TypeName class_;
output String[:] parameters;
end getParameterNames;
26.1.155 getParameterValue
function getParameterValue
input TypeName class_;
input String parameterName;
output String parameterValue;
end getParameterValue;
26.1.156 getSettings
function getSettings
output String settings;
end getSettings;
26.1.157 getShowAnnotations
function getShowAnnotations
output Boolean show;
end getShowAnnotations;
26.1.158 getSimulationOptions
function getSimulationOptions
input TypeName name;
input Real defaultStartTime = 0.0;
input Real defaultStopTime = 1.0;
input Real defaultTolerance = 1e-6;
input Integer defaultNumberOfIntervals = 500 "May be overridden by defining
˓→defaultInterval instead";
26.1.159 getSourceFile
function getSourceFile
input TypeName class_;
output String filename "empty on failure";
end getSourceFile;
26.1.160 getTearingMethod
function getTearingMethod
output String selected;
end getTearingMethod;
26.1.161 getTempDirectoryPath
function getTempDirectoryPath
output String tempDirectoryPath;
end getTempDirectoryPath;
26.1.162 getTimeStamp
function getTimeStamp
input TypeName cl;
output Real timeStamp;
output String timeStampAsString;
end getTimeStamp;
26.1.163 getTransitions
function getTransitions
input TypeName cl;
output String[:, :] transitions;
end getTransitions;
26.1.164 getUsedClassNames
function getUsedClassNames
input TypeName className;
output TypeName classNames[:];
end getUsedClassNames;
26.1.165 getUses
function getUses
input TypeName pack;
output String[:, :] uses;
end getUses;
26.1.166 getVectorizationLimit
function getVectorizationLimit
output Integer vectorizationLimit;
end getVectorizationLimit;
26.1.167 getVersion
function getVersion
input TypeName cl = $Code(OpenModelica);
output String version;
end getVersion;
26.1.168 help
function help
input String topic = "topics";
output String helpText;
end help;
26.1.169 iconv
function iconv
input String string;
input String from;
input String to = "UTF-8";
output String result;
end iconv;
26.1.170 importFMU
function importFMU
input String filename "the fmu file name";
input String workdir = "<default>" "The output directory for imported FMU files.
˓→<default> will put the files to current working directory.";
input Boolean fullPath = false "When true the full output path is returned
˓→otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
26.1.171 importFMUModelDescription
function importFMUModelDescription
input String filename "the fmu file name";
input String workdir = "<default>" "The output directory for imported FMU files.
˓→<default> will put the files to current working directory.";
input Boolean fullPath = false "When true the full output path is returned
˓→otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMUModelDescription;
26.1.172 inferBindings
function inferBindings
input TypeName path;
output Boolean success;
end inferBindings;
26.1.173 installPackage
function installPackage
input TypeName pkg;
input String version = "";
input Boolean exactMatch = false;
output Boolean result;
end installPackage;
26.1.174 instantiateModel
function instantiateModel
input TypeName className;
output String result;
end instantiateModel;
26.1.175 isBlock
function isBlock
input TypeName cl;
output Boolean b;
end isBlock;
26.1.176 isClass
function isClass
input TypeName cl;
output Boolean b;
end isClass;
26.1.177 isConnector
function isConnector
input TypeName cl;
output Boolean b;
end isConnector;
26.1.178 isEnumeration
function isEnumeration
input TypeName cl;
output Boolean b;
end isEnumeration;
26.1.179 isExperiment
function isExperiment
input TypeName name;
output Boolean res;
end isExperiment;
26.1.180 isFunction
function isFunction
input TypeName cl;
output Boolean b;
end isFunction;
26.1.181 isModel
function isModel
input TypeName cl;
output Boolean b;
end isModel;
26.1.182 isOperator
function isOperator
input TypeName cl;
output Boolean b;
end isOperator;
26.1.183 isOperatorFunction
function isOperatorFunction
input TypeName cl;
output Boolean b;
end isOperatorFunction;
26.1.184 isOperatorRecord
function isOperatorRecord
input TypeName cl;
output Boolean b;
end isOperatorRecord;
26.1.185 isOptimization
function isOptimization
input TypeName cl;
output Boolean b;
end isOptimization;
26.1.186 isPackage
function isPackage
input TypeName cl;
output Boolean b;
end isPackage;
26.1.187 isPartial
function isPartial
input TypeName cl;
output Boolean b;
end isPartial;
26.1.188 isProtectedClass
function isProtectedClass
input TypeName cl;
input String c2;
output Boolean b;
end isProtectedClass;
26.1.189 isRecord
function isRecord
input TypeName cl;
output Boolean b;
end isRecord;
26.1.190 isShortDefinition
function isShortDefinition
input TypeName class_;
output Boolean isShortCls;
end isShortDefinition;
26.1.191 isType
function isType
input TypeName cl;
output Boolean b;
end isType;
26.1.192 linearize
function linearize
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default>
˓→= 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file.
˓→<default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.193 list
function list
input TypeName class_ = $Code(AllLoadedClasses);
input Boolean interfaceOnly = false;
input Boolean shortOnly = false "only short class definitions";
input ExportKind exportKind = ExportKind.Absyn;
output String contents;
end list;
26.1.194 listFile
function listFile
input TypeName class_;
input Boolean nestedClasses = true;
output String contents;
end listFile;
26.1.195 listVariables
function listVariables
output TypeName variables[:];
end listVariables;
26.1.196 loadEncryptedPackage
function loadEncryptedPackage
input String fileName;
input String workdir = "<default>" "The output directory for imported encrypted
˓→files. <default> will put the files to current working directory.";
input Boolean skipUnzip = false "Skips the unzip of .mol if true. In that case
˓→we expect the files are already extracted e.g., because of
˓→parseEncryptedPackage() call.";
˓→match it.";
26.1.197 loadFile
function loadFile
input String fileName;
input String encoding = "UTF-8";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions
˓→that were loaded";
˓→match it.";
26.1.198 loadFileInteractive
function loadFileInteractive
input String filename;
input String encoding = "UTF-8";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions
˓→that were loaded";
˓→match it.";
26.1.199 loadFileInteractiveQualified
function loadFileInteractiveQualified
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractiveQualified;
26.1.200 loadFiles
function loadFiles
input String[:] fileNames;
input String encoding = "UTF-8";
input Integer numThreads = OpenModelica.Scripting.numProcessors();
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions
˓→that were loaded";
˓→match it.";
26.1.201 loadModel
function loadModel
input TypeName className;
input String[:] priorityVersion = {"default"};
input Boolean notify = false "Give a notification of the libraries and versions
˓→that were loaded";
input String languageStandard = "" "Override the set language standard. Parse
˓→with the given setting, but do not change it permanently.";
˓→match it.";
26.1.202 loadModelica3D
function loadModelica3D
input String version = "3.2.1";
output Boolean status;
end loadModelica3D;
26.1.203 loadOMSimulator
function loadOMSimulator
output Integer status;
end loadOMSimulator;
26.1.204 loadString
function loadString
input String data;
input String filename = "<interactive>";
input String encoding = "UTF-8";
input Boolean merge = false "if merge is true the parsed AST is merged with the
˓→existing AST, default to false which means that is replaced, not merged";
26.1.205 mkdir
function mkdir
input String newDirectory;
output Boolean success;
end mkdir;
26.1.206 modifierToJSON
function modifierToJSON
input String modifier;
input Boolean prettyPrint = false;
output String json;
end modifierToJSON;
26.1.207 moveClass
function moveClass
input TypeName className "the class that should be moved";
input Integer offset "Offset in the class list.";
output Boolean result;
end moveClass;
26.1.208 moveClassToBottom
function moveClassToBottom
input TypeName className;
output Boolean result;
end moveClassToBottom;
26.1.209 moveClassToTop
function moveClassToTop
input TypeName className;
output Boolean result;
end moveClassToTop;
26.1.210 ngspicetoModelica
function ngspicetoModelica
input String netlistfileName;
output Boolean success = false;
end ngspicetoModelica;
26.1.211 numProcessors
function numProcessors
output Integer result;
end numProcessors;
26.1.212 oms_RunFile
function oms_RunFile
input String filename;
output Integer status;
end oms_RunFile;
26.1.213 oms_addBus
function oms_addBus
input String cref;
output Integer status;
end oms_addBus;
26.1.214 oms_addConnection
function oms_addConnection
input String crefA;
input String crefB;
output Integer status;
end oms_addConnection;
26.1.215 oms_addConnector
function oms_addConnector
input String cref;
input oms_causality causality;
input oms_signal_type type_;
output Integer status;
end oms_addConnector;
26.1.216 oms_addConnectorToBus
function oms_addConnectorToBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_addConnectorToBus;
26.1.217 oms_addConnectorToTLMBus
function oms_addConnectorToTLMBus
input String busCref;
input String connectorCref;
input String type_;
output Integer status;
end oms_addConnectorToTLMBus;
26.1.218 oms_addDynamicValueIndicator
function oms_addDynamicValueIndicator
input String signal;
input String lower;
input String upper;
input Real stepSize;
output Integer status;
end oms_addDynamicValueIndicator;
26.1.219 oms_addEventIndicator
function oms_addEventIndicator
input String signal;
output Integer status;
end oms_addEventIndicator;
26.1.220 oms_addExternalModel
function oms_addExternalModel
input String cref;
input String path;
input String startscript;
output Integer status;
end oms_addExternalModel;
26.1.221 oms_addSignalsToResults
function oms_addSignalsToResults
input String cref;
input String regex;
output Integer status;
end oms_addSignalsToResults;
26.1.222 oms_addStaticValueIndicator
function oms_addStaticValueIndicator
input String signal;
input Real lower;
input Real upper;
input Real stepSize;
output Integer status;
end oms_addStaticValueIndicator;
26.1.223 oms_addSubModel
function oms_addSubModel
input String cref;
input String fmuPath;
output Integer status;
end oms_addSubModel;
26.1.224 oms_addSystem
function oms_addSystem
input String cref;
input oms_system type_;
output Integer status;
end oms_addSystem;
26.1.225 oms_addTLMBus
function oms_addTLMBus
input String cref;
input oms_tlm_domain domain;
input Integer dimensions;
input oms_tlm_interpolation interpolation;
output Integer status;
end oms_addTLMBus;
26.1.226 oms_addTLMConnection
function oms_addTLMConnection
input String crefA;
input String crefB;
input Real delay;
input Real alpha;
input Real linearimpedance;
input Real angularimpedance;
output Integer status;
end oms_addTLMConnection;
26.1.227 oms_addTimeIndicator
function oms_addTimeIndicator
input String signal;
output Integer status;
end oms_addTimeIndicator;
26.1.228 oms_compareSimulationResults
function oms_compareSimulationResults
input String filenameA;
input String filenameB;
input String var;
input Real relTol;
input Real absTol;
output Integer status;
end oms_compareSimulationResults;
26.1.229 oms_copySystem
function oms_copySystem
input String source;
input String target;
output Integer status;
end oms_copySystem;
26.1.230 oms_delete
function oms_delete
input String cref;
output Integer status;
end oms_delete;
26.1.231 oms_deleteConnection
function oms_deleteConnection
input String crefA;
input String crefB;
output Integer status;
end oms_deleteConnection;
26.1.232 oms_deleteConnectorFromBus
function oms_deleteConnectorFromBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromBus;
26.1.233 oms_deleteConnectorFromTLMBus
function oms_deleteConnectorFromTLMBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromTLMBus;
26.1.234 oms_export
function oms_export
input String cref;
input String filename;
output Integer status;
end oms_export;
26.1.235 oms_exportDependencyGraphs
function oms_exportDependencyGraphs
input String cref;
input String initialization;
input String event;
input String simulation;
output Integer status;
end oms_exportDependencyGraphs;
26.1.236 oms_exportSnapshot
function oms_exportSnapshot
input String cref;
output String contents;
output Integer status;
end oms_exportSnapshot;
26.1.237 oms_extractFMIKind
function oms_extractFMIKind
input String filename;
output Integer kind;
output Integer status;
end oms_extractFMIKind;
26.1.238 oms_faultInjection
function oms_faultInjection
input String signal;
input oms_fault_type faultType;
input Real faultValue;
output Integer status;
end oms_faultInjection;
26.1.239 oms_getBoolean
function oms_getBoolean
input String cref;
output Boolean value;
output Integer status;
end oms_getBoolean;
26.1.240 oms_getFixedStepSize
function oms_getFixedStepSize
input String cref;
output Real stepSize;
output Integer status;
end oms_getFixedStepSize;
26.1.241 oms_getInteger
function oms_getInteger
input String cref;
input Integer value;
output Integer status;
end oms_getInteger;
26.1.242 oms_getModelState
function oms_getModelState
input String cref;
output Integer modelState;
output Integer status;
end oms_getModelState;
26.1.243 oms_getReal
function oms_getReal
input String cref;
output Real value;
output Integer status;
end oms_getReal;
26.1.244 oms_getSolver
function oms_getSolver
input String cref;
output Integer solver;
output Integer status;
end oms_getSolver;
26.1.245 oms_getStartTime
function oms_getStartTime
input String cref;
output Real startTime;
output Integer status;
end oms_getStartTime;
26.1.246 oms_getStopTime
function oms_getStopTime
input String cref;
output Real stopTime;
output Integer status;
end oms_getStopTime;
26.1.247 oms_getSubModelPath
function oms_getSubModelPath
input String cref;
output String path;
output Integer status;
end oms_getSubModelPath;
26.1.248 oms_getSystemType
function oms_getSystemType
input String cref;
output Integer type_;
output Integer status;
end oms_getSystemType;
26.1.249 oms_getTolerance
function oms_getTolerance
input String cref;
output Real absoluteTolerance;
output Real relativeTolerance;
output Integer status;
end oms_getTolerance;
26.1.250 oms_getVariableStepSize
function oms_getVariableStepSize
input String cref;
output Real initialStepSize;
output Real minimumStepSize;
output Real maximumStepSize;
output Integer status;
end oms_getVariableStepSize;
26.1.251 oms_getVersion
function oms_getVersion
output String version;
end oms_getVersion;
26.1.252 oms_importFile
function oms_importFile
input String filename;
output String cref;
output Integer status;
end oms_importFile;
26.1.253 oms_importSnapshot
function oms_importSnapshot
input String cref;
input String snapshot;
output Integer status;
end oms_importSnapshot;
26.1.254 oms_initialize
function oms_initialize
input String cref;
output Integer status;
end oms_initialize;
26.1.255 oms_instantiate
function oms_instantiate
input String cref;
output Integer status;
end oms_instantiate;
26.1.256 oms_list
function oms_list
input String cref;
output String contents;
output Integer status;
end oms_list;
26.1.257 oms_listUnconnectedConnectors
function oms_listUnconnectedConnectors
input String cref;
output String contents;
output Integer status;
end oms_listUnconnectedConnectors;
26.1.258 oms_loadSnapshot
function oms_loadSnapshot
input String cref;
input String snapshot;
output String newCref;
output Integer status;
end oms_loadSnapshot;
26.1.259 oms_newModel
function oms_newModel
input String cref;
output Integer status;
end oms_newModel;
26.1.260 oms_removeSignalsFromResults
function oms_removeSignalsFromResults
input String cref;
input String regex;
output Integer status;
end oms_removeSignalsFromResults;
26.1.261 oms_rename
function oms_rename
input String cref;
input String newCref;
output Integer status;
end oms_rename;
26.1.262 oms_reset
function oms_reset
input String cref;
output Integer status;
end oms_reset;
26.1.263 oms_setBoolean
function oms_setBoolean
input String cref;
input Boolean value;
output Integer status;
end oms_setBoolean;
26.1.264 oms_setCommandLineOption
function oms_setCommandLineOption
input String cmd;
output Integer status;
end oms_setCommandLineOption;
26.1.265 oms_setFixedStepSize
function oms_setFixedStepSize
input String cref;
input Real stepSize;
output Integer status;
end oms_setFixedStepSize;
26.1.266 oms_setInteger
function oms_setInteger
input String cref;
input Integer value;
output Integer status;
end oms_setInteger;
26.1.267 oms_setLogFile
function oms_setLogFile
input String filename;
output Integer status;
end oms_setLogFile;
26.1.268 oms_setLoggingInterval
function oms_setLoggingInterval
input String cref;
input Real loggingInterval;
output Integer status;
end oms_setLoggingInterval;
26.1.269 oms_setLoggingLevel
function oms_setLoggingLevel
input Integer logLevel;
output Integer status;
end oms_setLoggingLevel;
26.1.270 oms_setReal
function oms_setReal
input String cref;
input Real value;
output Integer status;
end oms_setReal;
26.1.271 oms_setRealInputDerivative
function oms_setRealInputDerivative
input String cref;
input Real value;
output Integer status;
end oms_setRealInputDerivative;
26.1.272 oms_setResultFile
function oms_setResultFile
input String cref;
input String filename;
input Integer bufferSize;
output Integer status;
end oms_setResultFile;
26.1.273 oms_setSignalFilter
function oms_setSignalFilter
input String cref;
input String regex;
output Integer status;
end oms_setSignalFilter;
26.1.274 oms_setSolver
function oms_setSolver
input String cref;
input oms_solver solver;
output Integer status;
end oms_setSolver;
26.1.275 oms_setStartTime
function oms_setStartTime
input String cref;
input Real startTime;
output Integer status;
end oms_setStartTime;
26.1.276 oms_setStopTime
function oms_setStopTime
input String cref;
input Real stopTime;
output Integer status;
end oms_setStopTime;
26.1.277 oms_setTLMPositionAndOrientation
function oms_setTLMPositionAndOrientation
input String cref;
input Real x1;
input Real x2;
input Real x3;
input Real A11;
input Real A12;
input Real A13;
input Real A21;
input Real A22;
input Real A23;
input Real A31;
input Real A32;
input Real A33;
output Integer status;
end oms_setTLMPositionAndOrientation;
26.1.278 oms_setTLMSocketData
function oms_setTLMSocketData
input String cref;
input String address;
input Integer managerPort;
input Integer monitorPort;
output Integer status;
end oms_setTLMSocketData;
26.1.279 oms_setTempDirectory
function oms_setTempDirectory
input String newTempDir;
output Integer status;
end oms_setTempDirectory;
26.1.280 oms_setTolerance
function oms_setTolerance
input String cref;
input Real absoluteTolerance;
input Real relativeTolerance;
output Integer status;
end oms_setTolerance;
26.1.281 oms_setVariableStepSize
function oms_setVariableStepSize
input String cref;
input Real initialStepSize;
input Real minimumStepSize;
input Real maximumStepSize;
output Integer status;
end oms_setVariableStepSize;
26.1.282 oms_setWorkingDirectory
function oms_setWorkingDirectory
input String newWorkingDir;
output Integer status;
end oms_setWorkingDirectory;
26.1.283 oms_simulate
function oms_simulate
input String cref;
output Integer status;
end oms_simulate;
26.1.284 oms_stepUntil
function oms_stepUntil
input String cref;
input Real stopTime;
output Integer status;
end oms_stepUntil;
26.1.285 oms_terminate
function oms_terminate
input String cref;
output Integer status;
end oms_terminate;
26.1.286 optimize
function optimize
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default>
˓→= 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file.
˓→<default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.287 parseEncryptedPackage
function parseEncryptedPackage
input String fileName;
input String workdir = "<default>" "The output directory for imported encrypted
˓→files. <default> will put the files to current working directory.";
26.1.288 parseFile
function parseFile
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end parseFile;
26.1.289 parseString
function parseString
input String data;
input String filename = "<interactive>";
output TypeName names[:];
end parseString;
26.1.290 plot
function plot
input VariableNames vars "The variables you want to plot";
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables.
˓→<default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e simple, detailed,
˓→none.";
input Boolean logX = false "Determines whether or not the horizontal axis is
˓→logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is
˓→logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in
˓→the diagram.";
input String yLabel = "" "This text will be used as the vertical label in the
˓→diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e left,
˓→right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call
˓→callback function even if it is defined.";
26.1.291 plotAll
function plotAll
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables.
˓→<default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e simple, detailed,
˓→none.";
input Boolean logX = false "Determines whether or not the horizontal axis is
˓→logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is
˓→logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in
˓→the diagram.";
input String yLabel = "" "This text will be used as the vertical label in the
˓→diagram.";
(continues on next page)
input Real yRange[2] = {0.0, 0.0} "Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e left,
˓→right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call
˓→callback function even if it is defined.";
26.1.292 plotParametric
function plotParametric
input VariableName xVariable;
input VariableName yVariable;
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables.
˓→<default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e simple, detailed,
˓→none.";
input Boolean logX = false "Determines whether or not the horizontal axis is
˓→logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is
˓→logarithmically scaled.";
input String xLabel = "" "This text will be used as the horizontal label in the
˓→diagram.";
input String yLabel = "" "This text will be used as the vertical label in the
˓→diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e left,
˓→right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call
˓→callback function even if it is defined.";
26.1.293 readFile
26.1.294 readFileNoNumeric
function readFileNoNumeric
input String fileName;
output String contents;
end readFileNoNumeric;
26.1.295 readSimulationResult
function readSimulationResult
input String filename;
input VariableNames variables;
input Integer size = 0 "0=read any size... If the size is not the same as the
˓→result-file, this function fails";
26.1.296 readSimulationResultSize
function readSimulationResultSize
input String fileName;
output Integer sz;
end readSimulationResultSize;
26.1.297 readSimulationResultVars
function readSimulationResultVars
input String fileName;
input Boolean readParameters = true;
input Boolean openmodelicaStyle = false;
output String[:] vars;
end readSimulationResultVars;
26.1.298 realpath
function realpath
input String name "Absolute or relative file or directory name";
output String fullName "Full path of 'name'";
end realpath;
26.1.299 reduceTerms
function reduceTerms
input TypeName className "the class that should be built";
input Real startTime = 0.0 "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String method = "dassl" "integration method used for simulation. <default>
˓→= dassl";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.300 regex
function regex
input String str;
input String re;
input Integer maxMatches = 1 "The maximum number of matches that will be returned
˓→";
end regex;
26.1.301 regexBool
function regexBool
input String str;
input String re;
input Boolean extended = true "Use POSIX extended or regular syntax";
input Boolean caseInsensitive = false;
output Boolean matches;
end regexBool;
26.1.302 regularFileExists
function regularFileExists
input String fileName;
output Boolean exists;
end regularFileExists;
26.1.303 reloadClass
function reloadClass
input TypeName name;
input String encoding = "UTF-8";
output Boolean success;
end reloadClass;
26.1.304 remove
function remove
input String path;
output Boolean success "Returns true on success.";
end remove;
26.1.305 removeComponentModifiers
function removeComponentModifiers
input TypeName class_;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeComponentModifiers;
26.1.306 removeElementModifiers
function removeElementModifiers
input TypeName className;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeElementModifiers;
26.1.307 removeExtendsModifiers
function removeExtendsModifiers
input TypeName className;
input TypeName baseClassName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeExtendsModifiers;
26.1.308 reopenStandardStream
function reopenStandardStream
input StandardStream _stream;
input String filename;
output Boolean success;
end reopenStandardStream;
26.1.309 restoreAST
function restoreAST
input Integer id;
output Boolean success;
end restoreAST;
26.1.310 rewriteBlockCall
function rewriteBlockCall
input TypeName className;
input TypeName inDefs;
output Boolean success;
end rewriteBlockCall;
26.1.311 runConversionScript
function runConversionScript
input TypeName packageToConvert;
input String scriptFile;
output Boolean success;
end runConversionScript;
26.1.312 runScript
26.1.313 runScriptParallel
function runScriptParallel
input String scripts[:];
input Integer numThreads = numProcessors();
input Boolean useThreads = false;
output Boolean results[:];
end runScriptParallel;
26.1.314 save
function save
input TypeName className;
output Boolean success;
end save;
26.1.315 saveAll
function saveAll
input String fileName;
output Boolean success;
end saveAll;
26.1.316 saveModel
function saveModel
input String fileName;
input TypeName className;
output Boolean success;
end saveModel;
26.1.317 saveTotalModel
function saveTotalModel
input String fileName;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output Boolean success;
end saveTotalModel;
26.1.318 saveTotalModelDebug
function saveTotalModelDebug
input String filename;
input TypeName className;
output Boolean success;
end saveTotalModelDebug;
26.1.319 saveTotalSCode
26.1.320 searchClassNames
function searchClassNames
input String searchText;
input Boolean findInText = false;
output TypeName classNames[:];
end searchClassNames;
26.1.321 setAnnotationVersion
function setAnnotationVersion
input String annotationVersion;
output Boolean success;
end setAnnotationVersion;
26.1.322 setCFlags
function setCFlags
input String inString;
output Boolean success;
end setCFlags;
26.1.323 setCXXCompiler
function setCXXCompiler
input String compiler;
output Boolean success;
end setCXXCompiler;
26.1.324 setCheapMatchingAlgorithm
function setCheapMatchingAlgorithm
input Integer matchingAlgorithm;
output Boolean success;
end setCheapMatchingAlgorithm;
26.1.325 setClassComment
function setClassComment
input TypeName class_;
input String filename;
output Boolean success;
end setClassComment;
26.1.326 setCommandLineOptions
function setCommandLineOptions
input String option;
output Boolean success;
end setCommandLineOptions;
26.1.327 setCompileCommand
function setCompileCommand
input String compileCommand;
output Boolean success;
end setCompileCommand;
26.1.328 setCompiler
function setCompiler
input String compiler;
output Boolean success;
end setCompiler;
26.1.329 setCompilerFlags
function setCompilerFlags
input String compilerFlags;
output Boolean success;
end setCompilerFlags;
26.1.330 setCompilerPath
function setCompilerPath
input String compilerPath;
output Boolean success;
end setCompilerPath;
26.1.331 setDebugFlags
function setDebugFlags
input String debugFlags;
output Boolean success;
end setDebugFlags;
26.1.332 setDefaultOpenCLDevice
function setDefaultOpenCLDevice
input Integer defdevid;
output Boolean success;
end setDefaultOpenCLDevice;
26.1.333 setDocumentationAnnotation
function setDocumentationAnnotation
input TypeName class_;
input String info = "";
input String revisions = "";
output Boolean bool;
end setDocumentationAnnotation;
26.1.334 setEnvironmentVar
function setEnvironmentVar
input String var;
input String value;
output Boolean success;
end setEnvironmentVar;
26.1.335 setIndexReductionMethod
function setIndexReductionMethod
input String method;
output Boolean success;
end setIndexReductionMethod;
26.1.336 setInitXmlStartValue
function setInitXmlStartValue
input String fileName;
input String variableName;
input String startValue;
input String outputFile;
output Boolean success = false;
end setInitXmlStartValue;
26.1.337 setInstallationDirectoryPath
function setInstallationDirectoryPath
input String installationDirectoryPath;
output Boolean success;
end setInstallationDirectoryPath;
26.1.338 setLanguageStandard
function setLanguageStandard
input String inVersion;
output Boolean success;
end setLanguageStandard;
26.1.339 setLinker
function setLinker
input String linker;
output Boolean success;
end setLinker;
26.1.340 setLinkerFlags
function setLinkerFlags
input String linkerFlags;
output Boolean success;
end setLinkerFlags;
26.1.341 setMatchingAlgorithm
function setMatchingAlgorithm
input String matchingAlgorithm;
output Boolean success;
end setMatchingAlgorithm;
26.1.342 setModelicaPath
function setModelicaPath
input String modelicaPath;
output Boolean success;
end setModelicaPath;
26.1.343 setNoSimplify
function setNoSimplify
input Boolean noSimplify;
output Boolean success;
end setNoSimplify;
26.1.344 setOrderConnections
function setOrderConnections
input Boolean orderConnections;
output Boolean success;
end setOrderConnections;
26.1.345 setPlotCommand
function setPlotCommand
input String plotCommand;
output Boolean success;
end setPlotCommand;
26.1.346 setPostOptModules
function setPostOptModules
input String modules;
output Boolean success;
end setPostOptModules;
26.1.347 setPreOptModules
function setPreOptModules
input String modules;
output Boolean success;
end setPreOptModules;
26.1.348 setShowAnnotations
function setShowAnnotations
input Boolean show;
output Boolean success;
end setShowAnnotations;
26.1.349 setSourceFile
function setSourceFile
input TypeName class_;
input String filename;
output Boolean success;
end setSourceFile;
26.1.350 setTearingMethod
function setTearingMethod
input String tearingMethod;
output Boolean success;
end setTearingMethod;
26.1.351 setTempDirectoryPath
function setTempDirectoryPath
input String tempDirectoryPath;
output Boolean success;
end setTempDirectoryPath;
26.1.352 setVectorizationLimit
function setVectorizationLimit
input Integer vectorizationLimit;
output Boolean success;
end setVectorizationLimit;
26.1.353 simulate
function simulate
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default>
˓→= 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Only variables fully matching the regexp are
˓→stored in the result file. <default> = \".*\"";
26.1.354 solveLinearSystem
function solveLinearSystem
input Real[size(B, 1), size(B, 1)] A;
input Real[:] B;
output Real[size(B, 1)] X;
output Integer info;
end solveLinearSystem;
26.1.355 sortStrings
function sortStrings
input String arr[:];
output String sorted[:];
end sortStrings;
26.1.356 stat
26.1.357 storeAST
function storeAST
output Integer id;
end storeAST;
26.1.358 stringReplace
function stringReplace
input String str;
input String source;
input String target;
output String res;
end stringReplace;
26.1.359 stringSplit
function stringSplit
input String string;
input String token "single character only";
output String[:] strings;
end stringSplit;
26.1.360 stringTypeName
function stringTypeName
input String str;
output TypeName cl;
end stringTypeName;
26.1.361 stringVariableName
function stringVariableName
input String str;
output VariableName cl;
end stringVariableName;
26.1.362 strtok
function strtok
input String string;
input String token;
output String[:] strings;
end strtok;
26.1.363 system
output Integer retval "Return value of the system call; usually 0 on success";
end system;
26.1.364 system_parallel
26.1.365 testsuiteFriendlyName
function testsuiteFriendlyName
input String path;
output String fixed;
end testsuiteFriendlyName;
26.1.366 threadWorkFailed
26.1.367 translateGraphics
function translateGraphics
input TypeName className;
output String result;
end translateGraphics;
26.1.368 translateModelFMU
function translateModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 1.0 or 2.0.";
input String fmuType = "me" "FMU type, me (model exchange), cs (co-simulation),
˓→me_cs (both model exchange and co-simulation)";
output String generatedFileName "Returns the full path of the generated FMU.";
end translateModelFMU;
26.1.369 typeNameString
function typeNameString
input TypeName cl;
output String out;
end typeNameString;
26.1.370 typeNameStrings
function typeNameStrings
input TypeName cl;
output String out[:];
end typeNameStrings;
26.1.371 typeOf
function typeOf
input VariableName variableName;
output String result;
end typeOf;
26.1.372 unloadOMSimulator
function unloadOMSimulator
output Integer status;
end unloadOMSimulator;
26.1.373 updateConnection
function updateConnection
input TypeName className;
input String from;
input String to;
input ExpressionOrModification annotate;
output Boolean result;
end updateConnection;
26.1.374 updateConnectionAnnotation
function updateConnectionAnnotation
input TypeName className;
input String from;
input String to;
input String annotate;
output Boolean result;
end updateConnectionAnnotation;
26.1.375 updateConnectionNames
function updateConnectionNames
input TypeName className;
input String from;
input String to;
input String fromNew;
input String toNew;
output Boolean result;
end updateConnectionNames;
26.1.376 updateInitialState
function updateInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end updateInitialState;
26.1.377 updatePackageIndex
function updatePackageIndex
output Boolean result;
end updatePackageIndex;
26.1.378 updateTransition
function updateTransition
input TypeName cl;
input String from;
input String to;
input String oldCondition;
input Boolean oldImmediate;
input Boolean oldReset;
input Boolean oldSynchronize;
input Integer oldPriority;
input String newCondition;
input Boolean newImmediate;
input Boolean newReset;
input Boolean newSynchronize;
input Integer newPriority;
input ExpressionOrModification annotate;
output Boolean bool;
end updateTransition;
26.1.379 upgradeInstalledPackages
function upgradeInstalledPackages
input Boolean installNewestVersions = true;
output Boolean result;
end upgradeInstalledPackages;
26.1.380 uriToFilename
function uriToFilename
input String uri;
output String filename = "";
end uriToFilename;
26.1.381 val
function val
input VariableName var;
input Real timePoint = 0.0;
input String fileName = "<default>" "The contents of the currentSimulationResult
˓→variable";
26.1.382 verifyCompiler
function verifyCompiler
output Boolean compilerWorks;
end verifyCompiler;
26.1.383 writeFile
getErrorString();
end for;
We used the BouncingBall.mo in the example above. The above example produces three result files each contain-
ing different start value for e i.e., 1.7, 2.7, 3.7.
26.3 Examples
The following is an interactive session with the OpenModelica environment including some of the abovemen-
tioned commands and examples. First we start the system, and use the command line interface from OMShell,
OMNotebook, or command window of some of the other tools.
We type in a very small model:
model Test "Testing OpenModelica Scripts"
Real x, y;
equation
x = 5.0+time; y = 6.0;
end Test;
It is multiplied by 2:
>>> a*2
{2,4,6,8,10,12,14,16,18,20}
The common combination of a simulation followed by getting a value and doing a plot:
>>> simulate(Test, stopTime=3.0)
record SimulationResult
resultFile = "«DOCHOME»/Test_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 3.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'Test', options = '',
",
(continues on next page)
6.06
y
6.04
6.02
5.98
5.96
5.94
5.92
0 0.5 1 1.5 2 2.5 3
>>> plotall()
8
x
y
7.5
6.5
5.5
5
0 0.5 1 1.5 2 2.5 3
The function bubblesort is called to sort this vector in descending order. The sorted result is returned together with
its type. Note that the result vector is of type Real[:], instantiated as Real[12], since this is the declared type of the
function result. The input Integer vector was automatically converted to a Real vector according to the Modelica
type coercion rules.
>>> loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/
˓→bubblesort.mo")
true
>>> bubblesort(x)
{12.0,11.0,10.0,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0}
Now we want to try another small application, a simplex algorithm for optimization. First read in a small matrix
containing coefficients that define a simplex problem to be solved:
>>> a := {
{-1,-1,-1, 0, 0, 0, 0, 0, 0},
{-1, 1, 0, 1, 0, 0, 0, 0, 5},
{ 1, 4, 0, 0, 1, 0, 0, 0, 45},
{ 2, 1, 0, 0, 0, 1, 0, 0, 27},
{ 3,-4, 0, 0, 0, 0, 1, 0, 24},
{ 0, 0, 1, 0, 0, 0, 0, 1, 4}
}
{{-1,-1,-1,0,0,0,0,0,0},{-1,1,0,1,0,0,0,0,5},{1,4,0,0,1,0,0,0,45},{2,1,0,0,0,1,0,0,
˓→27},{3,-4,0,0,0,0,1,0,24},{0,0,1,0,0,0,0,1,4}}
function pivot1
input Real b[:,:];
input Integer p;
input Integer q;
output Real a[size(b,1),size(b,2)];
protected
Integer M;
Integer N;
algorithm
a := b;
N := size(a,1)-1;
M := size(a,2)-1;
for j in 1:N loop
for k in 1:M loop
if j<>p and k<>q then
a[j,k] := a[j,k]-0.3*j;
end if;
end for;
end for;
a[p,q] := 0.05;
end pivot1;
function misc_simplex1
input Real matr[:,:];
output Real x[size(matr,2)-1];
output Real z;
output Integer q;
output Integer p;
protected
(continues on next page)
Then call the simplex algorithm implemented as the Modelica function simplex1. This function returns four
results, which are represented as a tuple of four return values:
>>> misc_simplex1(a)
({0.05523110627056022,-1.104622125411205,-1.104622125411205,0.0,0.0,0.0,0.0,0.0},0.
˓→0,8,1)
TWENTYSEVEN
27.1 Options
-d, --debug
Sets debug flags. Use --help=debug to see available flags.
String list (default empty).
-h, --help
Displays the help text. Use --help=topics for more information.
String (default empty).
--v, --version
Print the version and exit.
Boolean (default false).
--target
Sets the target compiler to use.
String (default gcc). Valid options:
• gcc
• msvc
• msvc10
• msvc12
• msvc13
• msvc15
• msvc19
• vxworks69
• debugrt
-g, --grammar
Sets the grammar and semantics to accept.
String (default Modelica). Valid options:
• Modelica
• MetaModelica
• ParModelica
433
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
• Optimica
• PDEModelica
--annotationVersion
Sets the annotation version that should be used.
String (default 3.x). Valid options:
• 1.x
• 2.x
• 3.x
--std
Sets the language standard that should be used.
String (default latest). Valid options:
• 1.x
• 2.x
• 3.1
• 3.2
• 3.3
• 3.4
• 3.5
• latest
• experimental
--showErrorMessages
Show error messages immediately when they happen.
Boolean (default false).
--showAnnotations
Show annotations in the flattened code.
Boolean (default false).
--noSimplify
Do not simplify expressions if set.
Boolean (default false).
--preOptModules
Sets the pre optimization modules to use in the back end. See --help=optmodules for more info.
String list (default normalInlineFunction,evaluateParameters,simplifyIfEquations,expandDerOperator,clockPartitioning,findStateOrd
Valid options:
• introduceOutputAliases (Introduces aliases for top-level outputs.)
• clockPartitioning (Does the clock partitioning.)
• collapseArrayExpressions (Simplifies {x[1],x[2],x[3]} → x for arrays of whole variable references (simpli-
fies code generation).)
• comSubExp (Introduces alias assignments for variables which are assigned to simple terms i.e. a = b/c; d =
b/c; --> a=d)
• dumpDAE (dumps the DAE representation of the current transformation state)
• dumpDAEXML (dumps the DAE as xml representation of the current transformation state)
• encapsulateWhenConditions (This module replaces each when condition with a boolean variable.)
• symbolicJacobian (Detects the sparse pattern of the ODE system and calculates also the symbolic Jacobian
if flag '--generateSymbolicJacobian' is enabled.)
• tearingSystem (For method selection use flag tearingMethod.)
• wrapFunctionCalls (This module introduces variables for each function call and substitutes all these calls
with the newly introduced variables.)
--simCodeTarget
Sets the target language for the code generation.
String (default C). Valid options:
• None
• C
• Cpp
• omsicpp
• ExperimentalEmbeddedC
• JavaScript
• omsic
• XML
• MidC
--orderConnections
Orders connect equations alphabetically if set.
Boolean (default true).
-t, --typeinfo
Prints out extra type information if set.
Boolean (default false).
-a, --keepArrays
Sets whether to split arrays or not.
Boolean (default false).
-m, --modelicaOutput
Enables valid modelica output for flat modelica.
Boolean (default false).
-q, --silent
Turns on silent mode.
Boolean (default false).
-c, --corbaSessionName
Sets the name of the corba session if -d=interactiveCorba or --interactive=corba is used.
String (default empty).
-n, --numProcs
Sets the number of processors to use (0=default=auto).
Integer (default 0).
-l, --latency
Sets the latency for parallel execution.
Integer (default 0).
-b, --bandwidth
--dumpTarget
Redirect the dump to file. If the file ends with .html HTML code is generated.
String (default empty).
--delayBreakLoop
Enables (very) experimental code to break algebraic loops using the delay() operator. Probably messes with
initialization.
Boolean (default true).
--tearingMethod
Sets the tearing method to use. Select no tearing or choose tearing method.
String (default cellier). Valid options:
• noTearing (Skip tearing. This breaks models with mixed continuous-integer/boolean unknowns)
• minimalTearing (Minimal tearing method to only tear discrete variables.)
• omcTearing (Tearing method developed by TU Dresden: Frenkel, Schubert.)
• cellier (Tearing based on Celliers method, revised by FH Bielefeld: Täuber, Patrick)
--tearingHeuristic
Sets the tearing heuristic to use for Cellier-tearing.
String (default MC3). Valid options:
• MC1 (Original cellier with consideration of impossible assignments and discrete Vars.)
• MC2 (Modified cellier, drop first step.)
• MC11 (Modified MC1, new last step 'count impossible assignments'.)
• MC21 (Modified MC2, new last step 'count impossible assignments'.)
• MC12 (Modified MC1, step 'count impossible assignments' before last step.)
• MC22 (Modified MC2, step 'count impossible assignments' before last step.)
• MC13 (Modified MC1, build sum of impossible assignment and causalizable equations, choose var with
biggest sum.)
• MC23 (Modified MC2, build sum of impossible assignment and causalizable equations, choose var with
biggest sum.)
• MC231 (Modified MC23, Two rounds, choose better potentials-set.)
• MC3 (Modified cellier, build sum of impossible assignment and causalizable equations for all vars, choose
var with biggest sum.)
• MC4 (Modified cellier, use all heuristics, choose var that occurs most in potential sets)
--scalarizeMinMax
Scalarizes the builtin min/max reduction operators if true.
Boolean (default false).
--strict
Enables stricter enforcement of Modelica language rules.
Boolean (default false).
--scalarizeBindings
Always scalarizes bindings if set.
Boolean (default false).
--corbaObjectReferenceFilePath
Sets the path for corba object reference file if -d=interactiveCorba is used.
--gDynOpt
Generate dynamic optimization problem based on annotation approach.
Boolean (default false).
--maxSizeSolveLinearSystem
Max size for solveLinearSystem.
Integer (default 0).
--cppFlags
Sets extra flags for compilation with the C++ compiler (e.g. +cppFlags=-O3,-Wall)
String list (default ).
--removeSimpleEquations
Specifies method that removes simple equations.
String (default default). Valid options:
• none (Disables module)
• default (Performs alias elimination and removes constant variables. Default case uses in preOpt phase the
fastAcausal and in postOpt phase the causal implementation.)
• causal (Performs alias elimination and removes constant variables. Causal implementation.)
• fastAcausal (Performs alias elimination and removes constant variables. fastImplementation fastAcausal.)
• allAcausal (Performs alias elimination and removes constant variables. Implementation allAcausal.)
• new (New implementation (experimental))
--dynamicTearing
Activates dynamic tearing (TearingSet can be changed automatically during runtime, strict set vs. casual set.)
String (default false). Valid options:
• false (No dynamic tearing.)
• true (Dynamic tearing for linear and nonlinear systems.)
• linear (Dynamic tearing only for linear systems.)
• nonlinear (Dynamic tearing only for nonlinear systems.)
--symSolver
Activates symbolic implicit solver (original system is not changed).
String (default none). Valid options:
• none
• impEuler
• expEuler
--loop2con
Specifies method that transform loops in constraints. hint: using initial guess from file!
String (default none). Valid options:
• none (Disables module)
• lin (linear loops --> constraints)
• noLin (no linear loops --> constraints)
• all (loops --> constraints)
--forceTearing
Use tearing set even if it is not smaller than the original component.
Boolean (default false).
--simplifyLoops
Simplify algebraic loops.
Integer (default 0). Valid options:
• 0 (do nothing)
• 1 (special modification of residual expressions)
• 2 (special modification of residual expressions with helper variables)
--recursiveTearing
Inline and repeat tearing.
Integer (default 0). Valid options:
• 0 (do nothing)
• 1 (linear tearing set of size 1)
• 2 (linear tearing)
--flowThreshold
Sets the minium threshold for stream flow rates
Real (default 1e-07).
--matrixFormat
Sets the matrix format type in cpp runtime which should be used (dense | sparse ). Default: dense.
String (default dense).
--partlintorn
Sets the limit for partitionin of linear torn systems.
Integer (default 0).
--initOptModules
Sets the initialization optimization modules to use in the back end. See --help=optmodules for more info.
String list (default simplifyComplexFunction,tearingSystem,solveSimpleEquations,calculateStrongComponentJacobians,simplifyAl
Valid options:
• calculateStrongComponentJacobians (Generates analytical jacobian for torn linear and non-linear strong
components. By default linear components and non-linear components with user-defined function calls are
skipped. See also debug flags: LSanalyticJacobian, NLSanalyticJacobian and forceNLSanalyticJacobian)
• collapseArrayExpressions (Simplifies {x[1],x[2],x[3]} → x for arrays of whole variable references (simpli-
fies code generation).)
• constantLinearSystem (Evaluates constant linear systems (a*x+b*y=c; d*x+e*y=f; a,b,c,d,e,f are constants)
at compile-time.)
• extendDynamicOptimization (Move loops to constraints.)
• generateHomotopyComponents (Finds the parts of the DAE that have to be handled by the homotopy solver
and creates a strong component out of it.)
• inlineHomotopy (Experimental: Inlines the homotopy expression to allow symbolic simplifications.)
• inputDerivativesUsed (Checks if derivatives of inputs are need to calculate the model.)
• recursiveTearing (inline and repeat tearing)
• reduceDynamicOptimization (Removes equations which are not needed for the calculations of cost and
constraints. This module requires --postOptModules+=reduceDynamicOptimization.)
-r, --alarm
Sets the number seconds until omc timeouts and exits. Used by the testing framework to terminate infinite running
processes.
Integer (default 0).
--totalTearing
Activates total tearing (determination of all possible tearing sets) for the specified components. Use '-
d=tearingdump' to find out the relevant indexes.
Unknown default valueFlags.FlagData.INT_LIST_FLAG(data = {NIL})
--ignoreSimulationFlagsAnnotation
Ignores the simulation flags specified as annotation in the class.
Boolean (default false).
--dynamicTearingForInitialization
Enable Dynamic Tearing also for the initialization system.
Boolean (default false).
--preferTVarsWithStartValue
Prefer tearing variables with start value for initialization.
Boolean (default true).
--equationsPerFile
Generate code for at most this many equations per C-file (partially implemented in the compiler).
Integer (default 2000).
--evaluateFinalParameters
Evaluates all the final parameters in addition to parameters with annotation(Evaluate=true).
Boolean (default false).
--evaluateProtectedParameters
Evaluates all the protected parameters in addition to parameters with annotation(Evaluate=true).
Boolean (default false).
--replaceEvaluatedParameters
Replaces all the evaluated parameters in the DAE.
Boolean (default true).
--condenseArrays
Sets whether array expressions containing function calls are condensed or not.
Boolean (default true).
--wfcAdvanced
wrapFunctionCalls ignores more then default cases, e.g. exp, sin, cos, log, (experimental flag)
Boolean (default false).
--tearingStrictness
Sets the strictness of the tearing method regarding the solvability restrictions.
String (default strict). Valid options:
• casual (Loose tearing rules using ExpressionSolve to determine the solvability instead of considering the
partial derivative. Allows to solve for everything that is analytically possible. This could lead to singularities
during simulation.)
• strict (Robust tearing rules by consideration of the partial derivative. Allows to divide by parameters that
are not equal to or close to zero.)
• veryStrict (Very strict tearing rules that do not allow to divide by any parameter. Use this if you aim at
overriding parameters after compilation with values equal to or close to zero.)
--interactive
Sets the interactive mode for omc.
String (default none). Valid options:
• none (do nothing)
• corba (Starts omc as a server listening on the Corba interface.)
• tcp (Starts omc as a server listening on the socket interface.)
• zmq (Starts omc as a ZeroMQ server listening on the socket interface.)
-z, --zeroMQFileSuffix
Sets the file suffix for zeroMQ port file if --interactive=zmq is used.
String (default empty).
--homotopyApproach
Sets the homotopy approach.
String (default equidistantGlobal). Valid options:
• equidistantLocal (Local homotopy approach with equidistant lambda steps. The homotopy parameter only
effects the local strongly connected component.)
• adaptiveLocal (Local homotopy approach with adaptive lambda steps. The homotopy parameter only effects
the local strongly connected component.)
• equidistantGlobal (Default, global homotopy approach with equidistant lambda steps. The homotopy pa-
rameter effects the entire initialization system.)
• adaptiveGlobal (Global homotopy approach with adaptive lambda steps. The homotopy parameter effects
the entire initialization system.)
--ignoreReplaceable
Sets whether to ignore replaceability or not when redeclaring.
Boolean (default false).
--postOptModulesDAE
Sets the optimization modules for the DAEmode in the back end. See --help=optmodules for more info.
String list (default lateInlineFunction,wrapFunctionCalls,simplifysemiLinear,simplifyComplexFunction,removeConstants,simplifyT
--evalLoopLimit
The loop iteration limit used when evaluating constant function calls.
Integer (default 100000).
--evalRecursionLimit
The recursion limit used when evaluating constant function calls.
Integer (default 256).
--singleInstanceAglSolver
Sets to instantiate only one algebraic loop solver all algebraic loops
Boolean (default false).
--showStructuralAnnotations
Show annotations affecting the solution process in the flattened code.
Boolean (default false).
--initialStateSelection
Activates the state selection inside initialization to avoid singularities.
Add simulation flags to FMU. Will create <fmiPrefix>_flags.json in resources folder with given flags. Use --
fmiFlags or --fmiFlags=none to disable [default]. Use --fmiFlags=default for the default simulation flags. To pass
flags use e.g. --fmiFlags=s:cvode,nls:homotopy or --fmiFlags=path/to/yourFlags.json.
String list (default empty).
--fmuCMakeBuild
Defines if FMUs will be configured and build with CMake.
String (default default). Valid options:
• default (Let omc decide if CMake should be used.)
• true (Use CMake to compile FMU binaries.)
• false (Use default GNU Autoconf toolchain to compile FMU binaries.)
--newBackend
Activates experimental new backend for better array handling. This also activates the new frontend. [WIP]
Boolean (default false).
--parmodauto
Experimental: Enable parallelization of independent systems of equations in the translated model. Only works on
Linux systems.
Boolean (default false).
--interactivePort
Sets the port used by the interactive server.
Integer (default 0).
--allowNonStandardModelica
Flags to allow non-standard Modelica.
String list (default empty). Valid options:
• nonStdMultipleExternalDeclarations (Allow several external declarations in functions.See: https://
specification.modelica.org/maint/3.5/functions.html#function-as-a-specialized-class)
• nonStdEnumerationAsIntegers (Allow enumeration as integer without casting via Inte-
ger(Enum).See: https://specification.modelica.org/maint/3.5/class-predefined-types-and-declarations.
html#type-conversion-of-enumeration-values-to-string-or-integer)
• nonStdIntegersAsEnumeration (Allow integer as enumeration without casting via Enum(Integer).See:
https://specification.modelica.org/maint/3.5/class-predefined-types-and-declarations.html#
type-conversion-of-integer-to-enumeration-values)
• nonStdDifferentCaseFileVsClassName (Allow directory or file with different case in the name
than the contained class name.See: https://specification.modelica.org/maint/3.5/packages.html#
mapping-package-class-structures-to-a-hierarchical-file-system)
• protectedAccess (Allow access of protected elements)
• reinitInAlgorithms (Allow reinit in algorithm sections)
--exportClocksInModelDescription
exports clocks in modeldescription.xml for fmus, The default is false.
Boolean (default false).
--linkType
Sets the link type for the simulation executable. dynamic: libraries are dynamically linked; the executable is built
very fast but is not portable because of DLL dependencies. static: libraries are statically linked; the executable is
built more slowly but it is portable and dependency-free.
String (default dynamic). Valid options:
• dynamic
• static
--tearingAlwaysDer
Always choose state derivatives as iteration variables in strong components.
Boolean (default false).
--dumpFlatModel
Dumps the flat model at the given stages of the frontend.
String list (default all). Valid options:
• flatten (After flattening but before connection handling.)
• connections (After connection handling.)
• eval (After evaluating constants.)
• simplify (After model simplification.)
• scalarize (After scalarizing arrays.)
-u, --simulation
Simulates the last model in the given Modelica file.
Boolean (default false).
--obfuscate
Obfuscates identifiers in the simulation model
String (default none). Valid options:
• none (No obfuscation.)
• encrypted (Obfuscates protected variables in encrypted models)
• protected (Obfuscates protected variables in all models.)
• full (Obfuscates everything.)
--fmuRuntimeDepends
Defines if runtime library dependencies are included in the FMU. Only used when compiler flag fmuCMake-
Build=true.
String (default modelica). Valid options:
• none (No runtime library dependencies are copied into the FMU.)
• modelica (All modelica runtime library dependencies are copied into the FMU.System librarys located in
'/lib*', '/usr/lib*' and '/usr/local/lib*' are excluded.Needs --fmuCMakeBuild=true and CMake version >=
3.21.)
• all (All runtime library dependencies are copied into the FMU.System librarys are copied as well.Needs
--fmuCMakeBuild=true and CMake version >= 3.21.)
--frontendInline
Enables inlining of functions in the frontend.
Boolean (default false).
debugDifferentiation (default: off) Dumps debug output for the differentiation process.
debugDifferentiationVerbose (default: off) Dumps verbose debug output for the differentiation process.
disableColoring (default: off) Disables coloring algorithm while spasity detection.
disableDirectionalDerivatives (default: on) For FMI 2.0 only dependecy analysis will be perform.
disableFMIDependency (default: off) Disables the dependency analysis and generation for FMI 2.0.
disableJacsforSCC (default: off) Disables calculation of jacobians to detect if a SCC is linear or non-linear. By
disabling all SCC will handled like non-linear.
disableRecordConstructorOutput (default: off) Disables output of record constructors in the flat code.
disableSingleFlowEq (default: off) Disables the generation of single flow equations.
disableStartCalc (default: off) Deactivates the pre-calculation of start values during compile-time.
disableWindowsPathCheckWarning (default: off) Disables warnings on Windows if OPENMODELICA-
HOME/MinGW is missing.
discreteinfo (default: off) Enables dumping of discrete variables. Extends -d=backenddaeinfo.
dummyselect (default: off) Dumps information from dummy state selection heuristic.
dump (default: off) Dumps the absyn representation of a program.
dumpASSC (default: off) Dumps the conversion process of analytical to structural singularities.
dumpBackendClocks (default: off) Dumps times for each backend module (only new backend).
dumpBackendInline (default: off) Dumps debug output while inline function.
dumpBackendInlineVerbose (default: off) Dumps debug output while inline function.
dumpCSE (default: off) Additional output for CSE module.
dumpCSE_verbose (default: off) Additional output for CSE module.
dumpConstrepl (default: off) Dump the found replacements for constants.
dumpConversionRules (default: off) Dumps the rules when converting a package using a conversion script.
dumpEArepl (default: off) Dump the found replacements for evaluate annotations (evaluate=true) parameters.
dumpEncapsulateConditions (default: off) Dumps the results of the preOptModule encapsulateWhenCondi-
tions.
dumpEqInUC (default: off) Dumps all equations handled by the unit checker.
dumpEqUCStruct (default: off) Dumps all the equations handled by the unit checker as tree-structure.
dumpEvents (default: off) Dumps information about the detected event functions.
dumpExcludedSymJacExps (default: off) This flags dumps all expression that are excluded from differentiation
of a symbolic Jacobian.
dumpFPrepl (default: off) Dump the found replacements for final parameters.
dumpFunctions (default: off) Add functions to backend dumps.
dumpHomotopy (default: off) Dumps the results of the postOptModule optimizeHomotopyCalls.
dumpInlineSolver (default: off) Dumps the inline solver equation system.
dumpJL (default: off) Dumps the absyn representation of a program as a Julia representation
dumpLoops (default: off) Dumps loop equation.
dumpLoopsVerbose (default: off) Dumps loop equation and enhanced adjacency matrix.
dumpPPrepl (default: off) Dump the found replacements for protected parameters.
dumpParamrepl (default: off) Dump the found replacements for remove parameters.
dumpRecursiveTearing (default: off) Dump between steps of recursiveTearing
dumpSCCGraphML (default: off) Dumps graphml files with the strongly connected components.
dumpSetBasedGraphs (default: off) Dumps information about set based graphs for efficient array handling (only
new frontend and new backend).
dumpSimCode (default: off) Dumps the simCode model used for code generation.
dumpSimplify (default: off) Dumps expressions before and after simplification.
dumpSimplifyLoops (default: off) Dump between steps of simplifyLoops
dumpSlice (default: off) Dumps information about the slicing process (pseudo-array causalization).
dumpSortEqnsAndVars (default: off) Dumps debug output for the modules sortEqnsVars.
dumpSparsePattern (default: off) Dumps sparse pattern with coloring used for simulation.
dumpSparsePatternVerbose (default: off) Dumps in verbose mode sparse pattern with coloring used for simula-
tion.
dumpSynchronous (default: off) Dumps information of the clock partitioning.
dumpUnits (default: off) Dumps all the calculated units.
dumpdaelow (default: off) Dumps the equation system at the beginning of the back end.
dumpdgesv (default: off) Enables dumping of the information whether DGESV is used to solve linear systems.
dumpeqninorder (default: off) Enables dumping of the equations in the order they are calculated.
dumpindxdae (default: off) Dumps the equation system after index reduction and optimization.
dumpinitialsystem (default: off) Dumps the initial equation system.
dumprepl (default: off) Dump the found replacements for simple equation removal.
dynload (default: off) Display debug information about dynamic loading of compiled functions.
evalFuncDump (default: off) dumps debug information about the function evaluation
evalOutputOnly (default: off) Generates equations to calculate top level outputs only.
evalParameterDump (default: off) Dumps information for evaluating parameters.
evalfunc (default: on) Turns on/off symbolic function evaluation.
evaluateAllParameters (default: off) Evaluates all parameters if set.
events (default: on) Turns on/off events handling.
execHash (default: off) Measures the time it takes to hash all simcode variables before code generation.
execstat (default: off) Prints out execution statistics for the compiler.
execstatGCcollect (default: off) When running execstat, also perform an extra full garbage collection.
experimentalReductions (default: off) Turns on custom reduction functions (OpenModelica extension).
failtrace (default: off) Sets whether to print a failtrace or not.
fmuExperimental (default: off) Adds features to the FMI export that are considered experimental as of now:
fmi2GetSpecificDerivatives, canGetSetFMUState, canSerializeFMUstate
force-fmi-attributes (default: off) Force to export all fmi attributes to the modelDescription.xml, including those
which have default values
forceNLSanalyticJacobian (default: off) Forces calculation analytical jacobian also for non-linear strong com-
ponents with user-defined functions.
frontEndUnitCheck (default: off) Checks the consistency of units in equation.
gcProfiling (default: off) Prints garbage collection stats to standard output.
gen (default: off) Turns on/off dynamic loading of functions that are compiled during translation. Only enable
this if external functions are needed to calculate structural parameters or constants.
gendebugsymbols (default: off) Generate code with debugging symbols.
generateCodeCheat (default: off) Used to generate code for the bootstrapped compiler.
graphInst (default: off) Do graph based instantiation.
graphInstGenGraph (default: off) Dumps a graph of the program. Use with -d=graphInst
graphInstRunDep (default: off) Run scode dependency analysis. Use with -d=graphInst
graphml (default: off) Dumps .graphml files for the bipartite graph after Index Reduction and a task graph for
the SCCs. Can be displayed with yEd.
graphviz (default: off) Dumps the absyn representation of a program in graphviz format.
graphvizDump (default: off) Activates additional graphviz dumps (as .dot files). It can be used in addition to
one of the following flags: {dumpdaelow|dumpinitialsystems|dumpindxdae}.
hardcodedStartValues (default: off) Embed the start values of variables and parameters into the c++ code and
do not read it from xml file.
hpcom (default: off) Enables parallel calculation based on task-graphs.
hpcomDump (default: off) Dumps additional information on the parallel execution with hpcom.
hpcomMemoryOpt (default: off) Optimize the memory structure regarding the selected scheduler
ignoreCycles (default: off) Ignores cycles between constant/parameter components.
implOde (default: off) activates implicit codegen
infoXmlOperations (default: off) Enables output of the operations in the _info.xml file when translating models.
initialization (default: off) Shows additional information from the initialization process.
inlineFunctions (default: on) Controls if function inlining should be performed.
inlineSolver (default: off) Generates code for inline solver.
instance (default: off) Prints extra failtrace from InstanceHierarchy.
interactive (default: off) Starts omc as a server listening on the socket interface.
interactiveCorba (default: off) Starts omc as a server listening on the Corba interface.
interactivedump (default: off) Prints out debug information for the interactive server.
iterationVars (default: off) Shows a list of all iteration variables.
listAppendWrongOrder (default: on) Print notifications about bad usage of listAppend.
lookup (default: off) Print extra failtrace from lookup.
mergeAlgSections (default: off) Disables coloring algorithm while sparsity detection.
mergeComponents (default: off) Enables automatic merging of components into arrays.
metaModelicaRecordAllocWords (default: off) Instrument the source code to record memory allocations (re-
quires run-time and generated files compiled with -DOMC_RECORD_ALLOC_WORDS).
multirate (default: off) The solver can switch partitions in the system.
newInst (default: on) Enables new instantiation phase.
nfAPI (default: on) Enables experimental new instantiation use in the OMC API.
nfAPIDynamicSelect (default: off) Show DynamicSelect(static, dynamic) in annotations. Default to false and
will select the first (static) expression
nfAPINoise (default: off) Enables error display for the experimental new instantiation use in the OMC API.
nfEvalConstArgFuncs (default: on) Evaluate all functions with constant arguments in the new frontend.
nfExpandFuncArgs (default: off) Expand all function arguments in the new frontend.
nfExpandOperations (default: on) Expand all unary/binary operations to scalar expressions in the new frontend.
nfScalarize (default: on) Run scalarization in NF, default true.
oldFrontEndUnitCheck (default: off) Checks the consistency of units in equation (for the old front-end).
optdaedump (default: off) Dumps information from the optimization modules.
parallelCodegen (default: on) Enables code generation in parallel (disable this if compiling a model causes you
to run out of RAM).
paramdlowdump (default: off) Enables dumping of the parameters in the order they are calculated.
partitionInitialization (default: on) This flag controls if partitioning is applied to the initialization system.
patternmAllInfo (default: off) Adds notifications of all pattern-matching optimizations that are performed.
patternmDeadCodeElimination (default: on) Performs dead code elimination in match-expressions.
patternmMoveLastExp (default: on) Optimization that moves the last assignment(s) into the result of a match-
expression. For example: equation c = fn(b); then c; => then fn(b);
patternmSkipFilterUnusedBindings (default: off)
printRecordTypes (default: off) Prints out record types as part of the flat code.
printStructuralParameters (default: off) Prints the structural parameters identified by the front-end
pthreads (default: off) Experimental: Unused parallelization.
relidx (default: off) Prints out debug information about relations, that are used as zero crossings.
relocatableFunctions (default: off) Generates relocatable code: all functions become function pointers and can
be replaced at run-time.
reportSerializedSize (default: off) Reports serialized sizes of various data structures used in the compiler.
reshufflePost (default: off) Reshuffles the systems of equations.
resolveLoopsDump (default: off) Debug Output for ResolveLoops Module.
rml (default: off) Converts Modelica-style arrays to lists.
runtimeStaticLinking (default: off) Use the static simulation runtime libraries (C++ simulation runtime).
scodeDep (default: on) Does scode dependency analysis prior to instantiation. Defaults to true.
semiLinear (default: off) Enables dumping of the optimization information when optimizing calls to semiLinear.
shortOutput (default: off) Enables short output of the simulate() command. Useful for tools like OMNotebook.
showDaeGeneration (default: off) Show the dae variable declarations as they happen.
showEquationSource (default: off) Display the element source information in the dumped DAE for easier de-
bugging.
showExpandableInfo (default: off) Show information about expandable connector handling.
showInstCacheInfo (default: off) Prints information about instantiation cache hits and additions. Defaults to
false.
showStartOrigin (default: off) Enables dumping of the DAE startOrigin attribute of the variables.
showStatement (default: off) Shows the statement that is currently being evaluated when evaluating a script.
skipInputOutputSyntacticSugar (default: off) Used when bootstrapping to preserve the input output parsing of
the code output by the list command.
stateselection (default: off) Enables dumping of selected states. Extends -d=backenddaeinfo.
static (default: off) Enables extra debug output from the static elaboration.
stripPrefix (default: on) Strips the environment prefix from path/crefs. Defaults to true.
susanDebug (default: off) Makes Susan generate code using try/else to better debug which function broke the
expected match semantics.
symJacConstantSplit (default: off) Generates all symbolic Jacobians with splitted constant parts.
symjacdump (default: off) Dumps information about symbolic Jacobians. Can be used only with postOptMod-
ules: generateSymbolicJacobian, generateSymbolicLinearization.
symjacdumpeqn (default: off) Dump for debug purpose of symbolic Jacobians. (deactivated now).
symjacdumpverbose (default: off) Dumps information in verbose mode about symbolic Jacobians. Can be used
only with postOptModules: generateSymbolicJacobian, generateSymbolicLinearization.
symjacwarnings (default: off) Prints warnings regarding symoblic jacbians.
tail (default: off) Prints out a notification if tail recursion optimization has been applied.
tearingdump (default: off) Dumps tearing information.
tearingdumpV (default: off) Dumps verbose tearing information.
totaltearingdump (default: off) Dumps total tearing information.
totaltearingdumpV (default: off) Dumps verbose total tearing information.
tplPerfTimes (default: off) Enables output of template performance data for rendering text to file.
transformsbeforedump (default: off) Applies transformations required for code generation before dumping flat
code.
types (default: off) Prints extra failtrace from Types.
uncertainties (default: off) Enables dumping of status when calling modelEquationsUC.
updmod (default: off) Prints information about modification updates.
useMPI (default: off) Add MPI init and finalize to main method (CPPruntime).
vectorize (default: off) Activates vectorization in the backend.
vectorizeBindings (default: off) Turns on vectorization of bindings when scalarization is turned off.
visxml (default: off) Outputs a xml-file that contains information for visualization.
warnMinMax (default: on) Makes a warning assert from min/max variable attributes instead of error.
warnNoNominal (default: off) Prints the iteration variables in the initialization and simulation DAE, which do
not have a nominal value.
writeToBuffer (default: off) Enables writing simulation results to buffer.
zmqDangerousAcceptConnectionsFromAnywhere (default: off) When opening a zmq connection, listen on all
interfaces instead of only connections from 127.0.0.1.
TWENTYEIGHT
This chapter contains a short overview of simulation flags as well as additional details of the numerical integration
methods.
457
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
-inputPath=value or -inputPath value Value specifies a path for reading the input files i.e., model_init.xml and
model_info.json
-ipopt_hesse=value or -ipopt_hesse value Value specifies the hessematrix for Ipopt(OMC, BFGS, const).
-ipopt_init=value or -ipopt_init value Value specifies the initial guess for optimization (sim, const).
-ipopt_jac=value or -ipopt_jac value Value specifies the Jacobian for Ipopt(SYM, NUM, NUMDENSE).
-ipopt_max_iter=value or -ipopt_max_iter value Value specifies the max number of iteration for ipopt.
-ipopt_warm_start=value or -ipopt_warm_start value Value specifies lvl for a warm start in ipopt: 1,2,3,...
-jacobian=value or -jacobian value Select the calculation method for Jacobian used by the integration method:
• coloredNumerical (Colored numerical Jacobian, which is default for dassl and ida. With option -
idaLS=klu a sparse matrix is used.)
• internalNumerical (Dense solver internal numerical Jacobian.)
• coloredSymbolical (Colored symbolical Jacobian. Needs omc compiler flag --
generateSymbolicJacobian. With option -idaLS=klu a sparse matrix is used.)
• numerical (Dense numerical Jacobian.)
• symbolical (Dense symbolical Jacobian. Needs omc compiler flag --generateSymbolicJacobian.)
-jacobianThreads=value or -jacobianThreads value Value specifies the number of threads for jacobian evalua-
tion in dassl or ida. The value is an Integer with default value 1.
-l=value or -l value Value specifies a time where the linearization of the model should be performed.
-l_datarec Emit data recovery matrices with model linearization.
-logFormat=value or -logFormat value Value specifies the log format of the executable:
• text (default)
• xml
• xmltcp (required -port flag)
-ls=value or -ls value Value specifies the linear solver method
• lapack (method using LAPACK LU factorization)
• lis (method using iterative solver Lis)
• klu (method using KLU sparse linear solver)
• umfpack (method using UMFPACK sparse linear solver)
• totalpivot (method using a total pivoting LU factorization for underdetermination systems)
• default (default method - LAPACK with total pivoting as fallback)
-ls_ipopt=value or -ls_ipopt value Value specifies the linear solver method for Ipopt, default mumps. Note: Use
if you build ipopt with other linear solver like ma27
-lss=value or -lss value Value specifies the linear sparse solver method
• default (the default sparse linear solver (or a dense solver if there is none available) )
• lis (method using iterative solver Lis)
• klu (method using klu sparse linear solver)
• umfpack (method using umfpack sparse linear solver)
-lssMaxDensity=value or -lssMaxDensity value Value specifies the maximum density for using a linear sparse
solver. The value is a Double with default value 0.2.
-lssMinSize=value or -lssMinSize value Value specifies the minimum system size for using a linear sparse
solver. The value is an Integer with default value 1000.
-lv=value or -lv value Value (a comma-separated String list) specifies which logging levels to enable. Multiple
options can be enabled at the same time.
• hybrid (Modification of the Powell hybrid method from minpack - former default solver)
• kinsol (SUNDIALS/KINSOL includes an interface to the sparse direct solver, KLU. See simulation
option -nlsLS for more information.)
• newton (Newton Raphson - prototype implementation)
• mixed (Mixed strategy. First the homotopy solver is tried and then as fallback the hybrid solver.)
• homotopy (Damped Newton solver if failing case fixed-point and Newton homotopies are tried.)
-nlsInfo Outputs detailed information about solving process of non-linear systems into csv files.
-nlsLS=value or -nlsLS value Value specifies the linear solver used by the non-linear solver:
• default (chooses the nls linear solver based on which nls is being used.)
• totalpivot (internal total pivot implementation. Solve in some case even under-determined systems.)
• lapack (use external LAPACK implementation.)
• klu (use KLU direct sparse solver. Only with KINSOL available.)
-nlssMaxDensity=value or -nlssMaxDensity value Value specifies the maximum density for using a non-linear
sparse solver. The value is a Double with default value 0.1.
-nlssMinSize=value or -nlssMinSize value Value specifies the minimum system size for using a non-linear
sparse solver. The value is an Integer with default value 1000.
-noemit Do not emit any results to the result file.
-noEquidistantTimeGrid Output the internal steps given by dassl/ida instead of interpolating results into an
equidistant time grid as given by stepSize or numberOfIntervals.
-noEquidistantOutputFrequency=value or -noEquidistantOutputFrequency value Integer value n controls
the output frequency in noEquidistantTimeGrid mode and outputs every n-th time step
-noEquidistantOutputTime=value or -noEquidistantOutputTime value Real value timeValue controls the out-
put time point in noEquidistantOutputTime mode and outputs every time>=k*timeValue, where k is an
integer
-noEventEmit Do not emit event points to the result file.
-noRestart Disables the restart of the integration method after an event is performed, used by the methods: dassl,
ida
-noRootFinding Disables the internal root finding procedure of methods: dassl and ida.
-noScaling Disables scaling for the variables and the residuals in the algebraic nonlinear solver KINSOL.
-noSuppressAlg Flag to not suppress algebraic variables in the local error test of the ida solver in daeMode. In
general, the use of this option is discouraged when solving DAE systems of index 1, whereas it is generally
encouraged for systems of index 2 or more.
-optDebugJac=value or -optDebugJac value Value specifies the number of iterations from the dynamic opti-
mization, which will be debugged, creating .csv and .py files.
-optimizerNP=value or -optimizerNP value Value specifies the number of points in a subinterval. Currently
supports numbers 1 and 3.
-optimizerTimeGrid=value or -optimizerTimeGrid value Value specifies external file with time points.
-output=value or -output value Output the variables a, b and c at the end of the simulation to the standard output:
time = value, a = value, b = value, c = value
-outputPath=value or -outputPath value Value specifies a path for writing the output files i.e., model_res.mat,
model_prof.intdata, model_prof.realdata etc.
-override=value or -override value Override the variables or the simulation settings in the XML setup file For
example: var1=start1,var2=start2,par3=start3,startTime=val1,stopTime=val2
-overrideFile=value or -overrideFile value Will override the variables or the simulation settings in the XML
setup file with the values from the file. Note that: -overrideFile CANNOT be used with -override. Use when
variables for -override are too many. overrideFileName contains lines of the form: var1=start1
-port=value or -port value Value specifies the port for simulation status (default disabled).
-r=value or -r value Value specifies the name of the output result file. The default file-name is based on the model
name and output format. For example: Model_res.mat.
-reconcile Run the Data Reconciliation numerical computation algorithm for constrained equations
-reconcileBoundaryConditions Run the Data Reconciliation numerical computation algorithm for boundary con-
dition equations
-reconcileState Run the State Estimation numerical computation algorithm for constrained equations
-gbm=value or -gbm value Value specifies the chosen solver of solver gbode (single-rate, slow states integrator).
• adams (Implicit multistep method of type Adams-Moulton (order 2))
• expl_euler (Explizit Runge-Kutta Euler method (order 1))
• impl_euler (Implizit Runge-Kutta Euler method (order 1))
• trapezoid (Implicit Runge-Kutta trapezoid method (order 2))
• sdirk2 (Singly-diagonal implicit Runge-Kutta (order 2))
• sdirk3 (Singly-diagonal implicit Runge-Kutta (order 3))
• esdirk2 (Explicit singly-diagonal implicit Runge-Kutta (order 2))
• esdirk3 (Explicit singly-diagonal implicit Runge-Kutta (order 3))
• esdirk4 (Explicit singly-diagonal implicit Runge-Kutta (order 4))
• radauIA2 (Implicit Runge-Kutta method of Radau family IA (order 3))
• radauIA3 (Implicit Runge-Kutta method of Radau family IA (order 5))
• radauIA4 (Implicit Runge-Kutta method of Radau family IA (order 7))
• radauIIA2 (Implicit Runge-Kutta method of Radau family IIA (order 3))
• radauIIA3 (Implicit Runge-Kutta method of Radau family IIA (order 5))
• radauIIA4 (Implicit Runge-Kutta method of Radau family IIA (order 7))
• lobattoIIIA3 (Implicit Runge-Kutta method of Lobatto family IIIA (order 4))
• lobattoIIIA4 (Implicit Runge-Kutta method of Lobatto family IIIA (order 6))
• lobattoIIIB3 (Implicit Runge-Kutta method of Lobatto family IIIB (order 4))
• lobattoIIIB4 (Implicit Runge-Kutta method of Lobatto family IIIB (order 6))
• lobattoIIIC3 (Implicit Runge-Kutta method of Lobatto family IIIC (order 4))
• lobattoIIIC4 (Implicit Runge-Kutta method of Lobatto family IIIC (order 6))
• gauss2 (Implicit Runge-Kutta method of Gauss (order 4))
• gauss3 (Implicit Runge-Kutta method of Gauss (order 6))
• gauss4 (Implicit Runge-Kutta method of Gauss (order 8))
• gauss5 (Implicit Runge-Kutta method of Gauss (order 10))
• gauss6 (Implicit Runge-Kutta method of Gauss (order 12))
• merson (Explicit Runge-Kutta Merson method (order 4))
• mersonSsc1 (Explicit Runge-Kutta Merson method with large stability region (order 1))
• mersonSsc2 (Explicit Runge-Kutta Merson method with large stability region (order 2))
• heun (Explicit Runge-Kutta Heun method (order 2))
• fehlberg12 (Explicit Runge-Kutta Fehlberg method (order 2))
• fehlberg45 (Explicit Runge-Kutta Fehlberg method (order 5))
• fehlberg78 (Explicit Runge-Kutta Fehlberg method (order 8))
• fehlbergSsc1 (Explicit Runge-Kutta Fehlberg method with large stability region (order 1))
• fehlbergSsc2 (Explicit Runge-Kutta Fehlberg method with large stability region (order 2))
• rk810 (Explicit 8-10 Runge-Kutta method (order 10))
• rk1012 (Explicit 10-12 Runge-Kutta method (order 12))
• rk1214 (Explicit 12-14 Runge-Kutta method (order 14))
• dopri45 (Explicit Runge-Kutta method Dormand-Prince (order 5))
• dopriSsc1 (Explicit Runge-Kutta method Dormand-Prince with large stability region (order 1))
• dopriSsc2 (Explicit Runge-Kutta method Dormand-Prince with large stability region (order 2))
• tsit5 (Explicit Runge-Kutta method from Tsitouras (order 5))
• rungekutta (Explicit classical Runge-Kutta method (order 4))
• rungekuttaSsc (Explicit Runge-Kutta method with large stabiliy region (order 1))
-gbctrl=value or -gbctrl value Step size control of solver gbode (single-rate, slow states integrator).
• i (I controller for step size)
• pi (PI controller for step size)
• pid (PID controller for step size)
• const (Constant step size)
-gberr=value or -gberr value Error estimation method for solver gbode (single-rate, slow states integrator) Pos-
sible values:
• default - depending on the Runge-Kutta method
• richardson - Richardson extrapolation
• embedded - Embedded scheme
-gbint=value or -gbint value Interpolation method of solver gbode (single-rate, slow states integrator).
• linear (Linear interpolation (1st order))
• hermite (Hermite interpolation (3rd order))
• hermite_a (Hermite interpolation (only for left hand side))
• hermite_b (Hermite interpolation (only for right hand side))
• hermite_errctrl (Hermite interpolation with error control)
• dense_output (use dense output formula for interpolation)
• dense_output_errctrl (use dense output fomular with error control)
-gbnls=value or -gbnls value Non-linear solver method of solver gbode (single-rate, slow states integrator).
• newton (Newton method, dense)
• kinsol (SUNDIALS KINSOL: Inexact Newton, sparse)
-gbfm=value or -gbfm value Value specifies the chosen solver of solver gbode (multi-rate, fast states integrator).
Current Restriction: Fully implicit (Gauss, Radau, Lobatto) RK methods are not supported, yet.
• adams (Implicit multistep method of type Adams-Moulton (order 2))
• expl_euler (Explizit Runge-Kutta Euler method (order 1))
• impl_euler (Implizit Runge-Kutta Euler method (order 1))
• trapezoid (Implicit Runge-Kutta trapezoid method (order 2))
• sdirk2 (Singly-diagonal implicit Runge-Kutta (order 2))
• sdirk3 (Singly-diagonal implicit Runge-Kutta (order 3))
• esdirk2 (Explicit singly-diagonal implicit Runge-Kutta (order 2))
• esdirk3 (Explicit singly-diagonal implicit Runge-Kutta (order 3))
• esdirk4 (Explicit singly-diagonal implicit Runge-Kutta (order 4))
-gbferr=value or -gbferr value Error estimation method for solver gbode (multi-rate, fast states integrator) Pos-
sible values:
• default - depending on the Runge-Kutta method
• richardson - Richardson extrapolation
• embedded - Embedded scheme
-gbfint=value or -gbfint value Interpolation method of solver gbode (multi-rate, fast states integrator).
• linear (Linear interpolation (1st order))
• hermite (Hermite interpolation (3rd order))
• hermite_a (Hermite interpolation (only for left hand side))
• hermite_b (Hermite interpolation (only for right hand side))
• hermite_errctrl (Hermite interpolation with error control)
• dense_output (use dense output formula for interpolation)
• dense_output_errctrl (use dense output fomular with error control)
-gbfnls=value or -gbfnls value Non-linear solver method of solver gbode (multi-rate, fast states integrator).
• newton (Newton method, dense)
• kinsol (SUNDIALS KINSOL: Inexact Newton, sparse)
-gbratio=value or -gbratio value Define percentage of states for the fast states selection of solver gbode (values
from 0 to 1).
-rt=value or -rt value Value specifies the scaling factor for real-time synchronization (0 disables). A value > 1
means the simulation takes a longer time to simulate.
-s=value or -s value Value specifies the integration method. For additional information see the User's Guide
• euler - Euler - explicit, fixed step size, order 1
• heun - Heun's method - explicit, fixed step, order 2
• rungekutta - classical Runge-Kutta - explicit, fixed step, order 4
• impeuler - Euler - implicit, fixed step size, order 1
• trapezoid - trapezoidal rule - implicit, fixed step size, order 2
• imprungekutta - Runge-Kutta methods based on Radau and Lobatto IIA - implicit, fixed step size,
order 1-6(selected manually by flag -impRKOrder)
• gbode - generic bi-rate ODE solver - implicit, explicit, step size control, arbitrary order
• irksco - own developed Runge-Kutta solver - implicit, step size control, order 1-2
• dassl - default solver - BDF method - implicit, step size control, order 1-5
• ida - SUNDIALS IDA solver - BDF method with sparse linear solver - implicit, step size control, order
1-5
• cvode - experimental implementation of SUNDIALS CVODE solver - BDF or Adams-Moulton
method - step size control, order 1-12
• rungekuttaSsc - Runge-Kutta based on Novikov (2016) - explicit, step size control, order 4-5 [experi-
mental]
• symSolver - symbolic inline Solver [compiler flag +symSolver needed] - fixed step size, order 1
• symSolverSsc - symbolic implicit Euler with step size control [compiler flag +symSolver needed] -
step size control, order 1
• qss - A QSS solver [experimental]
• optimization - Special solver for dynamic optimization
-single Output results in single precision (mat-format only).
-steps Dumps the number of integration steps into the result file.
-steadyState Aborts the simulation if steady state is reached.
-steadyStateTol=value or -steadyStateTol value This relative tolerance is used to detect steady state:
max(|d(x_i)/dt|/nominal(x_i)) < steadyStateTol
-sx=value or -sx value Value specifies an csv-file with inputs as covariance matrix Sx for DataReconciliation
-keepHessian=value or -keepHessian value Value specifies the number of steps, which keep Hessian matrix con-
stant.
-w Shows all warnings even if a related log-stream is inactive.
-parmodNumThreads=value or -parmodNumThreads value Value specifies the number of threads for simula-
tion using parmodauto. If not specified (or is 0) it will use the systems max number of threads. Note that
this option is ignored if the model is not compiled with --parmodauto
TWENTYNINE
TECHNICAL DETAILS
This chapter gives an overview of some implementation details that might be interesting when building tools
around OpenModelica.
469
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
data_1 If it is an n x 1 matrix it contains the values of parameters. If it is an n x 2 matrix, the first and second
column signify start and stop-values.
data_2 Each row contains the values of a variable at the sampled times. The corresponding time stamps are stored
in data_2(1,:). data_2(2,1) is the value of some variable at time data_2(1,1).
THIRTY
DATA RECONCILIATION
Water flows from left to right, from the source to the sinks. The model is made of five different model components.
To perform data reconciliation, two kinds of variables must be declared:
1. The boundary conditions (which represent assumptions on the environment);
2. The variables of interest to be reconciled.
These two kinds of variables must be manually declared in the source code
1. With annotations for the boundary conditions;
2. With modifiers for the variables of interest.
The boundary conditions are declared with the annotation: annotation(__OpenModelica_BoundaryCondition =
true). For the pressure source, the boundary conditions are the pressure P0, and the specific enthalpy h0 or the
temperature T0 of the source (depending on the option chosen by the user).
471
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Boundary conditions are declared with annotations so that libraries can be modified to accomodate data reconcil-
iation, and still can be used with tools that do not support data reconciliation (because annotations not recognized
by a tool are ignored by that tool). The variables of interest are declared with the modifier "uncertain = Uncer-
tainty.refine"
A modifier is used instead of an annotation so that checks can be performed to detect errors such as declaring a
variable that does not exist to be a variable to be reconciled. The drawback is that tools that do not support data
reconciliation will produce an error. To avoid this problem, variables of interest should be declared in a separate
model (Splitter_DR in the example below) that instantiates the orginal model (Splitter), so that the original model
(Splitter) is not modified and can still be used with tools that do not support data reconciliation.
model Splitter_DR
Splitter splitter(
pipe1(Q(uncertain = Uncertainty.refine)),
pipe2(Q(uncertain = Uncertainty.refine)),
pipe3(Q(uncertain = Uncertainty.refine)),
pipe1(Pm(uncertain = Uncertainty.refine)),
pipe2(Pm(uncertain = Uncertainty.refine)),
pipe3(Pm(uncertain = Uncertainty.refine)),
pipe1(T(uncertain = Uncertainty.refine)),
pipe2(T(uncertain = Uncertainty.refine)),
pipe3(T(uncertain = Uncertainty.refine)));
end Splitter_DR;
In addition to declaring boundary conditions and variables of interest, one must provide two input files:
1. The measurement input file (mandatory).
2. The correlation matrix input file (optional).
The measurement input file is a csv file with three columns:
1. One column for the variable names [ident]
2. One column for measured values [positive floating point number]
3. One column for the half-width confidence intervals [positive floating point number].The half-with
confidence interval for variable 𝑥𝑖 is defined as 𝑤𝑖 = 𝜆95% 𝜎𝑖 , where 𝜎𝑖 is the standard deviation of 𝑥𝑖
and 𝜆95% = 1.96
The header of the file is the row
Variable Names; Measured Value-x; Half Width Confidence Interval
It is possible to insert comments with // at the beginning of a row
// Measurement input file for the Splitter model.
Variable Name;Measured Value;Half Width Confidence Interval
splitter.pipe1.Q; 2.50; 0.196
splitter.pipe2.Q; 1.15; 0.196
splitter.pipe3.Q; 1.25; 0.196
splitter.pipe1.Pm; 6.1e5; 0.392e5
splitter.pipe2.Pm; 2.55e5; 0.392e5
splitter.pipe3.Pm; 2.45e5; 0.392e5
splitter.pipe1.T; 292; 1.96
splitter.pipe2.T; 386; 1.91
splitter.pipe3.T; 388; 1.91
The above file can be more easily visualized in matrix form:
The correlation matrix file is a csv file that contains the off-diagonal lower triangular correlation coefficients of
the variables of interest:
1. The first row contains names of variables of interest [ident].
2. The first column contains names of variables of interest [ident].
3. The names in the first row and first column must be identical in the same order.
4. The first cell in the first row (which is also the first cell in the first column) must not be empty, but can
contain any character string (except column separators).
5. The off-diagonal lower triangular matrix cells contain the correlation coefficients [positive or nul floating
point number]. The correlation coefficients 𝑟𝑖𝑗 are defined such that 𝑠𝑖𝑗 = 𝑟𝑖𝑗 𝜎𝑖 𝜎𝑗 where 𝜎𝑖 and 𝜎𝑗 are
respectively the standard deviations of variables 𝑥𝑖 and 𝑥𝑗 , and 𝑠𝑖𝑗 is the covariance matrix. 𝑟𝑖𝑖 = 1
because 𝑠𝑖𝑖 = 𝜎𝑖2 |𝑟𝑖𝑗 | <= 1
6. The upper triangular and diagonal cells are ignored because the correlation matrix is symmetric 𝑟𝑗𝑖 = 𝑟𝑖𝑗 ,
and its diagonal is 𝑟𝑖𝑖 = 1
7. Only variables of interest with positive correlation coefficients must appear in the matrix. Unfilled cells are
equal to zero. Variables of interest that do not appear in the matrix have correlation coefficients equal to
zero. Therefore, if all correlation coefficients are equal to zero, the matrix can be empty and the correlation
matrix file is not needed
The following correlation file is drawn from the VDI2048 standard example of a heat circuit of a steam turbine
plant.
Sxy;mV;mHK;mSPLL;mSPL;mFDKELL;mFDKEL
mV
mHK
mSPLL
mSPL;;;0.39951
mFDKELL;;;0;0
mFDKEL;;;0;0;0.2
The above file can be more easily visualized in matrix form:
The variables mV and mHK could have been omitted because they do not have any positive correlation coefficients.
a. The number r of auxiliary equations is not strictly less than the number of variables of
interest.
b. The number r of auxiliary equations is zero.
Both errors occur when there are too many boundary conditions related to the variables of inter-
est. Variables of interest that are not involved in any of the auxiliary conditions or intermediate
equations are not reconciled.
2. The model is simulated to compute the Jacobian matrices and eliminate numerically the intermedi-
ate variables. At this step, numerical simulation errors can occur, such as divisions by zero, non-
convergence, etc. They can be corrected by improving the model or providing better start values.
3. The input files are read, the data reconciliation calculation is performed, and the results are displayed. Errors ca
i. All variables of interest declared in the model should be declared in the measurement
input file and reciprocally.
ii. All variables of interest declared in the correlation matrix file should be declared in the
model (the converse is not true).
c. If a variable of interest has multiple entries in an input file.
d. If the first row and the first column are different in the correlation matrix file.
e. If the numerical cells of the matrices are not positive real numbers.
30.3.1 Overview:
Model file: VDI2048Example.mo
Model name: NewDataReconciliationSimpleTests.VDI2048Example
Model directory: NewDataReconciliationSimpleTests
Measurement input file: VDI2048Example_Inputs.csv
Correlation matrix input file: VDI2048Example_Correlation.csv
Generated: Thu Jan 20 18:41:45 2022by OpenModelica v1.19.0-dev-500-g6c3a4e429f (64-bit)
30.3.2 Analysis:
Number of auxiliary conditions: 3
Number of variables to be reconciled: 11
Number of related boundary conditions: 0
Number of iterations to convergence: 2
Final value of (J*/r) : 4.56744e-28
Epsilon : 1e-10
Final value of the objective function (J*) : 1.37023e-27
Chi-square value : 7.81473
Result of global test : TRUE
30.3.6 Results
mD is not reconciled because it does not appear in any of the auxiliary conditions or intermediate equations.
For the VDI2048 example, the name of the csv output file is
<working direc-
tory>\NewDataReconciliationSimpleTests.VDI2048Example\NewDataReconciliationSimpleTests.VDI2048Example_Output
and the name of the reconciled covariance matrix csv file is
<working direc-
tory>\NewDataReconciliationSimpleTests.VDI2048Example\NewDataReconciliationSimpleTests.VDI2048Example_
Reconciled_Sx.csv
The Modelica model of the VDI2048 example is given below.
model VDI2048Example
Real mFDKEL(uncertain=Uncertainty.refine)=46.241;
Real mFDKELL(uncertain=Uncertainty.refine)=45.668;
Real mSPL(uncertain=Uncertainty.refine)=44.575;
Real mSPLL(uncertain=Uncertainty.refine)=44.319;
Real mV(uncertain=Uncertainty.refine);
Real mHK(uncertain=Uncertainty.refine)=69.978;
Real mA7(uncertain=Uncertainty.refine)=10.364;
Real mA6(uncertain=Uncertainty.refine)=3.744;
Real mA5(uncertain=Uncertainty.refine);
Real mHDNK(uncertain=Uncertainty.refine);
Real mD(uncertain=Uncertainty.refine)=2.092;
(continues on next page)
0 = mFD1 - mFD2;
0 = mFD2 - mFD3;
0 = mHDANZ - mHDNK;
end VDI2048Example;
Note that the binding equations that assign fixed values to the variables have been automatically eliminated by
the extraction algorithm. These equations are necessary to have a valid square Modelica model, but must be
eliminated for data reconciliation.
The table below compares the results obtained with OpenModelica with those given by the VDI2048 standard.
The value of mD is left unchanged after reconciliation. This is indicated by ‘Not reconciled’ in OpenModelica,
and by repeating the initial measured values in VDI2048. In order to compute the reconciled values of mFD1,
mFD2, mFD3 and mHDANZ, which have no measurements, it is possible to consider them as variables of interest
with very large half-width confidence, e.g., 1e4, and assign them arbitrary measured values, e.g. 0. The result is
For the splitter, the results are the following:
a. The boundary conditions that are the equations that compute the boundary conditions.
b. The intermediate equations that solve the intermediate variables from the variables of interest
(this is the numeric way of eliminating the intermediate variables).
2. The model is simulated to compute the Jacobian matrices and eliminate numerically the intermediate
equations. At this step, numerical simulation errors can occur, such as divisions by zero, non-convergence,
etc. They can be corrected by improving the model or providing better start values.
3. The input files are read, the numerical calculations are performed, and the results are displayed. The
half-width confidence intervals for the boundary conditions are calculated by propagating the recon-
ciled uncertainties on the variables of interest through the inverted model.
The results are displayed:
1. In an html file with the title: Boundary Condition Report. This file pops up automatically when the
calculation is completed.
2. In a csv output file. The name of the csv output file is <working directory>\<model name>\< model
name>_ BoundaryConditions_Outputs.csv
The Boundary Condition Report has three sections:
30.4.1 Overview
a. Model file: name of the Modelica model file
b. Model name: name of the Modelica model
c. Model directory: name of the directory of the Modelica model file
d. Reconciled values input file: name of the csv output file produced by the data reconciliation algorithm
e. Reconciled covariance matrix input file: name of the correlation matrix csv file produced by the data recon-
ciliation algorithm
f. Generated: date and time of the generation of the boundary condition report
30.4. Computing the Boundary Conditions from the Reconciled Values 481
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
30.4.2 Analysis
a. Number of boundary conditions.
b. Number of reconciled variables.
c. Boundary conditions: set of the boundary conditions (i.e., the equations that compute the boundary condi-
tions).
d. Intermediate equations: set of the intermediate equations (i.e., the equations that compute the intermediate
variables from the variables of interest).
30.4.4 Results
A table with the following columns
a. Boundary Conditions: the names of the boundary conditions.
b. Values: the computed values of the boundary conditions.
c. Reconciled Half-width Confidence Intervals: the half-with confidence intervals for the boundary con-
ditions.
The results for the splitter are:
30.5 Contacts
Daniel Bouskela ([email protected])
Audrey Jardin ([email protected]
Arunkumar Palanisamy ([email protected])
Lennart Ochel ([email protected])
Adrian Pop ([email protected])
30.6 References
Bouskela, D., Jardin, A., Palanisamy, A., Ochel, L., & Pop, A. (2021). New Method to Perform Data Recon-
ciliation with OpenModelica and ThermoSysPro. Proceedings of 14th Modelica Conference 2021, Linköping,
Sweden, September 20-24, 2021.
VDI - Verein Deutscher Ingenieure. (2000). Uncertainty of measurement during acceptance tests on energy-
conversion and power plants - Part 1: Fundamentals. VDI 2048 Blatt 1, October 2000.
THIRTYONE
Below are some frequently asked questions in three areas, with associated answers.
31.2 OMNotebook
• Q: OMNotebook hangs, what to do?
• A: It is probably waiting for the omc.exe (compiler) process. (Under windows): Kill the processes
omc.exe, g++.exe (C-compiler), as.exe (assembler), if present. If OMNotebook then asks whether
to restart OMC, answer yes. If not, kill the process OMNotebook.exe and restart manually.
• Q: After a previous session, when starting OMNotebook again, I get a strange message.
• A: You probably quit the previous OpenModelica session in the wrong way, which left the process
omc.exe running. Kill that process, and try starting OMNotebook again.
• Q: I copy and paste a graphic figure from Word or some other application into OMNotebook, but the
graphic does not appear. What is wrong?
• A: OMNotebook supports the graphic picture formats supported by Qt 4, including the .png, .bmp
(bitmap) formats, but not for example the gif format. Try to convert your picture into one of the
supported formats, (e.g. in Word, first do paste as bitmap format), and then copy the converted version
into a text cell in OMNotebook.
• Q: I select a cell, copy it (e.g. Ctrl-C), and try to paste it at another place in the notebook. However,
this does not work. Instead some other text that I earlier put on the clipboard is pasted into the nearest
text cell.
• A: The problem is wrong choice of cursor mode, which can be text insertion or cell insertion. If you
click inside a cell, the cursor become vertical, and OMNotebook expects you to paste text inside
483
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
the cell. To paste a cell, you must be in cell insertion mode, i.e., click between two cells (or after a
cell), you will get a vertical line. Place the cursor carefully on that vertical line until you see a small
horizontal cursor. Then you should past the cell.
• Q: I am trying to click in cells to place the vertical character cursor, but it does not seem to react.
• A: This seems to be a Qt feature. You have probably made a selection (e.g. for copying) in the output
section of an evaluation cell. This seems to block cursor position. Click again in the output section to
disable the selection. After that it will work normally.
• Q: I have copied a text cell and start writing at the beginning of the cell. Strangely enough, the font be-
comes much smaller than it should be.
• A: This seems to be a Qt feature. Keep some of the old text and start writing the new stuff inside the
text, i.e., at least one character position to the right. Afterwards, delete the old text at the beginning of
the cell.
THIRTYTWO
This Appendix lists the most important OpenModelica releases and a brief description of their contents. Right
now versions from 1.3.1 to v1.21.0 are described.
485
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
output for accurate resampling over a regular time grid. Implemented methods include Euler, Heun, Dormand-
Prince, Gauss, Radau, Lobatto, Adams-Moulton, Fehlberg, SDIRK, ESDIRK, etc. Adaptive multi-rate algorithms
are also available within this solver, although this feature is still experimental. This solver replaces previously
available solvers like euler, impeuler, trapezoid, etc., which are now deprecated and will be removed in
future versions of the tool.
The solver is currently only available via simulation flags, which can be set in OMEdit under Simulation Setup
| Simulation Flags | Additional Simulation Flags (optional). It will be supported via drop-down menus in future
releases. See the User's Guide under Solving Modelica Models for further information.
32.2.2 C Runtime
Besides introducing the new gbode solver, some other issues were fixed. The support for external input from
CSV files was improved and better documented. See here for a full list of closed issues.
32.2.4 FMI
Main highlights: - The FMI import feature allows to import an FMU as a block in a Modelica model. This
feature was broken in versions 1.18.0 and 1.19.0, it is now functional again, with some limitations, see the User's
Guide for further information. Support for this feature must be explicitly activated with the Enable FMU Import
checkbox in the Tools | Options | Simulation | Translation Flags tab of OMEdit. - Support of FMI code generation
using CMake, see the documentation in the User's Guide.
• Bug fixes.
See here for a full list of closed FMI issues.
The plotting of results has been significantly improved; appropriate prefixes are now automatically selected to
avoid getting very large or very small numbers on the Y-axis.
Overall, over 40 issues were fixed since the previous 1.18.1 release.
Work is on going to provide full support of parameter-depending conditional connectors, parameter-depending
dialog annotations, and editing of parameter modifiers in redeclared classes. Implementing these features requires
a fundamental re-design of the way OMEdit interacts with the OMC environment to get the required information.
These features should become available, at least experimentally, in the future 1.20.0 release.
• Introduced support for interpolation in CS-FMUs by setting "canInterpolateInputs=true" in modeldescrip-
tion.xml - Introduced support for getting partial derivatives in ME-FMUs by setting "providesDirection-
alDerivative=true" - Lots of improvements to OpenModelica FMU export configurations (black box as well
as source code FMUs). - Added source-code nonlinear solver CMINPACK to source-code FMUs
• Basic source-code FMU compilation with CMake; cross compilation with Docker now available on Win-
dows.
About 10 issues fixed.
• Support of importing and exporting Units and UnitDefinitions to SSP files. - Support for getting directional
derivative in OMSimulator using both Symbolic Jacobians and numerical approximation using KINSOL
solver.
List of closed tickets in 1.19.0. About 180 issues were resolved.
A 1.19.1 bugfix version may be released if critical bugs are identified and resolved before July 2022. The next
release 1.20.0 is planned to be beta-released in July 2022, and release in September 2022. On-going work to
further improve the level of support of the Buildings library should ensure a significant improvement in the level
of support of most Modelica libraries in that upcoming release.
Download it from: https://www.openmodelica.org
very large or very small numbers on the plot axes; - the rendering of plots and parameter windows on large and/or
high-resolution screens was further improved.
Several bugs were also fixed; in total, 27 issues were addressed.
FMI 2.0 export was further improved. OMSimulator development continues, over 30 issues were fixed.
The operation of power plants requires a good quality of the process data obtained through sensor measurements.
Unfortunately, sensor measurements such as flow rates, temperatures, and pressures are subject to errors that
lead to uncertainties in the assessment of the system's state. Operational margins are therefore set to take into
account uncertainties on the system's state. Their effect is to decrease production because safety regulations put
stringent limits on the thermal power of the plants. It is therefore important to compute the best estimates of
the measurement uncertainties in order to increase power production by reducing operational margins as much as
possible while still preserving system safety.
The best estimates can be obtained by combining data statistics with a knowledge a priori of the system in the
form of a physical model. Data reconciliation is a technique that has been conceived in the process industry for
that purpose. It is fully described in the VDI 2048 standard for the control and quality improvement of process
data and their uncertainties by means of correction calculation for operation and acceptance tests".
An extension of Modelica to perform data reconciliation on Modelica models was developed together with EDF
and is now fully implemented and integrated with the OMEdit GUI. The basic ideas are explained in this presen-
tation, and a section DataReconciliation was added to the User's Guide, explaing how to use it step-by-step.
We are currently transitioning from the old trac issue tracker to the GitHub issue tracker, which is fully integrated
with the GitHub revision control and continuous integration framework that we use for the development of Open-
Modelica. Eventually, the old trac tickets will be migrated onto the GitHub issue tracker. For the time being,
old tickets are still managed on trac, while new ones are on GitHub. Overall, about 80 issues were addressed
successfully since the 1.17.0 release.
• older tickets
• newer tickets
A 1.18.1 bugfix release is planned later this year with some critical bug fixes that have been identified and partially
addressed, but need some more testing. The next release 1.19.0 is planned to be released in February 2022, close
to the OpenModelica Workshop and Annual Meeting.
Version 1.19.0 is expected to contain a GUI integrated in OMEdit for library handling and conversions. It is also
planned to successfully run 100% or close to 100% of the Buildings 7.0.1 library. This will be a major milestone,
given the broad extent and complexity of that library.
Download it from: https://www.openmodelica.org
that do so. Automatic conversion of existing libraries from MSL 3.2.3 to MSL 4.0.0 is currently not yet available,
it is planned for version 1.18.0.
Please note that the synchronous features in MSL 4.0.0 are still not fully supported, so we suggest not to rely on
them in this version of the tool. Better support is planned for version 1.18.0.
The user experience with OMEdit is significantly improved in version 1.17.0, in particular for the Windows ver-
sion, where the compilation time was drastically reduced by using clang instead of gcc and by dynamic linking
instead of static linking of the simulation executable.
Thanks to the upgrade of the employed QT graphics libraries, several issues that plagued the graphical user
interface are now resolved.
Replaceable classes continue to have graphical support in OMEdit, even though parameters in redeclared classes
cannot yet be modified from the GUI, thus requiring to switch to text mode to do so. The new front end can also
be used for some of the API functions called by OMEdit to render the model diagrams, making the response of
the GUI much faster. Please note that both these features are currently optional and needs to be activated
by setting Tools | Options | General | Enable replaceable support and Enable new frontend use in the OMC API
(faster GUI response). These settings are retained from the previous installation upon version upgrading.
Unsaved code was sometimes lost when switching among different windows in OMEdit, this is no longer happen-
ing in this release. Several issues that caused occasional crashes of the GUI were also fixed.
OMEdit now can use both currently maintained versions of the Modelica Standard Library, MSL 3.2.3 and MSL
4.0.0. Please note that the Modelica.Clocked package in MSL 4.0.0 is still not handled in a completely reliable
way, while most other models work equally well in the two versions.
When starting the program for the first time after installation, one can choose among three options: load MSL
3.2.3 automatically, which however prevents using libraries that need MSL 4.0.0; load MSL 4.0.0 automatically,
which prevents using libraries that need MSL 3.2.3; not loading any version of the library upon starting OMEdit,
leaving it to the tool to load the right one when a model or library is opened, thanks to the uses() annotation. The
latter option allow to handle different projects that use either version of the MSL without problems, of course one
at a time. This choice can be later modified by going to the Tools | Options | Libraries menu and by adding or
removing the Modelica library from the automatically loaded system libraries, and/or by modifying the specific
version that gets loaded.
Proper support of the package manager from the GUI, including conversion scripts to upgrade existing libraries
from MSL 3.2.3 to MSL 4.0.0, is planned for version 1.18.0.
16 bug fixes were made to OMEdit in version 1.17.0, to increase usability of the GUI.
Until version 1.16.x, OpenModelica was built on Windows, Linux, and macOS. The core functionality of the tool
is implemented in Linux, and is ported to Windows using the MinGW environment, and on macOS using the
macports environment.
Unfortunately, many libraries OpenModelica depends on are not regularly updated on macports, which caused
the Mac build to break every other day. Given our limited resources, we can't take on the burden of the required
macports maintenance, so we regret to inform you that we decided to stop providing builds of OpenModelica for
macOS. It is still possible to run OpenModelica on the Mac by running a virtual machine with a Linux installation
of OpenModelica, see the instructions on the Mac download page. We are still trying to make it possible to
build OpenModelica from sources on macOS, please check ticket #6306 for the latest updates and if you want to
contribute to the effort. However, we do not guarantee this will be always possible in the future.
FMI 2.0 export and FMI simulation with OMSimulator was further improved.
OMSimulator is now integrated into pypi and installed via pip.
A prototype Flat Modelica code export feature is now available, a result of the Emphysis project and eFMI on-
going standardization effort. It can be activated with the compilation flag.
The Modelica package manager is still only available from the command line in this release. We plan to integrate
it the OMEdit GUI for the 1.18.0 release, together with conversion scripts.
Download it from: https://www.openmodelica.org
OMSimulator GUI improved: text editing of SSP models, undo/redo, delete components, etc.
Many FMI export bug fixes and improvements to increase usability of OMC-generated FMUs.
FMI/CS 2.0 now includes CVODE solvers (previously only fixed-step forward Euler) and customization via sim-
ulation flags.
Successful integration of Modelon's license manager for encrypted libraries. A special version of OMC avail-
able to Consortium members can now handle encrypted libraries, preventing source code browsing, and license
management, via Modelon's license manager, embedded in the encrypted library.
Improved Modelica package management. The conversion(noneFromVersion) annotation is now fully
supported, which means for example that OpenModelica will automatically use the Modelica Standard Library
3.2.3 even for libraries that have a uses annotation pointing to earlier MSL versions, e.g. 3.2.2 or 3.2.1, because the
conversion(noneFromVersion) annotations in the MSL specify that 3.2.3 can be used instead of 3.2.2
or 3.2.1 without any conversion script, i.e., it is fully backwards compatible. A full-fledged Modelica package
manager is also included in OpenModelica 1.16.0, currently only with a command line interface; integration in
the GUI is planned for the next 1.17.0 release, together with conversion scripts.
• Drag and drop for the text layer. • Auto completion of class names, components and annotations. • GUI
for data reconciliation – a method for increasing sensor data precision • Improved duplication functionality
for copying classes. • Better handling of Compiler flags. • Partly completed: annotations for dynamic icon
update. • Support for connectorSizing annotation • Several bug fixes. You can find the list here. • Docs:
https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/omedit.html. • Autocomplete annotations. •
Support for Icon/Diagram map annotation • Copy paste functionality • Reset OMEdit settings/options. •
Array plots update on re-simulation • Support for connectorSizing annotation. • Drag and drop class names
to text layer in OMEdit • OMPlot: Improved plotting e.g., top and bottom margins for better view, snap
to curve etc. • GUI support for replaceable libraries is being tested in a separate branch and will be made
available in the coming 1.15.0 release.
• A new more efficient and correct implementation of arrays and records.
• The FMI OMSimulator API calls are now also available in the OMC API functions, e.g. for use from
OMNotebook, Jupyter notebooks.
• Added possibility to generate analytic Jacobians for linear strong components • Use flag LSanalyticJaco-
bian to enable analytical Jacobian for linear loops. Default false.
• Added output language options for linearization: matlab, python, julia. • Available with --
linearizationDumpLanguage=modelica/matlab/python/julia. Default is modelica.
• Unified Jacobian evaluation from DASSL and IDA integrators • Added result check for linear solvers Lis,
Klu, Total Pivot and Umfpack if a residual function is available. • Improved debug dumping
Note: the replaceable GUI support has been moved to OpenModelica 1.14.0 and will be available in nightly builds.
• Code generation in parallel is enabled since #3356 (controlled by omc flag `-n`). This improves performance
since generating code directly to file avoid memory allocation.
• Allowing mixed dense and sparse linear solvers in the generated simulation (chosen depending on simflags
`-ls` (dense solver), `-lss` (sparse solver), `-lssMaxDensity` and `-lssMinSize`).
32.17.4 Optimization
32.19.4 Optimization
Several improvements of the Dynamic Optimization module with collocation, using Ipopt:
• Better performance due to smart treatment of algebraic loops for optimization.
• Improved formulation of optimization problems with an annotation approach which also allows graphical
problem formulation.
• Proper handling of constraints at final time.
• The OpenModelica graphic connection editor OMEdit has become 3-5 times faster due to faster commu-
nication with the OpenModelica compiler linked as a DLL. This was made possible by moving to the
bootstrapped compiler.
• Further improved simulation coverage for a number of libraries.
• OMEdit graphic connection editor improvements
32.20.3 Optimization
Some smaller improvements of the Dynamic Optimization module with collocation, using Ipopt.
32.21.3 OMPython
The interface was changed to version 2.0, which uses one object for each OpenModelica instance you want active.
It also features a new and improved parser that returns easier to use datatypes like maps and lists.
32.21.4 Optimization
A builtin integrated Dynamic Optimization module with collocation, using Ipopt, is now available.
• Prototype support for uncertainty computations, special feature enabled by special flag.
• Parallel algorithmic Modelica support (ParModelica) for efficient portable parallel algorithmic program-
ming based on the OpenCL standard, for CPUs and GPUs.
• Support for optimization of semiLinear according to MSL 3.3 chapter 3.7.2.5 semiLinear (r12657,r12658).
• The compiler is now fully bootstrapped and can compile itself using a modest amount of heap and stack
space (less than the RML-based compiler, which is still the default).
• Some old debug-flags were removed. Others were renamed. Debug flags can now be enabled by default.
• Removed old unused simulation flags noClean and storeInTemp (r15927).
• Many stack overflow issues were resolved.
• Dynamic Optimization with OpenModelica. Dynamic optimization with XML export to the CasADi pack-
age is now integrated with OpenModelica. Moreover, a native integrated Dynamic Optimization prototype
using Ipopt is now in the OpenModelica release, but currently needs a special flag to be turned on since it
needs more testing and refinement before being generally made available.
• Simulation: support for all the simulation flags, read the simulation output as soon as is is obtained, output
window for simulations, options to set matching algorithm and index reduction method for simulation.
Display all the files generated during the simulation is now supported. Options to set OMC command line
flags.
• Options: options for loading libraries via loadModel and loadFile each time GUI starts, save the last open
file directory location, options for setting line wrap mode and syntax highlighting.
• Modelica Text Editor: preserving user customizations, new search & replace functionality, support for
comment/uncomment.
• Notifications: show custom dialogs to users allowing them to choose whether they want to see this dialog
again or not.
• Model Creation: Better support for creating new classes. Easy creation of extends classes or nested classes.
• Messages Widget: Multi line error messages are now supported.
• Crash Detection: The GUI now automatically detects the crash and writes a stack trace file. The user is
given an option to send a crash report along with the stack trace file and few other useful files via email.
• Autosave: OMEdit saves the currently edited model regularly, in order to avoid losing edits after GUI or
compiler crash. The save interval can be set in the Options menu.
32.22.6 ModelicaML
• Enhanced ModelicaML version with support for value bindings in
requirements-driven modeling available for the latest Eclipse and Papyrus versions. GUI specific adaptations.
Automated model composition workflows (used for model-based design verification against requirements) are
modularized and have improved in terms of performance.
• Changed the internal representation of various structures to share more memory. This significantly improved
the performance for very large models that use records.
• Faster model flattening, Improved simulation, some graphical API bug fixes.
• More robust and general initialization, but currently time-consuming.
• New initialization flags to omc and options to simulate(), to control whether fast or robust initialization is
selected, or initialization from an external (.mat) data file.
• New options to API calls list, loadFile, and more.
• Enforce the restriction that input arguments of functions may not be assigned to.
• Improved the scripting environment. cl := $TypeName(Modelica);getClassComment(cl); now works as
expected. As does looping over lists of typenames and using reduction expressions.
• Beta version of Python scripting.
• Various bugfixes.
• NOTE: interactive simulation is not operational in this release. It will be put back again in the near future,
first available as a nightly build. It is also available in the previous 1.8.0 release.
THIRTYTHREE
CONTRIBUTORS TO OPENMODELICA
This Appendix lists the individuals who have made significant contributions to OpenModelica, in the form of soft-
ware development, design, documentation, project leadership, tutorial material, promotion, etc. The individuals
are listed for each year, from 1998 to the current year: the project leader and main author/editor of this document
followed by main contributors followed by contributors in alphabetical order.
521
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Eric Meyers, Pratt & Whitney Rocketdyne, Palm City, Florida, USA.
Tuomas Miettinen, VTT, Espoo, Finland.
Afshin Moghadam, PELAB, Linköping University, Linköping, Sweden.
Maroun Nemer, CEP Paristech, Ecole des Mines, Paris, France.
Hannu Niemistö, VTT, Espoo, Finland.
Peter Nordin, IEI, Linköping University, Linköping, Sweden.
Arunkumar Palanisamy, PELAB, Linköping University, Linköping, Sweden.
Karl Pettersson, IEI, Linköping University, Linköping, Sweden.
Pavol Privitzer, Institute of Pathological Physiology, Praha, Czech Republic.
Jhansi Remala, PELAB, Linköping University, Linköping, Sweden.
Reino Ruusu, VTT, Espoo, Finland.
Per Sahlin, Equa Simulation AB, Stockholm, Sweden.
Wladimir Schamai, EADS, Hamburg, Germany.
Gerhard Schmitz, University of Hamburg, Hamburg, Germany.
Alachew Shitahun, PELAB, Linköping University, Linköping, Sweden.
Anton Sodja, University of Ljubljana, Ljubljana, Slovenia
Ingo Staack, IEI, Linköping University, Linköping, Sweden.
Kristian Stavåker, PELAB, Linköping University, Linköping, Sweden.
Sonia Tariq, PELAB, Linköping University, Linköping, Sweden.
Hubert Thierot, CEP Paristech, Ecole des Mines, Paris, France.
Mohsen Torabzadeh-Tari, PELAB, Linköping University, Linköping, Sweden.
Parham Vasaiely, EADS, Hamburg, Germany.
Niklas Worschech, Bosch-Rexroth, Lohr am Main, Germany.
Robert Wotzlaw, Goettingen, Germany.
Azam Zia, PELAB, Linköping University, Linköping, Sweden.
[ABB+99] Edward Anderson, Zhaojun Bai, Christian Bischof, L Susan Blackford, James Demmel, Jack Don-
garra, Jeremy Du Croz, Anne Greenbaum, Sven Hammarling, Alan McKenney, and others. LAPACK
Users' guide. SIAM, 1999.
[BBOR15] Bernhard Bachmann, W Braun, L Ochel, and V Ruge. Symbolical and numerical approaches for
solving nonlinear systems. In Annual OpenModelica Workshop, volume 2015. 2015.
[CK06] Francois E. Cellier and Ernesto Kofman. Continuous System Simulation. Springer-Verlag New York,
Inc., Secaucus, NJ, USA, 2006. ISBN 0387261028.
[DN10] T. A. Davis and E. Palamadai Natarajan. Algorithm 907: klu, a direct sparse solver for circuit
simulation problems. ACM Trans. Math. Softw., 37(3):36:1–36:17, September 2010. URL: http:
//doi.acm.org/10.1145/1824801.1824814, doi:10.1145/1824801.1824814.
[Dav04] Timothy A Davis. Algorithm 832: umfpack v4. 3—an unsymmetric-pattern multifrontal method. ACM
Transactions on Mathematical Software (TOMS), 30(2):196–199, 2004.
[DJS96] John E Dennis Jr and Robert B Schnabel. Numerical methods for unconstrained optimization and
nonlinear equations. SIAM, 1996.
[HNorsettW93] E. Hairer, S. P. Nørsett, and G. Wanner. Solving Ordinary Differential Equations I: Nonstiff Prob-
lems. Springer-Verlag Berlin Heidelberg, 2nd rev. ed. 1993. corr. 3rd printing 2008 edition, 1993.
ISBN 978-3-540-56670-0. doi:10.1007/978-3-540-78862-1.
[HNorsettW00] E. Hairer, S.P. Nørsett, and G. Wanner. Solving Ordinary Differential Equations I Nonstiff prob-
lems. Springer, Berlin, second edition, 2000.
[HBG+05] A. C. Hindmarsh, P. N. Brown, K. E. Grant, S. L. Lee, R. Serban, D. E. Shumaker, and C. S. Wood-
ward. SUNDIALS: suite of nonlinear and differential/algebraic equation solvers. ACM Transactions
on Mathematical Software (TOMS), 31(3):363–396, 2005.
[Kel78] Herbert B Keller. Global homotopies and newton methods. In Recent advances in numerical analysis,
pages 73–94. Elsevier, 1978.
[KC19] Christopher A. Kennedy and Mark H. Carpenter. Diagonally implicit runge–kutta methods for stiff
odes. Applied Numerical Mathematics, 146:221–244, 2019. URL: https://www.sciencedirect.com/
science/article/pii/S0168927419301801, doi:https://doi.org/10.1016/j.apnum.2019.07.008.
[Nat05] Ekanathan Palamadai Natarajan. KLU–A high performance sparse linear solver for circuit simulation
problems. PhD thesis, University of Florida, 2005.
[Nis10] Akira Nishida. Experience in developing an open source scalable software infrastructure in japan. In
International Conference on Computational Science and Its Applications, 448–462. Springer, 2010.
[OB13] Lennart A Ochel and Bernhard Bachmann. Initialization of equation-based hybrid models within
openmodelica. In Proceedings of the 5th International Workshop on Equation-Based Object-Oriented
Modeling Languages and Tools; April 19; University of Nottingham; Nottingham; UK, number 084,
97–103. Linköping University Electronic Press, 2013.
[Pet82] L.R. Petzold. Description of dassl: a differential/algebraic system solver. 1982.
[SCO+11] Michael Sielemann, Francesco Casella, Martin Otter, Christop Clauß, Jonas Eborn, Sven Erik Mats-
son, and Hans Olsson. Robust initialization of differential-algebraic equations using homotopy. In
539
OpenModelica User’s Guide, Release v1.21.0-1-g4ef5d27bdd
Proceedings of the 8th International Modelica Conference; March 20th-22nd; Technical Univeristy;
Dresden; Germany, number 063, 75–85. Linköping University Electronic Press, 2011.
[T+98] Allan G Taylor and others. User documentation for kinsol, a nonlinear solver for sequential and par-
allel computers. Technical Report, Lawrence Livermore National Lab., CA (United States), 1998.
[Axe05] Ingemar Axelsson. OpenModelica Notebook for interactive structured Modelica documents. Master's
thesis, Linköping University, Department of Computer and Information Science, October 2005. LITH-
IDA-EX–05/080–SE.
[Fernstrom06] Anders Fernström. Extending OpenModelica Notebook – an interactive notebook for structured
Modelica documents. Master's thesis, Linköping University, Department of Computer and Informa-
tion Science, September 2006. LITH-IDA-EX–06/057—SE.
[Fri04] Peter Fritzson. Principles of Object-Oriented Modeling and Simulation with Modelica 2.1. Wiley-
IEEE Press, February 2004. ISBN 0-471-471631.
[Knu84] Donald E. Knuth. Literate programming. The Computer Journal, 27:97–111, 1984.
[Wol96] Stephen Wolfram. The Mathematica Book. Wolfram Media/Cambridge University Press, third edition,
1996.
[BOR+12] Bernhard Bachmann, Lennart Ochel, Vitalij Ruge, Mahder Gebremedhin, Peter Fritzson, Vaheed
Nezhadali, Lars Eriksson, and Martin Sivertsson. Parallel multiple-shooting and collocation Op-
timization with OpenModelica. In Martin Otter and Dirk Zimmer, editors, Proceedings of the
9th International Modelica Conference. Linköping University Electronic Press, September 2012.
doi:10.3384/ecp12076659.
[RBB+14] Vitalij Ruge, Willi Braun, Bernhard Bachmann, Andrea Walther, and Kshitij Kulshreshtha. Effi-
cient implementation of collocation methods for optimization using openmodelica and adol-c. In
Hubertus Tummescheit and Karl-Erik Årzén, editors, Proceedings of the 10th International Mod-
elica Conference. Modelica Association and Linköping University Electronic Press, March 2014.
doi:10.3384/ecp140961017.
540 Bibliography
INDEX
O
OMEdit, 202
OMSimulator, 131
Examples, 132
Flags, 131
OMSimulatorLib, 133
C-API, 133
OMSimulatorLua, 151
Examples, 151
Scripting Commands, 152
OMSimulatorPython, 169
Examples, 169
Scripting Commands, 170
OpenModelicaScripting, 188
Examples, 188
Scripting Commands, 189
S
SSP, 205
Bus connections, 207
TLM connections, 208
TLM Systems, 208
541