OpenModelicaUsersGuide Latest
OpenModelicaUsersGuide Latest
Release v1.23.0-dev-229-g14cdee7a2b
2024
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 29
2.1 Overview of Basic Modelica Package Management Concepts . . . . . . . . . . . . . . . . . . . 29
2.2 The Package Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3 How the package index works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
i
3.33 Temporary Directory, Log Files and Working Directory . . . . . . . . . . . . . . . . . . . . . . 77
3.34 High DPI Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4 2D Plotting 83
4.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.2 Plot Command Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
5 OpenModelica Compiler 87
5.1 Frontend Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.2 Backend Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.3 Code generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.4 Simulation Runtimes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7 Debugging 103
7.1 The Equation-based Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.2 The Algorithmic Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
11 OMSimulator 139
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
11.2 OMSimulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
11.3 OMSimulatorLib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.4 C-API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.5 OMSimulatorLua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
11.6 OMSimulatorPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
11.7 OpenModelicaScripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
11.8 Graphical Modelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
11.9 SSP Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
ii
14 OMNotebook with DrModelica and DrControl 239
14.1 Interactive Notebooks with Literate Programming . . . . . . . . . . . . . . . . . . . . . . . . . 239
14.2 DrModelica Tutoring System - an Application of OMNotebook . . . . . . . . . . . . . . . . . . 240
14.3 DrControl Tutorial for Teaching Control Theory . . . . . . . . . . . . . . . . . . . . . . . . . . 244
14.4 OpenModelica Notebook Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
14.5 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
17 PDEModelica1 305
17.1 PDEModelica1 language elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
17.2 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
17.3 Viewing results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
iii
25 OMJulia - OpenModelica Julia Scripting 365
26 Jupyter-OpenModelica 367
iv
34.10 OpenModelica Contributors 2006 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
34.11 OpenModelica Contributors 2005 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
34.12 OpenModelica Contributors 2004 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
34.13 OpenModelica Contributors 2003 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
34.14 OpenModelica Contributors 2002 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
34.15 OpenModelica Contributors 2001 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
34.16 OpenModelica Contributors 2000 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
34.17 OpenModelica Contributors 1999 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
34.18 OpenModelica Contributors 1998 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Bibliography 579
Index 581
v
vi
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
This work is licensed under a Creative Commons Attribution 4.0 International License.
This document is part of OpenModelica: https://www.openmodelica.org Contact: OpenModelica@ida.liu.se
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.23.0-dev-229-g14cdee7a2b
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 ap-
propriate 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. How-
ever, 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 submitted
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.23.0-dev-229-g14cdee7a2b
The OpenModelica environment consists of several interconnected subsystems, as depicted in Figure 1.1.
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.23.0-dev-229-g14cdee7a2b
• Optimization subsystem OMOptim. This is an optimization subsystem for OpenModelica, currently for de-
sign 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 Modelica
models extended with optimization specifications with goal functions and additional constraints. This sub-
system 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
including 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.
The following is an interactive session using the interactive session handler in the OpenModelica environment,
called OMShell - the OpenModelica Shell. Most of these examples are also available in the OMNotebook with
DrModelica and DrControl UsersGuideExamples.onb as well as the testmodels in:
>>> getVersion()
"OMCompiler v1.23.0-dev.229+g14cdee7a2b"
Under Windows, go to the Start Menu and run OpenModelica->OpenModelica Shell which responds with an
interaction window.
Under Linux, run OMShell-terminal to start the interactive session at the prompt.
We enter an assignment of a vector expression, created by the range construction expression 1:12, to be stored in
the variable x. The value of the expression is returned.
>>> x := 1:12
{1,2,3,4,5,6,7,8,9,10,11,12}
When running OMC in interactive mode (for instance using OMShell) one can make load classes and execute
commands. Here we give a few example sessions.
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.
Load the function bubblesort, either by using the pull-down menu File->Load Model, or by explicitly giving the
command:
true
The function bubblesort is called below to sort the vector x 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. 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:
6 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
>>> bubblesort({4,6,2,5,8})
{8.0,6.0,5.0,4.0,2.0}
It is also possible to give operating system commands via the system utility function. A command is provided as
a string argument. The example below shows the system utility applied to the UNIX command cat, which here
outputs the contents of the file bubblesort.mo to the output stream when running omc from the command-line.
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_master/build/share/doc/omc/testmodels"
>>> cd(dir)
"«DOCHOME»"
We load a model, here the whole Modelica standard library, which also can be done through the File->Load Mod-
elica Library menu item:
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:
8 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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.
>>> instantiateModel(dcmotor)
class dcmotor
parameter Real resistor1.R(quantity = "Resistance", unit = "Ohm", start = 1.0) = 10.
˓→0 "Resistance at temperature T_ref";
˓→"Reference temperature";
˓→heatPort - T_ref))";
˓→heatPort";
final parameter Boolean emf1.useSupport = false "= true, if support flange enabled,␣
˓→otherwise implicitly grounded";
10 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Real signalVoltage1.v(unit = "V") "Voltage between pin p and n (= p.v - n.v) as␣
˓→input signal";
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;
(continues on next page)
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.
12 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
4
load.w
load.phi
3.5
2.5
1.5
0.5
0
0 2 4 6 8 10
The val(variableName,time) scription function can be used to retrieve the interpolated value of a simulation result
variable at a certain point in the simulation time, see usage in the BouncingBall simulation below.
We load and simulate the BouncingBall example containing when-equations and if-expressions (the Modelica
keywords have been bold-faced by hand for better readability):
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:
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-6, 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;
14 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Retrieve the value of itot at time=0 using the val(variableName, time) function:
>>> val(itot,0)
1.0
2
itot
open
1.5
0.5
0
0 0.2 0.4 0.6 0.8 1
We note that the variable open switches from false (0) to true (1), causing itot to increase from 1.0 to 2.0.
>>> clear()
true
>>> list()
""
We load another model, the VanDerPol model (or via the menu File->Load Model):
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"
(continues on next page)
16 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Japenese, Chinese, and other kinds of UniCode characters can be used within quoted (single quote) identifiers, see
for example the variable name to the right in the plot below:
A simple summing integer loop (using multi-line input without evaluation at each line into OMShell requires copy-
paste as one operation from another document):
>>> 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.4500000000003
1479.0900000000001
>>> i:="";
>>> lst := {"Here ", "are ","some ","strings."};
>>> s := "";
>>> for i in lst loop
s := s + i;
end for;
>>> s
"Here are some strings."
>>> 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"
18 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
>>> 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
>>> 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
Call the function getErrorString() in order to get more information about the error cause after a simulation failure:
>>> getErrorString()
""
There are several output format possibilities, with mat being the default. plt and mat are the only formats that allow
you to use the val() or plot() functions after a simulation. Compared to the speed of plt, mat is roughly 5 times for
small files, and scales better for larger files due to being a binary format. The csv format is roughly twice as fast
as plt on data-heavy simulations. The plt format allocates all output data in RAM during simulation, which means
that simulations may fail due applications only being able to address 4GB of memory on 32-bit platforms. Empty
does no output at all and should be by far the fastest. The csv and plt formats are suitable when using an external
scripts or tools like gnuplot to generate plots or process data. The mat format can be post-processed in MATLAB
or Octave.
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
See Chapter Interoperability - C and Python for more information about calling functions in other programming
languages.
Faster simulations on multi-core computers can be obtained by using a new OpenModelica feature that automat-
ically partitions the system of equations and schedules the parts for execution on different cores using shared-
memory OpenMP based execution. The speedup obtained is dependent on the model structure, whether the system
of equations can be partitioned well. This version in the current OpenModelica release is an experimental version
without load balancing. The following command, not yet available from the OpenModelica GUI, will run a parallel
simulation on a model:
20 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
There exist many different versiosn of Modelica libraries which are not compatible. It is possible to keep mul-
tiple versions of the same library stored in the directory given by calling getModelicaPath(). By calling load-
Model(Modelica,{"3.2"}), OpenModelica will search for a directory called "Modelica 3.2" or a file called "Mod-
elica 3.2.mo". It is possible to give several library versions to search for, giving preference for a pre-release version
of a library if it is installed. If the searched version is "default", the priority is: no version name (Modelica), main
release version (Modelica 3.1), pre-release version (Modelica 3.1Beta 1) and unordered versions (Modelica Special
Release).
The loadModel command will also look at the uses annotation of the top-level class after it has been loaded. Given
the following package, Complex 1.0 and ModelicaServices 1.1 will also be loaded into the AST automatically.
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;
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.
In the OpenModelica System Documentation, an external API (application programming interface) is described
which returns information about models and/or allows manipulation of models. Calls to these functions can be
done interactively as below, but more typically by program clients to the OpenModelica Compiler (OMC) server.
Current examples of such clients are the OpenModelica MDT Eclipse plugin, OMNotebook, the OMEdit graphic
model editor, etc. This API is untyped for performance reasons, i.e., no type checking and minimal error checking
is done on the calls. The results of a call is returned as a text string in Modelica syntax form, which the client has
to parse. An example parser in C++ is available in the OMNotebook source code, whereas another example parser
in Java is available in the MDT Eclipse plugin.
Below we show a few calls on the previously simulated BouncingBall model. The full documentation on this API
is available in the system documentation. First we load and list the model again to show its structure:
>>> 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;
>>> getClassRestriction(BouncingBall)
"model"
>>> getClassInformation(BouncingBall)
("model","",false,false,false,"/var/lib/jenkins1/ws/OpenModelica_master/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",␣
22 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
>>> 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.23.0-dev.229+g14cdee7a2b"
>>> quit()
The command dumpXMLDAE dumps an XML representation of a model, according to several optional parameters.
dumpXMLDAE(modelname[,asInSimulationCode=<Boolean>] [,filePrefix=<String>] [,storeIn-
Temp=<Boolean>] [,addMathMLCode =<Boolean>])
This command dumps the mathematical representation of a model using an XML representation, with optional
parameters. In particular, asInSimulationCode defines where to stop in the translation process (before dumping the
model), the other options are relative to the file storage: filePrefix for specifying a different name and storeInTemp
to use the temporary directory. The optional parameter addMathMLCode gives the possibility to don't print the
MathML code within the xml file, to make it more readable. Usage is trivial, just: addMathMLCode=true/false
(default value is false).
The command export dumps an XML representation of a model, according to several optional parameters.
exportDAEtoMatlab(modelname);
This command dumps the mathematical representation of a model using a Matlab representation. Example:
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',
(continues on next page)
˓→if edge(impact) then (-e) * pre(v) else 0.0; end when;','when {h <= 0.0 and v <= 0.
The following is the complete list of commands currently available in the interactive session hander.
simulate(modelname) Translate a model named modelname and simulate it.
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.
24 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The OpenModelica compiler can also be used from command line, in Windows cmd.exe or a Unix shell. The
following examples assume omc is on the PATH; if it is not, you can run C:\OpenModelica 1.16.0\build\
bin\omc.exe or similar (depending on where you installed OpenModelica).
$ omc --help
OpenModelica Compiler OMCompiler v1.23.0-dev.229+g14cdee7a2b
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-6, method = 'dassl', fileNamePrefix = 'Modelica.Mechanics.MultiBody.
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:
26 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
...
timeSimulation = 0.0,
timeTotal = 0.0
end SimulationResult;
""
28 Chapter 1. Introduction
CHAPTER
TWO
PACKAGE MANAGEMENT
The Modelica language promotes the orderly reuse of component models by means of packages that contain struc-
tured libraries of reusable models. The most prominent example is the Modelica Standard Library (MSL), that
contains basic models covering many fields of engineering. Other libraries, both open-source and commercial, are
available to cover specific applications domains.
When you start a simulation project using Modelica, it is common practice to collect all related system models in a
project-specific package that you develop. The models in this package are often instantiated (e.g. by drag-and-drop
in OMEdit) from released libraries, which are read-only for your project. This establishes a dependency between
your project package and a certain version of a read-only package (or library), which is the one you have loaded in
OMEdit and that you drag-and-drop components from.
This dependency is automatically marked in your package by adding a uses annotation at the top level.
For example, if you drag and drop components from MSL 4.0.0 into models of your package, the
annotation(uses(Modelica(version="4.0.0"))); will be added automatically to it. This information al-
lows OpenModelica to automatically load all the libraries that are required to compile the models in your own
package next time you (or someone else, possibly on a different computer) loads your package, provided they are
installed in places on the computer's file system where OpenModelica can find them.
The default place where OpenModelica looks for packages is the so-called MODELICAPATH. You can check
where it is by typing getModelicaPath() in the Interactive Environment (Tools | OpenModelica Compiler CLI
in OMEdit). Installed read-only libraries are placed by default in the MODELICAPATH.
When a new version of certain package comes out, conversion annotations in it declare whether your models
using a certain older version of it can be used as they are with the new one, which is then 100% backwards-
compatible, or whether they need to be upgraded by running a conversion script, provided with the new version
of the package. The former case is declared explicitly by a conversion(noneFromVersion) annotation. For
example, a conversion(noneFromVersion="3.0.0") annotation in version 3.1.0 of a certain package means
that all packages using version 3.0.0 can use 3.1.0 without any change. Of course it is preferrable to use a newer,
backwards-compatible version, as it contains bugfixes and possibly new features.
Hence, if you install a new version of a library which is 100% backwards-compatible with the previous ones, all
your models that used the old one will automatically load and use the new one, without the need of any further
action.
If the new version is not backwards-compatible, instead, you will need to create a new version of your library that
uses it, by running the provided conversion scripts.
OpenModelica has a package manager that can be used to install and update libraries on your computer, and is
able to run conversion scripts. Keep in mind there are three stages in package usage: available packages are
indexed on the OSMC servers and can be downloaded from public repositories; installed packages are stored in
the MODELICAPATH of your computer; loaded packages are loaded in memory in an active OMC session, either
via the Interactive Environment, or via the OMEdit GUI, where they are shown in the Libraries Browser. When
you load a package, OpenModelica tries to load the best possible installed versions of all the dependencies declared
in the uses annotation.
29
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The Open Source Modelica Consortium (OSMC) maintains a collection of publicly available, open-source Mod-
elica libraries on its servers, see https://github.com/OpenModelica/OMPackageManager. These libraries are rou-
tinely tested with past released versions of OpenModelica, as well as with the current development version on the
master branch, see the overview report. Based on the testing results and on information gathered from the library
developers, these packages are classified in terms of level of support in OpenModelica. Backwards-compatibility
information is also collected from the conversion annotations.
The OpenModelica Package Manager relies on this information to install the best versions of the library depen-
dencies of your own, locally developed Modelica packages and models. It can be run both from the OMEdit GUI
and from the command-line interactive environment. The libraries and their index.json index file with all the
library metadata are installed in the ~/.openmodelica/libraries directory under Linux and in the %AppData%\
.openmodelica\libraries directory on Windows. Note that these directories are user-specific, so if there are
multiple users on the same computer, each of them will install and manage his/her own set of libraries independently
from the others.
The Package Manager may install multiple builds of the same library version in your own package manager di-
rectory, if they are indexed on the OSMC servers. When this happens, they are distinguished among each other
by means of semver-style pre- or post-release metadata in the top directory name on the file system. Post-release
builds are denoted by a plus sign (e.g. 2.0.0+build.02) and have higher priority over the corresponding plain
release (e.g. 2.0.0), while pre-release builds are denoted by a minus sign (e.g. 2.0.0-dev.30) and have a lower
priority.
When loading a certain version of a library, unless a specific build is explicitly referenced, the one with higher
precedence will always be loaded. For example, if the versions 2.0.0-beta.01, 2.0.0, and 2.0.0+build.01
are installed, the latter is loaded by libraries with uses annotation requiring version 2.0.0. Unless, of course,
there are later backwards-compatible versions installed, e.g., 2.0.1, in which case the one with the highest release
number and priority is installed.
In any case, semver version semantics is only used to order the releases, while backwards-compatibility is deter-
mined exclusively on the basis of noneFromVersion annotations.
When installing OpenModelica, a cached version of the latest versions of the Modelica Standard Library is included
in the installation files. As soon as a user starts any OpenModelica tool (e.g., OMEdit, OMNotebook, OMShell, or
direct command-line invocation of omc), if the user's .openmodelica directory is empty the Modelica Standard
Library will be installed automatically using this cached version. This happens when using OpenModelica for the
first time, or if the contents of the .openmodelica directory have been deleted to get rid of all installed libraries.
This automatic installation needs no Internet connection, so it also works behind firewalls or in set-ups with limited
available bandwidth. Therefore, the Modelica Standard Library is immediately available without the need of using
the package manager explicitly. It is then possible to install and manage other libraries using the package manager,
as explained previously.
As a final remark, please note that the version numbers of the various Modelica packages have no relation with the
version numbers of the OpenModelica tool itself. Since version 1.19.0, OpenModelica is no longer shipped with
built-in installed libraries, that are instead managed independently by the user with the online Package Manager.
You can install and use old and new versions of a certain open source Modelica library using the latest released
version of OpenModelica, by using the Package Manager. We strive to make sure that new released versions of
OpenModelica are backwards-compatible, meaning that you should always be able to run the same models/libraries
with a new version of OpenModelica if you could with an older version of the tool. Hence, we strongly advise you
to always use the latest released version of OpenModelica, even if you are running old models; by doing so, you
benefit from faster performance, more robust numerical performance, new tool features, and a lot of bug fixes.
You should never find yourself in a situation where you are forced to stick to an old version of OpenModelica to run
your models. If that happens to you, please open a ticket on the issue tracker, so we can hopefully fix the problem
and allow you to keep using the latest OpenModelica release.
When you start OMEdit, some packages can be automatically loaded into the environment, and shown in the
Libraries Browser. You can configure which ones are loaded from the Tools|Options|Libraries menu.
Please note that automatically loaded libraries may be in conflict with the dependencies of packages that you may
later load from the File menu. For example, if you automatically load Modelica 4.0.0, and then load a library
XYZ that still uses MSL 3.2.3, you get a conflict, because Modelica 4.0.0 is not backwards-compatible with
Modelica 3.2.3, so XYZ cannot be used.
In this case you have two options:
• Cancel Operation: this means XYZ is not actually loaded, and all previously loaded libraries remain in place.
• Unload all and Reload XYZ: in this case, all previously loaded libraries, that may generate conflicts, are
unloaded first; then XYZ is loaded, and finally the right versions of the libraries XYZ uses, as declared in
its uses annotation, will be loaded automatically.
If you are normally working with only one version of the Modelica standard library, you can set it to be automatically
loaded from the Tools|Options|Libraries menu; in case you need to work with a library that uses a previous, non-
backwards compatible version, the Unload all and Reload option comes handy. Otherwise, you can avoid loading
the Modelica library automatically upon starting OMEdit, and let the right version of the Modelica library be loaded
automatically when you open the library you want to work with. In this case, if you want to get the Modelica library
into the Package Browser to start developing a new library, you can do so easily from the Welcome tab, by clicking
on the System Libraries button and selecting the version that you want to load.
If you want to maintain full control over which library dependencies are loaded, you can use the File | Open
Model/Library Files(s) menu command in OMEdit to open the libraries one by one from specific locations in
your file system. Note, however, that whenever a library is loaded, its dependencies, that are declared in its uses
annotation, will automatically be loaded. If you want to avoid that, you need to load the library dependencies in
reverse order, so that the intended library dependencies are already loaded when you open the library that needs
them.
If you are using the Interactive Environment, you can use the loadFile() command to load libraries from specific
locations on the file system, also in reverse dependency order, unless you also set the optional uses = false input
argument to disable the automatic loading of dependencies.
The Package Manager can also be used from the Interactive Environment command line shell. Here is a list of ex-
amples of relevant commands; please type them followed by getErrorString(), e.g., updatePackageIndex(); getEr-
rorString(), in order to get additional information, notifications and error messages.
• updatePackageIndex() - this command puts the Package Manager in contact with the OSMC servers and
updates the internally stored list of available packages;
• getAvailablePackageVersions(Building, "") - lists all available versions of the Buildings library on the OSMC
server, starting from the most recent one, in descending order of priority. Note that pre-release versions have
lower priority than all other versions;
• getAvailablePackageVersions(Building, "7.0.0") - lists all available versions of the Buildings library on the
OSMC server that are backwards-compatible with version 7.0.0, in descending order of priority;
• installPackage(Buildings, "") - install the most recent version of the Building libraries, and all its dependen-
cies;
• installPackage(Buildings, "7.0.0") - install the most recent version of the Building libraries which is
backwards-compatible with version 7.0.0, and all its dependencies;
• installPackage(Buildings, "7.0.0", exactMatch = true) - install version 7.0.0 even if there are more recent
backwards-compatible versions available, and all its dependencies;
• upgradeInstalledPackages(installNewestVersions = true) - installs the latest available version of all installed
packages.
The package index is generated by OMPackageManager on an OSMC server, based on these settings. See its
documentation to see how to add new packages to the index, change support level, and so on.
The index is generated by scanning git repositories on github. All tags and optionally some specific branches are
scanned. The tag name is parsed as if it was a semantic version, with prerelease and metadata of the tag added to
the version of Modelica packages in the repository. If the tag name is not a semantic version, it is sorted differently.
Packages are sorted as follows:
• Support level: each package is given a level of support in the index
• Semantic version: according to the semver specification, but build metadata is also considered (sorted the
same way as pre-releases)
• Non-semantic versions: alphabetically
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 inter-
faces.
• Simulation - Subsystem for running simulations and specifying simulation parameters start and stop time,
etc.
• Plotting - Interface to plot variables from simulated models.
A splash screen similar to the one shown in Figure 3.1 will appear indicating that it is starting OMEdit. The
executable is found in different places depending on the platform (see below).
3.1.2 Linux
Start OMEdit by either selecting the corresponding menu application item or typing “OMEdit” at the shell or
command prompt.
33
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
3.1.3 Mac OS X
To filter a class click Edit > Filter Classes or press keyboard shortcut Ctrl+Shift+F. The loaded Modelica classes
can be filtered by typing any part of the class name.
To view the Libraries Browser click View > Windows > Libraries Browser. Shows the list of loaded Modelica
classes. Each item of the Libraries Browser has right click menu for easy manipulation and usage of the class.
The classes are shown in a tree structure with name and icon. The protected classes are not shown by default. If
you want to see the protected classes then you must enable the Show Protected Classes option, see section General
Options.
Displays the HTML documentation of Modelica classes. It contains the navigation buttons for moving forward and
backward. It also contains a WYSIWYG editor which allows writing class documentation in HTML format. To
view the Documentation Browser click View > Windows > Documentation Browser.
The class variables are structured in the form of the tree and are displayed in the Variables Browser. Each variable
has a checkbox. Ticking the checkbox will plot the variable values. The complete Variables Browser can be
collapsed and expanded using the Collapse All and Expand All buttons.
There is a find box for filtering the variable in the tree. By clicking the yellow down arrow you can set all the
filtering options. The filtering can be done using Regular Expression, Wildcard and Fixed String; in all three
cases, all variables whose full name contains a string corresponding to the filter string will be displayed.
Fixed String: shows all variables whose name contains the string verbatim
• abc shows abc, abc.def, xyz.abc, der(abc) etc.
• a.b shows a.b, a.bcd, a.b.c, x.a.b, x.a.b.c, etc.
Wildcard: same as Fixed String; additionally, asterisks match any number of characters
• der(*) shows all derivatives, e.g. der(x), der(abc), abc.der(xyz), etc.
• a*c shows ac, abc, abdc, xyz.adefc, etc.
Regular expression: shows all variables whose name contain a string that matches the regexp; if the regexp ends
with $, then the name must end with a string matching the regexp
• abc shows abc, abc.def, xyz.abc, der(abc) etc.
• abc$ shows abc, xyz.abc only
• a.c shows abc, abc.def, azc, xyz.adc etc. (. matches any character)
• a.*c shows abc, abc.def, axyc, xyz.axxxxdc etc. (.* matches any number of character)
• body\.a_0\[1\] shows variables containing body.a_0[1]. Note that ., [, and ] are special regexp char-
acters, so they must be escaped
• der\(.*\) shows all derivatives in the model. Note that ( and ) must be escaped
• x\[[2-4]\] shows elements 2, 3, and 4 of arrays x[:], abc.x[:], x[:].abc
• x\[.*\] shows all elements of arrays x[:], abc.x[:], x[:].abc
• abc|def shows all variables with names containing either abc or def
The browser allows manipulation of changeable parameters for Plot Window. It also displays the unit and descrip-
tion of the variable.
The browser also contains the slider and animation buttons. These controls are used for variable graphics and
schematic animation of models i.e., DynamicSelect annotation. They are also used for debugging of state machines.
Open the Diagram Window for animation. It is only possible to animate one model at a time. This is achieved by
marking the result file active in the Variables Browser. The animation only read the values from the active result
file. It is possible to simulate several models. In that case, the user will see a list of result files in the Variables
Browser. The user can switch between different result files by right clicking on the result file and selecting Set
Active in the context menu.
3.3 Perspectives
The perspective tabs are located at the bottom right of the Main Window:
• Welcome Perspective
• Modeling Perspective
• Plotting Perspective
• Debugging Perspective
The Welcome Perspective shows the list of recent files and the list of latest news from https://www.openmodelica.
org. See Figure 3.5. The orientation of recent files and latest news can be horizontal or vertical. User is allowed to
show/hide the latest news. See section General Options.
3.3. Perspectives 39
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The Modeling Perspective provides the interface where user can create and design their models. See Figure 3.6.
The Modeling Perspective interface can be viewed in two different modes, the tabbed view and sub-window view,
see section General Options.
The Plotting Perspective shows the simulation results of the models. Plotting Perspective will automatically become
active when the simulation of the model is finished successfully. It will also become active when user opens any
of the OpenModelica's supported result file. Similar to Modeling Perspective this perspective can also be viewed
in two different modes, the tabbed view and sub-window view, see section General Options.
3.3. Perspectives 41
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The application automatically switches to Debugging Perspective when user simulates the class with algorithmic
debugger. The perspective shows the list of stack frames, breakpoints and variables.
• New
• New Modelica Class - Creates a new Modelica class.
• New SSP Model - Creates a new SSP model.
• Open Model/Library File(s) - Opens the Modelica file or a library.
• Open/Convert Modelica File(s) With Encoding - Opens the Modelica file or a library with a specific encoding.
It is also possible to convert to UTF-8.
• Load Library - Loads a Modelica library. Allows the user to select the library path assuming that the path
contains a package.mo file.
• Load Encrypted Library - Loads an encrypted library. see OpenModelica Encryption
• Open Result File(s) - Opens a result file.
• Open Transformations File - Opens a transformational debugger file.
• Unload All - Unloads all loaded classes.
• Calculate Data Reconciliation - Opens the dialog to run the data reconciliation algorithm.
• Run Sensitivity Analysis and Optimization - Runs the sensitivity analysis and optimization.
• OpenModelica Compiler CLI - Opens the OpenModelica Compiler command line interface window.
• OpenModelica Command Prompt - Opens the OpenModelica Command Prompt (Only available on Win-
dows).
• Open Temporary Directory - Opens the current temporary directory.
• Open Working Directory - Opens the current working directory.
• Open Terminal - Runs the terminal command set in General Options.
• Options - Opens the options window.
Creating a new Modelica class in OMEdit is rather straightforward. Choose any of the following methods,
• Select File > New > New Modelica Class from the menu.
• Click on New Modelica Class toolbar button.
• Click on the Create New Modelica Class button available at the left bottom of Welcome Perspective.
• Press Ctrl+N.
Select File > Open/Convert Modelica File(s) With Encoding from the menu. It is also possible to convert files to
UTF-8.
For each Modelica class one Model Widget is created. It has a statusbar and a view area. The statusbar contains
buttons for navigation between the views and labels for information. The view area is used to display the icon,
diagram and text layers of Modelica class. See Figure 3.9.
Drag the models from the Libraries Browser and drop them on either Diagram or Icon View of Model Widget.
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.
• Simulate with steps (makes the interactive simulation synchronous; plots nicer curves at the expense of
performance)
• Simulation server port
• Model Setup File (Optional) - specifies a new setup XML file to the generated simulation code.
• Initialization Method (Optional) - specifies the initialization method.
• Equation System Initialization File (Optional) - specifies an external file for the initialization of the model.
• Equation System Initialization Time (Optional) - specifies a time for the initialization of the model.
• Clock (Optional) - the type of clock to use.
• Linear Solver (Optional) - specifies the linear solver method.
• Non Linear Solver (Optional) - specifies the nonlinear solver.
• Linearization Time (Optional) - specifies a time where the linearization of the model should be performed.
• Output Variables (Optional) - outputs the variables a, b and c at the end of the simulation to the standard
output.
• Profiling - creates a profiling HTML file.
• CPU Time - dumps the cpu-time into the result file.
• Enable All Warnings - outputs all warnings.
• Logging (Optional)
• LOG_STDOUT - standard output stream. This stream is always active, can be disabled with -lv=-
LOG_STDOUT
• LOG_ASSERT - This stream is always active, can be disabled with -lv=-LOG_ASSERT
• LOG_DASSL - additional information about dassl solver.
• LOG_DASSL_STATES - outputs the states at every dassl call.
3.15.5 Output
When simulating Modelica models with top-level inputs (input variables or input connectors), these inputs are
assumed to be equal to their start value by default. However, it is possible to feed them with input signals
obtained from CSV (Comma-Separated Value) input data files, by means of the -csvInput simulation flag, that
can be set in the Additional Simulation Flags (Optional) field of the Simulation Flags tab. For example, setting
-csvInput=myinput.csv causes the runtime executable to read such input data from the myinput.csv file.
CSV files should contain the names of the input variables in the first row, beginning with time on the first column,
and the values of such variables for each point in time in subsequent rows, with non-decreasing time values. The
variable names should be enclosed by quotation marks in case they contain spaces, to avoid ambiguities. The
default separator for data items within each row is the comma, but it is also possible to use other separators, e.g.,
space, tab, or semi-colon; in this case, the file should start with the separator specification "sep=x" (including the
quotation marks), where x is the separator character.
For example, assume your model has three top-level inputs named u1, u2, and u3. These are valid CSV input files:
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.
The plotting type depends on the active Plot Window. By default the plotting type is Time Plot.
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.
3.16. 2D Plotting 53
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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 ( ).
A plot window shows the plot curve of instance variables. Several plot curves can be plotted in the same plot
window. See Figure 3.7.
The Variables Browser allows manipulation of changeable parameters for re-simulation. After changing the pa-
rameter values user can click on the re-simulate toolbar button ( ), or right click the model in Variables Browser
and choose re-simulate from the menu.
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.
The 3d visualization is based on OpenSceneGraph. In order to run the visualization simply right click the class in
Libraries Browser an choose “Simulate with Animation” as shown in Figure 3.10.
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.
After the successful simulation of the model, the visualization window will show up automatically as shown in
Figure 3.11.
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 opened by using the open file button
and selecting a result file with a corresponding 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.
The shapes that are displayed in the viewer can be selected with shift + right click. If a shape is selected, a context
menu pops up that offers additional visualization features
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 57
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Instead of a result file, OMEdit can load Functional Mock-up Units to retrieve the data for the animation of multi-
body systems. Just like opening a mat-file from the animation-plotting view, one can open an FMU-file. Neces-
sarily, the FMU has to be generated with the +d=visxml flag activated, so that a scene description file is generated
in the same directory as the FMU. Currently, only FMU 1.0 and FMU 2.0 model exchange are supported. When
choosing an FMU, the simulation settings window pops up to choose solver and step size. Afterwards, the model
initializes and can be simulated by pressing the play button.
FMUs can be simulated with realtime user interaction. A possible solution is to equip the model with an inter-
action model from the Modelica_DeviceDrivers library (https://github.com/modelica/Modelica_DeviceDrivers).
The realtime synchronization is done by OMEdit so no additional time synchronization model is necessary.
Users can create shapes of their own by using the shape creation tools available in OMEdit.
• Line Tool - Draws a line. A line is created with a minimum of two points. In order to create a line, the user
first selects the line tool from the toolbar and then click on the Icon/Diagram View; this will start creating a
line. If a user clicks again on the Icon/Diagram View a new line point is created. In order to finish the line
creation, user has to double click on the Icon/Diagram View.
• Polygon Tool - Draws a polygon. A polygon is created in a similar fashion as a line is created. The only
difference between a line and a polygon is that, if a polygon contains two points it will look like a line and if
a polygon contains more than two points it will become a closed polygon shape.
• Rectangle Tool - Draws a rectangle. The rectangle only contains two points where first point indicates the
starting point and the second point indicates the ending the point. In order to create rectangle, the user
has to select the rectangle tool from the toolbar and then click on the Icon/Diagram View, this click will
become the first point of rectangle. In order to finish the rectangle creation, the user has to click again on the
Icon/Diagram View where he/she wants to finish the rectangle. The second click will become the second
point of rectangle.
• Ellipse Tool - Draws an ellipse. The ellipse is created in a similar way as a rectangle is created.
• Text Tool - Draws a text label.
• Bitmap Tool - Draws a bitmap container.
The shape tools are located in the toolbar. See Figure 3.12.
The user can select any of the shape tools and start drawing on the Icon/Diagram View. The shapes created on the
Diagram View of Model Widget are part of the diagram and the shapes created on the Icon View will become the
icon representation of the model.
For example, if a user creates a model with name testModel and add a rectangle using the rectangle tool and a
polygon using the polygon tool, in the Icon View of the model. The model's Modelica Text will appear as follows:
model testModel
annotation(Icon(graphics = {Rectangle(rotation = 0, lineColor = {0,0,255},␣
˓→fillColor = {0,0,255}, pattern = LinePattern.Solid, fillPattern = FillPattern.None,␣
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.
If you want to use same styles or same JavaScript for the classes contained inside a package then you can define
__OpenModelica_infoHeader annotation inside the Documentation annotation of a package. For 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\">
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="
(continues on next page)
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.
• General
• Language - Sets the application language.
• Working Directory - Sets the application working directory. All files are generated in this directory.
• Toolbar Icon Size - Sets the size for toolbar icons.
• Preserve User's GUI Customizations - If true then OMEdit will remember its windows and toolbars positions
and sizes.
• Terminal Command - Sets the terminal command. When user clicks on Tools > Open Terminal then this
command is executed.
• Terminal Command Arguments - Sets the terminal command arguments.
• Hide Variables Browser - Hides the variable browser when switching away from plotting perspective.
• Activate Access Annotations - Activates the access annotations for the non-encrypted libraries. Access an-
notations are always active for encrypted libraries.
• Create a model.bak-mo backup file when deleting a model
• Display errors/warnings when instantiating the graphical annotations - if true then the errors/warnings are
shown when using OMC API for graphical annotations.
• Libraries Browser
• Library Icon Size - Sets the size for library icons.
• Max. Library Icon Text Length to Show - Sets the maximum text length that can be shown in the icon in
Libraries Browser.
• Show Protected Classes - If enabled then Libraries Browser will also list the protected classes.
• Show Hidden Classes - If enabled then Libraries Browser will also list the hidden classes. Ignores the
annotation(Protection(access = Access.hide))
• Synchronize with Model Widget - If enabled then Libraries Browser will scroll automatically to the active
Model Widget i.e., the current model.
• Enable Auto Save - Enables/disables the auto save feature.
• Auto Save interval - Sets the auto save interval value. The minimum possible interval value is 60 seconds.
3.23. Options 61
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Welcome Page
• Horizontal View/Vertical View - Sets the view mode for welcome page.
• Show Latest News - If enabled then the latest news from https://openmodelica.org are shown.
• Recent Files and Latest News Size - Sets the display size for recent files and latest news items.
• Optional Features
• Disable new instance-based graphical editing of models - Enables/disables the use of instance-based graph-
ical editing. The instance-based graphical editing enables features like parameter-dependent conditional
connectors, conditional dialog enable, replaceable classes and models, etc. It also provides much faster
rendering than the previously implemented graphical editing framework. This feature has been thoroughly
tested, but it could still have some issues; in case the graphical rendering of models fails (blank screen) or
is not correct, you can disable the instance-based editing and fall back to the old editing framework. In that
case, please open a ticket on the OpenModelica issue tracker so we can fix the issue for the next release.
• General
• MODELICAPATH - Sets the MODELICAPATH. MODELICAPATH is used to load libraries.
• System libraries loaded automatically on startup - The list of system libraries that are loaded on startup.
• Load latest Modelica version on startup - Is true then the latest available version of the Modelica Standard
Library is always loaded along with its dependencies.
• User libraries loaded automatically on startup - The list of user libraries/files that are loaded on startup.
• Format
• Line Ending - Sets the file line ending.
• Byte Order Mark (BOM) - Sets the file BOM.
• Tabs and Indentation
• Tab Policy - Sets the tab policy to either spaces or tabs only.
• Tab Size - Sets the tab size.
• Indent Size - Sets the indent size.
• Syntax Highlight and Text Wrapping
• Enable Syntax Highlighting - Enable/Disable the syntax highlighting.
• Enable Code Folding - Enable/Disable the code folding. When code folding is enabled multi-
line annotations are collapsed into a compact icon (a rectangle containing "...)"). A marker
containing a "+" sign becomes available at the left-side of the involved line, allowing the code to
be expanded/re-collapsed at will.
• Match Parentheses within Comments and Quotes - Enable/Disable the matching of parentheses
within comments and quotes.
• Enable Line Wrapping - Enable/Disable the line wrapping.
• Autocomplete
• Enable Autocomplete - Enables/Disables the autocomplete.
• Font
• Font Family - Shows the names list of available fonts. Sets the font for the editor.
• Preserve Text Indentation - If true then uses diffModelicaFileListings API call otherwise uses the OMC
pretty-printing.
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
3.23. Options 63
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Colors
• Items - List of categories used of syntax highlighting the code.
• Item Color - Sets the color for the selected item.
• Preview - Shows the demo of the syntax highlighting.
• General
– Modeling View Mode
– Tabbed View/SubWindow View - Sets the view mode for modeling.
– Default View
– Icon View/DiagramView/Modelica Text View/Documentation View - If no preferredView annotation is
defined then this setting is used to show the respective view when user double clicks on the class in the
Libraries Browser.
– Move connectors together on both icon and diagram layers
• Graphics
– 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.
• Simulation
• Translation Flags
• Matching Algorithm - sets the matching algorithm for simulation.
• Index Reduction Method - sets the index reduction method for simulation.
• Show additional information from the initialization process - prints the information from the
initialization process
• Evaluate all parameters (faster simulation, cannot change them at runtime) - makes the simu-
lation more efficient but you have to recompile the model if you want to change the parameter
instead of re-simulate.
• Enable analytical jacobian for non-linear strong components - enables analytical jacobian for
non-linear strong components without user-defined function calls.
• Enable parallelization of independent systems of equations (Experimental)
• Enable old frontend for code generation
• Enable FMU Import - See FMI Import - SSP.
• Additional Translation Flags - sets the translation flags see Options
• Target Language - sets the target language in which the code is generated.
• Target Build - sets the target build that is used to compile the generated code.
• C Compiler - sets the C compiler for compiling the generated code.
• CXX Compiler - sets the CXX compiler for compiling the generated code.
• Use static linking - if true then static linking is used for simulation executable. The default is
dynamic linking. This option is only available on Windows.
• Post compilation command - if not empty allows to run a command after the compilation step. A
possible use-case is to be able to sign the binaries before execution to comply with the security
policy. The command is run in the same folder where the simulation executable is created. The
interpreter executable must be passed to run shell scripts, eg on Windows: powershell.exe -File
C:script.ps1
• Ignore __OpenModelica_commandLineOptions annotation - if true then ignores the __Open-
Modelica_commandLineOptions annotation while running the simulation.
• Ignore __OpenModelica_simulationFlags annotation - if true then ignores the __OpenModel-
ica_simulationFlags annotation while running the simulation.
• 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.
• General
• Output Size - Specifies the maximum number of rows the Messages Browser may have. If there are more
rows then the rows are removed from the beginning.
• Reset messages number before simulation - Resets the messages counter before starting the simulation.
• Clear messages browser before checking, instantiation & simulation - If enabled then the messages browser
is cleared before checking, instantiation & simulation of model.
• Font and Colors
3.23. Options 65
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Notifications
• Always quit without prompt - If true then OMEdit will quit without prompting the user.
• Show item dropped on itself message - If true then a message will pop-up when a class is dragged
and dropped on itself.
• Show model is partial and component is added as replaceable message - If true then a message
will pop-up when a partial class is added to another class.
• Show component is declared as inner message - If true then a message will pop-up when an inner
component is added to another class.
• Show save model for bitmap insertion message - If true then a message will pop-up when user
tries to insert a bitmap from a local directory to an unsaved class.
• Always ask for the dragged component name - If true then a message will pop-up when user drag
& drop the component on the graphical view.
• Always ask for what to do with the text editor error - If true then a message will always pop-up
when there is an error in the text editor.
• If new frontend for code generation fails
• Always ask for old frontend
• Try with old frontend once
• Switch to old frontend permanently
• Keep using new frontend
• Line Style
• Color - Sets the line color.
• Pattern - Sets the line pattern.
• Thickness - Sets the line thickness.
• Start Arrow - Sets the line start arrow.
• End Arrow - Sets the line end arrow.
• Arrow Size - Sets the start and end arrow size.
• Smooth - If true then the line is drawn as a Bezier curve.
• Fill Style
• Color - Sets the fill color.
• Pattern - Sets the fill pattern.
• General
• Auto Scale - Sets whether to auto scale the plots or not.
• Prefix Units - Automatically pick the right prefix for units for the new plot windows. For existing plot
windows use the Plot Window Menu.
• Plotting View Mode
• Tabbed View/SubWindow View - Sets the view mode for plotting.
• Curve Style
• Pattern - Sets the curve pattern.
• Thickness - Sets the curve thickness.
• Variable filter
• Filter Interval - Delay in filtering the variables. Set the value to 0 if you don't want any delay.
• Font Size - sets the font size for plot window items
• Title
• Vertical Axis Title
• Vertical Axis Numbers
• Horizontal Axis Title
• Horizontal Axis Numbers
• Footer
• Legend
• Figaro
• Figaro Library - the Figaro library file path.
• Tree generation options - the Figaro tree generation options file path.
• Figaro Processor - the Figaro processor location.
3.23. Options 67
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Algorithmic Debugger
• GDB Path - the gnu debugger path
• GDB Command Timeout - timeout for gdb commands.
• GDB Output Limit - limits the GDB output to N characters.
• Display C frames - if true then shows the C stack frames.
• Display unknown frames - if true then shows the unknown stack frames. Unknown stack frames means
frames whose file path is unknown.
• Clear old output on a new run - if true then clears the output window on new run.
• Clear old log on new run - if true then clears the log window on new run.
• Transformational Debugger
• Always show Transformational Debugger after compilation - if true then always open the Transformational
Debugger window after model compilation.
• Generate operations in the info xml - if true then adds the operations information in the info xml file.
• Export
• Version
• 1.0 - Sets the FMI export version to 1.0
• 2.0 - Sets the FMI export version to 2.0
• Type
• Model Exchange - Sets the FMI export type to Model Exchange.
• Co-Simulation - Sets the FMI export type to Co-Simulation.
• Model Exchange and Co-Simulation - Sets the FMI export type to Model Exchange and Co-
Simulation.
• FMU Name - Sets a prefix for generated FMU file.
• Move FMU - Moves the generated FMU to a specified path.
• Platforms: See Platforms.
• Solver for Co-Simulation
• Explicit Euler
• CVODE
• Model Description Filters - Sets the variable filter for model description file, see --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 direc-
tory that is created for importing the FMU will be deleted.
• General
• Path - path to OMTLMSimulator bin directory.
• Manager Process - path to OMTLMSimulator manager process.
• Monitor Process - path to OMTLMSimulator monitor process.
• General
• Command Line Options - sets the OMSimulator command line options.
• Logging Level - OMSimulator logging level.
OpenModelica specific annotation to define the command line options needed to simulate the model. For example
if you always want to simulate the model with a specific matching algorithm and index reduction method instead
of the default ones then you can write the following code,
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.
OpenModelica specific annotation to define the simulation options needed to simulate the model. For example if
you always want to simulate the model with a specific solver instead of the default DASSL and would also like to
see the cpu time then you can write the following code,
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 __Open-
Modelica_simulationFlags annotation.
There is a large number of optional settings and flags to influence the way OpenModelica generates the simulation
code (Compiler flags, a.k.a. Translation flags or Command Line Options) and the way the simulation executable
is run (Simulation Flags).
The global default settings can be accessed and changed with the Tools > Options menu. It is also possible to reset
them to factory state by clicking on the Reset button of the Tools > Options dialog window.
When you start OMEdit and you simulate a model for the first time, the model-specific simulation ses-
sion settings are initialized by copying the global default settings, and then by applying any further set-
tings that are saved in the model within OpenModelica-specific __OpenModelica_commandLineOptions and
__OpenModelica_simulationFlags annotations. Note that the latter may partially override the former, if they
give different values to the same flags.
You can change those model-specific settings at will with the Simulation Setup window. Any change you make
will be remembered until the end of the simulation session, i.e. until you close OMEdit. This is very useful to
experiment with different settings and find the optimal ones, or to investigate bugs by turning on logging options,
etc. If you check the Save translation flags and Save simulation flags options in the simulation setup,
those settings will be saved in the model within the corresponding OpenModelica-specific annotations, so that you
can get the same behavior when you start a new session later on, or if someone else loads the model on a different
computer. Otherwise, all of those changes will be forgotten when you exit OMEdit.
If you change the global default settings after running some models, the simulation settings of those models will
be reset as if you closed OMEdit and restarted a new session: the new global options will first be applied, and then
any further setting saved in the OpenModelica-specific annotations will be applied, possibly overriding the global
options if the same flags get different values from the annotations. Any model-specific settings that you may have
changed with Simulation Setup up to that point will be lost, unless you saved them in the OpenModelica-specific
annotations before changing the global default settings.
3.27 Debugger
By default OMEdit loads the Modelica Standard Library (MSL) as a system library. System libraries are read-only.
If you want to edit MSL you need to load it as user library instead of system library. We don't recommend editing
MSL but if you really need to and understand the consequences then follow these steps,
• Go to Tools > Options > Libraries.
• Remove Modelica & ModelicaReference from list of system libraries.
• Uncheck force loading of Modelica Standard Library.
• Add $OPENMODELICAHOME/lib/omlibrary/Modelica X.X/package.mo under user libraries.
• Restart OMEdit.
A new library can be installed with the help of the package manager. Click File->Manage Libraries->Install
Library to open the install library dialog. OMEdit lists the libraries that are available for installation through the
package manager.
In order to convert the libraries right-click the model/package in the Libraries Browser and choose Convert to
newer versions of used libraries. OMEdit will read the used libraries from the uses-annotation and list any new
version of the library that provide the conversion using the conversion script.
Follow the same steps as defined in Creating a New Modelica Class. Additionally make sure you check the State
checkbox.
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.
Support for Modelica state machines was added in the Modelica Language Specification v3.3. A subtle problem can
occur if Modelica v3.2 libraries are loaded, e.g., the Modelica Standard Library v3.2.2, because in this case OMC
automatically switches into Modelica v3.2 compatibility mode. Trying to simulate a state machine in Modelica
v3.2 compatibility mode results in an error. It is possible to use the OMC flag --std=latest in order to ensure
(at least) Modelica v3.3 support. In OMEdit this can be achieved by setting that flag in the Tools > Options >
Simulation dialog.
Modelica state machines debugger is implemented as a visualization, which allows the user to run the state machines
simulation as an animation.
A special Diagram Window is developed to visualize the active and inactive states. The active and inactive value
of the states are stored in the OpenModelica simulation result file. After the successful simulation, of the state
machine model, OMEdit reads the start, stop time values, and initializes the visualization controls accordingly.
The controls allows the easy manipulation of the visualization,
• Rewind - resets the visualization to start.
• Play - starts the visualization.
• Pause - pauses the visualization.
• Time - allows the user to jump at any specific time.
• Speed - speed of the visualization.
• Slider - controls the time.
The visualization is based on the simulation result file. All three formats of the simulation result file are supported
i.e., mat, csv and plt where mat is a matlab file format, csv is a comma separated file and plt is an ordered text file.
It is only possible to debug one state machine at a time. This is achieved by marking the result file active in the
Variables Browser. The visualization only read the values from the active result file. It is possible to simulate
several state machine models. In that case, the user will see a list of result files in the Variables Browser. The user
can switch between different result files by right clicking on the result file and selecting Set Active in the context
menu.
OMEdit can be be used as a Text editor. Currently support for editing MetaModelica,Modelica and C/C++ are
available with syntax highlighting and autocompletion of keywords and types. Additionaly the Modelica and
MetaModelica files are provided with autocompletion of code-snippets along with keywords and types. The users
can load the directory from file menu File > Open Directory. which opens the Directory structure in the Libraries-
browser.
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.
Support to search in OMEdit texteditor is available. The search browser can be enabled by selecting View >
Windows > Search browser or through shortcut keys (ctrl+h).
The users can start the search by loading the directory they want to search and fill in the text to be searched for and
file pattern if needed and click the search button.
After the search is completed the results are presented to the users in a separate window, The search results contains
the following
1) The name of the files where the searched word is matched
2) The line number and text of the matched word.
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.
On Unix/Linux systems temporary directory is the path in the TMPDIR environment variable or /tmp if TMPDIR is
not defined appended with directory paths OpenModelica<USERNAME>/OMEdit so the complete path is usually
/tmp/OpenModelica<USERNAME>/OMEdit.
On Windows its the path in the TEMP or TMP environment variable appended with directory paths OpenModel-
ica/OMEdit so the complete path is usually %TEMP%/OpenModelica/OMEdit.
All the log files are always generated in the temporary directory. Choose Tools > Open Temporary Directory to
open the temporary directory.
By default the working directory has the same path as the temporary directory. You can change the working
directory from Tools > Options > General see section General Options.
For each simulation a new directory with the model name is created in the working directory and then all the
simulation intermediate and results files are generated in it.
When the text is too big / too small to read there are options to change the font size used in OMEdit, see Text Editor
Options.
If you are using a high-resolution screen (1080p, 4k and more) and the app is blurry or the overall proportions of
the different windows are off, it can help to change the DPI settings.
On Windows it is possible to change the scaling factor to adjust the size of text, apps and other times, but the default
setting might not be appropriate for OMEdit e.g., on compact notebooks with high resolution screens.
You can either change the scaling factor for the whole Windows system or only change the scaling used for OMEdit.
This is done by changing the Compatibility settings for High DPI settings for OMEdit.exe with the following steps:
1. Press Windows-Key and type OpenModelica Connection Editor and right-click on the app and Open file
location, Figure 3.24.
2. Right-click on OpenModelica Connection Editor and open Properties.
3. In the properties window go to tab Compatibility and open Change high DPI settings. In the High DPI
settings for OMEdit.exe choose Use the settings to fix scaling problems for this program instead of the one
in Settings and Override high DPI scaling behavior.Scaling performed by: and choose System from the
drop-down menu, Figure 3.25.
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-6, 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.
83
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
When the simulation is finished the file HelloWorld_res.csv contains the simulation data:
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.
Plot command have a number of optional arguments to further customize the the resulting diagram.
>>> 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\";
84 Chapter 4. 2D Plotting
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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 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.\";
86 Chapter 4. 2D Plotting
CHAPTER
FIVE
OPENMODELICA COMPILER
The OpenModelica Compiler (OMC) consists of a frontend, backend, code generation and the runtimes.
1. Lexical Analysis
Keywords, operators and identifiers are extracted from the model.
2. Parsing
An abstract syntax tree represented in Meta-Modelica is created from the operators and identifiers.
3. Semantic Analysis
The abstract syntax tree gets tested for semantic errors.
4. Intermediate Representation
Translation of the abstract syntax tree to an intermediate representation called SCode in MetaModelica. This
is further processed by the frontend producing DAE intermediate representation code.
5. Symbolic Optimization Backend
The intermediate representation gets optimized and preprocessed.
6. Code Generation
Executable code gets generated from the low level intermediate representation.
For more details see [FPA+20]. A full list of compiler flags can be found in OpenModelica Compiler Flags.
1. Pre-Optimization
• Partitioning
• Alias removal
2. Causalization
• Matching
• Sorting
• Index reduction
3. Post-Optimization
• Tearing
• Jacobian
87
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
With compiler debug flag backenddaeinfo it is possible to get additional information from the Backend modules.
• Number of equations / variables
• Number of states
• Information about initialization and simulation system
– Equation types
– Equation system details (linear and non-linear)
The output of backenddaeinfo can be expanded by using additional compiler debug flags stateselection and dis-
creteinfo.
Example
true
>>> setCommandLineOptions("-d=backenddaeinfo,stateselection,discreteinfo")
true
>>> translateModel(BouncingBall)
true
"Notification: Model statistics after passing the front-end and creating the data␣
˓→structures used by the back-end:
* Number of equations: 6
* Number of variables: 6
Notification: Model statistics after passing the back-end for initialization:
* Number of independent subsystems: 3
* Number of states: 0 ()
* Number of discrete variables: 9 (v_new,$PRE.v_new,flying,$PRE.flying,foo,impact,
˓→$whenCondition1,$whenCondition2,$whenCondition3)
From the low level intermediate representation from the backend code will be generated. The default code genera-
tion target is C and offers the largest model coverage. An alternative is the C++ (Cpp) which can produce significant
faster executables in some cases.
The target language can be changed with compiler flag --simCodeTarget.
Depending on the target the compiler will write code and compile everything into a single simulation executable.
5.4.1 C Runtime
In Solving Modelica Models the methods implemented in the C runtime are described. In C Runtime Simulation
Flags the runtime flags are documented.
Solver methods and runtime flags are currently undocumented. Refer to the source code
5.4.3 References
SIX
By default OpenModelica transforms a Modelica model into an ODE representation to perform a simulation by
using numerical integration methods. This section contains additional information about the different integration
methods in OpenModelica. They can be selected by the method parameter of the simulate command or the -s
simflag.
The different methods are also called solver and can be distinguished by their characteristic:
• explicit vs. implicit
• order
• step size control
• multi step
A good introduction on this topic may be found in [CK06] and a more mathematical approach can be found in
[HNorsettW93].
6.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. Fur-
thermore 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 numerical
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.
1 DASPK Webpage
2 Cdaskr source
91
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
6.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.
6.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.
6.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 approx-
imation 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 simu-
lation 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
(continues on next page)
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
The basic explicit solvers are performing with a fixed step-size and differ only in the integration order. The step-size
is based on the numberOfIntervals, the startTime and stopTime parameters in the simulate command: stepSize ≈
stopTime − startTime
numberOfIntervals
• euler - order 1
• heun - order 2
• rungekutta - order 4
The basic implicit solvers are all based on the non-linear solver KINSOL from the SUNDIALS suite. The under-
lining linear solver can be modified with the simflag -impRKLS. The step-size is determined as for the basic explicit
solvers.
• impeuler - order 1
• trapezoid - order 2
• imprungekutta - Based on Radau IIA and Lobatto IIIA defined by its Butcher tableau where the order can
be adjusted by -impRKorder.
The following solvers are marked as experimental, mostly because they are till now not tested very well.
• 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
• irksco - Own developed Runge-Kutta solver - implicit, step-size control, order 1-2
• symSolver - Symbolic inline solver (requires --symSolver) - fixed step-size, order 1
• symSolverSsc - Symbolic implicit inline Euler with step-size control (requires --symSolver) - step-size con-
trol, order 1-2
• qss - A QSS solver
Beside the default ODE simulation, OpenModelica is able to simulate models in DAE mode. The DAE mode is
enabled by the flag --daeMode. In general the whole equation system of a model is passed to the DAE integrator,
including all algebraic loops. This reduces the amount of work that needs to be done in the post optimization phase
of the OpenModelica backend. Thus models with large algebraic loops might compile faster in DAE mode.
Once a model is compiled in DAE mode the simulation can be only performed with SUNDIALS/IDA integrator
and with enabled -daeMode simulation flag. Both are enabled automatically by default, when a simulation run is
started.
6.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.
Only non-linear iteration variables in non-linear strong components require start values. All other start values will
have no influence on convergence of the initial system.
Use -d=initialization to show additional information from the initialization process. In OMEdit Tools->Options-
>Simulation->OMCFlags, in OMNotebook call setCommandLineOptions("-d=initialization")
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␣
(continues on next page)
6.3. Initialization 95
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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_master/build/lib/omlibrary/Modelica 4.0.0+maint.
˓→om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body1.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body1.r_
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_master/build/lib/omlibrary/Modelica 4.0.0+maint.
˓→om/Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body2.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body1.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body1.r_
[/var/lib/jenkins1/ws/OpenModelica_master/build/lib/omlibrary/Modelica 4.0.0+maint.om/
˓→Mechanics/MultiBody/Parts/Body.mo:14:3-15:65:writable] Warning: Parameter body1.r_
"
6.3. Initialization 97
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
1.1
body2.framea.r0[1]
0.9
0.8
0.7
0.6
0.5
0 0.5 1 1.5 2
In many use cases it is useful to import initial values from previous simulations, possibly obtained with another
Modelica tool, which are saved in a .mat file. There are two different options to do that.
The first option is to solve the initial equations specified by the Modelica model, using the previous simulation
results to obtain good initial guesses for the iterative solvers. This can be very helpful in case the initialization
problem involves the solution of large nonlinear systems of equations by means of iterative algorithms, whose con-
vergence is sensitive to the selected initial guess. Importing a previously found solution allows the OpenModelica
solver to pick very good initial guesses for the unknowns of the iterative solvers, thus achieving convergence with a
few iterations at most. Since the initial equations are solved anyway, the values of all variables and derivatives, as
well as of all parameters with fixed = false attribute, are re-computed and fully consistent with the selected initial
conditions, even in case the previously saved simulation results refer to a slightly different model configuration.
Note that parameters with fixed = true will also get their values from the imported .mat file, so if you want to change
them you need to edit the .mat file accordingly.
This option is activated by selecting the simulation result file name in the OMEdit Simulation Setup | Simulation
Flag | Equation System Initialization File input field, or by setting the additional simulation flag -iif=resultfile.mat.
By activating the checkbox Save simulation flags inside the model i.e., __OpenModelica_simulationFlags anno-
tation, a custom annotation __OpenModelica_simulationFlags(iif="filename.mat") is added to the model, so this
setting is saved with the model and is reused when loading the model again later on. It is also possible to specify
at which point in time of the saved simulation results the initial values should be picked, by means of the Simu-
lation Setup | Simulation Flags | Equation System Initialization Time input field, or by setting the simulation flag
-iit=initialTimeValue.
The second option is to skip the solution of the initial equations entirely, and to directly start the simulation using
the imported start values. In this case, the initial equations of the model are ignored, and the initial values of all
parameters and state variables are set to the values loaded from the .mat file. This option is useful in particular to
restart a simulation from the final state of a previous one, without bothering about changing the initial conditions
manually in the Modelica model. Note that the algebraic variables will be recomputed starting from the imported
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 an initial.mat file with some initial values in the root OMEdit
working directory: p1 = 7, p2 = 10, p3 = 21, v1 = 2.8, v2 = 10, x = 4, der(x) = 0. Note that the default directory
when running simulations in OMEdit is a sub-directory named as the full model pathname, located in the working
directory, so it is necessary to go up one directory to access the root working directory.
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.
6.3. Initialization 99
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
When running model M2, the values of the initial.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, which is ignored. 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 variables
v1 and v2. However, in this case the solution of the initial equations is skipped, so the state variable gets its initial
value x = 4 straight from the imported initial.mat file.
For complex start conditions OpenModelica can have trouble finding a solution for the initialization problem with
the default Newton method.
Modelica offers the homotopy operator3 to formulate actual and simplified expression for equations, with homotopy
parameter 𝜆 going from 0 to 1:
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], [Sie12], 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.
If the ODE system contains equations that need to be solved together, so called algebraic loops, OpenModelica can
use a variety of different linear and non-linear methods to solve the equation system during simulation.
For the C runtime the linear solver can be set with -ls and the non-linear solver with -nls. There are dense and
sparse solver available.
Linear solvers
• default : Lapack with totalpivot as fallback [ABB+99]
• lapack : Non-Sparse LU factorization using [ABB+99]
3 Modelica Association, Modelica® - A Unified Object-Oriented Language for Systems Modeling Language Specification - Version 3.4,
6.4.1 References
SEVEN
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.
This section gives a short description how to get started using the equation-based debugger in OMEdit.
This enables tracing symbolic transformations of equations. It is optional but strongly recommended in order to
fully use the debugger. The compilation time overhead from having this tracing on is less than 1%, however, in
addition to that, some time is needed for the system to write the xml file containing the transformation tracing
information.
Enable -d=infoXmlOperations in Tools->Options->Simulation (see section Simulation Options) OR alternatively
click on the checkbox Generate operations in the info xml in Tools->Options->Debugger (see section Debugger
Options) which performs the same thing.
This adds all the transformations performed by OpenModelica on the equations and variables stored in the
model_info.xml file. This is necessary for the debugger to be able to show the whole path from the source equa-
tion(s) to the position of the bug.
Load an interesting model. We will use the package Debugging.mo since it contains suitable, broken models to
demonstrate common errors.
Select and simulate the model as usual. For example, if using the Debugging package, select the model Debug-
ging.Chattering.ChatteringEvents1. If there is an error, you will get a clickable link that starts the debugger. If the
user interface is unresponsive or the running simulation uses too much processing power, click cancel simulation
first.
103
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The debugger opens on the equation where the error was found. You can browse through the dependencies (vari-
ables that are defined by the equation, or the equation is dependent on), and similar for variables. The equations
and variables form a bipartite graph that you can walk.
If the -d=infoXmlOperations was used or you clicked the “generate operations” button, the operations performed
on the equations and variables can be viewed. In the example package, there are not a lot of operations because the
models are small.
Try some larger models, e.g. in the MultiBody library or some other library, to see more operations with several
transformation steps between different versions of the relevant equation(s). If you do not trigger any errors in a
model, you can still open the debugger, using File->Open Transformations File (model_info.json).
This section gives a short description how to get started using the algorithmic debugger in OMEdit. See section
Simulation Options for further details of debugger options.
You should add breakpoints before starting the debugger because sometimes the simulation finishes quickly and
you won't get any chance to add the breakpoints.
There are four ways to start the debugger,
• Open the Simulation Setup and click on Launch Algorithmic Debugger before pressing Simulate.
• Right click the model in Libraries Browser and select Simulate with Algorithmic Debugger.
• Open the Algorithmic Debugger window and from menu select Debug-> Debug Configurations.
• Open the Algorithmic Debugger window and from menu select Debug-> Attach to Running Process.
If you already have a simulation executable with debugging symbols outside of OMEdit then you can use the
Debug->Debug Configurations option to load it.
The debugger also supports MetaModelica data structures so one can debug omc executable. Select omc executable
as program and write the name of the mos script file in Arguments.
If you already have a running simulation executable with debugging symbols outside of OMEdit then you can
use the Debug->Attach to Running Process option to attach the debugger with it. Figure 7.5 shows the Attach
to Running Process dialog. The dialog shows the list of processes running on the machine. The user selects the
program that he/she wish to debug. OMEdit debugger attaches to the process.
Figure 7.6 shows the Algorithmic Debugger window. The window contains the following browsers,
• Stack Frames Browser - shows the list of frames. It contains the program context buttons like resume,
interrupt, exit, step over, step in, step return. It also contains a threads drop down which allows switching
between different threads.
• BreakPoints Browser - shows the list of breakpoints. Allows adding/editing/removing breakpoints.
• Locals Browser - Shows the list of local variables with values. Select the variable and the value will be
shown in the bottom right window. This is just for convenience because some variables might have long
values.
• Debugger CLI - shows the commands sent to gdb and their responses. This is for advanced users who want
to have more control of the debugger. It allows sending commands to gdb.
• Output Browser - shows the output of the debugged executable.
EIGHT
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
requirement 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.
Packages can be mapped onto individual .mo files or onto hierarchical directory structures on the file system,
according to the rules set forth in Section 13.4. of the language specification. The file encoding must be UTF-
8; the use of a BOM at the beginning of the file is deprecated and preferably avoided. If there are non-ASCII
characters in the comments or in the documentation of your library, make sure that the file is encoded as UTF-8.
If a directory-based representation is chosen, each .mo file must start with a within clause, and each directory should
contain a package.order file that lists all the classes and constants defined as separate files in that directory.
When using revision control systems such as GIT or SVN, if the library is stored in a directory structure, it is
recommended to include the top-level directory (that must have the same name as the top-level package) in the
repository itself, to avoid problems in case the repository is cloned locally on a directory that doesn't have the right
name.
The top-level directory name, or the single .mo file containing the entire package, should be named exactly as the
package (e.g. Modelica), possibly followed by a space and by the version number (e.g. Modelica 3.2.3).
111
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
According to the rules set forth in Section 7.2.5 of the language specification, when instantiating arrays of compo-
nents, modifier values should be arrays of the same size of the component array, unless the each prefix is introduced,
in which case the scalar modifier values is applied to all the elements of the array. Thus, if MyComponent has a
Real parameter p, these are all valid declarations
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.
According to Section 4.4.5 of the language specification, "A component declared with a condition-attribute can
only be modified and/or used in connections". When dealing, e.g., with conditional input connectors, one can use
the following patterns:
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;
(continues on next page)
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.
The following code is illegal, because it uses the equality '=' operator, which is reserved for equations, instead of
the assignment operator ':=' inside an algorithm:
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.
According to Section 12.2 of the language specification, only input and output formal parameters are allowed in
the function's public variable section. Hence, the following function declaration is not valid:
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.6, so it is not supported in OpenModelica up to version 1.22.0. It has now been included in the draft for
the 3.7 language specification, so it will be implemented in the future also by OpenModelica.
The simulation of Modelica models of dynamical systems requires the tool to determine a consistent initial solution
for the simulation to start. To do so, the system equations are augmented by adding one initial condition for each
continuous state variable (after index reduction) and one initial condition for each discrete state variable. Then, the
augmented system is solved upon initialization.
These initial conditions can be formulated by adding a start = <expression> and a fixed = true attribute to those
variables, e.g.
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 conditions,
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.
The Modelica_LinearSystem2 library was originally developed in Dymola with a plan of eventually making it
part of the Modelica Standard Library (thus the underscore in the library name). The library is based on several
functions, e.g. readStringMatrix(), simulateModel(), linearizeModel() that are built-in Dymola functions but are
not part of the Modelica Standard Library.
In principle, these functions could be standardized and become part of the ModelicaServices library, which collects
standardized interfaces to tool-specific functionality; then, OpenModelica could easily implement them based on
its internal functionality. However, until this effort is undertaken, the Modelica_LinearSystem2 library cannot be
considered as a full-fledged Modelica library, but only a Dymola-specific one.
If you are interested in using this library in OpenModelica and are willing to contribute to get it supported, please
contact the development team, e.g. by opening an ticket on the issue tracker.
NINE
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 vari-
ables 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.
117
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
TEN
The Functional Mock-up Interface (FMI) Standard for model exchange and co-simulation allows export, exchange
and import of pre-compiled models between different tools. The FMI standard is Modelica independent, so import
and export works both between different Modelica or non-Modelica tools.
See also OMSimulator documentation.
To export a FMU use the OpenModelica command buildModelFMU() from the command line interface, OMShell,
OMNotebook or MDT. The FMU export command is also integrated in OMEdit. Select File > Export > FMU.
Or alternatively, right click a model to obtain the export command. The FMU package is generated in the current
working directory of OMC or the directory set in OMEdit > Options > FMI > Move FMU. You can use the cd()
command to see the current location. The location of the generated FMU is printed in the Messages Browser of
OMEdit or on the command line.
You can set which version of FMI to export through OMEdit settings, see section FMI Options.
To export the bouncing ball example to an FMU, use the following commands:
true
>>> buildModelFMU(BouncingBall)
"«DOCHOME»/BouncingBall.fmu"
Note:
Notification: Model statistics after passing the front-end and creating the data structures used by the back-end:
* Number of equations: 6
* Number of variables: 6
Notification: Model statistics after passing the back-end for initialization:
* Number of independent subsystems: 3
* Number of states: 0 ()
* Number of discrete variables: 9 (v_new,$PRE.v_new,flying,$PRE.flying,foo,impact,$whenCondition1,$whenCondition2,$whenCo
* Number of discrete states: 0 ()
* Number of clocked states: 0 ()
* Top-level inputs: 0
119
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
120 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
After the command execution is complete you will see that a file BouncingBall.fmu has been created. Its contents
varies depending on the target platform. On the machine generating this documentation the contents in Listing
10.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
the FMU, they will be shown in the command line window and logged in this log file as well.
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.4 for Model Exchange FMUs and FMI 2.0.4 for Co-Simulation FMUs.
For the Co-Simulation FMU two integrator methods are available:
• Forward Euler [default]
• SUNDIALS CVODE (see1 )
Forward Euler uses root finding, which does an Euler step of communicationStepSize in fmi2DoStep. Events
are checked for before and after the call to fmi2GetDerivatives.
If CVODE is chosen as integrator the FMU should also include runtime dependencies (--
fmuRuntimeDepends=modelica) to copy all used dynamic libraries into the generated FMU to make it
exchangeable.
To export a Co-Simulation FMU with CVODE for the bouncing ball example use the following commands:
true
>>> setCommandLineOptions("--fmiFlags=s:cvode")
true
>>> buildModelFMU(BouncingBall, version = "2.0", fmuType="cs")
"«DOCHOME»/BouncingBall.fmu"
Note:
Notification: Model statistics after passing the front-end and creating the data structures used by the back-end:
* Number of equations: 6
* Number of variables: 6
1 Sundials Webpage
The FMU BouncingBall.fmu will have a new file BouncingBall_flags.json in its resources directory. By manually
changing its content users can change the solver method without recompiling the FMU.
The BouncingBall_flags.json for this example is displayed in Listing 10.2.
122 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
OpenModelica can export FMUs that are compiled with CMake (default) or Makefiles. CMake version v3.21 or
newer is recommended, minimum CMake version is v3.5.
The Makefile FMU export will be removed in a future version of OpenModelica. Set compiler flag --
fmuCMakeBuild=false to use the Makefiles export.
The FMU contains a CMakeLists.txt file in the sources directory that can be used to re-compile the FMU for a
different host and is also used to cross-compile for different platforms.
The CMake compilation accepts the following settings:
• BUILD_SHARED_LIBS: Boolean value to switch between dynamic and statically linked binaries.
– ON (default): Compile DLL/Shared Object binary object.
– OFF: Compile static binary object.
• FMI_INTERFACE_HEADER_FILES_DIRECTORY: String value specifying path to FMI header files containing
fmi2Functions.h, fmi2FunctionTypes.h and fmi2TypesPlatforms.h.
– Defaults to a location inside the OpenModelica installation directory, which was used to create the
FMU. They need to be version 2.0.4 from the FMI Standard.
• RUNTIME_DEPENDENCIES_LEVEL: String value to specify runtime dependencies set.
– none: Adds no runtime dependencies to FMU. The FMU can't be used on a system if it doesn't provided
all needed dependencies.
– modelica (default): Add Modelica runtime dependencies to FMU, e.g. a external C library used from
a Modelica function. Needs CMake version v3.21 or newer.
– all: Add system and Modelica runtime dependencies. Needs CMake version v3.21 or newer.
• NEED_CVODE: Boolean value to integrate CVODE integrator into CoSimulation FMU.
– ON: Link to SUNDIALS CVODE. If CVODE is not in a default location CVODE_DIRECTORY needs to
be set. Its also recommended to use RUNTIME_DEPENDENCIES_LEVEL=modelica or higher to add
SUNDIALS runtime dependencies into the FMU.
– OFF (default): Don't link to SUNDIALS CVODE.
• CVODE_DIRECTORY: String value with location of libraries sundials_cvode and sundials_nvecserial
with SUNDIALS version 5.4.0.
– Defaults to a location inside the OpenModelica installation directory, which was used to create the
FMU.
Then use CMake to configure, build and install the FMU. To repack the FMU after installation use custom target
create_fmu.
For example to re-compile the FMU with cmake and runtime dependencies use:
10.1.3 Platforms
The platforms setting specifies for what target system the FMU is compiled:
• Empty: Create a Source-Code-only FMU.
• native: Create a FMU compiled for the exporting system.
• <cpu>-<vendor>-<os> host triple: OpenModelica searches for programs in PATH matching pat-
tern <cpu>-<vendor>-<os>cc to compile. E.g. x86_64-linux-gnu for a 64 bit Linux OS or
i686-w64-mingw32 for a 32 bit Windows OS using MINGW.
• <cpu>-<vendor>-<os> docker run <image> Host triple with Docker image: OpenModelica will use
the specified Docker image to cross-compile for given host triple. Because privilege escalation is very easy
to achieve with Docker OMEdit adds --pull=never to the Docker calls for the multiarch/crossbuild
images. Only use this option if you understand the security risks associated with Docker images from
unknown sources. E.g. x86_64-linux-gnu docker run --pull=never multiarch/crossbuild to
cross-compile for a 64 bit Linux OS. Because system libraries can be different for different versions of the
same operating system, it is advised to use --fmuRuntimeDepends=all.
If you want to simulate a single, stand-alone FMU, or possibly a connection of several FMUs, the recommended tool
to do that is OMSimulator, see the OMSimulator documentation and Graphical Modelling for further information.
FMI Import allows to use an FMU, generated according to the FMI for Model Exchange 2.0 standard, as a com-
ponent in a Modelica model. This can be useful if the FMU describes the behavior of a component or sub-system
in a structured Modelica model, which is not easily turned into a pure FMI-based model that can be handled by
OMSimulator.
FMI is a computational description of a dynamic model, while a Modelica model is a declarative description;
this means that not all conceivable FMUs can be successfully imported as Modelica models. Also, the current
implementation of FMU import in OpenModelica is still somewhat experimental and not guaranteed to work in
all cases. However, if the FMU-ME you want to import was exported from a Modelica model and only represents
continuous time dynamic behavior, it should work without problems when imported as a Modelica block.
Please also note that the current implementation of FMI Import in OpenModelica is based on a built-in wrap-
per that uses a reinit() statement in an algorithm section. This is not allowed by the Modelica Language
Specification, so it is necessary to set the compiler to accept this non-standard construct by setting the --
allowNonStandardModelica=reinitInAlgorithms compiler flag. In OMEdit, you can set this option by activating
the Enable FMU Import checkbox in the Tools | Options | Simulation | Translation Flags tab. This will generate
a warning during compilation, as there is no guarantee that the imported model using this feature can be ported
to other Modelica tools; if you want to use a model that contains imported FMUs in another Modelica tool, you
should rely on the other tool's import feature to generate the Modelica blocks corresponding to the FMUs.
After setting the --allowNonStandardModelica flag, to import the FMU package use the OpenModelica command
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
124 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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.
This chapter gives a short description how to get started using the TLM-Based co-simulation accessible via
OMEdit.
The TLM Based co-simulation provides the following general functionalities:
• Import and add External non-Modelica models such as Matlab/SimuLink, Adams, and BEAST models
• Import and add External Modelica models e.g. from tools such as Dymola or Wolfram SystemModeler,
etc.
• Specify startup methods and interfaces of the external model
• Build the composite models by connecting the external models
• Set the co-simulation parameters in the composite model
• Simulate the composite models using TLM based co-simulation
The graphical composite model editor is an extension and specialization of the OpenModelica connection editor
OMEdit. A composite model is composed of several external sub-models including the interconnections between
these sub-models. External models are models which need not be in Modelica, they can be FMUs, or models
accessed by proxies for co-simulation and connected by TLM-connections. The standard way to store a composite
model is in an XML format. The XML schema standard is accessible from tlmModelDescription.xsd. Currently
composite models can only be used for TLM based co-simulation of external models.
To load the composite model, select File > Open Composite Model(s) from the menu and select composite-
model.xml.
OMEdit loads the composite model and show it in the Libraries Browser. Double-clicking the composite model
in the Libraries Browser will display the composite model as shown below in Figure 10.2.
• 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 10.3)
The TLM Co-Simulation setup appears as shown below in Figure 10.4.
Click Simulate from the Co-simulation setup to confirm the co-simulation. Figure 10.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.
126 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Figure 10.3: Co-simulating and Fetching Interface Data of a composite model from the Popup Menu .
128 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
When the co-simulation of the composite model is completed successful, simulation results are collected and
visualized in the OMEdit plotting perspective as shown in Figure 10.6 and Figure 10.7. The Variables Browser
display variables that can be plotted. Each variable has a checkbox, checking it will plot the variable.
First step in co-simulation Modeling is to prepare the different external simulation models with TLM interfaces.
Each external model belongs to a specific simulation tool, such as MATLAB/Simulink*, BEAST, MSC/ADAMS,
Dymola and Wolfram SystemModeler.
When the external models have all been prepared, the next step is to load external models in OMEdit by selecting
the File > Load External Model(s) from the menu.
OMEdit loads the external model and show it in the Libraries Browser as shown below in Figure 10.8.
130 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
We will use the "Double pendulum" composite model which is a multibody system that consists of three sub-
models: Two OpenModelica Shaft sub-models (Shaft1 and Shaft2) and one SKF/BEAST bearing sub-model
that together build a double pendulum. The SKF/BEAST bearing sub-model is a simplified model with only
three balls to speed up the simulation. Shaft1 is connected with a spherical joint to the world coordinate system.
The end of Shaft1 is connected via a TLM interface to the outer ring of the BEAST bearing model. The inner ring
of the bearing model is connected via another TLM interface to Shaft2. Together they build the double pendulum
with two shafts, one spherical OpenModelica joint, and one BEAST bearing.
To create a new composite model select File > New Composite Model from the menu.
Your new composite model will appear in the in the Libraries Browser once created. To facilitate the process of
textual composite modeling and to provide users with a starting point, the Text View (see Figure 10.9) includes
the composite model XML elements and the default simulation parameters.
132 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
It is possible to build the double pendulum by drag-and-drop of each simulation model component (sub-model)
from the Libraries Browser to the Diagram View. To place a component in the Diagram View of the double
pendulum model, drag each external sub-model of the double pendulum (i.e. Shaft1, Shaft2, and BEAST bearing
sub-model) from the Libraries Browser to the Diagram View.
To retrieve list of TLM interface data for sub-models, do any of the following methods:
• 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 10.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 10.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 10.12.
134 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
When the sub-models and interface points have all been placed in the Diagram View, similar to Figure 10.12, the
next step is to connect the sub-models. Sub-models are connected using the Connection Line Button ( ) from
the toolbar.
To connect two sub-models, select the Connection Line Button and place the mouse cursor over an interface and
click the left mouse button, then drag the cursor to the other sub-model interface, and click the left mouse button
again. A connection dialog box as shown below in Figure 10.13 will appear in which you will be able to specify
the connection attributes.
Continue to connect all sub-models until the composite model Diagram View looks like the one in Figure 10.14
below.
136 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Click Simulation Parameters button ( t0 t1) from the toolbar (requires a composite model to be active in Mod-
elWidget)
• Right click an empty location in the Diagram View of the composite model and choose Simulation Param-
eters from the popup menu (see Figure 10.16)
The co-simulation parameter dialog of the composite model appears as shown below in Figure 10.17 in which you
will be able to specify the simulation parameters.
138 Chapter 10. FMI and TLM-Based Simulation and Co-simulation of External Models
CHAPTER
ELEVEN
OMSIMULATOR
Version: v2.1.1.post247-g614c663
11.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 utilizing
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.
11.2 OMSimulator
A brief description of all command line flags will be displayed using OMSimulator --help:
139
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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.
11.2.2 Examples
11.3 OMSimulatorLib
This library is the core of OMSimulator and provides a C interface that can easily be utilized to handle co-simulation
scenarios.
11.4 C-API
11.4.1 RunFile
11.4.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.
11.4.3 addBus
11.4.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.
11.4.5 addConnector
11.4.6 addConnectorToBus
11.4.7 addConnectorToTLMBus
11.4.8 addExternalModel
11.4.9 addResources
Adds an external resources to an existing SSP. The external resources should be a ".ssv" or ".ssm" file
11.4.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.
11.4.11 addSubModel
11.4.12 addSystem
11.4.13 addTLMBus
11.4.14 addTLMConnection
11.4.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
11.4.16 copySystem
Copies a system.
11.4.17 delete
11.4.18 deleteConnection
The two arguments crefA and crefB get swapped automatically if necessary.
11.4.19 deleteConnectorFromBus
11.4.20 deleteConnectorFromTLMBus
11.4.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"
11.4.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.
11.4.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.
oms_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_setReal("model.root.A.param1", "10")
oms_duplicateVariant("model", "varB")
oms_addSubModel("varB.root.B" ,"B.fmu")
oms_setReal("varB.root.A.param2", "20")
oms_export("varB", "variant.ssp")
Variant.ssp
SystemStructure.ssd
varB.ssd
resources\
A.fmu
B.fmu
11.4.24 export
11.4.25 exportDependencyGraphs
11.4.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.
11.4.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.
11.4.28 exportSnapshot
11.4.29 extractFMIKind
Extracts the FMI kind of a given FMU from the file system.
11.4.30 faultInjection
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
11.4.31 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
11.4.32 getBoolean
11.4.33 getBus
11.4.34 getComponentType
11.4.35 getConnections
11.4.36 getConnector
11.4.37 getDirectionalDerivative
11.4.38 getElement
11.4.39 getElements
11.4.40 getFMUInfo
11.4.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.
11.4.42 getInteger
11.4.43 getModelState
11.4.44 getReal
11.4.45 getResultFile
Gets the result filename and buffer size of the given model cref.
11.4.46 getSolver
11.4.47 getStartTime
11.4.48 getStopTime
11.4.49 getString
11.4.50 getSubModelPath
11.4.51 getSystemType
11.4.52 getTLMBus
Gets the TLM bus objects of the given TLM bus cref.
11.4.53 getTLMVariableTypes
˓→***descriptions);
11.4.54 getTime
11.4.55 getTolerance
11.4.56 getVariableStepSize
11.4.57 getVersion
11.4.58 importFile
11.4.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.
11.4.60 initialize
11.4.61 instantiate
11.4.62 list
11.4.63 listUnconnectedConnectors
11.4.64 listVariants
This API shows the number of variants available [(e.g). SystemStructure.ssd, VarA.ssd, VarB.ssd ] from a ssp file.
oms_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_duplicateVariant("model", "varA")
oms_duplicateVariant("varA", "varB")
oms_listVariants("varB")
<oms:Variants>
<oms:variant name="model" />
<oms:variant name="varB" />
<oms:variant name="varA" />
</oms:Variants>
11.4.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.
11.4.66 newModel
11.4.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"
11.4.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.
11.4.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.
11.4.70 rename
11.4.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.
11.4.72 reset
11.4.73 setActivationRatio
Experimental feature for setting the activation ratio of FMUs for experimenting with multi-rate master algorithms.
11.4.74 setBoolean
11.4.75 setBusGeometry
11.4.76 setCommandLineOption
Available flags:
11.4.77 setConnectionGeometry
11.4.78 setConnectorGeometry
11.4.79 setElementGeometry
11.4.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.
11.4.81 setInteger
11.4.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.
11.4.83 setLoggingCallback
11.4.84 setLoggingInterval
11.4.85 setLoggingLevel
11.4.86 setMaxLogFileSize
Sets maximum log file size in MB. If the file exceeds this limit, the logging will continue on stdout.
11.4.87 setReal
11.4.88 setRealInputDerivative
11.4.89 setResultFile
11.4.90 setSolver
11.4.91 setStartTime
11.4.92 setStopTime
11.4.93 setString
11.4.94 setTLMBusGeometry
11.4.95 setTLMConnectionParameters
11.4.96 setTLMPositionAndOrientation
11.4.97 setTLMSocketData
11.4.98 setTempDirectory
11.4.99 setTolerance
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.
11.4.100 setUnit
11.4.101 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
11.4.102 setWorkingDirectory
11.4.103 simulate
11.4.104 simulate_realtime
11.4.105 stepUntil
11.4.106 terminate
11.5 OMSimulatorLua
This is a shared library that provides a Lua interface for the OMSimulatorLib library.
11.5.1 Examples
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
(continues on next page)
oms_instantiate("model")
oms_setReal("model.root.system1.x_start", 2.5)
oms_initialize("model")
oms_simulate("model")
oms_terminate("model")
oms_delete("model")
11.5.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.
11.5.3 addBus
status = oms_addBus(cref)
11.5.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.
11.5.5 addConnector
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
11.5.6 addConnectorToBus
11.5.7 addConnectorToTLMBus
11.5.8 addExternalModel
11.5.9 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")
11.5.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.
11.5.11 addSubModel
11.5.12 addSystem
11.5.13 addTLMBus
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
11.5.14 addTLMConnection
11.5.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
11.5.16 copySystem
Copies a system.
11.5.17 delete
status = oms_delete(cref)
11.5.18 deleteConnection
The two arguments crefA and crefB get swapped automatically if necessary.
11.5.19 deleteConnectorFromBus
11.5.20 deleteConnectorFromTLMBus
11.5.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"
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")
11.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.
oms_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_setReal("model.root.A.param1", "10")
oms_duplicateVariant("model", "varB")
oms_addSubModel("varB.root.B" ,"B.fmu")
oms_setReal("varB.root.A.param2", "20")
oms_export("varB", "variant.ssp")
Variant.ssp
SystemStructure.ssd
varB.ssd
resources\
A.fmu
B.fmu
11.5.23 export
11.5.24 exportDependencyGraphs
11.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.
11.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.
11.5.27 exportSnapshot
11.5.28 faultInjection
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
11.5.29 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.
11.5.30 getBoolean
11.5.31 getDirectionalDerivative
11.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.
11.5.33 getInteger
11.5.34 getModelState
11.5.35 getReal
11.5.36 getSolver
11.5.37 getStartTime
11.5.38 getStopTime
11.5.39 getString
11.5.40 getSystemType
11.5.41 getTime
11.5.42 getTolerance
11.5.43 getVariableStepSize
11.5.44 getVersion
version = oms_getVersion()
11.5.45 importFile
11.5.46 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.
11.5.47 initialize
status = oms_initialize(cref)
11.5.48 instantiate
status = oms_instantiate(cref)
11.5.49 list
11.5.50 listUnconnectedConnectors
11.5.51 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_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_duplicateVariant("model", "varA")
oms_duplicateVariant("varA", "varB")
oms_listVariants("varB")
<oms:Variants>
<oms:variant name="model" />
<oms:variant name="varB" />
<oms:variant name="varA" />
</oms:Variants>
11.5.52 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.
11.5.53 newModel
status = oms_newModel(cref)
11.5.54 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")
11.5.55 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")
11.5.56 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.
11.5.57 rename
11.5.58 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.
11.5.59 reset
status = oms_reset(cref)
11.5.60 setActivationRatio
Experimental feature for setting the activation ratio of FMUs for experimenting with multi-rate master algorithms.
status = experimental_setActivationRatio(cref, k)
11.5.61 setBoolean
11.5.62 setCommandLineOption
status = oms_setCommandLineOption(cmd)
Available flags:
11.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.
11.5.64 setInteger
11.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)
11.5.66 setLoggingInterval
11.5.67 setLoggingLevel
oms_setLoggingLevel(logLevel)
11.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)
11.5.69 setReal
• After instantiation and before initialization: Same as before instantiation, but the values are applied imme-
diately to the simulation unit.
• After initialization: Can be used to force external inputs, which might cause discrete changes of continuous
signals.
11.5.70 setRealInputDerivative
11.5.71 setResultFile
11.5.72 setSolver
11.5.73 setStartTime
11.5.74 setStopTime
11.5.75 setString
11.5.76 setTLMPositionAndOrientation
status = oms_setTLMPositionAndOrientation(cref, x1, x2, x3, A11, A12, A13, A21, A22,␣
˓→A23, A31, A32, A33)
11.5.77 setTLMSocketData
11.5.78 setTempDirectory
status = oms_setTempDirectory(newTempDir)
11.5.79 setTolerance
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.
11.5.80 setUnit
11.5.81 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
11.5.82 setWorkingDirectory
status = oms_setWorkingDirectory(newWorkingDir)
11.5.83 simulate
status = oms_simulate(cref)
11.5.84 simulate_realtime
status = experimental_simulate_realtime(ident)
11.5.85 stepUntil
11.5.86 terminate
status = oms_terminate(cref)
11.6 OMSimulatorPython
This is a shared library that provides a Python interface for the OMSimulatorLib library.
Installation using pip is recommended:
11.6.1 Examples
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()
11.6.3 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.
11.6.4 addBus
status = oms.addBus(cref)
11.6.5 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.
11.6.6 addConnector
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
11.6.7 addConnectorToBus
11.6.8 addConnectorToTLMBus
11.6.9 addExternalModel
11.6.10 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")
(continues on next page)
oms.addResources("addExternalResources", "../../resources/externalGain.ssv")
## export the ssp with new resources
oms_export("addExternalResources", "addExternalResources1.ssp")
11.6.11 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.
11.6.12 addSubModel
11.6.13 addSystem
11.6.14 addTLMBus
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
11.6.15 addTLMConnection
11.6.16 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
11.6.17 copySystem
Copies a system.
11.6.18 delete
status = oms.delete(cref)
11.6.19 deleteConnection
The two arguments crefA and crefB get swapped automatically if necessary.
11.6.20 deleteConnectorFromBus
11.6.21 deleteConnectorFromTLMBus
11.6.22 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")
11.6.23 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)
11.6.24 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.
oms_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_setReal("model.root.A.param1", "10")
oms_duplicateVariant("model", "varB")
oms_addSubModel("varB.root.B" ,"B.fmu")
oms_setReal("varB.root.A.param2", "20")
oms_export("varB", "variant.ssp")
Variant.ssp
SystemStructure.ssd
varB.ssd
resources\
A.fmu
B.fmu
11.6.25 export
11.6.26 exportDependencyGraphs
11.6.27 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.
11.6.28 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.
11.6.29 exportSnapshot
11.6.30 faultInjection
type Description"
oms_fault_type_bias y = y.$original + faultValue
oms_fault_type_gain y = y.$original * faultValue
oms_fault_type_const y = faultValue
11.6.31 freeMemory
Free the memory allocated by some other API. Pass the object for which memory is allocated.
oms.freeMemory(obj)
11.6.32 getBoolean
11.6.33 getDirectionalDerivative
11.6.34 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.
11.6.35 getInteger
11.6.36 getReal
11.6.37 getResultFile
Gets the result filename and buffer size of the given model cref.
11.6.38 getSolver
11.6.39 getStartTime
11.6.40 getStopTime
11.6.41 getString
11.6.42 getSubModelPath
11.6.43 getSystemType
11.6.44 getTime
11.6.45 getTolerance
11.6.46 getVariableStepSize
11.6.47 getVersion
oms = OMSimulator()
oms.getVersion()
11.6.48 importFile
11.6.49 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.
11.6.50 initialize
status = oms.initialize(cref)
11.6.51 instantiate
status = oms.instantiate(cref)
11.6.52 list
11.6.53 listUnconnectedConnectors
11.6.54 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_newModel("model")
oms_addSystem("model.root", "system_wc")
oms_addSubModel("model.root.A", "A.fmu")
oms_duplicateVariant("model", "varA")
oms_duplicateVariant("varA", "varB")
oms_listVariants("varB")
<oms:Variants>
<oms:variant name="model" />
<oms:variant name="varB" />
<oms:variant name="varA" />
</oms:Variants>
11.6.55 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.
11.6.56 newModel
status = oms.newModel(cref)
11.6.57 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)
(continues on next page)
## 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")
11.6.58 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")
11.6.59 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.
11.6.60 rename
11.6.61 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.
11.6.62 reset
status = oms.reset(cref)
11.6.63 setBoolean
11.6.64 setCommandLineOption
status = oms.setCommandLineOption(cmd)
Available flags:
11.6.65 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.
11.6.66 setInteger
11.6.67 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)
11.6.68 setLoggingInterval
11.6.69 setLoggingLevel
oms.setLoggingLevel(logLevel)
11.6.70 setMaxLogFileSize
Sets maximum log file size in MB. If the file exceeds this limit, the logging will continue on stdout.
oms.setMaxLogFileSize(size)
11.6.71 setReal
11.6.72 setRealInputDerivative
11.6.73 setResultFile
11.6.74 setSolver
11.6.75 setStartTime
11.6.76 setStopTime
11.6.77 setString
11.6.78 setTempDirectory
status = oms.setTempDirectory(newTempDir)
11.6.79 setTolerance
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.
11.6.80 setUnit
11.6.81 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
11.6.82 setWorkingDirectory
status = oms.setWorkingDirectory(newWorkingDir)
11.6.83 simulate
status = oms.simulate(cref)
11.6.84 stepUntil
11.6.85 terminate
status = oms.terminate(cref)
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];
(continues on next page)
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 11.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:
28 results.append(4.0*inside/i)
29 model.terminate()
30 model.delete()
31
The following figure shows the approximation of pi in relation to the number of samples.
Figure 11.1: Results of the above batch simulation which approximates the value of pi
11.7 OpenModelicaScripting
This is a shared library that provides a OpenModelica Scripting interface for the OMSimulatorLib library.
11.7.1 Examples
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
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");
unloadOMSimulator();
11.7.3 addBus
status := oms_addBus(cref);
11.7.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.
11.7.5 addConnector
"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"
11.7.6 addConnectorToBus
11.7.7 addConnectorToTLMBus
11.7.8 addExternalModel
11.7.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.
11.7.10 addSubModel
11.7.11 addSystem
"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"
11.7.12 addTLMBus
"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"
11.7.13 addTLMConnection
11.7.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
11.7.15 copySystem
Copies a system.
11.7.16 delete
status := oms_delete(cref);
11.7.17 deleteConnection
The two arguments crefA and crefB get swapped automatically if necessary.
11.7.18 deleteConnectorFromBus
11.7.19 deleteConnectorFromTLMBus
11.7.20 export
11.7.21 exportDependencyGraphs
11.7.22 exportSnapshot
11.7.23 extractFMIKind
Extracts the FMI kind of a given FMU from the file system.
(kind,status) := oms_extractFMIKind(filename);
11.7.24 faultInjection
"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
11.7.25 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
11.7.26 getBoolean
11.7.27 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.
11.7.28 getInteger
11.7.29 getModelState
11.7.30 getReal
11.7.31 getSolver
11.7.32 getStartTime
11.7.33 getStopTime
11.7.34 getSubModelPath
11.7.35 getSystemType
11.7.36 getTime
11.7.37 getTolerance
11.7.38 getVariableStepSize
11.7.39 getVersion
version := oms_getVersion();
11.7.40 importFile
11.7.41 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.
11.7.42 initialize
status := oms_initialize(cref);
11.7.43 instantiate
status := oms_instantiate(cref);
11.7.44 list
11.7.45 listUnconnectedConnectors
11.7.46 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.
11.7.47 newModel
status := oms_newModel(cref);
11.7.48 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.
11.7.49 rename
11.7.50 reset
status := oms_reset(cref);
11.7.51 setBoolean
11.7.52 setCommandLineOption
status := oms_setCommandLineOption(cmd);
Available flags:
11.7.53 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.
11.7.54 setInteger
11.7.55 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);
11.7.56 setLoggingInterval
11.7.57 setLoggingLevel
oms_setLoggingLevel(logLevel);
11.7.58 setReal
11.7.59 setRealInputDerivative
11.7.60 setResultFile
11.7.61 setSolver
"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"
11.7.62 setStartTime
11.7.63 setStopTime
11.7.64 setTLMPositionAndOrientation
status := oms_setTLMPositionAndOrientation(cref, x1, x2, x3, A11, A12, A13, A21, A22,␣
˓→A23, A31, A32, A33);
11.7.65 setTLMSocketData
11.7.66 setTempDirectory
status := oms_setTempDirectory(newTempDir);
11.7.67 setTolerance
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.
11.7.68 setVariableStepSize
Sets the step size parameters for methods with stepsize control.
11.7.69 setWorkingDirectory
status := oms_setWorkingDirectory(newWorkingDir);
11.7.70 simulate
status := oms_simulate(cref);
11.7.71 stepUntil
11.7.72 terminate
status := oms_terminate(cref);
OMSimulator has an optional dependency to OpenModelica in order to utilize the graphical modelling editor
OMEdit. This feature requires to install the full OpenModelica tool suite, which includes OMSimulator. The
independent stand-alone version doesn't provide any graphical modelling editor.
Composite models are imported and exported in the System Structure Description (SSD) format, which is part of
the System Structure and Parameterization (SSP) standard.
See also FMI documentation and SSP documentation.
A new and empty SSP model can be created from File->New->SSP menu item.
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
When a new model is created a root system is always generated. If you need to have another system in your root
system you can add it with SSP->Add System.
For example only a weakly coupled system (Co-Simulation) can integrate strongly coupled system (Model Ex-
change). Therefore, the weakly coupled system must be selected from the Libraries Browser and the respective
menu item can be selected:
That will pop-up a dialog to enter the names of the new system.
A sub-model is typically an FMU, but it also can be result file. In order to import a sub-model, the respective
system must be selected and the action can be selected from the menu bar:
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.
Figure 11.5: OMEdit: Newly created empty root system of SSP model
11.8.4 Simulate
Select the simulate button (symbol with green arrow) or select Simulation->Simulate from the menu in OMEdit to
simulate the SSP model.
The dual mass oscillator example from our testsuite is a simple example one can recreate using components from the
Modelica Standard Library. After splitting the model into two models and exporting each as an Model-Exchange
and Co-Simulation FMU.
Figure 11.11: Dual mass oscillator Modelica model (diagramm view) and FMUs
Composite models are imported and exported in the System Structure Description (SSD) format, which is part of
the System Structure and Parameterization (SSP) standard.
Bus connections are saved as annotations to the SSD file. Bus connectors are only allowed in weakly coupled and
strongly coupled systems. Bus connections can exist in any system type. Bus connectors are used to hide SSD
connectors and bus connections are used to hide existing SSD connections in the graphical user interface. It is not
required that all connectors referenced in a bus are connected. One bus may be connected to multiple other buses,
and also to SSD connectors.
The example below contains a root system with two subsystems, WC1 and WC2. Bus connector WC1.bus1 is con-
nected to WC2.bus2. Bus connector WC2.bus2 is also connected to SSD connector WC1.C3.
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 internal
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
connections are implemented as SSD annotations in the System tag.
The example below shows a TLM system containing two weakly coupled systems, wc1 and wc2. System wc1
contains two TLM connectors, one of type 1D signal and one of type 1D mechanical. System wc2 contains only a
1D signal type connector. The two 1D signal connectors are connected to each other in the TLM top-level system.
<?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" />
(continues on next page)
Depending on the type of TLM bus connector (dimension, domain and interpolation), connectors need to be as-
signed 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
"wave6_5" input
continues on next page
TWELVE
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
12.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()
(continues on next page)
227
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
oms.setLogFile("HelloWorld_cs_Fit_py.log")
oms.setTempDirectory("./HelloWorld_cs_Fit_py/")
oms.newModel("HelloWorld_cs_Fit")
oms.addSystem("HelloWorld_cs_Fit.root", oms.system_wc)
# oms.setTolerance("HelloWorld_cs_Fit.root", 1e-5)
# 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"
12.2.1 addInput
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).
12.2.2 addMeasurement
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).
12.2.3 addParameter
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).
12.2.4 describe
PYTHON
status = simodel.describe()
12.2.5 freeSysIdentModel
Unloads a model.
PYTHON
12.2.6 getParameter
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.
12.2.7 getState
PYTHON
Returns:
status
(int) The C-API status code (oms_status_enu_t).
state
(int) State of SysIdent model (omsi_simodelstate_t).
12.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).
12.2.9 newSysIdentModel
PYTHON
simodel = OMSysIdent(ident)
12.2.10 oms_status_str
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.
12.2.11 omsi_simodelstate_str
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.
12.2.12 setOptions_max_num_iterations
PYTHON
Args:
max_num_iterations
(int) Maximum number of iterations for which the solver should run (default: 25).
Returns:
status
(int) The C-API status code (oms_status_enu_t).
status = simodel.setOptions_max_num_iterations(max_num_iterations)
12.2.13 solve
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)
THIRTEEN
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 to do that, which is only released in binary
form. This version contains an OpenModelica-specific private key that is used internally to decrypt the encrypted
libraries for code generation only, not for display purposes.
If you are a library developer and are interested in distributing your library in encrypted form for use with Open-
Modelica, please contact us for further information. Please note that distributing the special version of OpenMod-
elica with encryption support to the users of your library requires you to be a Level 2 member of the Open Source
Modelica Consortium.
If you are a user of an encrypted library that is supported by OpenModelica, please contact your library supplier
for information on how to get the special version of OpenModelica that runs it.
In order to encrypt the Modelica package call buildEncryptedPackage(TopLevelPackageName) from mos script or
from OMEdit right click the package in Libraries Browser and select Export Encrypted Package or select Export
> Export Encrypted Package from the menu.
All the Modelica files are encrypted and the whole library is zipped into a single file i.e., PackageName.mol. Note
that you can only encrypt Modelica packages saved in a folder structure. The complete folder structure remains as
it is. No encryption is done on the resource files.
To load the encrypted package call loadEncryptedPackage(EncryptedPackage.mol) from the mos script or from
OMEdit File > Load Encrypted Package.
13.3 Notes
• Encryption support in OpenModelica does not include any license management, i.e., restricting the usage of
a certain libraries based on some conditions, e.g., having paid a fee. It is only meant to prevent end users
from seeing the Modelica source code of the encrypted parts of the libraries, for reasons of confidentiality
or IP protection.
• The parts of the library that are protected by encryption are specified by the access control annotations
defined by the Modelica Language Specification, Section 18.9.
• The generated C code corresponding to the encrypted parts of the library is obfuscated: all comments are
removed, and all component names are replaced by generic names such as n1, n2, n3, etc. This prevents easy
reverse-engineering of the encrypted library starting from generated simulation code.
237
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Encryption in OpenModelica is based on the SEMLA (Standardized Encryption of Modelica Libraries and
Artifacts) module from Modelon AB, which provides a tool-independent framework for Modelica library
encryption.
FOURTEEN
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.
Interactive Electronic Notebooks are active documents that may contain technical computations and text, as well as
graphics. Hence, these documents are suitable to be used for teaching and experimentation, simulation scripting,
model documentation and storage, etc.
Literate Programming [Knu84] is a form of programming where programs are integrated with documentation in
the same document. Mathematica notebooks [Wol96] is one of the first WYSIWYG (What-You-See-Is-What-You-
Get) systems that support Literate Programming. Such notebooks are used, e.g., in the MathModelica modeling
and simulation environment, see e.g. Figure 14.1 below and Chapter 19 in [Fri04].
14.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 14.1.
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.
239
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Figure 14.1: Examples of Mathematica notebooks in the MathModelica modeling and simulation environment.
Understanding programs is hard, especially code written by someone else. For educational purposes it is essential
to be able to show the source code and to give an explanation of it at the same time.
Moreover, it is important to show the result of the source code's execution. In modeling and simulation it is also
important to have the source code, the documentation about the source code, the execution results of the simulation
model, and the documentation of the simulation results in the same document. The reason is that the problem
solving process in computational simulation is an iterative process that often requires a modification of the original
mathematical model and its software implementation after the interpretation and validation of the computed results
corresponding to an initial model.
Most of the environments associated with equation-based modeling languages focus more on providing efficient
numerical algorithms rather than giving attention to the aspects that should facilitate the learning and teaching of
the language. There is a need for an environment facilitating the learning and understanding of Modelica. These
are the reasons for developing the DrModelica teaching material for Modelica and for teaching modeling and
simulation.
An earlier version of DrModelica was developed using the MathModelica (now Wolfram SystemModeler) environ-
ment. The rest of this chapter is concerned with the OMNotebook version of DrModelica and on the OMNotebook
tool itself.
DrModelica has a hierarchical structure represented as notebooks. The front-page notebook is similar to a table
of contents that holds all other notebooks together by providing links to them. This particular notebook is the first
page the user will see (Figure 14.2).
In each chapter of DrModelica the user is presented a short summary of the corresponding chapter of the Modelica
book [Fri04]. The summary introduces some keywords, being hyperlinks that will lead the user to other notebooks
describing the keywords in detail.
Now, let us consider that the link “HelloWorld” in DrModelica Section is clicked by the user. The new HelloWorld
notebook (see Figure 14.3), to which the user is being linked, is not only a textual description but also contains one
or more examples explaining the specific keyword. In this class, HelloWorld, a differential equation is specified.
No information in a notebook is fixed, which implies that the user can add, change, or remove anything in a
notebook. Alternatively, the user can create an entirely new notebook in order to write his/her own programs
or copy examples from other notebooks. This new notebook can be linked from existing notebooks.
When a class has been successfully evaluated the user can simulate and plot the result, as previously depicted in
Figure 14.3 for the simple HelloWorld example model.
After reading a chapter in DrModelica the user can immediately practice the newly acquired information by doing
the exercises that concern the specific chapter. Exercises have been written in order to elucidate language constructs
step by step based on the pedagogical assumption that a student learns better “using the strategy of learning by
doing”. The exercises consist of either theoretical questions or practical programming assignments. All exercises
provide answers in order to give the user immediate feedback.
Figure 14.2: The front-page notebook of the OMNotebook version of the DrModelica tutoring system.
Figure 14.3: The HelloWorld class simulated and plotted using the OMNotebook version of DrModelica.
Figure 14.4: DrModelica Chapter on Algorithms and Functions in the main page of the OMNotebook version of
DrModelica.
Figure 14.4 shows part of Chapter 9 of the DrModelica teaching material. Here the user can read about language
constructs, like algorithm sections, when-statements, and reinit equations, and then practice these constructs by
solving the exercises corresponding to the recently studied section.
Exercise 1 from Chapter 9 is shown in Figure 14.5. In this exercise the user has the opportunity to practice different
language constructs and then compare the solution to the answer for the exercise. Notice that the answer is not
visible until the Answer section is expanded. The answer is shown in Figure 14.6.
DrControl is an interactive OMNotebook document aimed at teaching control theory. It is included in the Open-
Modelica distribution and appears under the directory:
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.
One of the basic concepts of control theory is using feedback loops either for neutralizing the disturbances from
the surroundings or a desire for a smoother output.
In Figure 14.7, control of a simple car model is illustrated where the car velocity on a road is controlled, first with
an open loop control, and then compared to a closed loop system with a feedback loop. The car has a mass m,
velocity y, and aerodynamic coefficient α. The θ is the road slope, which in this case can be regarded as noise.
Lets look at the Modelica model for the open loop controlled car:
𝑚𝑦˙ = 𝑢 − 𝛼𝑦 − 𝑚𝑔 * 𝑠𝑖𝑛(𝜃)
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 14.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.
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").
25
y
yNoise
20
15
10
0
0 20 40 60 80 100
𝑢 = 𝐾 * (𝑟 − 𝑦)
model withFeedback
import SI = Modelica.SIunits;
SI.Velocity y; // output signal with feedback link␣
(continues on next page)
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 14.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
In most systems the relation between the inputs and outputs can be described by a linear differential equation. Tear-
ing apart the solution of the differential equation into homogenous and particular parts is an important technique
taught to the students in engineering courses, also illustrated in Figure 14.10.
𝜕𝑛𝑦 𝜕 𝑛−1 𝑦 𝜕𝑚𝑢 𝜕𝑢
𝑛
+ 𝑎1 𝑛−1 + . . . + 𝑎𝑛 𝑦 = 𝑏0 𝑚 + . . . + 𝑏𝑚−1 + 𝑏𝑚 𝑢
𝜕𝑡 𝜕𝑡 𝜕𝑡 𝜕𝑡
Now let us examine a second order system:
𝑦¨ + 𝑎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 14.11 and Figure 14.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 14.11.
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 14.11 and Figure
14.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 14.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.
OMNotebook currently supports the commands and concepts that are described in this section.
14.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 specifies 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 combination Shift+Return or Shift+Enter. All the text in the cell is sent to OMC
(OpenModelica Compiler/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 doc-
umentation in OMNotebook. Each Latexcell 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.
14.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 cursor 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).
To perform operations on text or cells we often need to select a range of characters or cells.
• Select characters - There are several ways of selecting characters,
e.g. double-clicking on a word, clicking and dragging the mouse, or click followed by a shift-click at
an adjacent positioin selects the text between the previous click and the position of the most recent
shift-click.
• Select cells - Cells can be selected by clicking on them. Holding
down Ctrl and clicking on the cell markers in the tree view allows several cells to be selected, one at
a time. Several cells can be selected at once in the tree view by holding down the Shift key. Holding
down Shift selects all cells between last selected cell and the cell clicked on. This only works if both
cells belong to the same groupcell.
The following file related operations are available in the file menu:
• Create a new notebook - A new notebook can be created using the
menu File->New or the key combination Ctrl+N. A new document window will then open, with a new
document inside.
• Open a notebook - To open a notebook use File->Open in the menu or
the key combination Ctrl+O. Only files of the type .onb or .nb can be opened. If a file does not follow
the OMNotebook format or the FullForm Mathematica Notebook format, a message box is displayed
telling the user what is wrong. Mathematica Notebooks must be converted to fullform before they can
be opened in OMNotebook.
• Save a notebook - To save a notebook use the menu item File->Save
or File->Save As. If the notebook has not been saved before the save as dialog is shown and a filename
can be selected. OMNotebook can only save in xml format and the saved file is not compatible with
Mathematica. Key combination for save is Ctrl+S and for save as Ctrl+Shift+S. The saved file by default
obtains the file extension .onb.
• Print - Printing a document to a printer is done by pressing the
key combination Ctrl+P or using the menu item File->Print. A normal print dialog is displayed where
the usually properties can be changed.
• Import old document - Old documents, saved with the old version of
OMNotebook where a different file format was used, can be opened using the menu item File->Import-
>Old OMNotebook file. Old documents have the extension .xml.
• Export text - The text inside a document can be exported to a text
document. The text is exported to this document without almost any structure saved. The only structure
that is saved is the cell structure. Each paragraph in the text document will contain text from one cell.
To use the export function, use menu item File->Export->Pure Text.
• Close a notebook window - A notebook window can be closed using the
menu item File->Close or the key combination Ctrl+F4. Any unsaved changes in the document are lost
when the notebook window is closed.
• Quitting OMNotebook - To quit OMNotebook, use menu item File->Quit
or the key combination Crtl+Q. This closes all notebook windows; users will have the option of closing
OMC also. OMC will not automatically shutdown because other programs may still use it. Evaluating
the command quit() has the same result as exiting OMNotebook.
• Add textcell - A new textcell is added with the menu item Cell->Add
Cell (previous cell style) or the key combination Alt+Enter. The new textcell gets the same style as the
previous selected cell had.
• Add inputcell - A new inputcell is added with the menu item
Cell->Add Inputcell or the key combination Ctrl+Shift+I.
• Add latexcell - A new latexcell is added with the menu item
Cell->Add Latexcell or the key combination Ctrl+Shift+E.
• Add groupcell - A new groupcell is inserted with the menu item
Cell->Groupcell or the key combination Ctrl+Shift+G. The selected cell will then become the first cell
inside the groupcell.
• Ungroup groupcell - A groupcell can be ungrouped by selecting it in
the tree view and using the menu item Cell->Ungroup Groupcell or by using the key combination
Ctrl+Shift+U. Only one groupcell at a time can be ungrouped.
• Split cell - Spliting a cell is done with the menu item Cell->Split
cell or the key combination Ctrl+Shift+P. The cell is splited at the position of the text cursor.
• Delete cell - The menu item Cell->Delete Cell will delete all cells
that have been selected in the tree view. If no cell is selected this action will delete the cell that have
been selected by the cellcursor. This action can also be called with the key combination Ctrl+Shift+D
or the key Del (only works when cells have been selected in the tree view).
• Cellcursor - This cell type is a special type that shows which cell
that currently has the focus. The cell is basically just a thin black line. The cellcursor is moved by
clicking on a cell 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.
• Insert image - Images are added to a document with the menu item
Insert->Image or the key combination Ctrl+Shift+M. After an image has been selected a dialog appears,
where the size of the image can be chosen. The images actual size is the default value of the image.
OMNotebook stretches the image accordantly to the selected size. All images are saved in the same
file as the rest of the document.
• Insert link - A document can contain links to other OMNotebook file
or Mathematica notebook and to add a new link a piece of text must first be selected. The selected
text make up the part of the link that the user can click on. Inserting a link is done from the menu
Insert->Link or with the key combination Ctrl+Shift+L. A dialog window, much like the one used to
open documents, allows the user to choose the file that the link refers to. All links are saved in the
document with a relative file path so documents that belong together easily can be moved from one
place to another without the links failing.
• Change window - Each opened document has its own document window.
To switch between those use the Window menu. The window menu lists all titles of the open documents,
in the same order as they were opened. To switch to another document, simple click on the title of that
document.
14.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.
FIFTEEN
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.
This part of the OM manual is a contribution by Massimo Ceraolo and Vitalij Ruge.
15.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.
263
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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:
15.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:
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. Therefore
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.:
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.
1 Hairer, Ernst and Wanner, Gerhard, Radau Methods, 2015, pp 1213-1216, DOI 10.1007/978-3-540-70529-1_139.
• Define the variable(s) to be determined by DO. The variables the DO must determine must have the in-
put attribute. They can have (with parameter variability) min and max attributes, which are interpreted as
boxed path constraints on input. It is recommended to also define a start value for them, since it is used for
initialization (see sect. DO Initialization). Here's an example:
• Indicate the minimisation goal. We can indicate whether we must just minimise a quantity, or the integral
of a quantity (see (1)., as follows:
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 t 0 and t f ).
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 modelica
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.
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:
To allow DO to operate in good conditions it is very important that the system has continuous derivatives.
Here we just give two examples:
• In case of a combiTimeTable is used to describe non-linear algebraic functions, it is highly recommended to
use Continuous derivative for the smoothness parameter
• If we need to use the absolute value of a variable, we have derivative discontinuity around zero. This can be
avoided, with negligible loss of precision, substituting 𝑎𝑏𝑠(𝑥) with 𝑠𝑞𝑟𝑡(𝑥2 + 𝜀), where eps is very low in
comparison with the values 𝑥 usually assumes during the simulation.
• Carefully consider having in the code asserts that cause simulation to stop. If for instance we have an assert
that stops simulation when a variable gets outside its limiting value, it may happen that during the optimisa-
tion cycle the limit is hit and simulation is stopped, which may not be desirable. Asserts can still be left in
place, adding a boolean variable, e.g.:
15.1.5 Initialization
DO algorithm requires initialization. This is controlled through the simulation flag ipopt_init. This flag has three
options: SIM, CONST, FILE. The preferred option can be selected adding the model the system annotation __Open-
Modelica_simulationFlags. For instance, the following example requires optimisation with SIM` initialisation:
The three options operate as follows: * SIM (the default). With this option, OM first makes an ordinary simulation;
the simulation result is the initial “point” for the optimization. During this simulation the input is constantly kept
at its value “start”. * CONST. With this option, the initial "point" for optimization is with all the quantities being
constant, and equal to their "start" values * FILE. In this case the initial point for optimization is taken from a file,
created by a previous simulation, usually with a non-constant input (otherwise it would be simpler to use SIM).
OpenModelica maps the variables between file and optimization via their name. The syntax is as in the following
example:
This example refers to a car, which is requested to cover the max possible distance using power from an engine
which has a torque limitation and a power limitation.
The torque limitation is transformed in a maximum force that the wheels can transfer to the road to pus the car.
This is a very easy dynamic optimization problem, whose solution is the so-called bang-bang control: accelerate
at the maximum possible degree, then, when half of the road is reached, decelerate with the maximum possible
degree.
The code is very simple and it is as follows:
model BangBang2021 "Model to verify that optimization gives bang-bang optimal control"
parameter Real m = 1;
(continues on next page)
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 can be 𝑔min ≤
𝑔(x(𝑡), u(𝑡), 𝑡) ≤ 𝑔max . Here we have box limits on pow, which are expressed as limits on g(v,f) = f*v = pow
−30 ≤ 𝑣 * 𝑓 = 𝑓 * 𝑣 ≤ 30
This usage of constraints allows implementing variable (non-boxed) constraints, which are not allowed explicitly.
Doing this the above code implements through g(.) a variable (so non-boxed) limit on force f.
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;
This example refers to the electricity generation of a hybrid vehicle. These vehicles can choose at any time which
amount of the propulsion power must be taken from a battery and which from the Internal combustion engine.
In this example the engine can be switched ON and off without penalty, so the DO can choose both when the ICE
must be ON /OFF; and the power it must deliver when it is ON.
Objective of the control is to minimise the fuel consumption. This must be done keeping the energy inside the
storage at the final time, equal to the one at t=0 (otherwise it is easy to have zero consumption: just keep the
Internal Combustion Engine OFF all the time!)
For simplicity's sake, the propulsion power, in this simple example is taken as being a sine wave plus an offset
(needed to make the average positive). When the power is positive the wheels transfer power to the road, when
negative they recover it (storing it into the battery).
To find the optimum, a fuel consumption curve is added, as follows:
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
Here we consider the storage to be ideal: the flow of power in and out causes no losses to occur
In this case the solution of our optimization problem is trivial:
• The Ice must supply the average power requested by the load, and when it does this it must do it at the optimal
point which, as seen above is when its power is at the 76.8% of its nominal value
• The battery supplies the load power minus ICE power.
Using iceNominalPower=60 kW we get the following output:
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):
As a last example, we replicate the optimization of Example 2, but the power to be delivered directly deriving from
simulation of a vehicle, modelled through its physical elements.
The considered diagram is as follows:
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 ex-
ample 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.
Note: this is a very short preliminary description which soon will be considerably improved.
OpenModelica provides builtin dynamic optimization of models by using the powerful symbolic machinery of the
OpenModelica compiler for more efficient and automatic solution of dynamic optimization problems.
The builtin dynamic optimization allows users to define optimal control problems (OCP) using the Modelica lan-
guage for the model and the optimization language extension called Optimica (currently partially supported) for
the optimization part of the problem. This is used to solve the underlying dynamic optimization model formula-
tion using collocation methods, using a single execution instead of multiple simulations as in the parameter-sweep
optimization described in section Parameter Sweep Optimization using OMOptim.
For more detailed information regarding background and methods, see [BOR+12, RBB+14]
Before starting the optimization the model should be symbolically instantiated by the compiler in order to get a
single flat system of equations. The model variables should also be scalarized. The compiler frontend performs this,
including syntax checking, semantics and type checking, simplification and constant evaluation etc. are applied.
Then the complete flattened model can be used for initialization, simulation and last but not least for model-based
dynamic optimization.
The OpenModelica command optimize(ModelName) from OMShell, OMNotebook or MDT runs immediately the
optimization. The generated result file can be read in and visualized with OMEdit or within OMNotebook.
15.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 speci-
fication 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, finalTime 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;
˓→options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = '
˓→'",
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 15.1: Optimization results for Batch Reactor model - input variables.
1
x1
x2
0.8
0.6
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
Figure 15.2: Optimization results for Batch Reactor model - state variables.
Table 15.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
OpenModelica coupling with CasADi supports dynamic optimization of models by OpenModelica exporting the
optimization problem to CasADi which performs the optimization. In order to convey the dynamic system model in-
formation between Modelica and CasADi, we use an XML-based model exchange format for differential-algebraic
equations (DAE). OpenModelica supports export of models written in Modelica and the Optimization language
extension using this XML format, while CasADi supports import of models represented in this format. This al-
lows users to define optimal control problems (OCP) using Modelica and Optimization language specifications,
and solve the underlying model formulation using a range of optimization methods, including direct collocation
and direct multiple shooting.
Before exporting a model to XML, the model should be symbolically instantiated by the compiler in order to get a
single flat system of equations. The model variables should also be scalarized. The compiler frontend performs this,
including syntax checking, semantics and type checking, simplification and constant evaluation etc. are applied.
Then the complete flattened model is exported to XML code. The exported XML document can then be imported
to CasADi for model-based dynamic optimization.
>>> 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 underlying 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 15.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="{ed7ec213-9791-48dc-8038-9e873979d008}"
generationDateAndTime="2024-01-18T15:17:12"
variableNamingConvention="structured"
numberOfContinuousStates="2"
numberOfEventIndicators="0"
(continues on next page)
<VendorAnnotations>
<Tool name="OpenModelica Compiler OMCompiler v1.23.0-dev.229+g14cdee7a2b"> </Tool>
</VendorAnnotations>
<ModelVariables>
<ScalarVariable name="x1" valueReference="0" variability="continuous" causality=
˓→"local" 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>
<exp:Sub>
<exp:Der>
<exp:Identifier>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
</exp:Der>
<exp:Mul>
<exp:Identifier>
<exp:QualifiedNamePart name="u"/>
</exp:Identifier>
<exp:Identifier>
<exp:QualifiedNamePart name="x1"/>
</exp:Identifier>
</exp:Mul>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
<exp:Der>
<exp:Identifier>
<exp:QualifiedNamePart name="x1"/>
</exp:Identifier>
</exp:Der>
<exp:Mul>
<exp:Sub>
<exp:Mul>
<exp:RealLiteral>-0.5</exp:RealLiteral>
<exp:Pow>
<exp:Identifier>
<exp:QualifiedNamePart name="u"/>
</exp:Identifier>
<exp:RealLiteral>2.0</exp:RealLiteral>
</exp:Pow>
</exp:Mul>
<exp:Identifier>
<exp:QualifiedNamePart name="u"/>
</exp:Identifier>
</exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x1"/>
(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>
<exp:RealLiteral>0.0</exp:RealLiteral>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x1"/>
</exp:Identifier>
<exp:Identifier>
<exp:QualifiedNamePart name="$START"/>
<exp:QualifiedNamePart name="x1"/>
</exp:Identifier>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
</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>
(continues on next page)
<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:
OMOptim is a tool for parameter sweep design optimization of Modelica models. By optimization, one should
understand a procedure which minimizes/maximizes one or more objective functions by adjusting one or more
parameters. This is done by the optimization algorithm performing a parameter swep, i.e., systematically adjusting
values of selected parameters and running a number of simulations for different parameter combinations to find a
parameter setting that gives an optimal value of the goal function.
OMOptim 0.9 contains meta-heuristic optimization algorithms which allow optimizing all sorts of models with
following functionalities:
• One or several objectives optimized simultaneously
• One or several parameters (integer or real variables)
However, the user must be aware of the large number of simulations an optimization might require.
Before launching OMOptim, one must prepare the model in order to optimize it.
An optimization parameter is picked up from all model variables. The choice of parameters can be done using the
OMOptim interface.
For all intended parameters, please note that:
• The corresponding variable is constant during all simulations.
The OMOptim optimization in version 0.9 only concerns static parameters' optimization i.e. values
found for these parameters will be constant during all simulation time.
• The corresponding variable should play an input role in the model
i.e. its modification influences model simulation results.
15.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.
15.4.2 Objectives
As parameters, objectives are picked up from model variables. Objectives' values are considered by the optimizer
at the final time.
First, you need to load the model(s) you want to optimize. To do so, click on Add .mo button on main window or
select menu Model -> Load Mo file. . .
When selecting a model, the file will be loaded in OpenModelica which runs in the background.
While OpenModelica is loading the model, you could have a frozen interface. This is due to multi-threading
limitation but the delay should be short (few seconds).
You can load as many models as you want.
If an error occurs (indicated in log window), this might be because:
• Dependencies have not been loaded before (e.g. modelica library)
• Model use syntax incompatible with OpenModelica.
OMOptim should detect dependencies and load corresponding files. However, it some errors occur, please load by
yourself dependencies. You can also load Modelica library using Model->Load Modelica library.
When the model correctly loaded, you should see a window similar to Figure 15.3.
Problem->Add Problem->Optimization
A dialog should appear. Select the model you want to optimize. Only Model can be selected (no Package, Com-
ponent, Block. . . ).
A new form will be displayed. This form has two tabs. One is called Variables, the other is called Optimization.
If variables are not displayed, right click on model name in model hierarchy, and select Read variables.
To set optimization, we first have to define the variables the optimizer will consider as free i.e. those that it should
find best values of. To do this, select in the left list, the variables concerned. Then, add them to Optimized variables
by clicking on corresponding button ( ).
For each variable, you must set minimum and maximum values it can take. This can be done in the Optimized
variables table.
Objectives correspond to the final values of chosen variables. To select these last, select in left list variables
concerned and click button of Optimization objectives table.
For each objective, you must:
• Set minimum and maximum values it can take. If a configuration does
not respect these values, this configuration won't be considered. You also can set minimum and maxi-
mum equals to “-“ : it will then
• Define whether objective should be minimized or maximized.
Figure 15.5: Selecting read variables, set parameters, and selecting simulator.
After having selected variables and objectives, you should now select and configure optimization algorithm. To do
this, click on Optimization tab.
Here, you can select optimization algorithm you want to use. In version 0.9, OMOptim offers three different genetic
algorithms. Let's for example choose SPEA2Adapt which is an auto-adaptative genetic algorithm.
By clicking on parameters. . . button, a dialog is opened allowing defining parameters. These are:
• Population size: this is the number of configurations kept after a
generation. If it is set to 50, your final result can't contain more than 50 different points.
• Off spring rate: this is the number of children per adult obtained
after combination process. If it is set to 3, each generation will contain 150 individual (considering
population size is 50).
• Max generations: this number defines the number of generations
after which optimization should stop. In our case, each generation corresponds to 150 simulations. Note
that you can still stop optimization while it is running by clicking on stop button (which will appear
once optimization is launched). Therefore, you can set a really high number and still stop optimization
when you want without losing results obtained until there.
• Save frequency: during optimization, best configurations can be
regularly saved. It allows to analyze evolution of best configurations but also to restart an optimization
from previously obtained results. A Save Frequency parameter set to 3 means that after three genera-
tions, a file is automatically created containing best configurations. These files are named iteraion1.sav,
iteration2.sav and are store in Temp directory, and moved to SolvedProblems directory when optimiza-
tion is finished.
• ReinitStdDev: this is a specific parameter of EAAdapt1. It defines
whether standard deviation of variables should be reinitialized. It is used only if you start optimization
from previously obtained configurations (using Use start file option). Setting it to yes (1) will, in
most of cases, lead to a spread research of optimized configurations, forgetting parameters' variations'
reduction obtained in previous optimization.
As indicated before, it is possible to pursue an optimization finished or stopped. To do this, you must enable Use
start file option and select file from which optimization should be started. This file is an iteration_.sav file created
in previous optimization. It is stored in corresponding SolvedProblems folder (iteration10.sav corresponds to the
tenth generation of previous optimization).
*Note that this functionality can only work with same variables and objectives*. However, minimum, maxi-
mum of variables and objectives can be changed before pursuing an optimization.
15.4.10 Launch
Optimization will be stopped when the generation counter will reach the generation number defined in parameters.
However, you can still stop the optimization while it is running without loosing obtained results. To do this, click
on Stop button. Note that this will not immediately stop optimization: it will first finish the current generation.
This stop function is especially useful when optimum points do not vary any more between generations. This
can be easily observed since at each generation, the optimum objectives values and corresponding parameters are
displayed in log window.
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.
During optimization, the values of optimized variables and objectives are memorized. The others are not. To get
these last, you must recomputed corresponding points. To achieve this, select one or several points in point's list
region and click on recompute.
For each point, it will simulate model setting input parameters to point corresponding values. All values of this
point (including those which are not optimization parameters neither objectives).
SIXTEEN
This section describes the use of OpenModelica to compute parameter sensitivities using forward sensitivity anal-
ysis together with the Sundials/IDA solver.
16.1.1 Background
Parameter sensitivity analysis aims at analyzing the behavior of the corresponding model states w.r.t. model pa-
rameters.
Formally, consider a Modelica model as a DAE system:
𝐹 (𝑥, 𝑥,
˙ 𝑦, 𝑝, 𝑡) = 0 𝑥(𝑡0 ) = 𝑥0 (𝑝)
where 𝑥(𝑡) ∈ R𝑛 represent state variables, 𝑥(𝑡)
˙ ∈ R𝑛 represent state derivatives, 𝑦(𝑡) ∈ R𝑘 represent algebraic
𝑚
variables, 𝑝 ∈ R model parameters.
For parameter sensitivity analysis the derivatives
𝜕𝑥
𝜕𝑝
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:
𝜕𝑥
𝑠˙ 𝑖 =
𝜕𝑝𝑖
16.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
289
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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.
3.5x1095
$Sensitivities.lambda1.x
$Sensitivities.lambda1.y
3x1095 $Sensitivities.lambda2.x
$Sensitivities.lambda2.y
2.5x1095 $Sensitivities.mu1.x
$Sensitivities.mu1.y
$Sensitivities.mu2.x
2x1095 $Sensitivities.mu2.y
1.5x1095
1x1095
5x1094
-5x1094
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
16.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.
16.2.2 Usage
Let's say we need to investigate the influence of model parameters on the predator population at 40 units of time.
We assume a +/-5% uncertainty on model parameters.
We can use OMSens to study the sensitivity model to each parameter, one at a time.
Open the Lotka-Volterra model using OMEdit.
• 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
parameters 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.
• Setup the optimization settings and run the analysis.
• The Parameters tab in the results window shows the values found by the optimization routine that maximize
pred_pop at t=40 s.
• The State Variable tab shows the comparison between the values of the variable in the standard run vs the
perturbed run at simulation time 40s.
• If we simulate using the optimum values and compare it to the standard (unperturbed) run, we see that it
delays the bell described by the variable.
• So far, we have only perturbed the top 3 parameters detected by the Individual Sensitivity method. Maybe
we can find a greater effect on the variable if we perturb all 6 parameters. Running a Sweep is not an option
as perturbing 6 parameters with 3 iterations each results in 36 =729 simulations. We run another Vectorial
Sensitivity Analysis instead but now choose to perturb all 6 parameters.
• The parameters tab shows that the optimum value is found by perturbing all of the parameters to their
boundaries.
• The State Variable tab shows that pred_pop can be increased by 98% when perturbing the 6 parameters as
opposed to 68% when perturbing the top 3 influencing parameters.
• The plot shows again that the parameters found delay the bell-shaped curve, but with a stronger impact than
before.
SEVENTEEN
PDEMODELICA1
PDEModelica1 is nonstandardised experimental Modelica language extension for 1-dimensional partial differential
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 PDEModelica 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".
Let us introduce new PDEModelica1 language elements by an advection equation example model:
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).
305
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The IC of the field variable u is written using an expression containing the coordinate variable omega.x.
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.
17.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.
During translation field variables are replaced with arrays. These arrays may be plotted using array-plot or even
better using Array Parametric Plot (to plot x-coordinate versus a field).
EIGHTEEN
18.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 compiler,
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.
18.2 Installation
The installation of MDT is accomplished by following the below installation instructions. These instructions as-
sume 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
307
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
MDT needs to be able to locate the binary of the compiler. It uses the environment variable OPENMODELICA-
HOME to do so.
If you have problems using MDT, make sure that OPENMODELICAHOME is pointing to the folder where the
OpenModelica Compiler is installed. In other words, OPENMODELICAHOME must point to the folder that
contains the Open Modelica Compiler (OMC) binary. On the Windows platform it's called omc.exe and on Unix
platforms it's called omc.
The most convenient way to work with Modelica projects is to use to the Modelica perspective. To switch to
the Modelica perspective, choose the Window menu item, pick Open Perspective followed by Other... Select the
Modelica option from the dialog presented and click OK..
Eclipse stores your projects in a folder called a workspace. You need to choose a workspace folder for this session,
see Figure 18.1.
To start a new project, use the New Modelica Project Wizard. It is accessible through File->New-> Modelica
Project or by right-clicking in the Modelica Projects view and selecting New->Modelica Project.
You need to disable automatic build for the project(s) (Figure 18.3).
Repeat the procedure for all the projects you need, e.g. for the exercises described in the MetaModelica users guide:
01_experiment, 02a_exp1, 02b_exp2, 03_assignment, 04a_assigntwotype, etc.
NOTE: Leave open only the projects you are working on! Close all the others!
After having created a project, you eventually need to build the project (Figure 18.4).
The build options are the same as the make targets: you can build, build from scratch (clean), or run simulations
depending on how the project is setup. See Figure 18.5 for an example of how omc can be compiled (make omc
builds OMC).
If you need, you can (temporarily) switch to another perspective, e.g. to the Java perspective for working with an
OpenModelica Java client as in Figure 18.7.
308 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
310 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Figure 18.3: Eclipse Setup - disable automatic build for the projects.
312 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Figure 18.7: Eclipse - Switching to another perspective - e.g. the Java Perspective.
To create a new package inside a Modelica project, select File->New->Modelica Package. Enter the desired name
of the package and a description of what it contains. Note: for the exercises we already have existing packages.
To create a new Modelica class, select where in the hierarchy that you want to add your new class and select File-
>New->Modelica Class. When creating a Modelica class you can add different restrictions on what the class can
contain. These can for example be model, connector, block, record, or function. When you have selected your
desired class type, you can select modifiers that add code blocks to the generated code. 'Include initial code block'
will for example add the line 'initial equation' to the class.
Whenever a build command is given to the MDT environment, modified and saved Modelica (.mo) files are checked
for syntactical errors. Any errors that are found are added to the Problems view and also marked in the source code
editor. Errors are marked in the editor as a red circle with a white cross, a squiggly red line under the problematic
construct, and as a red marker in the right-hand side of the editor. If you want to reach the problem, you can either
click the item in the Problems view or select the red box in the right-hand side of the editor.
MDT currently has support for automatic indentation. When typing the Return (Enter) key, the next line is indented
correctly. You can also correct indentation of the current line or a range selection using CTRL+I or “Correct
Indentation” action on the toolbar or in the Edit menu.
MDT supports Code Completion in two variants. The first variant, code completion when typing a dot after a class
(package) name, shows alternatives in a menu. Besides the alternatives, Modelica documentation from comments
is shown if is available. This makes the selection easyer.
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:
314 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
When hovering with the mouse over an identifier a popup with information about the identifier is displayed. If the
text is too long, the user can press F2 to focus the popup dialog and scroll up and down to examine all the text. As
one can see the information in the popup dialog is syntax-highlighted.
Besides hovering information the user can press CTRL+click to go to the definition of the identifier. When pressing
CTRL the identifier will be presented as a link and when pressing mouse click the editor will go to the definition
of the identifier.
When writing records, the same functionality as for function calls is used. This is useful especially in MetaModelica
when writing cases in match constructs.
316 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Figure 18.12: Code completion at a function call when typing left parenthesis.
Figure 18.14: Code assistance when writing cases with records in MetaModelica.
318 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
320 Chapter 18. MDT - The OpenModelica Development Tooling Eclipse Plugin
CHAPTER
NINETEEN
The algorithmic code debugger, used for the algorithmic subset of the Modelica language as well as the MetaMod-
elica 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 procedural or tra-
ditional object-oriented languages is supported, such as setting and removing breakpoints, stepping, inspecting
variables, etc. The debugger is integrated with Eclipse.
The debugging framework for the algorithmic subset of Modelica and MetaModelica is based on the Eclipse envi-
ronment and is implemented as a set of plugins which are available from Modelica Development Tooling (MDT)
environment. Some of the debugger functionality is presented below. In the right part a variable value is explored.
In the top-left part the stack trace is presented. In the middle-left part the execution point is presented.
The debugger provides the following general functionalities:
• Adding/Removing breakpoints.
• Step Over - moves to the next line, skipping the function calls.
• Step In - takes the user into the function call.
• Step Return - complete the execution of the function and takes the
user back to the point from where the function is called.
• Suspend - interrupts the running program.
To be able to run in debug mode, one has to go through the following steps:
• create a mos file
• setting the debug configuration
• setting breakpoints
• running the debug configuration
All these steps are presented below using images.
321
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
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 19.6: Eclipse will ask if the user wants to switch to the debugging perspective.
The Variables view shows the list of variables at a certain point in the program, containing four colums:
• Name - the variable name.
• Declared Type - the Modelica type of the variable.
• Value - the variable value.
• Actual Type - the mapped C type.
By preserving the stack frames and variables it is possible to keep track of the variables values. If the value of
any variable is changed while stepping then that variable will be highlighted yellow (the standard Eclipse way of
showing the change).
TWENTY
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-6, method = 'dassl', fileNamePrefix = 'ProfilingTest', options = '',␣
329
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
",
timeFrontend = 0.001825723,
timeBackend = 0.00932152,
timeSimCode = 0.001196514,
timeTemplates = 0.0029388920000000002,
timeCompile = 0.544664526,
timeSimulation = 0.034657842,
timeTotal = 0.594709943
end SimulationResult;
"Warning: There are nonlinear iteration variables with default zero start attribute␣
˓→found in NLSJac0. For more information set -d=initialization. In OMEdit Tools->
Warning: The initial conditions are not fully specified. For more information set -
˓→d=initialization. In OMEdit Tools->Options->Simulation->Show additional information␣
˓→d=initialization\").
"
20.1.1 Information
All times are measured using a real-time wall clock. This means context switching produces bad worst-case exe-
cution 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.
20.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
20.1.3 Summary
|Graph
th umbnail
count f unc-
tion fun0|
|Graph
th umbnail
count eq0|
|Graph th ` <#e 4 0.00 0.08% 0.00 3.12x
umbnail q11>`__ 0002024 0002084
eq11|
|Graph
th umbnail
count eq11|
|Graph th ` <#e 1006 0.00 24.43% 0.00 39.31x
umbnail q19>`__ 0613316 0024577
eq19|
|Graph
th umbnail
count eq19|
|Graph th ` <#e 1508 0.00 22.88% 0.00 52.15x
umbnail q21>`__ 0574213 0020238
eq21|
|Graph
th umbnail
count eq21|
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 running a simulation from OMEdit, it is possible to enable profiling information, which can be combined
with the transformations browser.
When profiling the DoublePendulum example from MSL, the following output in Figure 20.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 20.2: Profiling results of the Modelica standard library DoublePendulum example, sorted by execution time.
TWENTYONE
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.
337
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
TWENTYTWO
Below is information and examples about the OpenModelica external C interfaces, as well as examples of Python
interoperability.
The following is a small example (ExternalLibraries.mo) to show the use of external C functions:
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):
339
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
The following script file ExternalLibraries.mos will perform everything that is needed, provided you have gcc
installed in your path:
Note:
Notification: Model statistics after passing the front-end and creating the data structures used by the back-end:
* Number of equations: 2
* Number of variables: 2
Notification: Model statistics after passing the back-end for initialization:
* Number of independent subsystems: 2
* Number of states: 0 ()
* Number of discrete variables: 0 ()
* Number of discrete states: 0 ()
* Number of clocked states: 0 ()
* Top-level inputs: 0
Notification: Strong component statistics for initialization (4):
* Single equations (assignments): 4
* Array equations: 0
* Algorithm blocks: 0
* Record equations: 0
* When equations: 0
* If-equations: 0
* Equation systems (not torn): 0
* Torn equation systems: 0
* Mixed (continuous/discrete) equation systems: 0
Notification: Model statistics after passing the back-end for simulation:
* Number of independent subsystems: 2
* Number of states: 2 (y,x)
* Number of discrete variables: 0 ()
* Number of discrete states: 0 ()
* Number of clocked states: 0 ()
* Top-level inputs: 0
Notification: Strong component statistics for simulation (2):
* Single equations (assignments): 2
* Array equations: 0
* Algorithm blocks: 0
* Record equations: 0
* When equations: 0
* If-equations: 0
* Equation systems (not torn): 0
* Torn equation systems: 0
* Mixed (continuous/discrete) equation systems: 0
The following calls external Python code through a very simplistic external function (no data is retrieved from the
Python code). By making it a dynamically linked library, you might get the code to work without changing the
linker settings.
function pyRunString
input String s;
external "C" annotation(Include="
#include <Python.h>
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
model CallExternalPython
algorithm
pyRunString("
print 'Python says: simulation time',"+String(time)+"
");
end CallExternalPython;
˓→= '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
Error:
Notification: Model statistics after passing the front-end and creating the data structures used by the back-end:
* Number of equations: 0
* Number of variables: 0
Notification: Model statistics after passing the back-end for initialization:
* Number of independent subsystems: 1
* Number of states: 0 ()
* Number of discrete variables: 0 ()
* Number of discrete states: 0 ()
* Number of clocked states: 0 ()
* Top-level inputs: 0
Notification: Strong component statistics for initialization (0):
* Single equations (assignments): 0
* Array equations: 0
* Algorithm blocks: 0
* Record equations: 0
* When equations: 0
* If-equations: 0
* Equation systems (not torn): 0
* Torn equation systems: 0
* Mixed (continuous/discrete) equation systems: 0
Notification: Model statistics after passing the back-end for simulation:
* Number of independent subsystems: 1
* Number of states: 0 ()
* Number of discrete variables: 0 ()
* Number of discrete states: 0 ()
* Number of clocked states: 0 ()
* Top-level inputs: 0
Notification: Strong component statistics for simulation (0):
* Single equations (assignments): 0
* Array equations: 0
* Algorithm blocks: 0
* Record equations: 0
* When equations: 0
* If-equations: 0
* Equation systems (not torn): 0
* Torn equation systems: 0
* Mixed (continuous/discrete) equation systems: 0
Error: Error building simulator. Build log: make[1]: Entering directory '«DOCHOME»'
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython.o CallEx-
ternalPython.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_functions.o
CallExternalPython_functions.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_records.o
CallExternalPython_records.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_01exo.o
CallExternalPython_01exo.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_02nls.o
CallExternalPython_02nls.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_03lsy.o
CallExternalPython_03lsy.c
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_11mix.o
CallExternalPython_11mix.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_12jac.o
CallExternalPython_12jac.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_13opt.o
CallExternalPython_13opt.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_14lnz.o
CallExternalPython_14lnz.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_15syn.o
CallExternalPython_15syn.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_16dae.o
CallExternalPython_16dae.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_17inl.o
CallExternalPython_17inl.c
clang -Os -DOM_HAVE_PTHREADS -fPIC -falign-functions -mfpmath=sse -fno-dollars-
in-identifiers -Wno-parentheses-equality -I"«OPENMODELICAHOME»/include/omc/c" -
I"«OPENMODELICAHOME»/include/omc" -I. -DOPENMODELICA_XML_FROM_FILE_AT_RUNTIME
-DOMC_MODEL_PREFIX=CallExternalPython -DOMC_NUM_MIXED_SYSTEMS=0 -
DOMC_NUM_LINEAR_SYSTEMS=0 -DOMC_NUM_NONLINEAR_SYSTEMS=0 -
DOMC_NDELAY_EXPRESSIONS=0 -DOMC_NVAR_STRING=0 -c -o CallExternalPython_18spd.o
CallExternalPython_18spd.c
In file included from CallExternalPython_functions.c:7:
This section describes a simple-minded approach to calling Python code from OpenModelica. For a description
of Python scripting with OpenModelica, see OMPython - OpenModelica Python Interface.
The interaction with Python can be perfomed in four different ways whereas one is illustrated below. Assume that
we have the following Modelica code:
In the following Python (.py) files the above Modelica model is simulated via the OpenModelica scripting interface:
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.
TWENTYTHREE
OMPython - OpenModelica Python API is a free, open source, highly portable Python based interactive ses-
sion 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.
OMPython is architectured to combine both the solving strategy and model building. So domain experts (peo-
ple 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. OMPython is not a standalone package, it depends upon the OpenModelica installation.
OMPython is implemented in Python and depends either on the OmniORB and OmniORBpy - high performance
CORBA ORBs for Python or 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 OMPython follow the instructions at https://github.com/OpenModelica/OMPython
349
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
OMPython provides two classes for communicating with OpenModelica i.e., OMCSession and OMCSessionZMQ.
Both classes have the same interface, the only difference is that OMCSession uses omniORB and OMCSes-
sionZMQ uses ZeroMQ. All the examples listed down uses OMCSessionZMQ but if you want to test OMCSession
simply replace OMCSessionZMQ with OMCSession. We recommend to use OMCSessionZMQ.
To test the command outputs, simply create an OMCSessionZMQ object by importing from the OMPython library
within Python interepreter. The module allows you to interactively send commands to the OMC server and display
their output.
To get started, create an OMCSessionZMQ object:
>>> omc.sendExpression("getVersion()")
OMCompiler v1.23.0-dev.229+g14cdee7a2b
>>> 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;
>>> omc.sendExpression("getClassNames()")
('BouncingBall', 'ModelicaServices', 'Complex', 'Modelica')
>>> omc.sendExpression("isPartial(BouncingBall)")
False
>>> omc.sendExpression("isPackage(BouncingBall)")
False
>>> omc.sendExpression("isModel(BouncingBall)")
True
>>> omc.sendExpression("checkModel(BouncingBall)")
(continues on next page)
>>> 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_master/doc/UsersGuide/../../build//bin:/usr/local/sbin:/
˓→5.15.0-91-generic #101-Ubuntu SMP Tue Nov 14 13:30:08 UTC 2023 x86_64 x86_64 x86_64␣
The common combination of a simulation followed by getting a value and doing a plot:
˓→= '.*', cflags = '', simflags = ''", 'messages': 'LOG_SUCCESS | info | The␣
˓→initialization finished successfully without homotopy method.\nLOG_SUCCESS |␣
˓→info | The simulation finished successfully.\n', 'timeFrontend': 0.279138592,
˓→'timeBackend': 0.003929839, 'timeSimCode': 0.001198658, 'timeTemplates': 0.
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)",
"plot(h)"
]
for cmd in cmds:
answer = omc.sendExpression(cmd)
print("\n{}:\n{}".format(cmd, answer))
23.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.
Some more improvements are added to OMPython functionality for querying more information about the models
and simulate them. A list of new user friendly API functionality allows user to extract information about models
using python objects. A list of API functionality is described below.
To get started, create a ModelicaSystem object:
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 argu-
ment useCorba=True to the constructor.
23.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()
• getQuantities()
• getContinuous()
• getInputs()
• getOutputs()
• getParameters()
• getSimulationOptions()
• getSolutions()
Three calling possibilities are accepted using getXXX() where "XXX" can be any of the above functions (eg:)
getParameters().
• getXXX() without input argument, returns a dictionary with names as keys and values as values.
• getXXX(S), where S is a string of names.
• getXXX(["S1","S2"]) where S1 and S1 are list of string elements
˓→': None, 'Name': 'c', 'Variability': 'parameter', 'Value': '0.9', 'alias': 'noAlias
(-1.825929609047952, 0.65907039052943617)
>>> mod.getInputs()
{}
>>> mod.getOutputs()
{}
˓→provided by user
• setInputs()
• setParameters()
• setSimulationOptions()
Two setting possibilities are accepted using setXXXs(),where "XXX" can be any of above functions.
• setXXX("Name=value") string of keyword assignments
• setXXX(["Name1=value1","Name2=value2","Name3=value3"]) list of string of keyword assignments
23.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
23.2.7 Linearization
>>> mod.setLinearizationOptions(["stopTime=2.0","tolerance=1e-06"])
23.3 PySimulator
PySimulator provides a graphical user interface for performing analyses and simulating different model types (cur-
rently Functional Mockup Units and Modelica Models are supported), plotting result variables and applying sim-
ulation result analysis tools like Fast Fourier Transform.
Read more about the PySimulator at https://github.com/PySimulator/PySimulator.
TWENTYFOUR
OMMatlab - the OpenModelica Matlab API is a free, open source, highly portable Matlab-based interactive ses-
sion 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 (peo-
ple 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 library
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
357
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
OMMatlab package has advanced functionality for querying more information about the models and simulate them.
A list of new user friendly API functionality allows user to extract information about models using matlab objects.
A list of API functionality is described below.
To get started, create a ModelicaSystem object:
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.,
• The fourth input argument (optional), which is used to set the command line options e.g.,
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")
24.3 WorkDirectory
For each Matlab session a temporary work directory is created and the results are published in that working direc-
tory, 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'
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)
• getQuantities()
• showQuantities()
• getContinuous()
• getInputs()
• getOutputs()
• getParameters()
• getSimulationOptions()
• getSolutions()
Three calling possibilities are accepted using getXXX() where "XXX" can be any of the above functions (eg:)
getParameters().
• getXXX() without input argument, returns a dictionary with names as keys and values as values.
• getXXX(S), where S is a string of names.
• getXXX(["S1","S2"]) where S1 and S1 are array of string elements
+----------+------------+-------------------------+--------------+------------+-------
˓→----+---------------+-------+
>>> omc.getInputs()
struct with no fields
>>> omc.getOutputs()
struct with no fields
˓→provided by user
• setInputs()
• setParameters()
• setSimulationOptions()
Two setting possibilities are accepted using setXXXs(),where "XXX" can be any of above functions.
• setXXX("Name=value") string of keyword assignments
• setXXX(["Name1=value1","Name2=value2","Name3=value3"]) array of string of keyword assignments
>>> omc.setSimulationOptions(["stopTime=2.0","tolerance=1e-08"])
An example of how to do advanced simulation to set parameter values using set methods and finally simulate the
"BouncingBall.mo" model is given below .
>>> 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)
24.10 Linearization
>>> omc.setLinearizationOptions(["stopTime=2.0","tolerance=1e-08"])
TWENTYFIVE
OMJulia - the OpenModelica Julia API is a free, open source, highly portable Julia based interactive session handler
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
(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. OMJulia is not a standalone
package, it depends upon the OpenModelica installation.
OMJulia.jl is implemented in Julia and depends on ZeroMQ - high performance asynchronous messaging library
and it supports the Modelica Standard Library that is included in OpenModelica 1.9.2.
The latest OMJulia.jl documentation can be found online: OMJulia.jl documentation
365
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
TWENTYSIX
JUPYTER-OPENMODELICA
An OpenModelica Kernel for Jupyter Notebook. All commands are interpreted by OMPython which communicates
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
367
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
TWENTYSEVEN
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.
The following are brief descriptions of the scripting commands available in the OpenModelica environment. See
also https://build.openmodelica.org/Documentation/OpenModelica.Scripting.html. All commands are shown in
alphabetical order:
27.1.1 interactiveDumpAbsynToJL
function interactiveDumpAbsynToJL
output String res;
end interactiveDumpAbsynToJL;
27.1.2 relocateFunctions
function relocateFunctions
input String fileName;
input String names[:, 2];
output Boolean success;
end relocateFunctions;
369
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
27.1.3 toJulia
function toJulia
output String res;
end toJulia;
27.1.4 GC_expand_hp
function GC_expand_hp
input Integer size;
output Boolean success;
end GC_expand_hp;
27.1.5 GC_gcollect_and_unmap
27.1.6 GC_get_prof_stats
function GC_get_prof_stats
output GC_PROFSTATS gcStats;
end GC_get_prof_stats;
27.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;
27.1.8 addClassAnnotation
function addClassAnnotation
input TypeName class_;
input ExpressionOrModification annotate;
output Boolean bool;
end addClassAnnotation;
27.1.9 addInitialState
function addInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end addInitialState;
27.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;
27.1.11 alarm
27.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;
27.1.13 basename
function basename
input String path;
output String basename;
end basename;
27.1.14 buildEncryptedPackage
function buildEncryptedPackage
input TypeName className "the class that should encrypted";
input Boolean encrypt = true;
output Boolean success;
end buildEncryptedPackage;
27.1.15 buildLabel
builds Label.
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";
27.1.16 buildModel
˓→[simflags])
Example command:
simulate(A);
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 method = "<default>" "integration method used for simulation. <default>
˓→ = dassl";
27.1.17 buildModelFMU
Example command:
buildModelFMU(className, version="2.0");
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)";
input String platforms[:] = {"static"} "The list of platforms to generate code for.
\"dynamic\"=current platform, dynamically␣
˓→link the runtime.
˓→multiarch/crossbuild\"";
27.1.18 cd
change directory to the given path (which may be either relative or absolute)
returns the new working directory on success or a message on failure
if the given path is the empty string, the function simply returns the current␣
˓→working directory.
function cd
input String newWorkingDirectory = "";
output String workingDirectory;
end cd;
27.1.19 checkAllModelsRecursive
Checks all models recursively and returns number of variables and equations.
function checkAllModelsRecursive
input TypeName className;
input Boolean checkProtected = false "Checks also protected classes if true";
output String result;
end checkAllModelsRecursive;
27.1.20 checkCodeGraph
Checks if the given taskgraph has the same structure as the graph described in the␣
˓→codefile.
function checkCodeGraph
input String graphfile;
input String codefile;
output String[:] result;
end checkCodeGraph;
27.1.21 checkInterfaceOfPackages
function checkInterfaceOfPackages
input TypeName cl;
input String dependencyMatrix[:, :];
output Boolean success;
end checkInterfaceOfPackages;
27.1.22 checkModel
function checkModel
input TypeName className;
output String result;
end checkModel;
27.1.23 checkSettings
function checkSettings
output CheckSettingsResult result;
end checkSettings;
27.1.24 checkTaskGraph
Checks if the given taskgraph has the same structure as the reference taskgraph and␣
˓→if all attributes are set correctly.
function checkTaskGraph
input String filename;
input String reffilename;
output String[:] result;
end checkTaskGraph;
27.1.25 classAnnotationExists
function classAnnotationExists
input TypeName className;
input TypeName annotationName;
output Boolean exists;
end classAnnotationExists;
27.1.26 clear
function clear
output Boolean success;
end clear;
27.1.27 clearCommandLineOptions
function clearCommandLineOptions
output Boolean success;
end clearCommandLineOptions;
27.1.28 clearDebugFlags
function clearDebugFlags
output Boolean success;
end clearDebugFlags;
27.1.29 clearMessages
function clearMessages
output Boolean success;
end clearMessages;
27.1.30 clearProgram
Clears loaded .
function clearProgram
output Boolean success;
end clearProgram;
27.1.31 clearVariables
function clearVariables
output Boolean success;
end clearVariables;
27.1.32 closeSimulationResultFile
To allow OMEdit to make successful simulation again on the same file we must close␣
˓→the file after reading the Simulation Result Variables.
function closeSimulationResultFile
output Boolean success;
end closeSimulationResultFile;
27.1.33 codeToString
function codeToString
input $Code className;
output String string;
end codeToString;
27.1.34 compareFiles
27.1.35 compareFilesAndMove
27.1.36 convertPackageToLibrary
function convertPackageToLibrary
input TypeName packageToConvert;
input TypeName library;
input String libraryVersion;
output Boolean success;
end convertPackageToLibrary;
27.1.37 convertUnits
function convertUnits
input String s1;
input String s2;
output Boolean unitsCompatible;
output Real scaleFactor;
output Real offset;
end convertUnits;
27.1.38 copy
copies the source file to the destination file. Returns true if the file has been␣
˓→copied.
function copy
input String source;
input String destination;
output Boolean success;
end copy;
27.1.39 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;
27.1.40 countMessages
function countMessages
output Integer numMessages;
output Integer numErrors;
output Integer numWarnings;
end countMessages;
27.1.41 deleteFile
function deleteFile
input String fileName;
output Boolean success;
end deleteFile;
27.1.42 deleteInitialState
function deleteInitialState
input TypeName cl;
input String state;
output Boolean bool;
end deleteInitialState;
27.1.43 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;
27.1.44 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;
27.1.45 diffModelicaFileListings
function diffModelicaFileListings
input String before, after;
input DiffFormat diffFormat = DiffFormat.color;
input Boolean failOnSemanticsChange = false "Defaults to returning after instead of␣
˓→hard fail";
27.1.46 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";
27.1.47 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";
27.1.48 directoryExists
function directoryExists
input String dirName;
output Boolean exists;
end directoryExists;
27.1.49 dirname
function dirname
input String path;
output String dirname;
end dirname;
27.1.50 disableNewInstantiation
function disableNewInstantiation
output Boolean success;
end disableNewInstantiation;
27.1.51 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";
27.1.52 echo
function echo
input Boolean setEcho;
output Boolean newEcho;
end echo;
27.1.53 enableNewInstantiation
function enableNewInstantiation
output Boolean success;
end enableNewInstantiation;
27.1.54 escapeXML
function escapeXML
input String inStr;
output String outStr;
end escapeXML;
27.1.55 exit
function exit
input Integer status;
end exit;
27.1.56 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;
27.1.57 extendsFrom
returns true if the given class extends from the given base class
function extendsFrom
input TypeName className;
input TypeName baseClassName;
output Boolean res;
end extendsFrom;
27.1.58 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;
27.1.59 generateCode
The input is a function name for which C-code is generated and compiled into a dll/so
function generateCode
input TypeName className;
output Boolean success;
end generateCode;
27.1.60 generateEntryPoint
function generateEntryPoint
input String fileName;
input TypeName entryPoint;
input String url = "https://trac.openmodelica.org/OpenModelica/newticket";
end generateEntryPoint;
27.1.61 generateHeader
function generateHeader
input String fileName;
output Boolean success;
end generateHeader;
27.1.62 generateJuliaHeader
function generateJuliaHeader
input String fileName;
output Boolean success;
end generateJuliaHeader;
27.1.63 generateScriptingAPI
function generateScriptingAPI
input TypeName cl;
input String name;
output Boolean success;
output String moFile;
output String qtFile;
output String qtHeader;
end generateScriptingAPI;
27.1.64 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.";
27.1.65 generateSeparateCodeDependencies
function generateSeparateCodeDependencies
input String stampSuffix = ".c" "Suffix to add to dependencies (often .c.stamp)";
output String[:] dependencies;
end generateSeparateCodeDependencies;
27.1.66 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;
27.1.67 generateVerificationScenarios
function generateVerificationScenarios
input TypeName path;
output Boolean success;
end generateVerificationScenarios;
27.1.68 getAlgorithmCount
function getAlgorithmCount
input TypeName class_;
output Integer count;
end getAlgorithmCount;
27.1.69 getAlgorithmItemsCount
function getAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getAlgorithmItemsCount;
27.1.70 getAllSubtypeOf
Returns the list of all classes that extend from className given a parentClass where␣
˓→the lookup for className should start
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;
27.1.71 getAnnotationCount
function getAnnotationCount
input TypeName class_;
output Integer count;
end getAnnotationCount;
27.1.72 getAnnotationModifierValue
function getAnnotationModifierValue
input TypeName name;
input String vendorannotation;
input String modifiername;
output String modifiernamevalue;
end getAnnotationModifierValue;
27.1.73 getAnnotationNamedModifiers
function getAnnotationNamedModifiers
input TypeName name;
input String vendorannotation;
output String[:] modifiernamelist;
end getAnnotationNamedModifiers;
27.1.74 getAnnotationVersion
function getAnnotationVersion
output String annotationVersion;
end getAnnotationVersion;
27.1.75 getAstAsCorbaString
Print the whole AST on the CORBA format for records, e.g.
record Absyn.PROGRAM
classes = ...,
within_ = ...,
globalBuildTimes = ...
end Absyn.PROGRAM;
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;
27.1.76 getAvailableIndexReductionMethods
function getAvailableIndexReductionMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableIndexReductionMethods;
27.1.77 getAvailableLibraries
function getAvailableLibraries
output String[:] libraries;
end getAvailableLibraries;
27.1.78 getAvailableLibraryVersions
function getAvailableLibraryVersions
input TypeName libraryName;
output String[:] librariesAndVersions;
end getAvailableLibraryVersions;
27.1.79 getAvailableMatchingAlgorithms
function getAvailableMatchingAlgorithms
output String[:] allChoices;
output String[:] allComments;
end getAvailableMatchingAlgorithms;
27.1.80 getAvailablePackageConversionsFrom
function getAvailablePackageConversionsFrom
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsFrom;
27.1.81 getAvailablePackageConversionsTo
function getAvailablePackageConversionsTo
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsTo;
27.1.82 getAvailablePackageVersions
function getAvailablePackageVersions
input TypeName pkg;
input String version;
output String[:] withoutConversion;
end getAvailablePackageVersions;
27.1.83 getAvailableTearingMethods
function getAvailableTearingMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableTearingMethods;
27.1.84 getBooleanClassAnnotation
function getBooleanClassAnnotation
input TypeName className;
input TypeName annotationName;
output Boolean value;
end getBooleanClassAnnotation;
27.1.85 getBuiltinType
function getBuiltinType
input TypeName cl;
output String name;
end getBuiltinType;
27.1.86 getCFlags
CFLAGS
function getCFlags
output String outString;
end getCFlags;
27.1.87 getCXXCompiler
CXX
function getCXXCompiler
output String compiler;
end getCXXCompiler;
27.1.88 getClassComment
function getClassComment
input TypeName cl;
output String comment;
end getClassComment;
27.1.89 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;
output String dimensions[:];
output Boolean isProtectedClass;
output Boolean isDocumentationClass;
output String version;
output String preferredView;
output Boolean state;
output String access;
output String versionDate;
output String versionBuild;
output String dateModified;
output String revisionId;
end getClassInformation;
27.1.90 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";
output TypeName classNames[:];
end getClassNames;
27.1.91 getClassRestriction
function getClassRestriction
input TypeName cl;
output String restriction;
end getClassRestriction;
27.1.92 getClassesInModelicaPath
function getClassesInModelicaPath
output String classesInModelicaPath;
end getClassesInModelicaPath;
27.1.93 getCommandLineOptions
Returns all command line options who have non-default values as a list of
strings. The format of the strings is '--flag=value --flag2=value2'.
function getCommandLineOptions
output String[:] flags;
end getCommandLineOptions;
27.1.94 getCompileCommand
function getCompileCommand
output String compileCommand;
end getCompileCommand;
27.1.95 getCompiler
CC
function getCompiler
output String compiler;
end getCompiler;
27.1.96 getComponentModifierNames
function getComponentModifierNames
input TypeName class_;
input String componentName;
output String[:] modifiers;
end getComponentModifierNames;
27.1.97 getComponentModifierValue
function getComponentModifierValue
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValue;
27.1.98 getComponentModifierValues
function getComponentModifierValues
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValues;
27.1.99 getComponentsTest
returns an array of records with information about the components of the given class
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;
27.1.100 getConfigFlagValidOptions
Returns the list of valid options for a string config flag, and the description␣
˓→strings for these options if available
function getConfigFlagValidOptions
input String flag;
output String validOptions[:];
output String mainDescription;
output String descriptions[:];
end getConfigFlagValidOptions;
27.1.101 getConnectionCount
function getConnectionCount
input TypeName className;
output Integer count;
end getConnectionCount;
27.1.102 getConnectionList
function getConnectionList
input TypeName className;
output String[:, :] result;
end getConnectionList;
27.1.103 getConversionsFromVersions
function getConversionsFromVersions
input TypeName pack;
output String[:] withoutConversion;
output String[:] withConversion;
end getConversionsFromVersions;
27.1.104 getDefaultOpenCLDevice
function getDefaultOpenCLDevice
output Integer defdevid;
end getDefaultOpenCLDevice;
27.1.105 getDerivedClassModifierNames
function getDerivedClassModifierNames
input TypeName className;
output String[:] modifierNames;
end getDerivedClassModifierNames;
27.1.106 getDerivedClassModifierValue
function getDerivedClassModifierValue
input TypeName className;
input TypeName modifierName;
output String modifierValue;
end getDerivedClassModifierValue;
27.1.107 getDerivedUnits
function getDerivedUnits
input String baseUnit;
output String[:] derivedUnits;
end getDerivedUnits;
27.1.108 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;
27.1.109 getElementAnnotation
function getElementAnnotation
input TypeName elementName;
output String annotationString;
end getElementAnnotation;
27.1.110 getElementModifierNames
function getElementModifierNames
input TypeName className;
input String elementName;
output String[:] modifiers;
end getElementModifierNames;
27.1.111 getElementModifierValue
function getElementModifierValue
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValue;
27.1.112 getElementModifierValues
function getElementModifierValues
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValues;
27.1.113 getEnvironmentVar
function getEnvironmentVar
input String var;
output String value "returns empty string on failure";
end getEnvironmentVar;
27.1.114 getEquationCount
function getEquationCount
input TypeName class_;
output Integer count;
end getEquationCount;
27.1.115 getEquationItemsCount
function getEquationItemsCount
input TypeName class_;
output Integer count;
end getEquationItemsCount;
27.1.116 getErrorString
27.1.117 getHomeDirectoryPath
function getHomeDirectoryPath
output String homeDirectoryPath;
end getHomeDirectoryPath;
27.1.118 getImportCount
function getImportCount
input TypeName class_;
output Integer count;
end getImportCount;
27.1.119 getImportedNames
function getImportedNames
input TypeName class_;
output String[:] out_public;
output String[:] out_protected;
end getImportedNames;
27.1.120 getIndexReductionMethod
function getIndexReductionMethod
output String selected;
end getIndexReductionMethod;
27.1.121 getInheritedClasses
function getInheritedClasses
input TypeName name;
output TypeName inheritedClasses[:];
end getInheritedClasses;
27.1.122 getInitialAlgorithmCount
function getInitialAlgorithmCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmCount;
27.1.123 getInitialAlgorithmItemsCount
function getInitialAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmItemsCount;
27.1.124 getInitialEquationCount
function getInitialEquationCount
input TypeName class_;
output Integer count;
end getInitialEquationCount;
27.1.125 getInitialEquationItemsCount
function getInitialEquationItemsCount
input TypeName class_;
output Integer count;
end getInitialEquationItemsCount;
27.1.126 getInitialStates
function getInitialStates
input TypeName cl;
output String[:, :] initialStates;
end getInitialStates;
27.1.127 getInstallationDirectoryPath
This returns OPENMODELICAHOME if it is set; on some platforms the default path is␣
˓→returned if it is not set.
function getInstallationDirectoryPath
output String installationDirectoryPath;
end getInstallationDirectoryPath;
27.1.128 getInstantiatedParametersAndValues
function getInstantiatedParametersAndValues
input TypeName cls;
output String[:] values;
end getInstantiatedParametersAndValues;
27.1.129 getLanguageStandard
function getLanguageStandard
output String outVersion;
end getLanguageStandard;
27.1.130 getLinker
function getLinker
output String linker;
end getLinker;
27.1.131 getLinkerFlags
function getLinkerFlags
output String linkerFlags;
end getLinkerFlags;
27.1.132 getLoadedLibraries
function getLoadedLibraries
output String[:, 2] libraries;
end getLoadedLibraries;
27.1.133 getMMfileTotalDependencies
function getMMfileTotalDependencies
input String in_package_name;
input String public_imports_dir;
output String[:] total_pub_imports;
end getMMfileTotalDependencies;
27.1.134 getMatchingAlgorithm
function getMatchingAlgorithm
output String selected;
end getMatchingAlgorithm;
27.1.135 getMemorySize
function getMemorySize
output Real memory(unit = "MiB");
end getMemorySize;
27.1.136 getMessagesString
see getErrorString()
function getMessagesString
output String messagesString;
end getMessagesString;
27.1.137 getModelInstance
function getModelInstance
input TypeName className;
input String modifier = "";
input Boolean prettyPrint = false;
output String result;
end getModelInstance;
27.1.138 getModelInstanceAnnotation
function getModelInstanceAnnotation
input TypeName className;
input String[:] filter = fill("", 0);
input Boolean prettyPrint = false;
output String result;
end getModelInstanceAnnotation;
27.1.139 getModelicaPath
function getModelicaPath
output String modelicaPath;
end getModelicaPath;
27.1.140 getNoSimplify
function getNoSimplify
output Boolean noSimplify;
end getNoSimplify;
27.1.141 getNthAlgorithm
function getNthAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithm;
27.1.142 getNthAlgorithmItem
function getNthAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithmItem;
27.1.143 getNthAnnotationString
function getNthAnnotationString
input TypeName class_;
input Integer index;
output String result;
end getNthAnnotationString;
27.1.144 getNthConnection
function getNthConnection
input TypeName className;
input Integer index;
output String[:] result;
end getNthConnection;
27.1.145 getNthEquation
function getNthEquation
input TypeName class_;
input Integer index;
output String result;
end getNthEquation;
27.1.146 getNthEquationItem
function getNthEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthEquationItem;
27.1.147 getNthImport
function getNthImport
input TypeName class_;
input Integer index;
output String out[3] "{\"Path\",\"Id\",\"Kind\"}";
end getNthImport;
27.1.148 getNthInitialAlgorithm
function getNthInitialAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithm;
27.1.149 getNthInitialAlgorithmItem
function getNthInitialAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithmItem;
27.1.150 getNthInitialEquation
function getNthInitialEquation
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquation;
27.1.151 getNthInitialEquationItem
function getNthInitialEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquationItem;
27.1.152 getOrderConnections
function getOrderConnections
output Boolean orderConnections;
end getOrderConnections;
27.1.153 getPackages
function getPackages
input TypeName class_ = $Code(AllLoadedClasses);
output TypeName classNames[:];
end getPackages;
27.1.154 getParameterNames
function getParameterNames
input TypeName class_;
output String[:] parameters;
end getParameterNames;
27.1.155 getParameterValue
function getParameterValue
input TypeName class_;
input String parameterName;
output String parameterValue;
end getParameterValue;
27.1.156 getSettings
function getSettings
output String settings;
end getSettings;
27.1.157 getShowAnnotations
function getShowAnnotations
output Boolean show;
end getShowAnnotations;
27.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";
input Real defaultInterval = 0.0 "If = 0.0, then numberOfIntervals is used to␣
˓→calculate the step size";
27.1.159 getSourceFile
function getSourceFile
input TypeName class_;
output String filename "empty on failure";
end getSourceFile;
27.1.160 getTearingMethod
function getTearingMethod
output String selected;
end getTearingMethod;
27.1.161 getTempDirectoryPath
function getTempDirectoryPath
output String tempDirectoryPath;
end getTempDirectoryPath;
27.1.162 getTimeStamp
function getTimeStamp
input TypeName cl;
output Real timeStamp;
output String timeStampAsString;
end getTimeStamp;
27.1.163 getTransitions
function getTransitions
input TypeName cl;
output String[:, :] transitions;
end getTransitions;
27.1.164 getUsedClassNames
Returns the list of class names used in the total program defined by the class.
function getUsedClassNames
input TypeName className;
output TypeName classNames[:];
end getUsedClassNames;
27.1.165 getUses
function getUses
input TypeName pack;
output String[:, :] uses;
end getUses;
27.1.166 getVectorizationLimit
function getVectorizationLimit
output Integer vectorizationLimit;
end getVectorizationLimit;
27.1.167 getVersion
function getVersion
input TypeName cl = $Code(OpenModelica);
output String version;
end getVersion;
27.1.168 help
function help
input String topic = "topics";
output String helpText;
end help;
27.1.169 iconv
The iconv() function converts one multibyte characters from one character
set to another.
See man (3) iconv for more information.
function iconv
input String string;
input String from;
input String to = "UTF-8";
output String result;
end iconv;
27.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.";
input Boolean generateInputConnectors = true "When true creates the input connector␣
˓→pins.";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
27.1.171 importFMUModelDescription
Imports modelDescription.xml
Example command:
importFMUModelDescription("A.xml");
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.";
input Boolean generateInputConnectors = true "When true creates the input connector␣
˓→pins.";
output String generatedFileName "Returns the full path of the generated file.";
end importFMUModelDescription;
27.1.172 inferBindings
function inferBindings
input TypeName path;
output Boolean success;
end inferBindings;
27.1.173 installPackage
function installPackage
input TypeName pkg;
input String version = "";
input Boolean exactMatch = false;
output Boolean result;
end installPackage;
27.1.174 instantiateModel
function instantiateModel
input TypeName className;
output String result;
end instantiateModel;
27.1.175 isBlock
function isBlock
input TypeName cl;
output Boolean b;
end isBlock;
27.1.176 isClass
function isClass
input TypeName cl;
output Boolean b;
end isClass;
27.1.177 isConnector
function isConnector
input TypeName cl;
output Boolean b;
end isConnector;
27.1.178 isEnumeration
function isEnumeration
input TypeName cl;
output Boolean b;
end isEnumeration;
27.1.179 isExperiment
function isExperiment
input TypeName name;
output Boolean res;
end isExperiment;
27.1.180 isFunction
function isFunction
input TypeName cl;
output Boolean b;
end isFunction;
27.1.181 isModel
function isModel
input TypeName cl;
output Boolean b;
end isModel;
27.1.182 isOperator
function isOperator
input TypeName cl;
output Boolean b;
end isOperator;
27.1.183 isOperatorFunction
function isOperatorFunction
input TypeName cl;
output Boolean b;
end isOperatorFunction;
27.1.184 isOperatorRecord
function isOperatorRecord
input TypeName cl;
output Boolean b;
end isOperatorRecord;
27.1.185 isOptimization
function isOptimization
input TypeName cl;
output Boolean b;
end isOptimization;
27.1.186 isPackage
function isPackage
input TypeName cl;
output Boolean b;
end isPackage;
27.1.187 isPartial
function isPartial
input TypeName cl;
output Boolean b;
end isPartial;
27.1.188 isProtectedClass
function isProtectedClass
input TypeName cl;
input String c2;
output Boolean b;
end isProtectedClass;
27.1.189 isRecord
function isRecord
input TypeName cl;
output Boolean b;
end isRecord;
27.1.190 isRedeclare
function isRedeclare
input TypeName element;
output Boolean b;
end isRedeclare;
27.1.191 isReplaceable
function isReplaceable
input TypeName element;
output Boolean b;
end isReplaceable;
27.1.192 isShortDefinition
function isShortDefinition
input TypeName class_;
output Boolean isShortCls;
end isShortDefinition;
27.1.193 isType
function isType
input TypeName cl;
output Boolean b;
end isType;
27.1.194 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 method = "<default>" "integration method used for simulation. <default>
˓→ = dassl";
27.1.195 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;
27.1.196 listFile
function listFile
input TypeName class_;
input Boolean nestedClasses = true;
output String contents;
end listFile;
27.1.197 listVariables
function listVariables
output TypeName variables[:];
end listVariables;
27.1.198 loadClassContentString
Loads class elements from a string and inserts them into the given loaded class.
function loadClassContentString
input String data;
input TypeName className;
output Boolean success;
end loadClassContentString;
27.1.199 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.";
27.1.200 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";
27.1.201 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";
27.1.202 loadFileInteractiveQualified
function loadFileInteractiveQualified
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractiveQualified;
27.1.203 loadFiles
load files (*.mo) and merges them with the loaded AST.
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";
27.1.204 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.";
27.1.205 loadModelica3D
function loadModelica3D
input String version = "3.2.1";
output Boolean status;
end loadModelica3D;
27.1.206 loadOMSimulator
function loadOMSimulator
output Integer status;
end loadOMSimulator;
27.1.207 loadString
Parses the data and merges the resulting AST with ithe
loaded AST.
If a filename is given, it is used to provide error-messages as if the string
was read in binary format from a file with the same name.
The file is converted to UTF-8 from the given character set.
When merge is true the classes cNew in the file will be merged with the already␣
˓→loaded classes cOld in the following way:
1. get all the inner class definitions from cOld that were loaded from a different␣
˓→file than itself
function loadString
input String data;
input String filename = "<interactive>";
input String encoding = "UTF-8" "Deprecated as *ALL* strings are now UTF-8 encoded";
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";
(continues on next page)
27.1.208 mkdir
function mkdir
input String newDirectory;
output Boolean success;
end mkdir;
27.1.209 modifierToJSON
function modifierToJSON
input String modifier;
input Boolean prettyPrint = false;
output String json;
end modifierToJSON;
27.1.210 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;
27.1.211 moveClassToBottom
Moves a class to the bottom of its enclosing class. Returns true if the move
was successful, otherwise false.
function moveClassToBottom
input TypeName className;
output Boolean result;
end moveClassToBottom;
27.1.212 moveClassToTop
Moves a class to the top of its enclosing class. Returns true if the move
was successful, otherwise false.
function moveClassToTop
input TypeName className;
output Boolean result;
end moveClassToTop;
27.1.213 ngspicetoModelica
Converts ngspice netlist to Modelica code. Modelica file is created in the same␣
˓→directory as netlist file.
function ngspicetoModelica
input String netlistfileName;
output Boolean success = false;
end ngspicetoModelica;
27.1.214 numProcessors
function numProcessors
output Integer result;
end numProcessors;
27.1.215 oms_RunFile
function oms_RunFile
input String filename;
output Integer status;
end oms_RunFile;
27.1.216 oms_addBus
function oms_addBus
input String cref;
output Integer status;
end oms_addBus;
27.1.217 oms_addConnection
function oms_addConnection
input String crefA;
input String crefB;
output Integer status;
end oms_addConnection;
27.1.218 oms_addConnector
function oms_addConnector
input String cref;
input oms_causality causality;
input oms_signal_type type_;
output Integer status;
end oms_addConnector;
27.1.219 oms_addConnectorToBus
function oms_addConnectorToBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_addConnectorToBus;
27.1.220 oms_addConnectorToTLMBus
function oms_addConnectorToTLMBus
input String busCref;
input String connectorCref;
input String type_;
output Integer status;
end oms_addConnectorToTLMBus;
27.1.221 oms_addDynamicValueIndicator
function oms_addDynamicValueIndicator
input String signal;
input String lower;
input String upper;
input Real stepSize;
output Integer status;
end oms_addDynamicValueIndicator;
27.1.222 oms_addEventIndicator
function oms_addEventIndicator
input String signal;
output Integer status;
end oms_addEventIndicator;
27.1.223 oms_addExternalModel
function oms_addExternalModel
input String cref;
input String path;
input String startscript;
output Integer status;
end oms_addExternalModel;
27.1.224 oms_addSignalsToResults
function oms_addSignalsToResults
input String cref;
input String regex;
output Integer status;
end oms_addSignalsToResults;
27.1.225 oms_addStaticValueIndicator
function oms_addStaticValueIndicator
input String signal;
input Real lower;
input Real upper;
input Real stepSize;
output Integer status;
end oms_addStaticValueIndicator;
27.1.226 oms_addSubModel
function oms_addSubModel
input String cref;
input String fmuPath;
output Integer status;
end oms_addSubModel;
27.1.227 oms_addSystem
function oms_addSystem
input String cref;
input oms_system type_;
output Integer status;
end oms_addSystem;
27.1.228 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;
27.1.229 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;
27.1.230 oms_addTimeIndicator
function oms_addTimeIndicator
input String signal;
output Integer status;
end oms_addTimeIndicator;
27.1.231 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;
27.1.232 oms_copySystem
function oms_copySystem
input String source;
input String target;
output Integer status;
end oms_copySystem;
27.1.233 oms_delete
function oms_delete
input String cref;
output Integer status;
end oms_delete;
27.1.234 oms_deleteConnection
function oms_deleteConnection
input String crefA;
input String crefB;
output Integer status;
end oms_deleteConnection;
27.1.235 oms_deleteConnectorFromBus
function oms_deleteConnectorFromBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromBus;
27.1.236 oms_deleteConnectorFromTLMBus
function oms_deleteConnectorFromTLMBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromTLMBus;
27.1.237 oms_export
function oms_export
input String cref;
input String filename;
output Integer status;
end oms_export;
27.1.238 oms_exportDependencyGraphs
function oms_exportDependencyGraphs
input String cref;
input String initialization;
input String event;
input String simulation;
output Integer status;
end oms_exportDependencyGraphs;
27.1.239 oms_exportSnapshot
function oms_exportSnapshot
input String cref;
output String contents;
output Integer status;
end oms_exportSnapshot;
27.1.240 oms_extractFMIKind
function oms_extractFMIKind
input String filename;
output Integer kind;
output Integer status;
end oms_extractFMIKind;
27.1.241 oms_faultInjection
function oms_faultInjection
input String signal;
input oms_fault_type faultType;
input Real faultValue;
output Integer status;
end oms_faultInjection;
27.1.242 oms_getBoolean
function oms_getBoolean
input String cref;
output Boolean value;
output Integer status;
end oms_getBoolean;
27.1.243 oms_getFixedStepSize
function oms_getFixedStepSize
input String cref;
output Real stepSize;
output Integer status;
end oms_getFixedStepSize;
27.1.244 oms_getInteger
function oms_getInteger
input String cref;
input Integer value;
output Integer status;
end oms_getInteger;
27.1.245 oms_getModelState
function oms_getModelState
input String cref;
output Integer modelState;
output Integer status;
end oms_getModelState;
27.1.246 oms_getReal
function oms_getReal
input String cref;
output Real value;
output Integer status;
end oms_getReal;
27.1.247 oms_getSolver
function oms_getSolver
input String cref;
output Integer solver;
output Integer status;
end oms_getSolver;
27.1.248 oms_getStartTime
function oms_getStartTime
input String cref;
output Real startTime;
output Integer status;
end oms_getStartTime;
27.1.249 oms_getStopTime
function oms_getStopTime
input String cref;
output Real stopTime;
output Integer status;
end oms_getStopTime;
27.1.250 oms_getSubModelPath
function oms_getSubModelPath
input String cref;
output String path;
output Integer status;
end oms_getSubModelPath;
27.1.251 oms_getSystemType
function oms_getSystemType
input String cref;
output Integer type_;
output Integer status;
end oms_getSystemType;
27.1.252 oms_getTolerance
function oms_getTolerance
input String cref;
output Real absoluteTolerance;
output Real relativeTolerance;
output Integer status;
end oms_getTolerance;
27.1.253 oms_getVariableStepSize
function oms_getVariableStepSize
input String cref;
output Real initialStepSize;
output Real minimumStepSize;
output Real maximumStepSize;
output Integer status;
end oms_getVariableStepSize;
27.1.254 oms_getVersion
function oms_getVersion
output String version;
end oms_getVersion;
27.1.255 oms_importFile
function oms_importFile
input String filename;
output String cref;
output Integer status;
end oms_importFile;
27.1.256 oms_importSnapshot
function oms_importSnapshot
input String cref;
input String snapshot;
output Integer status;
end oms_importSnapshot;
27.1.257 oms_initialize
function oms_initialize
input String cref;
output Integer status;
end oms_initialize;
27.1.258 oms_instantiate
function oms_instantiate
input String cref;
output Integer status;
end oms_instantiate;
27.1.259 oms_list
function oms_list
input String cref;
output String contents;
output Integer status;
end oms_list;
27.1.260 oms_listUnconnectedConnectors
function oms_listUnconnectedConnectors
input String cref;
output String contents;
output Integer status;
end oms_listUnconnectedConnectors;
27.1.261 oms_loadSnapshot
function oms_loadSnapshot
input String cref;
input String snapshot;
output String newCref;
output Integer status;
end oms_loadSnapshot;
27.1.262 oms_newModel
function oms_newModel
input String cref;
output Integer status;
end oms_newModel;
27.1.263 oms_removeSignalsFromResults
function oms_removeSignalsFromResults
input String cref;
input String regex;
output Integer status;
end oms_removeSignalsFromResults;
27.1.264 oms_rename
function oms_rename
input String cref;
input String newCref;
output Integer status;
end oms_rename;
27.1.265 oms_reset
function oms_reset
input String cref;
output Integer status;
end oms_reset;
27.1.266 oms_setBoolean
function oms_setBoolean
input String cref;
input Boolean value;
output Integer status;
end oms_setBoolean;
27.1.267 oms_setCommandLineOption
function oms_setCommandLineOption
input String cmd;
output Integer status;
end oms_setCommandLineOption;
27.1.268 oms_setFixedStepSize
function oms_setFixedStepSize
input String cref;
input Real stepSize;
output Integer status;
end oms_setFixedStepSize;
27.1.269 oms_setInteger
function oms_setInteger
input String cref;
input Integer value;
output Integer status;
end oms_setInteger;
27.1.270 oms_setLogFile
function oms_setLogFile
input String filename;
output Integer status;
end oms_setLogFile;
27.1.271 oms_setLoggingInterval
function oms_setLoggingInterval
input String cref;
input Real loggingInterval;
output Integer status;
end oms_setLoggingInterval;
27.1.272 oms_setLoggingLevel
function oms_setLoggingLevel
input Integer logLevel;
output Integer status;
end oms_setLoggingLevel;
27.1.273 oms_setReal
function oms_setReal
input String cref;
input Real value;
output Integer status;
end oms_setReal;
27.1.274 oms_setRealInputDerivative
function oms_setRealInputDerivative
input String cref;
input Real value;
output Integer status;
end oms_setRealInputDerivative;
27.1.275 oms_setResultFile
function oms_setResultFile
input String cref;
input String filename;
input Integer bufferSize;
output Integer status;
end oms_setResultFile;
27.1.276 oms_setSignalFilter
function oms_setSignalFilter
input String cref;
input String regex;
output Integer status;
end oms_setSignalFilter;
27.1.277 oms_setSolver
function oms_setSolver
input String cref;
input oms_solver solver;
output Integer status;
end oms_setSolver;
27.1.278 oms_setStartTime
function oms_setStartTime
input String cref;
input Real startTime;
output Integer status;
end oms_setStartTime;
27.1.279 oms_setStopTime
function oms_setStopTime
input String cref;
input Real stopTime;
output Integer status;
end oms_setStopTime;
27.1.280 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;
27.1.281 oms_setTLMSocketData
function oms_setTLMSocketData
input String cref;
input String address;
input Integer managerPort;
input Integer monitorPort;
output Integer status;
end oms_setTLMSocketData;
27.1.282 oms_setTempDirectory
function oms_setTempDirectory
input String newTempDir;
output Integer status;
end oms_setTempDirectory;
27.1.283 oms_setTolerance
function oms_setTolerance
input String cref;
input Real absoluteTolerance;
input Real relativeTolerance;
output Integer status;
end oms_setTolerance;
27.1.284 oms_setVariableStepSize
function oms_setVariableStepSize
input String cref;
input Real initialStepSize;
input Real minimumStepSize;
input Real maximumStepSize;
output Integer status;
end oms_setVariableStepSize;
27.1.285 oms_setWorkingDirectory
function oms_setWorkingDirectory
input String newWorkingDir;
output Integer status;
end oms_setWorkingDirectory;
27.1.286 oms_simulate
function oms_simulate
input String cref;
output Integer status;
end oms_simulate;
27.1.287 oms_stepUntil
function oms_stepUntil
input String cref;
input Real stopTime;
output Integer status;
end oms_stepUntil;
27.1.288 oms_terminate
function oms_terminate
input String cref;
output Integer status;
end oms_terminate;
27.1.289 optimize
The only required argument is the className, while all others have some default␣
˓→values.
˓→[cflags], [simflags])
Example command:
simulate(A);
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";
27.1.290 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.";
27.1.291 parseFile
function parseFile
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end parseFile;
27.1.292 parseString
function parseString
input String data;
input String filename = "<interactive>";
output TypeName names[:];
end parseString;
27.1.293 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␣
(continues on next page)
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.";
27.1.294 plotAll
Works in the same way as plot(), but does not accept any
variable names as input. Instead, all variables are part of the plot window.
Example command sequences:
simulate(A);plotAll();
simulate(A);plotAll(externalWindow=true);
simulate(A,fileNamePrefix="B");simulate(C);plotAll(x,fileName="B.mat");
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.";
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.";
(continues on next page)
27.1.295 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.";
27.1.296 qualifyPath
function qualifyPath
input TypeName classPath;
input TypeName path;
output TypeName qualifiedPath;
end qualifyPath;
27.1.297 readFile
27.1.298 readFileNoNumeric
Returns the contents of the file, with anything resembling a (real) number stripped␣
˓→out, and at the end adding:
function readFileNoNumeric
input String fileName;
output String contents;
end readFileNoNumeric;
27.1.299 readSimulationResult
Reads a result file, returning a matrix corresponding to the variables and size given.
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";
27.1.300 readSimulationResultSize
function readSimulationResultSize
input String fileName;
output Integer sz;
end readSimulationResultSize;
27.1.301 readSimulationResultVars
Returns the variables in the simulation file; you can use val() and plot() commands␣
˓→using these names.
function readSimulationResultVars
input String fileName;
input Boolean readParameters = true;
input Boolean openmodelicaStyle = false;
output String[:] vars;
end readSimulationResultVars;
27.1.302 realpath
function realpath
input String name "Absolute or relative file or directory name";
output String fullName "Full path of 'name'";
end realpath;
27.1.303 reduceTerms
reduce terms.
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";
27.1.304 regex
Sets the error buffer and returns -1 if the regex does not compile.
The returned result is the same as POSIX regex():
The first value is the complete matched string
The rest are the substrings that you wanted.
For example:
regex(lorem," \([A-Za-z]*\) \([A-Za-z]*\) ",maxMatches=3)
=> {" ipsum dolor ","ipsum","dolor"}
This means if you have n groups, you want maxMatches=n+1
function regex
input String str;
input String re;
input Integer maxMatches = 1 "The maximum number of matches that will be returned";
input Boolean extended = true "Use POSIX extended or regular syntax";
input Boolean caseInsensitive = false;
output Integer numMatches "-1 is an error, 0 means no match, else returns a number␣
˓→1..maxMatches";
end regex;
27.1.305 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;
27.1.306 regularFileExists
function regularFileExists
input String fileName;
output Boolean exists;
end regularFileExists;
27.1.307 reloadClass
function reloadClass
input TypeName name;
input String encoding = "UTF-8";
output Boolean success;
end reloadClass;
27.1.308 remove
removes a file or directory of given path (which may be either relative or absolute).
function remove
input String path;
output Boolean success "Returns true on success.";
end remove;
27.1.309 removeComponentModifiers
function removeComponentModifiers
input TypeName class_;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeComponentModifiers;
27.1.310 removeElementModifiers
function removeElementModifiers
input TypeName className;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeElementModifiers;
27.1.311 removeExtendsModifiers
function removeExtendsModifiers
input TypeName className;
input TypeName baseClassName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeExtendsModifiers;
27.1.312 reopenStandardStream
function reopenStandardStream
input StandardStream _stream;
input String filename;
output Boolean success;
end reopenStandardStream;
27.1.313 restoreAST
function restoreAST
input Integer id;
output Boolean success;
end restoreAST;
27.1.314 rewriteBlockCall
Function for property modeling, transforms block calls into instantiations for a␣
˓→loaded model
function rewriteBlockCall
input TypeName className;
input TypeName inDefs;
output Boolean success;
end rewriteBlockCall;
27.1.315 runConversionScript
function runConversionScript
input TypeName packageToConvert;
input String scriptFile;
output Boolean success;
end runConversionScript;
27.1.316 runScript
27.1.317 runScriptParallel
function runScriptParallel
input String scripts[:];
input Integer numThreads = numProcessors();
input Boolean useThreads = false;
output Boolean results[:];
end runScriptParallel;
27.1.318 save
function save
input TypeName className;
output Boolean success;
end save;
27.1.319 saveAll
function saveAll
input String fileName;
output Boolean success;
end saveAll;
27.1.320 saveModel
function saveModel
input String fileName;
input TypeName className;
output Boolean success;
end saveModel;
27.1.321 saveTotalModel
function saveTotalModel
input String fileName;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
(continues on next page)
27.1.322 saveTotalModelDebug
Saves the className model in a single file, together with all other classes
that it depends on. This function uses a naive heuristic based on which
identifiers are used and might save things which are not actually used,
and is meant to be used in cases where the normal saveTotalModel fails.
function saveTotalModelDebug
input String filename;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output Boolean success;
end saveTotalModelDebug;
27.1.323 saveTotalSCode
27.1.324 searchClassNames
Searches for the class name in the all the loaded classes.
Example command:
searchClassNames("ground");
searchClassNames("ground", true);
function searchClassNames
input String searchText;
input Boolean findInText = false;
output TypeName classNames[:];
end searchClassNames;
27.1.325 setAnnotationVersion
function setAnnotationVersion
input String annotationVersion;
output Boolean success;
end setAnnotationVersion;
27.1.326 setCFlags
CFLAGS
function setCFlags
input String inString;
output Boolean success;
end setCFlags;
27.1.327 setCXXCompiler
CXX
function setCXXCompiler
input String compiler;
output Boolean success;
end setCXXCompiler;
27.1.328 setCheapMatchingAlgorithm
example input: 3
function setCheapMatchingAlgorithm
input Integer matchingAlgorithm;
output Boolean success;
end setCheapMatchingAlgorithm;
27.1.329 setClassComment
function setClassComment
input TypeName class_;
input String filename;
output Boolean success;
end setClassComment;
27.1.330 setCommandLineOptions
function setCommandLineOptions
input String option;
output Boolean success;
end setCommandLineOptions;
27.1.331 setCompileCommand
function setCompileCommand
input String compileCommand;
output Boolean success;
end setCompileCommand;
27.1.332 setCompiler
CC
function setCompiler
input String compiler;
output Boolean success;
end setCompiler;
27.1.333 setCompilerFlags
function setCompilerFlags
input String compilerFlags;
output Boolean success;
end setCompilerFlags;
27.1.334 setCompilerPath
function setCompilerPath
input String compilerPath;
output Boolean success;
end setCompilerPath;
27.1.335 setComponentModifierValue
27.1.336 setDebugFlags
function setDebugFlags
input String debugFlags;
output Boolean success;
end setDebugFlags;
27.1.337 setDefaultOpenCLDevice
function setDefaultOpenCLDevice
input Integer defdevid;
output Boolean success;
end setDefaultOpenCLDevice;
27.1.338 setDocumentationAnnotation
function setDocumentationAnnotation
input TypeName class_;
input String info = "";
input String revisions = "";
output Boolean bool;
end setDocumentationAnnotation;
27.1.339 setElementAnnotation
function setElementAnnotation
input TypeName elementName;
input ExpressionOrModification annotationMod;
output Boolean success;
end setElementAnnotation;
27.1.340 setElementModifierValue
function setElementModifierValue
input TypeName className;
input TypeName elementName;
input ExpressionOrModification modifier;
output Boolean success;
end setElementModifierValue;
27.1.341 setEnvironmentVar
function setEnvironmentVar
input String var;
input String value;
output Boolean success;
end setEnvironmentVar;
27.1.342 setExtendsModifierValue
function setExtendsModifierValue
input TypeName className;
input TypeName extendsName;
input TypeName elementName;
input ExpressionOrModification modifier;
output Boolean success;
end setExtendsModifierValue;
27.1.343 setIndexReductionMethod
function setIndexReductionMethod
input String method;
output Boolean success;
end setIndexReductionMethod;
27.1.344 setInitXmlStartValue
function setInitXmlStartValue
input String fileName;
input String variableName;
input String startValue;
input String outputFile;
output Boolean success = false;
end setInitXmlStartValue;
27.1.345 setInstallationDirectoryPath
Sets the OPENMODELICAHOME environment variable. Use this method instead of␣
˓→setEnvironmentVar.
function setInstallationDirectoryPath
input String installationDirectoryPath;
output Boolean success;
end setInstallationDirectoryPath;
27.1.346 setLanguageStandard
function setLanguageStandard
input String inVersion;
output Boolean success;
end setLanguageStandard;
27.1.347 setLinker
function setLinker
input String linker;
output Boolean success;
end setLinker;
27.1.348 setLinkerFlags
function setLinkerFlags
input String linkerFlags;
output Boolean success;
end setLinkerFlags;
27.1.349 setMatchingAlgorithm
function setMatchingAlgorithm
input String matchingAlgorithm;
output Boolean success;
end setMatchingAlgorithm;
27.1.350 setModelicaPath
function setModelicaPath
input String modelicaPath;
output Boolean success;
end setModelicaPath;
27.1.351 setNoSimplify
function setNoSimplify
input Boolean noSimplify;
output Boolean success;
end setNoSimplify;
27.1.352 setOrderConnections
function setOrderConnections
input Boolean orderConnections;
output Boolean success;
end setOrderConnections;
27.1.353 setPlotCommand
function setPlotCommand
input String plotCommand;
output Boolean success;
end setPlotCommand;
27.1.354 setPostOptModules
function setPostOptModules
input String modules;
output Boolean success;
end setPostOptModules;
27.1.355 setPreOptModules
function setPreOptModules
input String modules;
output Boolean success;
end setPreOptModules;
27.1.356 setShowAnnotations
function setShowAnnotations
input Boolean show;
output Boolean success;
end setShowAnnotations;
27.1.357 setSourceFile
function setSourceFile
input TypeName class_;
input String filename;
output Boolean success;
end setSourceFile;
27.1.358 setTearingMethod
function setTearingMethod
input String tearingMethod;
output Boolean success;
end setTearingMethod;
27.1.359 setTempDirectoryPath
function setTempDirectoryPath
input String tempDirectoryPath;
output Boolean success;
end setTempDirectoryPath;
27.1.360 setVectorizationLimit
function setVectorizationLimit
input Integer vectorizationLimit;
output Boolean success;
end setVectorizationLimit;
27.1.361 simulate
simulates a modelica model by generating c code, build it and run the simulation␣
˓→executable.
The only required argument is the className, while all others have some default␣
˓→values.
˓→[simflags])
Example command:
simulate(A);
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 String method = "<default>" "integration method used for simulation. <default>
˓→ = dassl";
27.1.362 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;
27.1.363 sortStrings
function sortStrings
input String arr[:];
output String sorted[:];
end sortStrings;
27.1.364 stat
27.1.365 storeAST
function storeAST
output Integer id;
end storeAST;
27.1.366 stringReplace
function stringReplace
input String str;
input String source;
input String target;
output String res;
end stringReplace;
27.1.367 stringSplit
function stringSplit
input String string;
input String token "single character only";
output String[:] strings;
end stringSplit;
27.1.368 stringTypeName
function stringTypeName
input String str;
output TypeName cl;
end stringTypeName;
27.1.369 stringVariableName
function stringVariableName
input String str;
output VariableName cl;
end stringVariableName;
27.1.370 strtok
Splits the strings at the places given by the token, for example:
strtok("abcbdef","b") => {"a","c","def"}
strtok("abcbdef","cd") => {"ab","ef"}
function strtok
input String string;
input String token;
output String[:] strings;
end strtok;
27.1.371 system
output Integer retval "Return value of the system call; usually 0 on success";
end system;
27.1.372 system_parallel
Similar to system(3). Executes the given commands in the system shell, in parallel if␣
˓→omc was compiled using OpenMP.
27.1.373 testsuiteFriendlyName
function testsuiteFriendlyName
input String path;
output String fixed;
end testsuiteFriendlyName;
27.1.374 threadWorkFailed
27.1.375 translateGraphics
function translateGraphics
input TypeName className;
output String result;
end translateGraphics;
27.1.376 typeNameString
function typeNameString
input TypeName cl;
output String out;
end typeNameString;
27.1.377 typeNameStrings
function typeNameStrings
input TypeName cl;
output String out[:];
end typeNameStrings;
27.1.378 typeOf
function typeOf
input VariableName variableName;
output String result;
end typeOf;
27.1.379 unloadOMSimulator
function unloadOMSimulator
output Integer status;
end unloadOMSimulator;
27.1.380 updateConnection
function updateConnection
input TypeName className;
input String from;
input String to;
input ExpressionOrModification annotate;
output Boolean result;
end updateConnection;
27.1.381 updateConnectionAnnotation
function updateConnectionAnnotation
input TypeName className;
input String from;
input String to;
input String annotate;
output Boolean result;
end updateConnectionAnnotation;
27.1.382 updateConnectionNames
function updateConnectionNames
input TypeName className;
input String from;
input String to;
input String fromNew;
input String toNew;
output Boolean result;
end updateConnectionNames;
27.1.383 updateInitialState
function updateInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end updateInitialState;
27.1.384 updatePackageIndex
function updatePackageIndex
output Boolean result;
end updatePackageIndex;
27.1.385 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;
27.1.386 upgradeInstalledPackages
function upgradeInstalledPackages
input Boolean installNewestVersions = true;
output Boolean result;
end upgradeInstalledPackages;
27.1.387 uriToFilename
function uriToFilename
input String uri;
output String filename = "";
end uriToFilename;
27.1.388 val
function val
input VariableName var;
input Real timePoint = 0.0;
input String fileName = "<default>" "The contents of the currentSimulationResult␣
˓→variable";
27.1.389 verifyCompiler
function verifyCompiler
output Boolean compilerWorks;
end verifyCompiler;
27.1.390 writeFile
Following example shows how to update the parameters and re-run the simulation without compiling the model.
loadFile("BouncingBall.mo");
getErrorString();
// build the model once
buildModel(BouncingBall);
getErrorString();
for i in 1:3 loop
// We update the parameter e start value from 0.7 to "0.7 + i".
value := 0.7 + i;
// call the generated simulation code to produce a result file BouncingBall%i%_res.
˓→mat
getErrorString();
end for;
We used the BouncingBall.mo in the example above. The above example produces three result files each containing
different start value for e i.e., 1.7, 2.7, 3.7.
27.3 Examples
The following is an interactive session with the OpenModelica environment including some of the abovementioned
commands and examples. Run the examples below using OMShell or OMNotebook.
We type in a very small model in the command window:
>>> instantiateModel(Test)
class Test "Testing OpenModelica Scripts"
Real x;
Real y;
equation
x = 5.0 + time;
y = 6.0;
end Test;
>>> a:=1:10
{1,2,3,4,5,6,7,8,9,10}
It is multiplied by 2:
>>> a*2
{2,4,6,8,10,12,14,16,18,20}
>>> clearVariables()
true
>>> list(Test)
model Test "Testing OpenModelica Scripts"
Real x, y;
equation
x = 5.0 + time;
y = 6.0;
end Test;
>>> getClassNames()
{Test,ProfilingTest}
>>> getClassComment(Test)
"Testing OpenModelica Scripts"
>>> isPartial(Test)
false
>>> isPackage(Test)
false
>>> isModel(Test)
true
>>> checkModel(Test)
"Check of Test completed successfully.
Class Test has 2 equation(s) and 2 variable(s).
2 of these are trivial equation(s)."
The common combination of a simulation followed by getting a value and doing a plot:
",
timeFrontend = 0.0016950490000000001,
timeBackend = 0.0015995,
timeSimCode = 5.621840000000001e-4,
timeTemplates = 0.007651288000000001,
timeCompile = 0.514146969,
timeSimulation = 0.024017379000000002,
timeTotal = 0.5497756810000001
end SimulationResult;
>>> val(x , 2.0)
7.0
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()
We enter an assignment of a vector expression, created by the range construction expression 1:12, to be stored in
the variable x. The type and the value of the expression is returned.
>>> x := 1:12
{1,2,3,4,5,6,7,8,9,10,11,12}
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.
8
x
y
7.5
6.5
5.5
5
0 0.5 1 1.5 2 2.5 3
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
(continues on next page)
function misc_simplex1
input Real matr[:,:];
output Real x[size(matr,2)-1];
output Real z;
output Integer q;
output Integer p;
protected
Real a[size(matr,1),size(matr,2)];
Integer M;
Integer N;
algorithm
N := size(a,1)-1;
M := size(a,2)-1;
a := matr;
p:=0;q:=0;
a := pivot1(a,p+1,q+1);
while not (q==(M) or p==(N)) loop
q := 0;
while not (q == (M) or a[0+1,q+1]>1) loop
q:=q+1;
end while;
p := 0;
while not (p == (N) or a[p+1,q+1]>0.1) loop
p:=p+1;
end while;
if (q < M) and (p < N) and(p>0) and (q>0) then
a := pivot1(a,p,q);
end if;
if(p<=0) and (q<=0) then
a := pivot1(a,p+1,q+1);
end if;
if(p<=0) and (q>0) then
a := pivot1(a,p+1,q);
end if;
if(p>0) and (q<=0) then
a := pivot1(a,p,q+1);
end if;
end while;
z := a[1,M];
x := {a[1,i] for i in 1:size(x,1)};
for i in 1:10 loop
for j in 1:M loop
x[j] := x[j]+x[j]*0.01;
end for;
end for;
end misc_simplex1;
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.1046221254112045,-1.1046221254112045,0.0,0.0,0.0,0.0,0.0},0.
˓→0,8,1)
TWENTYEIGHT
28.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
459
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• MetaModelica
• ParModelica
• 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.)
• evalFunc (evaluates functions partially)
• evaluateParameters (Evaluates parameters with annotation(Evaluate=true). Use '--
evaluateFinalParameters=true' or '--evaluateProtectedParameters=true' to specify additional parameters to
be evaluated. Use '--replaceEvaluatedParameters=true' if the evaluated parameters should be replaced in the
DAE. To evaluate all parameters in the Frontend use -d=evaluateAllParameters.)
• expandDerOperator (Expands der(expr) using Derive.differentiteExpTime.)
• findStateOrder (Sets derivative information to states.)
• inlineArrayEqn (This module expands all array equations to scalar equations.)
• normalInlineFunction (Perform function inlining for function with annotation Inline=true.)
• inputDerivativesForDynOpt (Allowed derivatives of inputs in dyn. optimization.)
• introduceDerAlias (Adds for every der-call an alias equation e.g. dx = der(x).)
• removeEqualRHS (Detects equal expressions of the form a=<exp> and b=<exp> and substitutes them to get
speed up.)
• removeProtectedParameters (Replace all parameters with protected=true in the system.)
• removeSimpleEquations (Performs alias elimination and removes constant variables from the DAE, replac-
ing all occurrences of the old variable reference with the new value (constants) or variable reference (alias
elimination).)
• removeUnusedParameter (Strips all parameter not present in the equations from the system.)
• removeUnusedVariables (Strips all variables not present in the equations from the system.)
• removeVerySimpleEquations ([Experimental] Like removeSimpleEquations, but less thorough. Note that
this always uses the experimental new alias elimination, --removeSimpleEquations=new, which makes it
unstable. In particular, MultiBody systems fail to translate correctly. It can be used for simple (but large)
systems of equations.)
• replaceEdgeChange (Replace edge(b) = b and not pre(b) and change(b) = v <> pre(v).)
• residualForm (Transforms simple equations x=y to zero-sum equations 0=y-x.)
• resolveLoops (resolves linear equations in loops)
• simplifyAllExpressions (Does simplifications on all expressions.)
• simplifyIfEquations (Tries to simplify if equations by use of information from evaluated parameters.)
• sortEqnsVars (Heuristic sorting for equations and variables.)
• unitChecking (This module is no longer available and its use is deprecated. Use --unitChecking instead.)
• wrapFunctionCalls (This module introduces variables for each function call and substitutes all these calls
with the newly introduced variables.)
--cheapmatchingAlgorithm
Sets the cheap matching algorithm to use. A cheap matching algorithm gives a jump start matching by heuristics.
Integer (default 3). Valid options:
• 0 (No cheap matching.)
• 1 (Cheap matching, traverses all equations and match the first free variable.)
• 3 (Random Karp-Sipser: R. M. Karp and M. Sipser. Maximum matching in sparse random graphs.)
--matchingAlgorithm
Sets the matching algorithm to use. See --help=optmodules for more info.
String (default PFPlusExt). Valid options:
• BFSB (Breadth First Search based algorithm.)
• DFSB (Depth First Search based algorithm.)
• MC21A (Depth First Search based algorithm with look ahead feature.)
• PF (Depth First Search based algorithm with look ahead feature.)
• PFPlus (Depth First Search based algorithm with look ahead feature and fair row traversal.)
• HK (Combined BFS and DFS algorithm.)
• HKDW (Combined BFS and DFS algorithm.)
• ABMP (Combined BFS and DFS algorithm.)
• PR (Matching algorithm using push relabel mechanism.)
• DFSBExt (Depth First Search based Algorithm external c implementation.)
• BFSBExt (Breadth First Search based Algorithm external c implementation.)
• MC21AExt (Depth First Search based Algorithm with look ahead feature external c implementation.)
• PFExt (Depth First Search based Algorithm with look ahead feature external c implementation.)
• PFPlusExt (Depth First Search based Algorithm with look ahead feature and fair row traversal external c
implementation.)
• HKExt (Combined BFS and DFS algorithm external c implementation.)
• HKDWExt (Combined BFS and DFS algorithm external c implementation.)
• ABMPExt (Combined BFS and DFS algorithm external c implementation.)
• PRExt (Matching algorithm using push relabel mechanism external c implementation.)
• BB (BBs try.)
• SBGraph (Set-Based Graph matching algorithm for efficient array handling.)
• pseudo (Pseudo array matching that uses scalar matching and reconstructs arrays afterwards as much as
possible.)
--indexReductionMethod
Sets the index reduction method to use. See --help=optmodules for more info.
String (default dynamicStateSelection). Valid options:
• none (Skip index reduction)
• uode (Use the underlying ODE without the constraints.)
• dynamicStateSelection (Simple index reduction method, select (dynamic) dummy states based on analysis
of the system.)
• dummyDerivatives (Simple index reduction method, select (static) dummy states based on heuristic.)
--postOptModules
Sets the post optimization modules to use in the back end. See --help=optmodules for more info.
String list (default lateInlineFunction,wrapFunctionCalls,inlineArrayEqn,constantLinearSystem,simplifysemiLinear,removeSimpleE
Valid options:
• addScaledVars_states (added var_norm = var/nominal, where var is state)
• addScaledVars_inputs (added var_norm = var/nominal, where var is input)
• addTimeAsState (Experimental feature: this replaces each occurrence of variable time with a new introduced
state $time with equation der($time) = 1.0)
• calculateStateSetsJacobians (Generates analytical jacobian for dynamic state selection sets.)
• 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.)
• countOperations (Count the mathematical operations of the system.)
• cseBinary (Common Sub-expression Elimination)
• dumpComponentsGraphStr (Dumps the assignment graph used to determine strong components to format
suitable for Mathematica)
• dumpDAE (dumps the DAE representation of the current transformation state)
• dumpDAEXML (dumps the DAE as xml representation of the current transformation state)
• evaluateParameters (Evaluates parameters with annotation(Evaluate=true). Use '--
evaluateFinalParameters=true' or '--evaluateProtectedParameters=true' to specify additional parameters to
be evaluated. Use '--replaceEvaluatedParameters=true' if the evaluated parameters should be replaced in the
DAE. To evaluate all parameters in the Frontend use -d=evaluateAllParameters.)
• extendDynamicOptimization (Move loops to constraints.)
• generateSymbolicLinearization (Generates symbolic linearization matrices A,B,C,D for linear model:𝑥˙ =
𝐴𝑥 + 𝐵𝑢‘ : 𝑚𝑎𝑡ℎ : ‘𝑦 = 𝐶𝑥 + 𝐷𝑢)
• generateSymbolicSensitivities (Generates symbolic Sensivities matrix, where der(x) is differentiated w.r.t.
param.)
• inlineArrayEqn (This module expands all array equations to scalar equations.)
• inputDerivativesUsed (Checks if derivatives of inputs are need to calculate the model.)
• lateInlineFunction (Perform function inlining for function with annotation LateInline=true.)
• partlintornsystem (partitions linear torn systems.)
• recursiveTearing (inline and repeat tearing)
• reduceDynamicOptimization (Removes equations which are not needed for the calculations of cost and con-
straints. This module requires --postOptModules+=reduceDynamicOptimization.)
• relaxSystem (relaxation from gausian elemination)
• removeConstants (Remove all constants in the system.)
• removeEqualRHS (Detects equal function calls of the form a=f(b) and c=f(b) and substitutes them to get
speed up.)
• removeSimpleEquations (Performs alias elimination and removes constant variables from the DAE, replac-
ing all occurrences of the old variable reference with the new value (constants) or variable reference (alias
elimination).)
• removeUnusedParameter (Strips all parameter not present in the equations from the system to get speed up
for compilation of target code.)
• removeUnusedVariables (Strips all variables not present in the equations from the system to get speed up for
compilation of target code.)
• reshufflePost (Reshuffles algebraic loops.)
• simplifyAllExpressions (Does simplifications on all expressions.)
• simplifyComplexFunction (Some simplifications on complex functions (complex refers to the internal data
structure))
• simplifyConstraints (Rewrites nonlinear constraints into box constraints if possible. This module requires
+gDynOpt.)
• simplifyLoops (Simplifies algebraic loops. This modules requires +simplifyLoops.)
• simplifyTimeIndepFuncCalls (Simplifies time independent built in function calls like pre(param) -> param,
der(param) -> 0.0, change(param) -> false, edge(param) -> false.)
• simplifysemiLinear (Simplifies calls to semiLinear.)
• solveLinearSystem (solve linear system with newton step)
• solveSimpleEquations (Solves simple equations)
• symSolver (Rewrites the ode system for implicit Euler method. This module requires +symSolver.)
• 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
• substitution
• linearization
--demoMode
Disable Warning/Error Massages.
Boolean (default false).
--locale
Override the locale from the environment.
String (default empty).
-o, --defaultOCLDevice
Sets the default OpenCL device to be used for parallel execution.
Integer (default 0).
--maxTraversals
Maximal traversals to find simple equations in the acausal system.
Integer (default 2).
--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 ini-
tialization.
Boolean (default true).
--tearingMethod
Sets the tearing method to use. Select no tearing or choose tearing method.
String (default cellier). Valid options:
• noTearing (Deprecated, use minimalTearing.)
• 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.
String (default empty).
--hpcomScheduler
Sets the scheduler for task graph scheduling (list | listr | level | levelfix | ext | metis | mcp | taskdep | tds | bls | rand |
none). Default: level.
String (default level).
--hpcomCode
Sets the code-type produced by hpcom (openmp | pthreads | pthreads_spin | tbb | mpi). Default: openmp.
String (default openmp).
--rewriteRulesFile
Activates user given rewrite rules for Absyn expressions. The rules are read from the given file and are of the form
rewrite(fromExp, toExp);
String (default empty).
--replaceHomotopy
Replaces homotopy(actual, simplified) with the actual expression or the simplified expression. Good for debugging
models which use homotopy. The default is to not replace homotopy.
String (default none). Valid options:
• none (Default, do not replace homotopy.)
• actual (Replace homotopy(actual, simplified) with actual.)
• simplified (Replace homotopy(actual, simplified) with simplified.)
--generateSymbolicJacobian
Generates symbolic Jacobian matrix, where der(x) is differentiated w.r.t. x. This matrix can be used by dassl or
ida solver with simulation flag '-jacobian'.
Boolean (default false).
--generateSymbolicLinearization
--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-7).
--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,simplifyAll
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).)
• inlineArrayEqn (This module expands all array equations to scalar equations.)
• 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 con-
straints. This module requires --postOptModules+=reduceDynamicOptimization.)
• replaceHomotopyWithSimplified (Replaces the homotopy expression homotopy(actual, simplified) with the
simplified part.)
• simplifyAllExpressions (Does simplifications on all expressions.)
• simplifyComplexFunction (Some simplifications on complex functions (complex refers to the internal data
structure))
• simplifyConstraints (Rewrites nonlinear constraints into box constraints if possible. This module requires
+gDynOpt.)
• simplifyLoops (Simplifies algebraic loops. This modules requires +simplifyLoops.)
• solveSimpleEquations (Solves simple equations)
• 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.)
--maxMixedDeterminedIndex
Sets the maximum mixed-determined index that is handled by the initialization.
Integer (default 10).
--useLocalDirection
Keeps the input/output prefix for all variables in the flat model, not only top-level ones.
Boolean (default false).
--defaultOptModulesOrdering
If this is activated, then the specified pre-/post-/init-optimization modules will be rearranged to the recommended
ordering.
Boolean (default true).
--preOptModules+
Enables additional pre-optimization modules, e.g. --preOptModules+=module1,module2 would additionally en-
able module1 and module2. See --help=optmodules for more info.
String list (default empty).
--preOptModules-
Disables a list of pre-optimization modules, e.g. --preOptModules-=module1,module2 would disable module1 and
module2. See --help=optmodules for more info.
String list (default empty).
--postOptModules+
Enables additional post-optimization modules, e.g. --postOptModules+=module1,module2 would additionally en-
able module1 and module2. See --help=optmodules for more info.
String list (default empty).
--postOptModules-
Disables a list of post-optimization modules, e.g. --postOptModules-=module1,module2 would disable module1
and module2. See --help=optmodules for more info.
String list (default empty).
--initOptModules+
Enables additional init-optimization modules, e.g. --initOptModules+=module1,module2 would additionally en-
able module1 and module2. See --help=optmodules for more info.
String list (default empty).
--initOptModules-
Disables a list of init-optimization modules, e.g. --initOptModules-=module1,module2 would disable module1
and module2. See --help=optmodules for more info.
String list (default empty).
--instCacheSize
Sets the size of the internal hash table used for instantiation caching.
Integer (default 25343).
--maxSizeLinearTearing
Sets the maximum system size for tearing of linear systems (default 200).
Integer (default 200).
--maxSizeNonlinearTearing
Sets the maximum system size for tearing of nonlinear systems (default 10000).
Integer (default 10000).
--noTearingForComponent
Deactivates tearing for the specified components. Use '-d=tearingdump' to find out the relevant indexes.
Unknown default valueFlags.FlagData.INT_LIST_FLAG(data = {NIL})
--daeMode
Generates code to simulate models in DAE mode. The whole system is passed directly to the DAE solver SUNDI-
ALS/IDA and no algebraic solver is involved in the simulation process.
Boolean (default false).
--inlineMethod
Sets the inline method to use. replace : This method inlines by replacing in place all expressions. Might lead to
very long expression. append : This method inlines by adding additional variables to the whole system. Might
lead to much bigger system.
String (default replace). Valid options:
• replace
• append
--setTearingVars
Sets the tearing variables by its strong component indexes. Use '-d=tearingdump' to find out the relevant indexes.
Use following format: '--setTearingVars=(sci,n,t1,...,tn)*', with sci = strong component index, n = number of tearing
variables, t1,...tn = tearing variables. E.g.: '--setTearingVars=4,2,3,5' would select variables 3 and 5 in strong
component 4.
Unknown default valueFlags.FlagData.INT_LIST_FLAG(data = {NIL})
--setResidualEqns
Sets the residual equations by its strong component indexes. Use '-d=tearingdump' to find out the relevant indexes
for the collective equations. Use following format: '--setResidualEqns=(sci,n,r1,...,rn)*', with sci = strong compo-
nent index, n = number of residual equations, r1,...rn = residual equations. E.g.: '--setResidualEqns=4,2,3,5' would
select equations 3 and 5 in strong component 4. Only works in combination with 'setTearingVars'.
Unknown default valueFlags.FlagData.INT_LIST_FLAG(data = {NIL})
--ignoreCommandLineOptionsAnnotation
Ignores the command line options specified as annotation in the class.
Boolean (default false).
--calculateSensitivities
Generates sensitivities variables and matrices.
Boolean (default false).
-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
--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,simplifyTi
--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.
Boolean (default false).
--linearizationDumpLanguage
Sets the target language for the produced code of linearization. Only works with '--generateSymbolicLinearization'
and 'linearize(modelName)'.
String (default modelica). Valid options:
• modelica
• matlab
• julia
• python
--noASSC
Disables analytical to structural singularity conversion.
Boolean (default false).
--fullASSC
Enables full equation replacement for BLT transformation from the ASSC algorithm.
Boolean (default false).
--realASSC
Enables the ASSC algorithm to evaluate real valued coefficients (usually only integers).
Boolean (default false).
--initASSC
Enables the ASSC algorithm for initialization.
Boolean (default false).
--maxSizeASSC
Sets the maximum system size for the analytical to structural conversion algorithm (default 200).
Integer (default 200).
-f, --flatModelica
Outputs experimental flat Modelica.
Boolean (default false).
--fmiFilter
Specifies which model variables are exposed by the modelDescription.xml
String (default protected). Valid options:
• none (All variables are exposed, even variables introduced by the symbolic transformations. This is mainly
for debugging purposes.)
• internal (All model variables are exposed, including protected ones. Variables introduced by the symbolic
transformations are filtered out, with minor exceptions, e.g. for state sets.)
• protected (All public model variables are exposed. Internal and protected variables are filtered out, with
small exceptions, e.g. for state sets.)
• blackBox (Only the interface is exposed. All other variables are hidden or exposed with concealed names.)
--fmiSources
Defines if FMUs will be exported with sources or not. --fmiFilter=blackBox might override this, because black
box FMUs do never contain their source code.
Boolean (default true).
--fmiFlags
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
Configured and build FMU with CMake if true.
Boolean (default true).
--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)
• nonStdTopLevelOuter (Allow top level outer.See: https://specification.modelica.org/maint/3.6/
scoping-name-lookup-and-flattening.html#S4.p1)
• 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:
The debug flag takes a comma-separated list of flags which are used by the compiler for debugging or experimental
purposes. Flags prefixed with "-" or "no" will be disabled. The available flags are (+ are enabled by default, - are
disabled):
Cache (default: on)
Turns off the instantiation cache.
LSanalyticJacobian (default: off)
Enables analytical jacobian for linear strong components. Defaults to false
NLSanalyticJacobian (default: on)
Enables analytical jacobian for non-linear strong components without user-defined function calls, for that
see forceNLSanalyticJacobian
acceptTooManyFields (default: off)
Accepts passing records with more fields than expected to a function. This is not allowed, but is used in
Fluid.Dissipation. See https://trac.modelica.org/Modelica/ticket/1245 for details.
aliasConflicts (default: off)
Dumps alias sets with different start or nominal values.
arrayConnect (default: off)
Use experimental array connection handler.
backendKeepEnv (default: on)
When enabled, the environment is kept when entering the backend, which enables CevalFunction (function
interpretation) to work. This module not essential for the backend to function in most cases, but can improve
simulation performance by evaluating functions. The drawback to keeping the environment graph in memory
is that it is huge (~80% of the total memory in use when returning the frontend DAE).
backendReduceDAE (default: off)
Prints all Reduce DAE debug information.
backenddaeinfo (default: off)
Enables dumping of back-end information about system (Number of equations before back-end,...).
bltdump (default: off)
Dumps information from index reduction.
bltmatrixdump (default: off)
Dumps the blt matrix in html file. IE seems to be very good in displaying large matrices.
buildExternalLibs (default: on)
Use the autotools project in the Resources folder of the library to build missing external libraries.
ceval (default: off)
Prints extra information from Ceval.
cgraph (default: off)
Prints out connection graph information.
cgraphGraphVizFile (default: off)
Generates a graphviz file of the connection graph.
cgraphGraphVizShow (default: off)
Displays the connection graph with the GraphViz lefty tool.
checkASUB (default: off)
Prints out a warning if an ASUB is created from a CREF expression.
checkBackendDae (default: off)
Do some simple analyses on the datastructure from the frontend to check if it is consistent.
checkDAECrefType (default: off)
Enables extra type checking for cref expressions.
Flags that determine which symbolic methods are used to produce the causalized equation system.
The --preOptModules flag sets the optimization modules which are used before the matching and index reduction
in the back end. These modules are specified as a comma-separated list.
The --matchingAlgorithm sets the method that is used for the matching algorithm, after the pre optimization mod-
ules.
The --indexReductionMethod sets the method that is used for the index reduction, after the pre optimization mod-
ules.
The --initOptModules then sets the optimization modules which are used after the index reduction to optimize the
system for initialization, specified as a comma-separated list.
The --postOptModules then sets the optimization modules which are used after the index reduction to optimize the
system for simulation, specified as a comma-separated list.
TWENTYNINE
This chapter contains a short overview of simulation flags as well as additional details of the numerical integration
methods.
489
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
-daeMode
Enables daeMode simulation if the model was compiled with the omc flag --daeMode and ida method is
used.
-deltaXLinearize=value or -deltaXLinearize value
Value specifies the delta x value for numerical differentiation used by linearization. The default value is
sqrt(DBL_EPSILON*2e1).
-deltaXSolver=value or -deltaXSolver value
Value specifies the delta x value for numerical differentiation used by integration method. The default values
is sqrt(DBL_EPSILON).
-embeddedServer=value or -embeddedServer value
Enables an embedded server. Valid values:
• none - default, run without embedded server
• opc-da - [broken] run with embedded OPC DA server (WIN32 only, uses proprietary OPC SC interface)
• opc-ua - [experimental] run with embedded OPC UA server (TCP port 4841 for now; will have its own
configuration option later)
• filename - path to a shared object implementing the embedded server interface (requires access to
internal OMC data-structures if you want to read or write data)
-embeddedServerPort=value or -embeddedServerPort value
Value specifies the port number used by the embedded server. The default value is 4841.
-mat_sync=value or -mat_sync value
Syncs the mat file header after emitting every N time-points.
-emit_protected
Emits protected variables to the result-file.
-eps=value or -eps value
Value specifies the number of convergence iteration to be performed for DataReconciliation
-f=value or -f value
Value specifies a new setup XML file to the generated simulation code.
-help=value or -help value
Get detailed information that specifies the command-line flag
For example, -help=f prints detailed information for command-line flag f.
-homAdaptBend=value or -homAdaptBend value
Maximum trajectory bending to accept the homotopy step. Default: 0.5, which means the corrector vector
has to be smaller than half of the predictor vector.
-homBacktraceStrategy=value or -homBacktraceStrategy value
Value specifies the backtrace strategy in the homotopy corrector step. Valid values:
• fix - default, go back to the path by fixing one coordinate
• orthogonal - go back to the path in an orthogonal direction to the tangent vector
-homHEps=value or -homHEps value
Tolerance respecting residuals for the homotopy H-function (default: 1e-5).
In the last step (lambda=1) newtonFTol is used as tolerance.
-homMaxLambdaSteps=value or -homMaxLambdaSteps value
Maximum lambda steps allowed to run the homotopy path (default: system size * 100).
-homMaxNewtonSteps=value or -homMaxNewtonSteps value
Maximum newton steps in the homotopy corrector step (default: 20).
-homMaxTries=value or -homMaxTries value
Maximum number of tries for one homotopy lambda step (default: 10).
-homNegStartDir
Start to run along the homotopy path in the negative direction.
If one direction fails, the other direction is always used as fallback option.
-homotopyOnFirstTry
If the model contains the homotopy operator, directly use the homotopy method to solve the initial-
ization problem. This is already the default behaviour, this flag can be used to undo the effect of -
noHomotopyOnFirstTry
-noHomotopyOnFirstTry
Disable the use of the homotopy method to solve the initialization problem. Without this flag, the solver tries
to solve the initialization problem with homotopy if the model contains the homotopy-operator.
-homTauDecFac=value or -homTauDecFac value
Decrease homotopy step size tau by this factor if tau is too big in the homotopy corrector step (default: 10.0).
-homTauDecFacPredictor=value or -homTauDecFacPredictor value
Decrease homotopy step size tau by this factor if tau is too big in the homotopy predictor step (default: 2.0).
-homTauIncFac=value or -homTauIncFac value
Increase homotopy step size tau by this factor if tau can be increased after the homotopy corrector step
(default: 2.0).
-homTauIncThreshold=value or -homTauIncThreshold value
Increase the homotopy step size tau if homAdaptBend/bend > homTauIncThreshold (default: 10).
-homTauMax=value or -homTauMax value
Maximum homotopy step size tau for the homotopy process (default: 10).
-homTauMin=value or -homTauMin value
Minimum homotopy step size tau for the homotopy process (default: 1e-4).
-homTauStart=value or -homTauStart value
Homotopy step size tau at the beginning of the homotopy process (default: 0.2).
-idaMaxErrorTestFails=value or -idaMaxErrorTestFails value
Value specifies the maximum number of error test failures in attempting one step. The default value is 7.
-idaMaxNonLinIters=value or -idaMaxNonLinIters value
Value specifies the maximum number of nonlinear solver iterations at one step. The default value is 3.
-idaMaxConvFails=value or -idaMaxConvFails value
Value specifies the maximum number of nonlinear solver convergence failures at one step. The default value
is 10.
-idaNonLinConvCoef=value or -idaNonLinConvCoef value
Value specifies the safety factor in the nonlinear convergence test. The default value is 0.33.
-idaLS=value or -idaLS value
Value specifies the linear solver of the ida integration method. Valid values:
• dense (ida internal dense method.)
• klu (ida use sparse direct solver KLU. (default))
• spgmr (ida generalized minimal residual method. Iterative method)
• spbcg (ida Bi-CGStab. Iterative method)
• sptfqmr (ida TFQMR. Iterative method)
-idaScaling
Enable scaling of the IDA solver.
-idaSensitivity
Enables sensitivity analysis with respect to parameters if the model is compiled with omc flag --
calculateSensitivities.
-ignoreHideResult
Emits also variables with HideResult=true annotation.
-iif=value or -iif value
Value specifies an external file for the initialization of the model.
-iim=value or -iim value
Value specifies the initialization method. Following options are available: 'symbolic' (default) and 'none'.
• none (sets all variables to their start values and skips the initialization process)
• symbolic (solves the initialization problem symbolically - default)
-iit=value or -iit value
Value [Real] specifies a time for the initialization of the model.
-ils=value or -ils value
Value specifies the number of steps for homotopy method (required: -iim=symbolic). The value is an Integer
with default value 3.
-impRKOrder=value or -impRKOrder value
Value specifies the integration order of the implicit Runge-Kutta method. Valid values: 1 to 6. Default order
is 5.
-impRKLS=value or -impRKLS value
Selects the linear solver of the integration methods impeuler, trapezoid and imprungekuta:
• iterativ - default, sparse iterativ linear solver with fallback case to dense solver
• dense - dense linear solver, SUNDIALS default method
-initialStepSize=value or -initialStepSize value
Value specifies an initial step size, used by the methods: dassl, ida, gbode
-csvInput=value or -csvInput value
Value specifies an csv-file with inputs for the simulation/optimization of the model
-stateFile=value or -stateFile value
Value specifies an file with states start values for the optimization of the model.
-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.)
-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 optimization, 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 condition 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))
-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 constant.
-w
Shows all warnings even if a related log-stream is inactive.
-parmodNumThreads=value or -parmodNumThreads value
Value specifies the number of threads for simulation 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
THIRTY
TECHNICAL DETAILS
This chapter gives an overview of some implementation details that might be interesting when building tools around
OpenModelica.
The default result-file format of OpenModelica is based on MATLAB level 4 MAT-files as described in the MAT-
LAB documentation. This format can be read by tools such as MATLAB, Octave, Scilab, and SciPy. OpenModel-
ica will write the result-files in a particular way that can be read by tools such as DyMat and Dymola (OpenModelica
can also read files generated by Dymola since the used format is the same).
The variables stored in the MAT-file are (in the order required by OpenModelica):
Aclass
• Aclass(1,:) is always Atrajectory
• Aclass(2,:) is 1.1 in OpenModelica
• Aclass(3,:) is empty
• Aclass(4,:) is either binTrans or binNormal
The most important part of the variable is Aclass(4,:) since there are two main ways the result-file is
stored: transposed or not. For efficiency, the result-file is written time-step by time-step during simulation.
But the best way to read the data for a single variable is if the variables are stored variable by variable. If
Aclass(4,:) is binTrans, all matrices need to be transposed since the file was not transposed for efficient
reading of the file. Note that this affects all matrices, even matrices that do not change during simulation
(such as name and description).
name
Is an n x m character (int8) matrix, where n is the number of variables stored in the result-file (including
time). m is the length of the longest variable. OpenModelica stores the trailing part of the name as NIL bytes
(0) whereas other tools use spaces for the trailing part.
description
Is an n x m character (int8) matrix containing the comment-string corresponding to the variable in the name
matrix.
dataInfo
Is an n x 4 integer matrix containing information for each variable (in the same order as the name and
description matrices).
• dataInfo(i,1) is 1 or 2, saying if variable i is stored in the data_1 or data_2 matrix. If it is 0, it is
the abscissa (time variable).
• dataInfo(i,2) contains the index in the data_1 or data_2 matrix. The index is 1-based and may
contain several variables pointing to the same row (alias variables). A negative value means that the
variable is a negated alias variable.
503
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• dataInfo(i,3) is 0 to signify linear interpolation. In other tools the value is the number of times
differentiable this variable is, which may improve plotting.
• dataInfo(i,4) is -1 in OpenModelica to signify that the value is not defined outside the time range.
0 keeps the first/last value when going outside the time range and 1 performs linear interpolation on
the first/last two points.
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).
THIRTYONE
DATA RECONCILIATION
The objective of data reconciliation is to use physical models to reduce the impact of measurement errors by
decreasing measurement uncertainties and detecting faulty sensors. Data reconciliation is possible only when
redundant measurements are available. Redundancy can be achieved by linking together the measured variables
of interest using the physical laws that constrain them. This can be done with static Modelica models (models
featuring algebraic equations only, no differential equations).
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).
505
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
Boundary conditions are declared with annotations so that libraries can be modified to accomodate data reconcili-
ation, 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 con-
fidence 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.
e. If the numerical cells of the matrices are not positive real numbers.
The results are displayed:
1. In an html file with the title: Data Reconciliation Report. This file automatically pops up when the
calculation is completed.
2. In two csv output files:
a. One that contains the reconciled values and the reconciled half-width confidence intervals.
b. The other that contains the reconciled covariance matrix.
These files do not pop up automatically when the calculation is completed. The names of the files are
respectively
<working directory>\<model name>\< model name>_Outputs.csv
and
<working directory>\<model name>\< model name>_Reconciled_Sx.csv,
where <model name> denotes the full name of the model, including its path. The name of the working
directory can be read with the command Tools > Options.
The Data Reconciliation Report has three sections:
1. Overview, with the following information:
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. Measurement input file: name of the measurement input file
e. Correlation matrix input file: name of the correlation matrix file (if any)
f. Generated: date and time of the generation of the data reconciliation report
2. Analysis, with the following information:
a. Number of auxiliary conditions, denoted r in the sequel.
b. Number of variables to be reconciled.
c. Number of related boundary conditions: number of boundary conditions related to the variables to
be reconciled. This number should be strictly less than the number of variables to be reconciled,
otherwise the data reconciliation problem is ill-posed and data reconciliation cannot be performed.
d. Number of iterations to convergence: number of iterations of the data reconciliation numerical
loop.
e. Final value of J*/r: final value of the data reconciliation iteration loop. This value is smaller than
epsilon when the iterations are completed (cf. below).
f. Epsilon: stopping criteria of the data reconciliation iteration loop. The recommended value by
VDI 2048 is 1.e-10.
g. Final value of the objective function J*: is equal to J*/r multiplied by r, where r is the number of
auxiliary conditions.
h. Chi-square value: value of the chi-square distribution for r degrees of freedom and statistical cer-
tainty of probability of 95%.
i. Result of global test: true if J* is less than the chi-square value, false otherwise. If false, the
results for the reconciled values should be rejected because the vector of contradictions (i.e. the
discrepancy between the measured values and the reconciled values) is too large.
j. Auxiliary conditions: set of the auxiliary conditions (i.e., the equations that constrain the variables
of interest).
k. Intermediate equations: set of the intermediate equations (i.e., the equations that compute the inter-
mediate variables from the variables of interest). This set can be empty if there are no intermediate
variables.
l. Debug log: log of the numerical iteration loop.
3. Results, which is a table with the following columns:
a. Variables to be Reconciled: the names of the variables of interest.
b. Initial Measured Values: the measured values entered in the measurement input file.
c. Reconciled Values: the reconciled values computed by the data reconciliation algorithm.
d. Initial Half-width Confidence Intervals: the half-width confidence intervals entered in the mea-
surement input file.
e. Reconciled Half-width Confidence Intervals: the reconciled half-width confidence intervals com-
puted by the data reconciliation algorithm.
f. Results of Local Tests: true if the values of local tests (cf. below) are less than the quantile of
normal distribution with probability 95% (𝜆95% ), false otherwise.
g. Values of Local Tests: values of the improvements (i.e., the difference between the initial and the
reconciled values) divided by the square root of the diagonal element of the covariance matrix of
the improvements.
h. Margin to Correctness: 𝜆95% minus the values of local tests.
The data reconciliation report for the the VDI2048 standard example of a heat circuit of a steam turbine plant is
given below.
31.3.1 Overview:
31.3.2 Analysis:
31.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_Outputs
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;
Real mFD1;
Real mFD2;
Real mFD3;
Real mHDANZ;
equation
mFD1 = mFDKEL + mFDKELL - 0.2*mV;
mFD2 = mSPL + mSPLL - 0.6*mV;
mFD3 = mHK + mA7 + mA6 + mA5 + 0.4*mV;
mHDANZ = mA7 + mA6 + mA5;
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
The values and uncertainties of the boundary conditions that correspond to the reconciled values of the
variables of interest can be computed by:
1. Selecting Data Reconciliation > Calculate Data Reconciliation
2. Selecting the Boundary Conditions algorithm.
3. Filling the Data Reconciliation form with
a. The name of the Reconciled Measurement File (mandatory). It is the name of the csv output
file produced by the data reconciliation algorithm.
b. The name of the Reconciled Correlation Matrix file (mandatory). It is the name of the corre-
lation matrix csv file produced by the data reconciliation algorithm.
4. Clicking on Save Settings to save the above settings in the Modelica model.
5. Clicking on Calculate to launch the calculation.
At least one boundary condition must be declared in the model, otherwise the computation fails with a
difficult to interpret error message such as
Cannot Compute Jacobian Matrix F.
A better error message will be posted in a future version.
The computation of the boundary conditions is performed in three main steps:
1. Static analysis is performed on the model to extract the equations that compute the boundary
conditions from the variables of interest. This corresponds to automatically inverting the
original model. There are two groups of extracted equations:
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:
31.4. Computing the Boundary Conditions from the Reconciled Values 515
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
31.4.1 Overview
31.4.2 Analysis
31.4.4 Results
31.5 Contacts
31.6 References
Bouskela, D., Jardin, A., Palanisamy, A., Ochel, L., & Pop, A. (2021). New Method to Perform Data Reconciliation
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.
THIRTYTWO
Below are some frequently asked questions in three areas, with associated answers.
32.2 OMNotebook
519
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• Q: I get problems compiling and linking some files when using OMDev
with the MINGW (Gnu) C compiler under Windows.
• A: You probably have some Logitech software installed. There is a
known bug/incompatibility in Logitech products. For example, if lvprcsrv.exe is running, kill it and/or
prevent it to start again at reboot; it does not do anything really useful, not needed for operation of web
cameras or mice.
THIRTYTHREE
This Appendix lists the most important OpenModelica releases and a brief description of their contents. Right now
versions from 1.3.1 to v1.22.1 are described.
The main highlight of the 1.22.0 release of OpenModelica is a significant improvement of the OMEdit GUI, made
possible by the new instance-based architecture for the interaction between the OMEdit GUI and the underlying
OMC compiler, which is now activated by default; see below for further details. Many bugs were also fixed, leading
to a much improved user experience, compared to the previous 1.20.0 release.
The new front end has been further improved with about 25 bug fixes, here is a complete list. The conversion from
Integer to Enumeration, which was introduced in Modelica 3.4, is now supported by OMC.
Most of the work on the backend is currently focused on developing the new backend; a few fixes
were made to the current backend. The `--tearingMethod=noTearing <https://openmodelica.org/
doc/OpenModelicaUsersGuide/latest/omchelptext.html#omcflag-tearingmethod>`__ was deprecated, because it
breaks models with discrete variables involved in algebraic loops, `--tearingMethod=minimalTearing <https:
//openmodelica.org/doc/OpenModelicaUsersGuide/latest/omchelptext.html#omcflag-tearingmethod>`__ should
be used instead. A few bug fixes were also made to the code generation process.
Several bug fixes and improvements were made to the C runtime. A new simulation flag `-lv_system <https:
//openmodelica.org/doc/OpenModelicaUsersGuide/1.22/simulationflags.html#simflag-lv-system>`__ was added,
to enable logging of solver behaviour for selected systems; together with `-lv_time <https://openmodelica.org/
doc/OpenModelicaUsersGuide/1.22/simulationflags.html#simflag-lv-time>`__, this allows to avoid huge log files
when debugging solver issues taking place at some point in time with some specific system of equations.
Several improvements were made to the C++ runtime:
521
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
• support for ExternalMedia library (fix record inputs of external functions and bindings of records to scalar
variables)
• support for ThermofluidStream library (fix array dimensions of created temporary variables)
• preliminary support for DAE mode
• fixed issue with start attributes for iteration variables of implicit nonlinear systems, which were previously
lost
As mentioned above, the new instance-based infrastructure for model editing is now firmly in place and is activated
by default. This supports long awaited-for features, namely conditional connectors and parameter input dialogs
activated by boolean variables, replaceable classes and models with parameter editing. It also improves the support
of the DynamicSelect annotation. In case of remaining issues, it is still possible to de-activate the new infrastructure
and fall back to the old one, using the checkbox Tools | Options | General | Optional Features | Disable new
instance-based graphical editing of models.
Connection handling and rendering is also much improved:
• it is no longer possible to make connections between incompatible connectors (that previously only failed
later on when trying to compile the model);
• connection lines are drawn with a white background that allows to reveal bogus connections that were pre-
viously hidden by the component itself (e.g., inadvertently short-circuiting a resistor or capacitor). It also
show clearly that two apparently crossing connection lines have no actual connection to each other;
• connection lines spanning a connection set with more than one connector are now rendered with dot-like
branching points, increasing readability.
Over 70 issues were successfully addressed in the OMEdit graphical editor. About 35 issues concerned the debug-
ging and fine-tuning of the new instance-based infrastructure.
Improvement made to the OMMatlab concening the efficiency of the linearize() API function call were ported
to OMPython and OMJulia. The updated implementation avoids recompiling the model from scratch every time
when multiple calls to linearize() are made on the same model, resulting in dramatic performance improvement.
Further development work was carried out to support source-code FMI export across all operating systems using
CMAKE, see closed tickets, in addition to the old workflow that was based on GNU makefiles and only worked in
POSIX environments. This functionality, documented here, is now mostly in place, though it requires more testing
to become fully usable. To get the latest developments in FMI export support, consider trying the 1.23.0-dev nightly
builds.
A new flag --nonStandardExposeLocalIOs was introduced to export input/output connectors of sub-models, like
sources, sinks and sensors. The default value 0 expose the top-level public inputs and outputs, the value 1 also
exposes public inputs and outputs of components, the value 2 also exposes public inputs and outputs of components
within components, and so on.
The next release 1.23.0 is planned to be release in Q2 2024. It should include further improvements to the GUI such
as parameter editing in hiearchically structured model, fully functional Duplicate feature, restructured Simulation
Setup dialog, etc. Further improvements in FMI 2.0.x export are also planned.
Download it from: https://openmodelica.org
Full Changelog: https://github.com/OpenModelica/OpenModelica/compare/v1.21.0...v1.22.0
The 1.21.0 release of OpenModelica doesn't contain any major new feature, but it contains many improvements
and bugfixes that significantly improved the quality of the software with respect to the previous 1.20.0 release.
The new single-step gbode solver has been further developed and can now be used as a serious alternative to the
more established dassl, ida, and cvode solvers. A full-fledged GUI for its configuration is still not available and
will be added in future versions. Currently, the method defaults to esdirk4, a general-purpose 4-th order implicit
method. Other methods can be set with the -gbm simulation flag, and each method now automatically selects the
best advanced options. All solvers use variable step-size with error control by default, but they can be turned to
fixed time step by adding the -gbctrl=const simulation flag.
A completely overhauled architecture for the interaction between the OMEdit GUI and the underlying OMC com-
piler is now experimentally available in 1.21.0. It relies on the new frontend to instantiate the classes being edited,
rather than trying to re-do it from scratch on the GUI side. This architecture provides faster user interaction and
allowed to fix many shortcomings of the GUI, e.g. lack of proper support for replaceable classes with parameters,
conditional connectors and parameter dialog activation depending on parameters, etc.
The new front end has been further improved with about 20 bug fixes, here is a complete list. Major development
work went into supporting the development and fine-tuning a new API for the the OMEdit GUI, see tickets.
Several fixes were made to the current backend, although development work is now mostly focused on the new
backend, which includes array-preserving code generation features. The new backend is still not capable of running
most models from mainstream libraries. However, it is starting to show interesting results on selected large-scale
test models, with size up to a million equations. These models can now be handled with reasonable amounts of
time required to build and compile the simulation code. The new backend can be activated with the --newBackend
compiler flag.
Several bug fixes were made to the code generation process. The new CMake-based build infrastructure has been
further developed and is now nearly complete, including support for FMI generation.
Many bug fixes and improvements were made to the C runtime, mostly regarding the new gbode solver. This solver
is fast reaching production quality and can now be used as a serious alternative to the mainstream dassl, ida, and
cvode solvers; it also replaces deprecated obsolete solvers such as impeuler, trapezoid, imprungekutta, etc., that
will be removed in future versions.
About 60 issues were successfully addressed in the OMEdit graphical editor. Most notably, the performance of the
GUI support for replaceable classes has been improved dramatically; therefore that option, which is required to use
Modelica.Media and Modelica.Fluid, is no longer optional but always active by default.
About half of the addressed issues concern the development and fine tuning of the new instance-based interface, that
is going to be much faster than the existing one and to address long-standing issues such as supporting conditional
connectors and replaceable classes with parameter modifiers.
This new interface can be activated with the Tools | Options | General | Enable instance API option. It is mostly
in place now, but it still requires further testing and debugging before it can replace the existing one for good. If
you want to experiment with it, we suggest you to use the latest 1.22.0-dev nightly build version, that incorporates
the latest developments and bug fixes. Please try that one before reporting issues on the bug tracker.
The OMMatlab interface was significantly improved in this version, see tickets. In particular, it is now possible
to linearize a system in many different conditions without recompiling it each time, which is useful model-based
control design.
The next release 1.22.0 is planned to be release in Q4 2023. It will include the new instance-based editing in
OMEdit, featuring support of conditional connectors, parameter-depending dialog annotation, hierarchical editing
of models, and faster rendering of complex diagrams.
Download it from: https://openmodelica.org
Full Changelog: https://github.com/OpenModelica/OpenModelica/compare/v1.20.0...v1.21.0
The first most notable feature of this release is the automatic installation of the Modelica Standard Library (MSL),
which is now fully integrated with the Package Manager. Every time any tool of the OpenModelica suite (e.g.
OMEdit, OMNotebook, OMShell, etc.) attempts to load a version of the MSL, it checks if it has already been
installed in the user's set of system libraries, which is handled by the Package Manager and is located in the user's
.openmodelica directory. If that directory is empty, either because of a fresh install, or because it has been deleted,
then the MSL is automatically installed in the user's system libraries from cached zip files in the OpenModelica
installation directory; in fact, both MSL 3.2.3 (which is backwards compatible with 3.2.2 and 3.2.1) and 4.0.0 are
installed, so that any library created during the last ten years can run out of the box.
This automatic installation does not require any Internet connection, so it also works behind corporate firewalls
or in situations with limited available bandwidth. This solution uses the same package manager that is also used
to install other system libraries, contrary to the solution implemented in versions 1.18.0 and 1.19.x, which used
two different directories in the MODELICAPATH, one for the package manager and one for the preinstalled MSL,
leading to slightly confusing duplicate installations of MSL.
OMEdit loads MSL 4.0.0 by default in the Libraries Browswer. However, if one then loads a package using MSL
3.2.3, it is possible to unload MSL 4.0.0 and load MSL 3.2.3 just with a click of a button.
The second most notable feature is that a new general purpose ODE solver, named gbode, was introduced. This
solver is a fully configurable single-step solver, supporting many different integration methods, both explicit and
implicit, using either fixed time step or variable time step with error control, handling event detection and dense
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.
The new front end has been further improved, with over a dozen bug fixes.
Some issues were fixed in the current backend, although most of the development work is now focused on the new
backend, which can be optionally activated with the --newBackend compiler flag, and will become the default
choice in a future release.
Regarding code generation several issues were fixed, including one that affected the ExternalMedia library, which
is now fully supported by OpenModelica.
33.4.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.
Besides improved support of the Modelica Standard Library with the package manager, over a dozen issues were
fixed, see the full list.
33.4.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.
A 1.20.1 bugfix version may be released if critical bugs are identified and resolved before January 2023. The next
release 1.21.0 is planned to be beta-released in February 2023, and released in March 2023; it should include a
completely restructured handling of model editing in OMEdit, including long awaited-for features like support of
conditional connectors, parameter-depending dialog annotation, and faster rendering of complex diagrams.
Download it from: https://openmodelica.org
Full Changelog: https://github.com/OpenModelica/OpenModelica/compare/v1.19.0...v1.20.0
Version 1.19.2 is a bugfix release, where some critical bugs that were present in 1.19.0 got fixed.
The most important one is #8772: parameter dependencies were not handled correctly in some cases, leading to
some parameters being wrongly evaluated to zero, which also impacted multibody system animations, see #8938.
Some further remaining issues with directory names containing accented letters were fixed in #8777. A problem
with the delay operator was also fixed, see #9116.
Here is the complete list of bug fixes in release 1.19.2.
Download it from: https://www.openmodelica.org
The new front end has been further improved, with over 40 bug fixes.
Several issues were fixed in the backend, most notably problems affecting event generation and issues involving
algorithms and arrays, which led to a wrong diagnosis of under-determined system of equations. Overall, over 15
issues were addressed.
Regarding code generation 5 issues were fixed, mostly concerning corner cases that involved arrays, record, and
slicing operators.
33.6.2 C Runtime
Remaining issues concerning Clock variables were resolved; so, starting from this version, the synchronous features
of the Modelica language, in particular the Modelica.Clocked library, are now fully supported. The configuration of
runtime and external libraries on Windows was substantially improved. A bug was fixed in daeMode that prevented
correct event handling in state-less models, which now run correctly. Overall about 20 issues were fixed.
The most important new feature in 1.19.0 is the fully integrated package management and conversion script support
in the GUI. We suggest you to read the Package Management section of the user's guide for an introduction to the
basic concepts.
The package management functionality is now available under the File | Manage Libraries menu. It is possible to
install supported (or experimental) open-source libraries from the internet, and upgrade them when newer versions
are released; all the required dependencies are installed automatically. The Windows installer by default also installs
the basic versions of the Modelica standard library, as a fallback in case internet connection is not available, e.g.
in corporate environments. All other libraries are no longer supplied with the installer and must be installed via
the package manager. Off-line use of the package manager will be improved in future versions.
When right-clicking on a library in the libraries browser, a new context menu item "Convert to Newer versions of
used libraries" is available. This allows you to convert your library to newer versions of its dependencies, once you
have installed them. If the newer version of the used library is backwards compatible with the previous one, this
just changes the uses annotation, otherwise, the conversion script is run automatically. The most common use of
this feature is to upgrade models or libraries that you developed using the Modelica library 3.2.3 to use Modelica
4.0.0. We recommend that you use this functionality on your own libraries only; for libraries that you download
from the internet, it is best to wait for the developers to perform the conversion and release new versions of their
libraries, that you can then get through the package manager.
Support of the dynamicSelect annotation has been improved, although it is still not 100% functional in all cases.
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.
33.6.5 OMSimulator
• 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.
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
The development of the new front end continued further, after becoming the default in the previous version. The
compiler can now successfully flatten 100% of the models of the Modelica Standard Library 3.2.3 and 4.0.0 that
have an experiment annotation. It can also successfully flatten 100% of many other open-source Modelica libraries,
such as Chemical, HelmholtzMedia, IBPSA, ModelicaTest, OpenIPSL, PNLib, PhotoVoltaics, PlanarMechanics,
PowerGrids, PowerSysPro, PowerSystems, SystemDynamics, TAeZoSysPro, ThermofluidStream. The success
ratio when flattening the models of the Buildings library is currently at 96%, on-going work aims at reaching
100% by the end of 2021. Overall, 20 front end issues were fixed since the last official release.
Regarding symbolic analysis and code generation, the handling of index reduction in non-trivial cases where the
state constraints are spread among many equations has been improved by the introduction of the ASCC algorithm,
coupled with the existing reshuffle loop algorithm; this had beneficial effects in particular on three-phase circuit
models. Some bugs in the generation of symbolic jacobians for nonlinear systems were also fixed. Overall, 11
issues were resolved.
33.7.2 C Runtime
Full support of the spatialDistribution() operator was introduced, including accurate handling of events. Several
low-level issues were resolved, involving memory leaks and segmentation faults.
The C++ runtime was improved to handle more Modelica language features that are used by the new frontend. The
previously release OMC 1.17 had worse coverage for the C++ runtime since it used the new frontend by default
without supporting it in the C++ code generator. With these improvements, the coverage of libraries improved
significantly, also compared to previous versions of OpenModelica with the old frontend, since the new frontend
handles more models correctly than the old one, see the regression report, column "Compilation".
Several new features were added to the plotting functionality of OMEdit, in particular: - a "Fit to Diagram" button
was added close to the zoom buttons to automatically adjust the extent of a model diagram to its actual content; -
the sign of plotted variables can now be toggled by means of the context menu on the variable legends, to compare
directly variables that are opposite in sign; - appropriate multiples of SI units (e.g. mW, W, kW, MW, GW for
power) are automatically selected for display based on the order of magnitude of the variable, to avoid 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 presentation,
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
The new frontend has been further improved, and is now the default choice for all the OpenModelica tools. The
-d=newInst flag no longer needs to be set in scripts. The old frontend is no longer maintained and will pro-
gressively be replaced also for the API interface used by OMEdit. 21 tickets were fixed since the previous 1.16.5
release.
Some issues were fixed in the backend, in particular regarding homotopy during initialization. Some improvements
to code generation, in particular enhancing the support of the HelmholtzMedia library.
The MSYS environment used on Windows was updated to a more recent version, with several benefits: - clang is
now also available on Windows and used by default instead of gcc for the compilation of the generated C code,
providing much faster C compile time on Windows; - dynamic linking is used instead of static linking, further
reducing the overall compilation time on Windows; - a more recent version of the QT library is used, which solves
some issues with the rendering of features in OMEdit.
The Sundials solvers and basic linear algebra library KLU were upgraded to the most recent available versions,
with benefits in performance and roubustness at runtime.
OpenModelica now supports both currently maintained versions of the Modelica Standard Library, MSL 3.2.3 and
MSL 4.0.0. This means that you can use Modelica libraries that use either version of the MSL, or create new ones
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 version,
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 happening
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.
This hopefully the final bugfix release of 1.16.0, which addresses an issue that affected diagrams in OMEdit under
certain conditions.
This is a further bugfix release of 1.16.0, which addresses an issue that affected diagrams in OMEdit under certain
conditions.
• Move the nfAPI and nfAPINoise settings to general page (#7171) by @adeas31 in https://github.com/
OpenModelica/OpenModelica/pull/7175
• Prepare for 1.16.4 by @adrpo in https://github.com/OpenModelica/OpenModelica/pull/7186
Full Changelog: https://github.com/OpenModelica/OpenModelica/compare/v1.16.3...v1.16.4
The new frontend has been further improved, with enhanced support of records and arrays. 33 tickets were fixed
since the previous 1.14.0 release. The new front-end can now handle 100% of the Modelica Standard Library 3.2.3
models.
Improvements to the back-end:
• new minimal tearing option --minimalTearing to disable tearing except for discrete variables
• improved symbolic Jacobian evaluation option --simJacConstantSplit reuses constant part of the Jaco-
bian
• improvements to dynamic state selection and common subexpression elimination
• new ASCC algorithm replaces and improves resolveLoops algorithm, allowing to detect high-index problems
with indirect structural state constraints, e.g. in three-phase AC circuits
• homotopy operator now used on first try by default
• linearized model export also available in Matlab, Python, and Julia with option
--linearizationDumpLanguage
Improvements to code generation and runtime:
• Better support for models with records
• CVODE solver from SUNDIALS added;
• 2 methods available: BDF (stiff) and Adams-Moulton (non-stiff)
It is now possible to build a version of OMC with parallel Jacobian evaluation using OpenMP
• On Windows build OMC with make -f Makefile.omdev.mingw omc -j4 USE_PARJAC=yes
• On Unix configure with --enable-parjac and build OMC.
• Only DASSL and IDA can use parallelized symbolic Jacobians.
• Simulate with -jacobianThreads=<numberOfThreads> or set environment variable
OMP_NUM_THREADS=<numberOfThreads> to use a specific number of threads. Otherwise all avail-
able threads will be used.
Replaceable classes now have graphical support in OMEdit. This feature was planned to be included in release
1.15.0, but it eventually turned out to be more convenient to merge it in the 1.16.0 release. Support for replaceable
elements in OMEdit is currently limited to redeclare statements without parameter modifiers. This is enough to
handle Modelica.Media medium models in Modelica.Fluid components. Please note that this feature is currently
optional and needs to be activated by setting ToolsGeneral|Enable replaceable support in OMEdit.
Over 50 bug fixes were made to OMEdit to increase usability of the GUI.
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 sup-
ported, 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.
A bug fix release for v1.14.1, fixing among other things compilation on Ubuntu 20.04.
The most dramatic enhancement of the OpenModelica Compiler is the New Frontend, which on the average gives
a factor of 10-20 speed improvement in the flattening phase of compilation. The new frontend is default in this
release, but a feature is implemented that allows the user to switch to the old frontend if problems appear for a
specific model The speed of the OMEdit GUI has only slightly increased in this version, since it is still dependent
mostly on the old frontend. Further GUI speed increases are available in the coming OpenModelica.1.15.0. About
200 issues have been fixed, including enhancements, compared to the previous 1.13.2 release. The bug fixes are
on trac.
OpenModelica Compiler New Frontend news: • Implementation of expandable connectors completed, a rather
large piece of work. • A number of smaller enhancements and fixes • The New Frontend (NF)gives slightly better
simulation coverage on MSL 3.2.3 than the Old Frontend • The New Frontend is on the average about 20 times faster
on flattening. • Remaining work is mainly on further bug fixing and testing the new frontend for all other libraries,
as well as more work on modifiers of arrays in conjunction with non-expanded arrays. (The array modifiers have
now been implemented in 1.16.0 but not yet it 1.14.0 in order to not delay the 1.14.0 release)
• 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.
• 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.
Backend enhancements
• 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
Backend bugfixes
• Homotopy: Use simplified version only during initialization to avoid errors during matching and differenti-
ation. • Logging for Homotopy path fixed so log can be loaded in OMEdit. • Support general function call
differentiation for equations in residual form. • Equations in residual form don't fail during index reduction
any more.
• A new (stand-alone) FMI- and TLM-based simulation tool OMSimulator, first version for connected FMUs,
TLM objects, Simulink models (via wrappers), Adams models (via wrappers), BEAST models (via wrap-
pers), Modelica models
• Graphic configuration editing of composite models consisting of FMUs
• Basic graphical editing support for state machines and transitions
• Faster lookup processing, making some libraries faster to browse and compile
• Additional advanced visualization features for multibody animation
• Increased library coverage including significantly increased verification coverage
• Increased tool interoperability by addition of the ZeroMQ communications protocol
• Further enhanced OMPython including linearization, now also working with Python 3
• Support for RedHat/Fedora binary builds of OpenModelica
• Additional advanced visualization features for multibody animation (transparency, textures, change colours
by dialog)
• An HTML WYSIWYG Editor, e.g. useful for documentation
• Support for choices(checkBox=true) annotation.
• Support for loadSelector & saveSelector attribute of Dialog annotation.
• Panning of icon/diagram view and plot window.
• AutoComplete feature in text editing for keywords, types, common Modelica constructs
• Follow connector transformation from Diagram View to Icon View.
• Further stability improvements
• Improved performance for rendering some icons using the interactive API
• Improved handling of parameters that cannot be evaluated in Icon annotations
• Basic graphic editing support for state machines and transitions (not yet support for showing state internals
on diagram layer)
• Interactive state manipulation for FMU-based animations
FMI Support
• A new (stand-alone) FMI- and TLM-based simulation tool OMSimulator, first version (a main deliverable
of the OPENCPS project, significant contributions and code donations from SKF)
• Graphic configuration editing of composite models consisting of FMUs
• Co-simulation/simulation of connected FMUs, TLM objects, Simulink models (via wrappers), Adams mod-
els (via wrappers), BEAST models (via wrappers), Modelica models.
Other things
• Increased OpenModelica tool interoperability by adding the ZeroMQ communications protocol in addition
to the previously available Corba. This also enables Python 3 usage in OMPython on all platforms.
• Textual support through the OpenModelica API and graphical support in OMEdit for generation of single or
multiple requirement verification scenarios
• VVDRlib – a small library for connecting requirements and models together, with notions for mediators,
scenarios, design alternatives
• Further enhanced OMPython including linearization, now also working with Python 3.¨
• Jupyter notebooks also supported with OMPython and Python 3
• New enhanced library testing script (libraries.openmodelica.org/branches).
• Addition of mutable reference data types in MetaModelica
• Support for RedHat/Fedora binary builds of OpenModelica
• Support for exporting the system of equations in GraphML (yEd) format for debugging
• Dramatically improved compilation speed and performance, in particular for large models.
• 3D animation visualization of regular MSL MultiBody simulations and for real-time FMUs.
• Better support for synchronous and state machine language elements, now supports 90% of the clocked
synchronous library.
• Several OMEdit improvements including folding of large annotations.
• 64-bit OM on Windows further stabilized
• An updated OMDev (OpenModelica Development Environment), involving msys2. This was needed for the
shift to 64-bit on Windows.
• Integration of Sundials/IDA DAE solver with potentially large increase of simulation performance for large
models with sparse structure.
• Improved library coverage.
• Parameter sensitivity analysis added to OMC.
• Real-time synchronization support by using simFlag -rt=1.0 (or some other time scaling factor).
• A prototype implementation of OPC UA using an open source OPC UA implementation. The old OPC
implementation was not maintained and relied on a Windows-only proprietary OPC DA+UA package. (At
the moment, OPC is experimental and lacks documentation; it only handles reading/writing Real/Boolean
input/state variables. It is planned for OMEdit to use OPC UA to re-implement interactive simulations and
plotting.)
• Dramatically improved compilation speed and dramatically reduced memory requirements for very large
models. In Nov 2015, the largest power generation and transmission system model that OMC could handle
had 60000 equations and it took 700 seconds to generate the simulation executable code; it now takes only
45 seconds to do so with OMC 1.11.0, which can also handle a model 10 times bigger (600 000 equations) in
less than 15 minutes and with less than 32 GB of RAM. Simulation times are comparable to domain-specific
simulation tools. See for example ScalableTestSuite for some of the improvements.
• Improved library coverage
• Better support for synchronous and state machine language elements, now simulates 90% of the clocked
synchronous library.
• Enhanced Cpp runtime to support the PowerSystems library.
• Integration of Sundials/IDA solver as an alternative to DASSL.
• A DAEMode solver mode was added, which allows to use the sparse IDA solver to handle the DAEs di-
rectly. This can lead to substantially faster simulation on large systems with sparse structure, compared to
the traditional approach.
• The direct sparse solvers KLU and SuperLU have been added, with benefits for models with large algebraic
loops.
• Multi-parameter sensitivity analysis added to OMC.
• Progress on more efficient inline function mechanism.
• Stabilized 64-bit Windows support.
• Performance improvement of parameter evaluation.
• Enhanced tearing support, with prefer iteration variables and user-defined tearing.
• Support for external object aliases in connectors and equations (a non-standard Modelica extension).
• Code generation directly to file (saves maximum memory used). #3356
• 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`).
FMI Support
• Cross compilation of C++ FMU export. Compared to the C runtime, the C++ cross compilation covers the
whole runtime for model exchange.
• Improved Newton solver for C++ FMUs (scaling and step size control).
Other things
• 3D animation visualization of regular MSL MultiBody simulations and for real-time FMUs.
• An updated OMDev (OpenModelica Development Environment), involving msys2. This was needed for the
shift to 64-bit on Windows.
• OMWebbook, a web version of OMNotebook online. Also, a script is available to convert an OMNotebook
to an OMWebbook.
• A Jupyter notebook Modelica mode, available in OpenModelica.
1.11.0,status=closed,severity!=trivial,resolution=fixed|-,col=changelog,group=component,format=table)
New features:
• Real-time synchronization support by using simFlag -rt=1.0 (or some
other time scaling factor). - A prototype implementation of OPC UA using an open source OPC UA imple-
mentation. The old OPC implementation was not maintained and relied on a Windows-only proprietary OPC
DA+UA package. (At the moment, OPC is experimental and lacks documentation; it only handles reading/writing
Real/Boolean input/state variables. It is planned for OMEdit to use OPC UA to re-implement interactive simula-
tions and plotting.)
Performance enhancements:
• Code generation directly to file (saves maximum memory used). #3356 -
Code generation in parallel enabled since #3356 allows this without allocating too much memory (controlled by
omc flag `-n`). - Various scalability enhancements, allowing the compiler to handle hundreds of thousands of
equations. See for example ScalableTestSuite for some of the improvements. - Better defaults for handling tearing
(OMC flags `--maxSizeLinearTearing` and `--maxSizeNonlinearTearing`). - Allowing mixed dense and sparse
linear solvers in the generated simulation (chosen depending on simflags `-ls` (dense solver), `-lss` (sparse solver),
`-lssMaxDensity` and `-lssMinSize`).
Optimization
FMI Support
OpenModelica v1.9.4 was released 2016-03-09. These notes cover the v1.9.4 release and its subsequent bug-fix
releases (now up to 1.9.7).
• Improved simulation speed for many models. simulation speed went up for 80% of the models. The compiler
frontend became faster for almost all models, average about 40% faster.
• Initial support for synchronous models with clocked equations as defined in the Modelica 3.3 standard
• Support for homotopy operator
• Undo/Redo support.
• Preserving text formatting, including indentation and whitespace. This is especially important for diff/merge
with several collaborating developers possibly using several different Modelica tools.
• Better support for inherited classes.
• Allow simulating models using visual studio compiler.
• Support for saving Modelica package in a folder structure.
• Allow reordering of classes inside a package.
• Highlight matching parentheses in text view.
• When copying the text retain the text highlighting and formatting.
• Support for global head definition in the documentation by using `__OpenModelica_infoHeader` annotation.
• Support for expandable connectors.
• Support for uses annotation.
FMI Support
This release mainly includes improvements of the OpenModelica Compiler (OMC), including, but not restricted
to the following:
• Further improved simulation speed and coverage for several libraries.
• Faster generated code for functions involving arrays, factor 2 speedup for many power generation models.
• Better initialization.
• An implicit inline Euler solver available.
• Code generation to enable vectorization of for-loops.
• Improved non-linear, linear and mixed system solving.
• Cross-compilation for the ARMhf architecture.
There are several improvements to the OpenModelica graphic connection editor OMEdit:
• Support for uses annotations.
• Support for declaring components as vectors.
• Faster messages browser with clickable error messages.
• Support for managing the stacking order of graphical shapes.
• Several improvements to the plot tool and text editor in OMEdit.
Several improvements:
• Support for moving cells from one place to another in a notebook.
• A button for evaluation of whole notebooks.
• A new cell type called Latex cells, supporting Latex formatted input that provides mathematical typesetting
of formulae when evaluated.
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.
FMI Support
A big change: version handling and parallel development has been improved by moving from SVN to GIThub. This
makes it easier for each developer to test his/her fixes and enhancements before committing the code. Automatic
mirroring of all code is still performed to the OpenModelica SVN site.
The OpenModelica 1.9.2 Beta release is available now, January 31, 2015. Please try it and give feedback! The
final release is planned within 1-2 weeks after some more testing. The most important enhancements in the Open-
Modelica 1.9.2 release:
• The OpenModelica compiler has moved to a new development and release platform: the bootstrapped Open-
Modelica compiler. This gives advantages in terms of better programmability, maintenance, debugging,
modularity and current/future performance increases.
• The OpenModelica graphic connection editor OMEdit has become 3-5 times faster due to faster communica-
tion 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
This release mainly includes improvements of the OpenModelica Compiler (OMC), including, but not restricted
to the following:
• The OpenModelica compiler has moved to a new development and release platform: the bootstrapped Open-
Modelica compiler. This gives advantages in terms of better programmability, maintenance, debugging,
modularity and current/future performance increases.
• Further improved simulation coverage for a number of libraries compared to 1.9.1. For example:
– MSL 3.2.1 100% compilation, 97% simulation (3% increase)
– MSL Trunk 99% compilation (1% increase), 93% simulation (3% increase)
– ModelicaTest 3.2.1 99% compilation (2% increase), 95% simulation (6% increase)
– ThermoSysPro 100% compilation, 80% simulation (17% increase)
– ThermoPower 97% compilation (5% increase), 85% simulation (5% increase)
– Buildings 80% compilation (1% increase), 73% simulation (1% increase)
• Further enhanced OMC compiler front-end coverage, scalability, speed and memory.
• Better initialization.
• Improved tearing.
• Improved non-linear, linear and mixed system solving.
• Common subexpression elimination support - drastically increases performance of some models.
• The OpenModelica graphic connection editor OMEdit has become 3-5 times faster due to faster communica-
tion with the OpenModelica compiler linked as a DLL. This was made possible by moving to the bootstrapped
compiler.
• Enhanced simulation setup window in OMEdit, which among other things include better support for inte-
gration methods and dassl options.
• Support for running multiple simultaneous simulation.
• Improved handling of modifiers.
• Re-simulate with changed options, including history support and re-simulating with previous options possi-
bly edited.
• More user friendly user interface by improved connection line drawing, added snap to grid for icons and
conversion of icons from PNG to SVG, and some additional fixes.
Optimization
Some smaller improvements of the Dynamic Optimization module with collocation, using Ipopt.
FMI Support
Further improved for FMI 2.0 model exchange import and export, now compliant according to the FMI compliance
tests. FMI 1.0 support has been further improved.
This release mainly includes improvements of the OpenModelica Compiler (OMC), including, but not restricted
to the following:
• Further improved OMC model compiler support for a number of libraries including MSL 3.2.1, ModelicaTest
3.2.1, PetriNet, Buildings, PowerSystems, OpenHydraulics, ThermoPower, and ThermoSysPro.
• Further enhanced OMC compiler front-end coverage, scalability, speed and memory.
• Better coverage of Modelica libraries using Fluid and Media.
• Automatic differentiation of algorithms and functions.
• Improved testing facilities and library coverage reporting.
• Improved model compilation speed by compiling model parts in parallel (bootstrapped compiler).
• Support for running model simulations in a web browser.
• New faster initialization that handles over-determined systems, under-determined systems, or both.
• Compiler back-end partly redesigned for improved scalability and better modularity.
• Better tearing support.
• The first run-time Modelica equation-based model debugger, not available in any other Modelica tool, inte-
grated with OMEdit.
• Enhanced performance profiler integrated with the debugger.
• Improved parallelization prototype with several parallelization strategies, task merging and duplication,
shorter critical paths, several scheduling strategies.
• Some support for general solving of mixed systems of equations.
• Convenient editing of model parameter values and re-simulation without recompilation after parameter
changes.
• Improved plotting.
• Better handling of flags/units/resources/crashes.
• Run-time Modelica equation-based model debugger that provides both dynamic run-time debugging and
debugging of symbolic transformations.
• Run-time Modelica algorithmic code debugger; also MetaModelica debugger with the bootstrapped Open-
Modelica compiler.
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.
Optimization
A builtin integrated Dynamic Optimization module with collocation, using Ipopt, is now available.
FMI Support
Support for FMI 2.0 model exchange import and export has been added. FMI 1.0 support has been further improved.
This is the summary description of changes to OpenModelica from 1.8.1 to 1.9.0, released 2013-10-09. This
release mainly includes improvements of the OpenModelica Compiler (OMC), including, but not restricted to the
following:
This release mainly includes bug fixes and improvements of the OpenModelica Compiler (OMC), including, but
not restricted to the following:
• A more stable and complete OMC model compiler. The 1.9.0 final version simulates many more models
than the previous 1.8.1 version and OpenModelica 1.9.0 beta versions.
• Much better simulation support for MSL 3.2.1, now 270 out of 274 example models compile (98%) and 245
(89%) simulate, compared to 30% simulating in the 1.9.0 beta1 release.
• Much better simulation for the ModelicaTest 3.2.1 library, now 401 out of 428 models build (93%) and 364
simulate (85%), compared to 32% in November 2012.
• Better simulation support for several other libraries, e.g. more than twenty examples simulate from Ther-
moSysPro, and all but one model from PlanarMechanics simulate.
• Improved tearing algorithm for the compiler backend. Tearing is by default used.
• Much faster matching and dynamic state selection algorithms for the compiler backend.
• New index reduction algorithm implementation.
• New default initialization method that symbolically solves the initialization problem much faster and more
accurately. This is the first version that in general initialize hybrid models correctly.
• Better class loading from files. The package.order file is now respected and the file structure is more thor-
oughly examined (#1764).
• It is now possible to translate the error messages in the omc kernel (#1767).
• FMI Support. FMI co-simulation with OpenModelica as master. Improved
FMI Import and export for model exchange. Most of FMI 2.0 is now also supported.
• Checking (when possible) that variables have been assigned to before they are used in algorithmic code
(#1776).
• Full version of Python scripting.
• 3D graphics visualization using the Modelica3D library.
• The PySimulator package from DLR for additional analysis is integrated with OpenModelica (see Model-
ica2012 paper), and included in the OpenModelica distribution (Windows only).
• Prototype support for uncertainty computations, special feature enabled by special flag.
• Parallel algorithmic Modelica support (ParModelica) for efficient portable parallel algorithmic programming
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 package
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.
• General GUI: backward and forward navigation support in Documentation view, enhanced parameters win-
dow with support for Dialog annotation. Most of the images are converted from raster to vector graphics i.e
PNG to SVG.
• Libraries Browser: better loading of libraries, library tree can now show protected classes, show library
items class names as middle ellipses if the class name text is larger, more options via the right click menu
for quick usage.
• ModelWidget: add the partial class as a replaceable component, look for the default component prefixes and
name when adding the component.
• GraphicsView: coordinate system manipulation for icon and diagram layers. Show red box for models that do
not exist. Show default graphical annotation for the components that doesn't have any graphical annotations.
Better resizing of the components. Properties dialog for primitive shapes i.e Line, Polygon, Rectangle,
Ellipse, Text and Bitmap.
• File Opening: open one or more Modelica files, allow users to select the encoding while opening the file,
convert files to UTF-8 encoding, allow users to open the OpenModelica result files.
• Variables Browser: find variables in the variables browser, sorting in the variables browser.
• Plot Window: clear all curves of the plot window, preserve the old selected variable and update its value
with the new simulation result.
• Simulation: support for all the simulation flags, read the simulation output as soon as is is obtained, out-
put 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 com-
ment/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.
ModelicaML
The OpenModelica 1.8.1 release has a faster and more stable OMC model compiler. It flattens and simulates
more models than the previous 1.8.0 version. Significant flattening speedup of the compiler has been achieved for
certain large models. It also contains a New ModelicaML version with support for value bindings in requirements-
driven modeling and importing Modelica library models into ModelicaML models. A beta version of the new
OpenModelica Python scripting is also included. The release was made on 2012-04-03 (r11645).
This release includes bug fixes and improvements of the flattening frontend part of the OpenModelica Compiler
(OMC) and several improvements of the backend, including, but not restricted to:
• A faster and more stable OMC model compiler. The 1.8.1 version flattens and simulates more models than
the previous 1.8.0 version.
• Support for operator overloading (except Complex numbers).
• New ModelicaML version with support for value bindings in requirements-driven modeling and importing
Modelica library models into ModelicaML models.
• Faster plotting in OMNotebook. The feature sendData has been removed from OpenModelica. As a result,
the kernel no longer depends on Qt. The plot3() family of functions have now replaced to plot(), which in
turn have been removed. The non-standard visualize() command has been removed in favour of more recent
alternatives.
• Store OpenModelica documentation as Modelica Documentation annotations.
• Re-implementation of the simulation runtime using C instead of C++ (this was needed to export FMI source-
based packages).
• FMI import/export bug fixes.
• 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 ex-
pected. 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.
• No changes.
• No changes.
• Bug fixes.
• Bug fixes.
FMI Support
• Bug fixes.
The OpenModelica 1.8.0 release contains OMC flattening improvements for the Media library - it now flattens the
whole library and simulates about 20% of its example models. Moreover, about half of the Fluid library models
also flatten. This release also includes two new tool functionalities - the FMI for model exchange import and export,
and a new efficient Eclipse-based debugger for Modelica/MetaModelica algorithmic code.
This release includes bug fixes and improvements of the flattening frontend part of the OpenModelica Compiler
(OMC) and several improvements of the backend, including, but not restricted to: A faster and more stable OMC
model compiler. The 1.8.0 version flattens and simulates more models than the previous 1.7.0 version.
• Flattening of the whole Media library, and about half of the Fluid
library. Simulation of approximately 20% of the Media library example models. - Functional Mockup Interface
FMI 1.0 for model exchange, export and import, for the Windows platform. - Bug fixes in the OpenModelica graph-
ical model connection editor OMEdit, supporting easy-to-use graphical drag-and-drop modeling and MSL 3.1. -
Bug fixes in the OMOptim optimization subsystem. - Beta version of compiler support for a new Eclipse-based
very efficient algorithmic code debugger for functions in MetaModelica/Modelica, available in the development
environment when using the bootstrapped OpenModelica compiler. - Improvements in initialization of simulations.
- Improved index reduction with dynamic state selection, which improves simulation. - Better error messages from
several parts of the compiler, including a new API call for giving better error messages. - Automatic partitioning
of equation systems and multi-core parallel simulation of independent parts based on the shared-memory OpenMP
model. This version is a preliminary experimental version without load balancing.
No changes.
Small fixes and improvements. MDT now also includes a beta version of a new Eclipse-based very efficient algo-
rithmic code debugger for functions in MetaModelica/Modelica.
Third party binaries, including Qt libraries and executable Qt clients, are now part of the OMDev package. Also,
now uses GCC 4.4.0 instead of the earlier GCC 3.4.5.
Bug fixes. Access to FMI Import/Export through a pull-down menu. Improved configuration of library loading.
A function to go to a specific line number. A button to cancel an on-going simulation. Support for some updated
OMC API calls.
FMI Support
The Functional Mockup Interface FMI 1.0 for model exchange import and export is supported by this release. The
functionality is accessible via API calls as well as via pull-down menu commands in OMEdit.
The OpenModelica 1.7.0 release contains OMC flattening improvements for the Media library, better and faster
event handling and simulation, and fast MetaModelica support in the compiler, enabling it to compiler itself. This
release also includes two interesting new tools – the OMOptim optimization subsystem, and a new performance
profiler for equation-based Modelica models.
This release includes bug fixes and performance improvements of the flattening frontend part of the OpenModelica
Compiler (OMC) and several improvements of the backend, including, but not restricted to:
• Flattening of the whole Modelica Standard Library 3.1 (MSL 3.1),
except Media and Fluid. - Progress in supporting the Media library, some models now flatten. - Much faster
simulation of many models through more efficient handling of alias variables, binary output format, and faster
event handling. - Faster and more stable simulation through new improved event handling, which is now default.
- Simulation result storage in binary .mat files, and plotting from such files. - Support for Unicode characters
in quoted Modelica identifiers, including Japanese and Chinese. - Preliminary MetaModelica 2.0 support. (use
setCommandLineOptions({"+g=MetaModelica"}) ). Execution is as fast as MetaModelica 1.0, except for garbage
collection. - Preliminary bootstrapped OpenModelica compiler: OMC now compiles itself, and the bootstrapped
compiler passes the test suite. A garbage collector is still missing. - Many bug fixes.
Improved much faster and more stable 2D plotting through the new OMPlot module. Plotting from binary .mat
files. Better integration between OMEdit and OMNotebook, copy/paste between them.
Several enhancements of OMEdit are included in this release. Support for Icon editing is now available. There is
also an improved much faster 2D plotting through the new OMPlot module. Better integration between OMEdit
and OMNotebook, with copy/paste between them. Interactive on-line simulation is available in an easy-to-use way.
A new optimization subsystem called OMOptim has been added to OpenModelica. Currently, parameter optimiza-
tion using genetic algorithms is supported in this version 0.9. Pareto front optimization is also supported.
A new, low overhead, performance profiler for Modelica models has been developed.
The OpenModelica 1.6.0 release primarily contains flattening, simulation, and performance improvements regard-
ing Modelica Standard Library 3.1 support, but also has an interesting new tool – the OMEdit graphic connection
editor, and a new educational material called DrControl, and an improved ModelicaML UML/Modelica profile
with better support for modeling and requirement handling.
This release includes bug fix and performance improvemetns of the flattening frontend part of the OpenModelica
Compiler (OMC) and some improvements of the backend, including, but not restricted to:
• Flattening of the whole Modelica Standard Library 3.1 (MSL 3.1),
except Media and Fluid. - Improved flattening speed of a factor of 5-20 compared to OpenModelica 1.5 for a number
of models, especially in the MultiBody library. - Reduced memory consumption by the OpenModelica compiler
frontend, for certain large models a reduction of a factor 50. - Reorganized, more modular OpenModelica compiler
backend, can now handle approximately 30 000 equations, compared to previously approximately 10 000 equations.
- Better error messages from the compiler, especially regarding functions. - Improved simulation coverage of MSL
3.1. Many models that did not simulate before are now simulating. However, there are still many models in certain
sublibraries that do not simulate. - Progress in supporting the Media library, but simulation is not yet possible. -
Improved support for enumerations, both in the frontend and the backend. - Implementation of stream connectors.
- Support for linearization through symbolic Jacobians. - Many bug fixes.
A new DrControl electronic notebook for teaching control and modeling with Modelica.
Several enhancements. Support for match-expressions in addition to matchcontinue. Support for real if-then-else.
Support for if-then without else-branches. Modelica Development Tooling 0.7.7 with small improvements such as
more settings, improved error detection in console, etc.
A new improved open source graphic model connection editor called OMEdit, supporting 3.1 graphical annota-
tions, which makes it possible to move models back and forth to other tools without problems. The editor has been
implemented by students at Linköping University and is based on the C++ Qt library.
This OpenModelica 1.5 release has major improvements in the OpenModelica compiler frontend and some in the
backend. A major improvement of this release is full flattening support for the MultiBody library as well as limited
simulation support for MultiBody. Interesting new facilities are the interactive simulation and the integrated UML-
Modelica modeling with ModelicaML. Approximately 4 person-years of additional effort have been invested in the
compiler compared to the 1.4.5 version, e.g., in order to have a more complete coverage of Modelica 3.0, mainly
focusing on improved flattening in the compiler frontend.
This release includes major improvements of the flattening frontend part of the OpenModelica Compiler (OMC)
and some improvements of the backend, including, but not restricted to:
• Improved flattening speed of at least a factor of 10 or more compared
to the 1.4.5 release, primarily for larger models with inner-outer, but also speedup for other models, e.g. the robot
model flattens in approximately 2 seconds. - Flattening of all MultiBody models, including all elementary models,
breaking connection graphs, world object, etc. Moreover, simulation is now possible for at least five MultiBody
models: Pendulum, DoublePendulum, InitSpringConstant, World, PointGravityWithPointMasses. - Progress in
supporting the Media library, but simulation is not yet possible. - Support for enumerations, both in the frontend
and the backend. - Support for expandable connectors. - Support for the inline and late inline annotations in
functions. - Complete support for record constructors, also for records containing other records. - Full support
for iterators, including nested ones. - Support for inferred iterator and for-loop ranges. - Support for the function
derivative annotation. - Prototype of interactive simulation. - Prototype of integrated UML-Modelica modeling
and simulation with ModelicaML. - A new bidirectional external Java interface for calling external Java functions,
or for calling Modelica functions from Java. - Complete implementation of replaceable model extends. - Fixed
problems involving arrays of unknown dimensions. - Limited support for tearing. - Improved error handling at
division by zero. - Support for Modelica 3.1 annotations. - Support for all MetaModelica language constructs
inside OpenModelica. - OpenModelica works also under 64-bit Linux and Mac 64-bit OSX. - Parallel builds and
running test suites in parallel on multi-core platforms. - New OpenModelica text template language for easier
implementation of code generators, XML generators, etc. - New OpenModelica code generators to C and C# using
the text template language. - Faster simulation result data file output optionally as comma-separated values. - Many
bug fixes.
It is now possible to graphically edit models using parts from the Modelica Standard Library 3.1, since the simForge
graphical editor (from Politecnico di Milano) that is used together with OpenModelica has been updated to version
0.9.0 with a important new functionality, including support for Modelica 3.1 and 3.0 annotations. The 1.6 and
2.2.1 Modelica graphical annotation versions are still supported.
This release has several improvements, especially platform availability, less compiler memory usage, and support-
ing more aspects of Modelica 3.0.
This release includes small improvements and some bugfixes of the OpenModelica Compiler (OMC):
• Less memory consumption and better memory management over time. This
also includes a better API supporting automatic memory management when calling C functions from within the
compiler. - Modelica 3.0 parsing support. - Export of DAE to XML and MATLAB. - Support for several platforms
Linux, MacOS, Windows (2000, Xp, Vista). - Support for record and strings as function arguments. - Many bug
fixes. - (Not part of OMC): Additional free graphic editor SimForge can be used with OpenModelica.
This release is primarily a bug fix release, except for a preliminary version of new plotting functionality available
both from the OMNotebook and separately through a Modelica API. This is also the first release under the open
source license OSMC-PL (Open Source Modelica Consortium Public License), with support from the recently
created Open Source Modelica Consortium. An integrated version handler, bug-, and issue tracker has also been
added.
This release includes small improvements and some bugfixes of the OpenModelica Compiler (OMC):
• Better support for if-equations, also inside when. - Better support
for calling functions in parameter expressions and interactively through dynamic loading of functions. - Less
memory consumtion during compilation and interactive evaluation. - A number of bug-fixes.
Test release of improvements, primarily in the plotting functionality and platform availability.
• Preliminary version of improvements in the plotting functionality:
scalable plots, zooming, logarithmic plots, grids, etc., currently available in a preliminary version through the plot2
function. - Programmable plotting accessible through a Modelica API.
This release includes minor bugfixes of MDT and the associated MetaModelica debugger.
Extended test suite with a better structure. Version handling, bug tracking, issue tracking, etc. now available under
the integrated Codebeamer.
This release has a number of significant improvements of the OMC compiler, OMNotebook, the MDT plugin and
the OMDev. Increased platform availability now also for Linux and Macintosh, in addition to Windows. OMShell
is the same as previously, but now ported to Linux and Mac.
This release includes major improvements of MDT and the associated MetaModelica debugger:
• Greatly improved browsing and code completion works both for standard
Modelica and for MetaModelica. - Hovering over identifiers displays type information. - A new and greatly im-
proved implementation of the debugger for MetaModelica algorithmic code, operational in Eclipse. Greatly im-
proved performance - only approx 10% speed reduction even for 100 000 line programs. Greatly improved single
stepping, step over, data structure browsing, etc. - Many bug fixes.
This release has improvements and bug fixes of the OMC compiler, OMNotebook, the MDT plugin and the OMDev.
OMShell is the same as previously.
Search and replace functions have been added. The DrModelica tutorial (all files) has been updated, obsolete
sections removed, and models which are not supported by the current implementation marked clearly. Automatic
recognition of the .onb suffix (e.g. when double-clicking) in Windows makes it even more convenient to use.
This release has only improvements and bug fixes of the OMC compiler, the MDT plugin and the OMDev compo-
nents. The OMShell and OMNotebook are the same.
Improvements of the error reporting when building the OMC compiler. The errors are now added to the problems
view. The latest MDT release is version 0.6.6 (2006-06-06).
Small fixes in the MetaModelica compiler. MetaModelica Users Guide is now part of the OMDev release. The
latest OMDev was release in 2006-06-06.
This release has a number of improvements described below. The most significant change is probably that OMC has
now been translated to an extended subset of Modelica (MetaModelica), and that all development of the compiler
is now done in this version..
Essentially the same OMShell as in 1.3.1. One difference is that now all error messages are sent to the command
window instead of to a separate log window.
Many significant improvements and bug fixes. This version supports graphic plots within the cells in the notebook.
Improved cell handling and Modelica code syntax highlighting. Command completion of the most common OMC
commands is now supported. The notebook has been used in several courses.
This is the first really useful version of MDT. Full browsing of Modelica code, e.g. the MSL 2.2, is now supported.
(MetaModelica browsing is not yet fully supported). Full support for automatic indentation of Modelica code,
including the MetaModelica extensions. Many bug fixes. The Eclipse plug-in is now in use for OpenModelica
development at PELAB and MathCore Engineering AB since approximately one month.
The following mechanisms have been put in place to support OpenModelica development.
• A separate web page for OMDev (OpenModelica Development Environment).
• A pre-packaged OMDev zip-file with precompiled binaries for
development under Windows using the mingw Gnu compiler from the Eclipse MDT plug-in. (Development is
also possible using Visual Studio). - All source code of the OpenModelica compiler has recently been translated
to an extended subset of Modelica, currently called MetaModelica. The current size of OMC is approximately
100 000 lines All development is now done in this version. - A new tutorial and users guide for development in
MetaModelica. - Successful builds and tests of OMC under Linux and Solaris.
An improved window-based interactive command shell, now including command completion and better editing
and font size support.
A free implementation of an OpenModelica notebook (OMNotebook), for electronic books with course material,
including the DrModelica interactive course material. It is possible to simulate and plot from this notebook.
An early alpha version of the first Eclipse plug-in (called MDT for Modelica Development Tooling) for Modelica
Development. This version gives compilation support and partial support for browsing Modelica package hierar-
chies and classes.
The following mechanisms have been put in place to support OpenModelica development.
• Bugzilla support for OpenModelica bug tracking, accessible to anybody.
• A system for automatic regression testing of the compiler and
simulator, (+ other system parts) usually run at check in time. - Version handling is done using SVN, which is
better than the previously used CVS system. For example, name change of modules is now possible within the
version handling system.
THIRTYFOUR
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.
561
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
[FPA+20] Peter Fritzson, Adrian Pop, Karim Abdelhak, Adeel Ashgar, Bernhard Bachmann, Willi Braun, Daniel
Bouskela, Robert Braun, Lena Buffoni, Francesco Casella, Rodrigo Castro, Rüdiger Franke, Dag
Fritzson, Mahder Gebremedhin, Andreas Heuermann, Bernt Lie, Alachew Mengist, Lars Mikelsons,
Kannan Moudgalya, Lennart Ochel, Arunkumar Palanisamy, Vitalij Ruge, Wladimir Schamai, Martin
Sjölund, Bernhard Thiele, John Tinnerholm, and Per Östlund. The OpenModelica Integrated Environ-
ment for Modeling, Simulation, and Model-Based Development. Modeling, Identification and Control,
41(4):241–295, 2020. doi:10.4173/mic.2020.4.1.
[ABB+99] Edward Anderson, Zhaojun Bai, Christian Bischof, L Susan Blackford, James Demmel, Jack Dongarra,
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 solv-
ing 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 non-
linear 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.
579
OpenModelica User’s Guide, Release v1.23.0-dev-229-g14cdee7a2b
[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.
[Sie12] Michael Sielemann. Device-Oriented Modeling and Simulation in Aircraft Energy Systems Design.
PhD thesis, TU Hamburg-Harburg, Germany, 2012. doi:10.15480/882.1111.
[SCO+11] Michael Sielemann, Francesco Casella, Martin Otter, Christop Clauß, Jonas Eborn, Sven Erik Matsson,
and Hans Olsson. Robust initialization of differential-algebraic equations using homotopy. In Proceed-
ings 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 parallel
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 Information
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.
580 Bibliography
INDEX
O
OMEdit, 213
OMSimulator, 139
Examples, 140
Flags, 139
OMSimulatorLib, 141
C-API, 141
OMSimulatorLua, 160
Examples, 160
Scripting Commands, 161
OMSimulatorPython, 178
Examples, 179
Scripting Commands, 180
OpenModelicaScripting, 198
Examples, 200
Scripting Commands, 200
S
SSP, 217
Bus connections, 219
TLM connections, 221
TLM Systems, 220
581