OpenModelicaUsersGuide-1 14
OpenModelicaUsersGuide-1 14
OpenModelicaUsersGuide-1 14
Release v1.14.2-6-g5c52d52477
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 . . . . . . . . . . . . . . . . . . . . 23
1.4 Running the compiler from command line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3 2D Plotting 67
3.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.2 Plot Command Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5 Debugging 73
5.1 The Equation-based Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
i
5.2 The Algorithmic Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8 OMSimulator 101
13 PDEModelica1 153
13.1 PDEModelica1 language elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
13.2 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
13.3 Viewing results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
ii
19 OpenModelica Python Interface and PySimulator 189
19.1 OMPython – OpenModelica Python Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
19.2 Enhanced OMPython Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
19.3 PySimulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
22 Jupyter-OpenModelica 211
27 DataReconciliation 319
27.1 Defining DataReconciliation Problem in OpenModelica . . . . . . . . . . . . . . . . . . . . . . 319
27.2 DataReconcilation Support with Scripting Interface . . . . . . . . . . . . . . . . . . . . . . . . . 320
27.3 DataReconciliation Support in OMEdit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
27.4 DataReconcilation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
iii
28.3 OMDev - OpenModelica Development Environment . . . . . . . . . . . . . . . . . . . . . . . . 328
Bibliography 371
iv
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
CONTENTS 1
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
The system described in this document has both short-term and long-term goals:
• The short-term goal is to develop an efficient interactive computational environment for the Modelica lan-
guage, as well as a rather complete implementation of the language. It turns out that with support of
appropriate tools and libraries, Modelica is very well suited as a computational language for development
and execution of both low level and high level numerical algorithms, e.g. for control system design, solving
nonlinear equation systems, or to develop optimization algorithms that are applied to complex applications.
• The long-term goal is to have a complete reference implementation of the Modelica language, including
simulation of equation based models and additional facilities in the programming environment, as well
as convenient facilities for research and experimentation in language design or other research activities.
However, our goal is not to reach the level of performance and quality provided by current commercial
Modelica environments that can handle large models requiring advanced analysis and optimization by the
Modelica compiler.
The long-term research related goals and issues of the OpenModelica open source implementation of a Modelica
environment include but are not limited to the following:
• Development of a complete formal specification of Modelica, including both static and dynamic semantics.
Such a specification can be used to assist current and future Modelica implementers by providing a semantic
reference, as a kind of reference implementation.
• Language design, e.g. to further extend the scope of the language, e.g. for use in diagnosis, structural
analysis, system identification, etc., as well as modeling problems that require extensions such as partial
differential equations, enlarged scope for discrete modeling and simulation, etc.
• Language design to improve abstract properties such as expressiveness, orthogonality, declarativity, reuse,
configurability, architectural properties, etc.
• Improved implementation techniques, e.g. to enhance the performance of compiled Modelica code by gen-
erating code for parallel hardware.
• Improved debugging support for equation based languages such as Modelica, to make them even easier to
use.
• Easy-to-use specialized high-level (graphical) user interfaces for certain application domains.
• Visualization and animation techniques for interpretation and presentation of results.
• Application usage and model library development by researchers in various application areas.
The OpenModelica environment provides a test bench for language design ideas that, if successful, can be submit-
ted to the Modelica Association for consideration regarding possible inclusion in the official Modelica standard.
The current version of the OpenModelica environment allows most of the expression, algorithm, and function
parts of Modelica to be executed interactively, as well as equation models and Modelica functions to be compiled
into efficient C code. The generated C code is combined with a library of utility functions, a run-time library, and
a numerical DAE solver.
3
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Interactive
OMOptim sessionhandler Textual
Optimization
Model Editor
Subsystem
OMNotebook
DrModelica Execution Modelica
Model Editor Compiler
Modelica
Debugger
Figure 1.1: The architecture of the OpenModelica environment. Arrows denote data and control flow. The inter-
active session handler receives commands and shows results from evaluating commands and expressions that are
translated and executed. Several subsystems provide different forms of browsing and textual editing of Modelica
code. The debugger currently provides debugging of an extended algorithmic subset of Modelica.
4 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
• Optimization subsystem OMOptim. This is an optimization subsystem for OpenModelica, currently for
design optimization choosing an optimal set of design parameters for a model. The current version has a
graphical user interface, provides genetic optimization algorithms and Pareto front optimization, works in-
tegrated with the simulators and automatically accesses variables and design parameters from the Modelica
model.
• Dynamic Optimization subsystem. This is dynamic optimization using collocation methods, for Model-
ica models extended with optimization specifications with goal functions and additional constraints. This
subsystem is integrated with in the OpenModelica compiler.
• Modelica equation model debugger. The equation model debugger shows the location of an error in the
model equation source code. It keeps track of the symbolic transformations done by the compiler on the
way from equations to low-level generated C code, and also explains which transformations have been done.
• Modelica algorithmic code debugger. The algorithmic code Modelica debugger provides debugging for an
extended algorithmic subset of Modelica, excluding equation-based models and some other features, but in-
cluding some meta-programming and model transformation extensions to Modelica. This is a conventional
full-feature debugger, using Eclipse for displaying the source code during stepping, setting breakpoints, etc.
Various back-trace and inspection commands are available. The debugger also includes a data-view browser
for browsing hierarchical data such as tree- or list structures in extended Modelica.
>>> getVersion()
"OMCompiler v1.14.2-v1.14.2.6+g5c52d52477"
>>> x := 1:12
{1,2,3,4,5,6,7,8,9,10,11,12}
Example Session 1
To get help on using OMShell and OpenModelica, type "help()" and press enter.
>>> 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
To get help on using OMShell and OpenModelica, type "help()" and press enter.
model C
Integer a;
Real b;
equation
der(a) = b;
der(b) = 12.0;
end C;
>>> instantiateModel(C)
""
Error:
[<interactive>:5:3-5:13:writable] Error: Argument ’a’ to der has illegal type Integer, must be a subtype of
Real.
Error: Error occurred while flattening model C
true
The function bubblesort is called below to sort the vector x in descending order. The sorted result is returned to-
gether with its type. Note that the result vector is of type Real[:], instantiated as Real[12], since this is the declared
type of the function result. The input Integer vector was automatically converted to a Real vector according to
the Modelica type coercion rules. The function is automatically compiled when called if this has not been done
before.
>>> bubblesort(x)
{12.0,11.0,10.0,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0}
Another call:
>>> bubblesort({4,6,2,5,8})
{8.0,6.0,5.0,4.0,2.0}
6 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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/jenkins/ws/OpenModelica_maintenance_v1.14/build/share/doc/omc/testmodels"
>>> cd(dir)
"«DOCHOME»"
>>> loadModel(Modelica)
true
true
Warning:
Warning: Requested package Modelica of version 3.2.2, but this package was already loaded with version
3.2.3. You might experience problems if these versions are incompatible.
It is simulated:
Warning:
Warning: Requested package Modelica of version 3.2.2, but this package was already loaded with version
3.2.3. You might experience problems if these versions are incompatible.
8 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
>>> list(dcmotor)
model dcmotor
import Modelica.Electrical.Analog.Basic;
Basic.Resistor resistor1(R = 10);
Basic.Inductor inductor1(L = 0.2, i.fixed = true);
Basic.Ground ground1;
Modelica.Mechanics.Rotational.Components.Inertia load(J = 1, phi.fixed = true, w.
˓→fixed = true);
>>> instantiateModel(dcmotor)
class dcmotor
Real resistor1.v(quantity = "ElectricPotential", unit = "V") "Voltage drop of
˓→the two pins (= p.v - n.v)";
˓→of heatPort";
˓→"Reference temperature";
˓→heatPort - T_ref))";
˓→der(phi))";
10 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
equation
assert(1.0 + resistor1.alpha * (resistor1.T_heatPort - resistor1.T_ref) >= 1e-15,
˓→ "Temperature outside scope of model!");
Warning:
Warning: Requested package Modelica of version 3.2.2, but this package was already loaded with version
3.2.3. You might experience problems if these versions are incompatible.
4
load.w
load.phi
3.5
2.5
1.5
0.5
0
0 2 4 6 8 10
12 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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-06, method = 'dassl', fileNamePrefix = 'BouncingBall', options =
model Switch
Real v;
Real i;
Real i1;
Real itot;
Boolean open;
equation
itot = i + i1;
if open then
v = 0;
else
i = 0;
end if;
1 - i1 = 0;
1 - v - i = 0;
open = time >= 0.5;
end Switch;
Retrieve the value of itot at time=0 using the val(variableName, time) function:
>>> val(itot,0)
1.0
14 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
2
itot
open
1.5
0.5
0
0 0.2 0.4 0.6 0.8 1
true
It is simulated:
It is plotted:
>>> plotParametric("x","y")
>>> instantiateModel(VanDerPol)
class VanDerPol "Van der Pol oscillator model"
Real x(start = 1.0, fixed = true);
Real y(start = 1.0, fixed = true);
parameter Real lambda = 0.3;
equation
der(x) = y;
(continues on next page)
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
16 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
>>> k := 0;
>>> for i in 1:1000 loop
k := k + i;
end for;
>>> k
500500
>>> g := 0.0;
>>> h := 5;
>>> for i in {23.0,77.12,88.23} loop
for j in i:0.5:(i+1) loop
g := g + j;
g := g + h / 2;
end for;
h := h + g;
end for;
By putting two (or more) variables or assignment statements separated by semicolon(s), ending with a variable,
one can observe more than one variable value:
>>> h; g
1997.45
1479.09
>>> i:="";
>>> lst := {"Here ", "are ","some ","strings."};
>>> s := "";
>>> for i in lst loop
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"
>>> 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
18 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
>>> getErrorString()
""
It is also possible to specify which variables should be present in the result-file. This is done by using POSIX
Extended Regular Expressions. The given expression must match the full variable name (^ and $ symbols are
automatically added to the given regular expression).
// Default, match everything
// match indices of variable myVar that only contain the numbers using combinations
// of the letters 1 through 3
// match x or y or z
package Modelica
annotation(uses(Complex(version="1.0"),
ModelicaServices(version="1.1")));
end Modelica;
>>> clear()
true
model M
annotation(uses(Modelica(version="3.2.1")));
end M;
>>> instantiateModel(M)
class M
end M;
Note:
Notification: Automatically loaded package Modelica 3.2.1 due to uses annotation.
Notification: Automatically loaded package Complex 3.2.1 due to uses annotation.
Notification: Automatically loaded package ModelicaServices 3.2.1 due to uses annotation.
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.v = 0.0;
p.i = 0.0;
end Modelica.Electrical.Analog.Basic.Ground;
Note:
Notification: Automatically loaded package Complex 3.2.3 due to uses annotation.
Notification: Automatically loaded package ModelicaServices 3.2.3 due to uses annotation.
Notification: Automatically loaded package Modelica default due to uses annotation.
20 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
>>> 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/jenkins/ws/OpenModelica_maintenance_v1.14/
˓→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",
true
>>> exportDAEtoMatlab(BouncingBall)
"The equation system was dumped to Matlab file:BouncingBall_imatrix.m"
% Incidence Matrix
% ====================================
% number of rows: 6
IM={{3,6},{1,{'if', 'true','==' {3},{},}},{{'if', 'true','==' {4},{},}},{5},{2,{'if
˓→', 'edge(impact)' {3},{5},}},{4,2}};
VL = {'foo','v_new','impact','flying','v','h'};
˓→new = if edge(impact) then (-e) * pre(v) else 0.0; end when;','when {h <= 0.0
(continues on next page)
˓→and v <= 0.0, impact} then flying = v_new > 0.0; end when;'};
22 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
simulate(modelname[,startTime=<Real>][,stopTime=<Real>][,numberOfIntervals
=<Integer>][,outputInterval=<Real>][,method=<String>]
[,tolerance=<Real>][,fixedStepSize=<Real>]
[,outputFormat=<String>]) Translate and simulate a model, with optional start time, stop time, and optional
number of simulation intervals or steps for which the simulation results will be computed. More intervals will
give higher time resolution, but occupy more space and take longer to compute. The default number of intervals
is 500. It is possible to choose solving method, default is “dassl”, “euler” and “rungekutta” are also available.
Output format “mat” is default. “plt” and “mat” (MATLAB) are the only ones that work with the val() command,
“csv” (comma separated values) and “empty” (no output) are also available (see section Alternative Simulation
Output Formats).
plot(vars) Plot the variables given as a vector or a scalar, e.g. plot({x1,x2}) or plot(x1).
plotParametric(var1, var2) Plot var2 relative to var1 from the most recently simulated model, e.g. plotParamet-
ric(x,y).
cd() Return the current directory.
cd(dir) Change directory to the directory given as string.
clear() Clear all loaded definitions.
clearVariables() Clear all defined variables.
dumpXMLDAE(modelname, ...) Dumps an XML representation of a model, according to several optional param-
eters.
exportDAEtoMatlab(name) Dumps a Matlab representation of a model.
instantiateModel(modelname)Performs code instantiation of a model/class and return a string containing the flat
class definition.
list() Return a string containing all loaded class definitions.
list(modelname) Return a string containing the class definition of the named class.
listVariables() Return a vector of the names of the currently defined variables.
loadModel(classname) Load model or package of name classname from the path indicated by the environment
variable OPENMODELICALIBRARY.
loadFile(str) Load Modelica file (.mo) with name given as string argument str.
readFile(str) Load file given as string str and return a string containing the file content.
runScript(str) Execute script file with file name given as string argument str.
system(str) Execute str as a system(shell) command in the operating system; return integer success value. Output
into stdout from a shell command is put into the console window.
timing(expr) Evaluate expression expr and return the number of seconds (elapsed time) the evaluation took.
typeOf(variable) Return the type of the variable as a string.
saveModel(str,modelname) Save the model/class with name modelname in the file given by the string argument
str.
val(variable,timePoint) Return the (interpolated) value of the variable at time timePoint.
help() Print this helptext (returned as a string).
quit() Leave and quit the OpenModelica environment
C:\dev> echo model TestModel parameter Real x = 1; end TestModel; > TestModel.mo
C:\dev> C:\OpenModelica1.9.2 \bin\omc TestModel.mo
class TestModel
parameter Real x = 1.0;
end TestModel;
C:\dev>
24 Chapter 1. Introduction
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
In order to obtain more information from the compiler one can use the command line options –
showErrorMessages -d=failtrace when running the compiler:
C:\dev> C:\OpenModelica1.9.2 \bin\omc –showErrorMessages -d=failtrace script.mos
26 Chapter 1. Introduction
CHAPTER
TWO
OMEdit – OpenModelica Connection Editor is the new Graphical User Interface for graphical model editing in
OpenModelica. It is implemented in C++ using the Qt graphical user interface library and supports the Modelica
Standard Library that is included in the latest OpenModelica installation. This chapter gives a brief introduction
to OMEdit and also demonstrates how to create a DCMotor model using the editor.
OMEdit provides several user friendly features for creating, browsing, editing, and simulating models:
• Modeling – Easy model creation for Modelica models.
• Pre-defined models – Browsing the Modelica Standard library to access the provided models.
• User defined models – Users can create their own models for immediate usage and later reuse.
• Component interfaces – Smart connection editing for drawing and editing connections between model in-
terfaces.
• Simulation – Subsystem for running simulations and specifying simulation parameters start and stop time,
etc.
• Plotting – Interface to plot variables from simulated models.
2.1.2 Linux
Start OMEdit by either selecting the corresponding menu application item or typing “OMEdit” at the shell or
command prompt.
2.1.3 Mac OS X
The default installation is /Application/MacPorts/OMEdit.app.
27
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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.
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.
2.3 Perspectives
The perspective tabs are loacted at the bottom right of the MainWindow:
• 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 2.6. 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.
2.3. Perspectives 33
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
2.3. Perspectives 35
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
• Open Directory - Loads the files of a directory recursively. The files are loaded as text files.
• Save - Saves the class.
• Save As - Save as the class.
• Save Total - Saves the class and all the classes it uses in a single file. The class and its dependencies can
only be loaded later by using the loadFile() API function in a script. Allows third parties to reproduce an
issue with a class without worrying about library dependencies.
• Import
• FMU - Imports the FMU.
• FMU Model Description - Imports the FMU model description.
• From OMNotbook - Imports the Modelica models from OMNotebook.
• Ngspice netlist - Imports the ngspice netlist to Modelica code.
• "Export"
• To Clipboard - Exports the current model to clipboard.
• Image - Exports the current model to image.
• FMU - Exports the current model to FMU.
• Read-only Package - Exports a zipped Modelica library with file extension .mol
• Encrypted Package - Exports an encrypted package. see OpenModelica Encryption
• XML - Exports the current model to a xml file.
• Figaro - Exports the current model to Figaro.
• To OMNotebook - Exports the current model to a OMNotebook file.
• System Libraries - Contains a list of system libraries.
• Recent Files - Contains a list of recent files.
• Clear Recent Files - Clears the list of recent files.
• Print - Prints the current model.
• Quit - Quit the OpenModelica Connection Editor.
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.
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 ( ).
Array Plot
Plots an array variable so that the array elements’ indexes are on the x-axis and corresponding elements’ values
are on the y-axis. The time is controlled by the slider above the variable tree. When an array is present in the
model, it has a principal array node in the variable tree. To plot this array as an Array Plot, match the principal
node. The principal node may be expanded into particular array elements. To plot a single element in the Time
Plot, match the element. A new Array Plot window is opened using the New Array Plot Window toolbar button
( ).
Plots the first array elements’ values on the x-axis versus the second array elements’ values on the y-axis. The
time is controlled by the slider above the variable tree. To create a new Array Parametric Plot, press the New
Array Parametric Plot Window toolbar button ( ), then match the principle array node in the variable tree view
to be plotted on the x-axis and match the principle array node to be plotted on the y-axis.
Diagram Window
Shows the active ModelWidget as a read only diagram. You can only have one Diagram Window. To show it click
on Diagram Window toolbar button ( ).
2.16 3D Visualization
Since OpenModelica 1.11 , OMEdit has built-in 3D visualization, which replaces third-party libraries (such as
Modelica3D) for 3D visualization.
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.
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.
2.16. 3D Visualization 45
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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.
Interactive simulation is enabled by selecting interactive simulation in the General tab of the simulation setup.
There are two main modes of execution: asynchronous and synchronous (simulate with steps). The difference is
that in synchronous (step mode), OMEdit sends a command to the simulation for each step that the simulation
should take. The asynchronous mode simply tells the simulation to run and samples variables values in real-time;
if the simulation runs very fast, fewer values will be sampled.
When running in asynchronous mode, it is possible to simulate the model in real-time (with a scaling factor just
like simulation flag -rt, but with the ability to change the scaling factor during the interactive simulation). In the
synchronous mode, the speed of the simulation does not directly correspond to real-time.
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.
end testModel;
In the above code snippet of testModel, the rectangle and a polygon are added to the icon annotation of the model.
Similarly, any user defined shape drawn on a Diagram View of the model will be added to the diagram annotation
of the model.
package P
model M
annotation(Documentation(info="<html>
<a href=\"javascript:HelloWorld()\">Click here</a>
</html>"));
end M;
annotation(Documentation(__OpenModelica_infoHeader="
<script type=\"text/javascript\">
function HelloWorld() {
alert(\"Hello World!\");
}
</script>"));
end P;
In the above example model M does not need to define the javascript function HelloWorld. It is only defined
once at the package level using the __OpenModelica_infoHeader and then all classes contained in the
package can use it.
In addition styles and JavaScript can be added from file locations using Modelica URIs. Example:
package P
model M
annotation(Documentation(info="<html>
<a href=\"javascript:HelloWorld()\">Click here</a>
</html>"));
end M;
annotation(Documentation(__OpenModelica_infoHeader="
<script type=\"text/javascript\">
src=\"modelica://P/Resources/hello.js\">
}
</script>"));
end P;
function HelloWorld() {
alert("Hello World!");
}
2.21 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.
2.21.1 General
• 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 posi-
tions 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
annotations are always active for encrypted libraries.
• Libraries Browser
• Library Icon Size – Sets the size for library icons.
• Show Protected Classes – If enabled then Libraries Browser will also list the protected classes.
• 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 de-
fined then this setting is used to show the respective view when user double clicks on the class in the
Libraries Browser.
• Enable Auto Save
• Auto Save interval – Sets the auto save interval value. The minimum possible interval value is 60 seconds.
• Enable Auto Save for single classes – Enables the auto save for one class saved in one file.
• Enable Auto Save for one file packages – Enables the auto save for packages saved in one file.
• Welcome Page
• Horizontal View/Vertical View – Sets the view mode for welcome page.
• Show Latest News – if true then displays the latest news.
2.21.2 Libraries
• System Libraries – The list of system libraries that should be loaded every time OMEdit starts.
• Force loading of Modelica Standard Library – If true then Modelica and ModelicaReference will always
load even if user has removed them from the list of system libraries.
• Load OpenModelica library on startup – If true then OpenModelica package will be loaded when OMEdit
is started.
• User Libraries – The list of user libraries/files that should be loaded every time OMEdit starts.
2.21. Options 51
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
2.21.9 Simulation
• 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 pedantic debug-mode, to get much more feedback
• Enable parallelization of independent systems of equations (Experimental)
• Enable experimental new instantiation phase
• 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.
2.21. Options 53
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
2.21.10 Messages
• 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.
• Font and Colors
• Font Family – Sets the font for the messages.
• Font Size – Sets the font size for the messages.
• Notification Color – Sets the text color for notification messages.
• Warning Color – Sets the text color for warning messages.
• Error Color – Sets the text color for error messages.
2.21.11 Notifications
• 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 defined as partial and component will be 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.
2.21.14 Plotting
• General
• Auto Scale – sets whether to auto scale the plots or not.
• 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.
2.21.15 Figaro
• Figaro
• Figaro Library – the Figaro library file path.
• Tree generation options – the Figaro tree generation options file path.
• Figaro Processor – the Figaro processor location.
2.21.16 Debugger
• 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.
2.21. Options 55
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
• 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.
2.21.17 FMI
• 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.
• Platforms - list of platforms to generate FMU binaries.
• Import
• Delete FMU directory and generated model when OMEdit is closed - If true then the temporary FMU
directory that is created for importing the FMU will be deleted.
2.21.18 OMTLMSimulator
• General
• Path - path to OMTLMSimulator bin directory.
• Manager Process - path to OMTLMSimulator managar process.
• Monitor Process - path to OMTLMSimulator monitor process.
2.21.19 OMSimulator
• General
• Working Directory - working directory for OMSimulator files.
• Logging Level - OMSimulator logging level.
model Test
annotation(__OpenModelica_commandLineOptions = "--matchingAlgorithm=BFSB --
˓→indexReductionMethod=dynamicStateSelection");
end Test;
The annotation is a space separated list of options where each option is either just a command line flag or a flag
with a value.
In OMEdit open the Simulation Setup and set the Translation Flags then in the bottom check Save translation
flags inside model i.e., __OpenModelica_commandLineOptions annotation and click on OK.
If you want to ignore this annotation then use setCommandLineOptions("–
ignoreCommandLineOptionsAnnotation=true"). In OMEdit Tools > Options > Simulation check Ignore
__OpenModelica_commandLineOptions annotation.
model Test
annotation(__OpenModelica_simulationFlags(s = "heun", cpu = "()"));
end Test;
The annotation is a comma separated list of options where each option is a simulation flag with a value. For flags
that doesn’t have any value use () (See the above code example).
In OMEdit open the Simulation Setup and set the Simulation Flags then in the bottom check Save simulation flags
inside model i.e., __OpenModelica_simulationFlags annotation and click on OK.
If you want to ignore this annotation then use setCommandLineOptions("–
ignoreSimulationFlagsAnnotation=true"). In OMEdit Tools > Options > Simulation check Ignore __OpenMod-
elica_simulationFlags annotation.
2.24 Debugger
For debugging capability, see Debugging.
In order to make a transition from one state to another the user first needs to enable the transition mode ( ) from
the toolbar.
Move the mouse over the state. The mouse cursor will change from arrow cursor to cross cursor. To start the
transition press left button and move while keeping the button pressed. Now release the left button. Move towards
the end state and click when cursor changes to cross cursor.
A Create Transition dialog box will appear which allows you to set the transition attributes. Cancelling the dialog
will cancel the transition.
Double click the transition or right click and choose Edit Transition to modify the transition attributes.
THREE
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.
3.1 Example
class HelloWorld
Real x(start = 1, fixed = true);
parameter Real a = 1;
equation
der(x) = - a * x;
end HelloWorld;
To create a simple time plot the above model HelloWorld is simulated. To reduce the amount of simulation data in
this example the number of intervals is limited with the argument numberOfIntervals=5. The simulation is started
with the command below.
record SimulationResult
resultFile = "«DOCHOME»/HelloWorld_res.csv",
simulationOptions = "startTime = 0.0, stopTime = 4.0, numberOfIntervals = 5,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'HelloWorld', options = '',
When the simulation is finished the file HelloWorld_res.csv contains the simulation data:
67
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Diagrams are now created with the new OMPlot program by using the following plot command:
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.
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 3.2: Simple 2D plot of the HelloWorld example with a larger number of output points.
68 Chapter 3. 2D Plotting
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
>>> list(OpenModelica.Scripting.plot,interfaceOnly=true)
"function plot
input VariableNames vars \"The variables you want to plot\";
input Boolean externalWindow = false \"Opens the plot in a new plot window\";
input String fileName = \"<default>\" \"The filename containing the variables.
˓→<default> will read the last simulation result\";
input String title = \"\" \"This text will be used as the diagram title.\";
input String grid = \"detailed\" \"Sets the grid for the plot i.e simple,
˓→detailed, none.\";
input Boolean logX = false \"Determines whether or not the horizontal axis is
˓→logarithmically scaled.\";
input Boolean logY = false \"Determines whether or not the vertical axis is
˓→logarithmically scaled.\";
input String xLabel = \"time\" \"This text will be used as the horizontal label
˓→in the diagram.\";
input String yLabel = \"\" \"This text will be used as the vertical label in the
˓→diagram.\";
input Real xRange[2] = {0.0, 0.0} \"Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.\";
input Real yRange[2] = {0.0, 0.0} \"Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.\";
input String legendPosition = \"top\" \"Sets the POSITION of the legend i.e left,
˓→ right, top, bottom, none.\";
input String footer = \"\" \"This text will be used as the diagram footer.\";
input Boolean autoScale = true \"Use auto scale while plotting.\";
input Boolean forceOMPlot = false \"if true launches OMPlot and doesn't call
˓→callback function even if it is defined.\";
70 Chapter 3. 2D Plotting
CHAPTER
FOUR
4.1.1 DASSL
DASSL is the default solver in OpenModelica, because of a severals reasons. It is an implicit, higher order,
multi-step solver with a step-size control and with these properties it is quite stable for a wide range of models.
Furthermore it has a mature source code, which was originally developed in the eighties an initial description may
be found in [Pet82].
This solver is based on backward differentiation formula (BDF), which is a family of implicit methods for numer-
ical integration. The used implementation is called DASPK2.0 (see2 ) and it is translated automatically to C by f2c
(see3 ).
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.
4.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.
2 DASPK Webpage
3 Cdaskr source
71
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
4.2.1 References
FIVE
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.
73
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
74 Chapter 5. Debugging
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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).
76 Chapter 5. Debugging
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
78 Chapter 5. Debugging
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
80 Chapter 5. Debugging
CHAPTER
SIX
The system of equations after symbolic transformation is represented by a graph. OpenModelica can generate
graph representations which can be displayed in the graph tool yed (http://www.yworks.com/products/yed). The
graph generation is activated with the debug flag
+d=graphml
Two different graphml- files are generated in the working directory. TaskGraph_model.graphml, showing the
strongly-connected components of the model and BipartiteGraph_CompleteDAE_model.graphml showing all
variables and equations. When loading the graphs with yEd, all nodes are in one place. Please use the various
layout algorithms to get a better overview.
81
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
SEVEN
true
>>> translateModelFMU(BouncingBall)
"«DOCHOME»/BouncingBall.fmu"
>>> system("unzip -l BouncingBall.fmu | egrep -v 'sources|files' | tail -n+3 |
˓→grep -o '[A-Za-z._0-9/]*$' > BB.log")
After the command execution is complete you will see that a file BouncingBall.fmu has been created. Its contents
varies depending on the current platform. On the machine generating this documentation, the contents in Listing
7.1 are generated (along with the C source code).
A log file for FMU creation is also generated named ModelName_FMU.log. If there are some errors while creating
FMU they will be shown in the command line window and logged in this log file as well.
By default an FMU that can be used for both Model Exchange and Co-Simulation is generated. We only support
FMI 2.0 for Co-Simulation FMUs.
83
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Currently the Co-Simulation FMU supports only the forward Euler solver with root finding which does an
Euler step of communicationStepSize in fmi2DoStep. Events are checked for before and after the call to
fmi2GetDerivatives.
input Boolean fullPath = false "When true the full output path is returned
˓→otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
The command could be used from command line interface, OMShell, OMNotebook or MDT. The importFMU
command is also integrated with OMEdit. Select FMI > Import FMU the FMU package is extracted in the
directory specified by workdir, since the workdir parameter is optional so if its not specified then the current
directory of omc is used. You can use the cd() command to see the current location.
The implementation supports FMI for Model Exchange 1.0 & 2.0 and FMI for Co-Simulation 1.0 stand-alone.
The support for FMI Co-Simulation is still under development.
The FMI Import is currently a prototype. The prototype has been tested in OpenModelica with several examples.
It has also been tested with example FMUs from FMUSDK and Dymola. A more fullfleged version for FMI
Import will be released in the near future.
When importing the model into OMEdit, roughly the following commands will be executed:
>>> imported_fmu_mo_file:=importFMU("BouncingBall.fmu")
"BouncingBall_me_FMU.mo"
>>> loadFile(imported_fmu_mo_file)
true
The imported FMU can then be simulated like any normal model:
˓→= ''",
1
h
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3
• 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 7.3)
The TLM Co-Simulation setup appears as shown below in Figure 7.4.
Click Simulate from the Co-simulation setup to confirm the co-simulation. Figure 7.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.
Figure 7.3: Co-simulating and Fetching Interface Data of a composite model from the Popup Menu .
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 7.9) includes the
composite model XML elements and the default simulation parameters.
• 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 7.3).
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 7.12.
• Click Simulation Parameters button ( t0 t1) from the toolbar (requires a composite model to be active in
ModelWidget)
• Right click an empty location in the Diagram View of the composite model and choose Simulation Param-
eters from the popup menu (see Figure 7.16)
The co-simulation parameter dialog of the composite model appears as shown below in Figure 7.17 in which you
will be able to specify the simulation parameters.
100 Chapter 7. FMI and TLM-Based Simulation and Co-simulation of External Models
CHAPTER
EIGHT
OMSIMULATOR
101
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
NINE
OPENMODELICA ENCRYPTION
The encryption module allows the library developers to encrypt their libraries for different platforms. Note that
you need a special version of OpenModelica with encryption support. Contact us if you want one.
9.3 Notes
• There is no license management and obfuscation of the generated code and files. However just a basic
encryption and decryption is supported along with full support for protection access annotation as defined
in Modelica specification 18.9. This means that anyone who has an OpenModelica version with encryption
support can encrypt or decrypt files.
• OpenModelica encryption is based on SEMLA (Safe/Superiour/Super Encryption of Modelica Libraries
and Artifacts) module from Modelon AB.
103
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
TEN
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.
10.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 10.1.
Figure 10.1: Examples of Mathematica notebooks in the MathModelica modeling and simulation environment.
105
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Traditional documents, e.g. books and reports, essentially always have a hierarchical structure. They are divided
into sections, subsections, paragraphs, etc. Both the document itself and its sections usually have headings as
labels for easier navigation. This kind of structure is also reflected in electronic notebooks. Every notebook
corresponds to one document (one file) and contains a tree structure of cells. A cell can have different kinds of
contents, and can even contain other cells. The notebook hierarchy of cells thus reflects the hierarchy of sections
and subsections in a traditional document such as a book.
Figure 10.2: The front-page notebook of the OMNotebook version of the DrModelica tutoring system.
Figure 10.3: The HelloWorld class simulated and plotted using the OMNotebook version of DrModelica.
Figure 10.4: DrModelica Chapter on Algorithms and Functions in the main page of the OMNotebook version of
DrModelica.
The front-page of DrControl resembles a linked table of content that can be used as a navigation center. The
content list contains topics like:
• Getting started
• The control problem in ordinary life
• Feedback loop
• Mathematical modeling
• Transfer function
• Stability
• Example of controlling a DC-motor
• Feedforward compensation
• State-space form
• State observation
• Closed loop control system.
• Reconstructed system
• Linear quadratic optimization
• Linearization
Each entry in this list leads to a new notebook page where either the theory is explained with Modelica examples
or an exercise with a solution is provided to illustrate the background theory. Below we show a few sections of
DrControl.
𝑚𝑦˙ = 𝑢 − 𝛼𝑦 − 𝑚𝑔 * 𝑠𝑖𝑛(𝜃)
model noFeedback
import SI = Modelica.SIunits;
SI.Velocity y; // output signal without noise,
˓→theta = 0 -> v(t) = 0
By applying a road slope angle different from zero the car velocity is influenced which can be regarded as noise in
this model. The output signal in Figure 10.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.
>>> loadModel(Modelica)
true
>>> simulate(noFeedback, stopTime=100)
record SimulationResult
resultFile = "«DOCHOME»/noFeedback_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 100.0, numberOfIntervals =
˓→500, tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'noFeedback', options
˓→= '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization.
In OMEdit Tools->Options->Simulation->OMCFlags, in OMNotebook call setCommandLineOptions("-
d=initialization").
𝑢 = 𝐾 * (𝑟 − 𝑦)
model withFeedback
import SI = Modelica.SIunits;
SI.Velocity y; // output signal with feedback
˓→link and without noise, theta = 0 -> v(t) = 0
25
y
yNoise
20
15
10
0
0 20 40 60 80 100
By using the information about the current level of the output signal and re-tune the regulator the output quantity
can be controlled towards the reference signal smoothly and without an overshoot, as shown in Figure 10.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.
>>> loadModel(Modelica)
true
>>> simulate(withFeedback, stopTime=10)
record SimulationResult
resultFile = "«DOCHOME»/withFeedback_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 10.0, numberOfIntervals = 500,
˓→ tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'withFeedback', options =
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization.
In OMEdit Tools->Options->Simulation->OMCFlags, in OMNotebook call setCommandLineOptions("-
d=initialization").
20
y
18 yNoise
16
14
12
10
0
0 2 4 6 8 10
𝑦¨ + 𝑎1 𝑦˙ + 𝑎2 𝑦 = 1
model NegRoots
Real y;
Real der_y;
parameter Real a1 = 3;
parameter Real a2 = 2;
equation
der_y = der(y);
der(der_y) + a1*der_y + a2*y = 1;
end NegRoots;
Choosing different values for a1 and a2 leads to different behavior as shown in Figure 10.11 and Figure 10.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 10.11.
>>> simulate(NegRoots, stopTime=10)
record SimulationResult
resultFile = "«DOCHOME»/NegRoots_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 10.0, numberOfIntervals = 500,
˓→ tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'NegRoots', options = '',
Warning:
Warning: The initial conditions are not fully specified. For more information set -d=initialization.
In OMEdit Tools->Options->Simulation->OMCFlags, 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 10.11 and Figure
10.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->OMCFlags, in OMNotebook call setCommandLineOptions("-
d=initialization").
1500
y
1000
500
-500
-1000
-1500
0 2 4 6 8 10
Figure 10.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.
10.4.1 Cells
Everything inside an OMNotebook document is made out of cells. A cell basically contains a chunk of data. That
data can be text, images, or other cells. OMNotebook has four types of cells: headercell, textcell, inputcell, and
groupcell. Cells are ordered in a tree structure, where one cell can be a parent to one or more additional cells. A
tree view is available close to the right border in the notebook window to display the relation between the cells.
• Textcell – This cell type is used to display ordinary text and images. Each textcell has a style that spec-
ifies how text is displayed. The cell´s style can be changed in the menu Format->Styles, example of
different styles are: Text, Title, and Subtitle. The Textcell type also has support for following links to
other notebook documents.
• Inputcell – This cell type has support for syntax highlighting and evaluation. It is intended to be used
for writing program code, e.g. Modelica code. Evaluation is done by pressing the key combina-
tion Shift+Return or Shift+Enter. All the text in the cell is sent to OMC (OpenModelica Com-
piler/interpreter), where the text is evaluated and the result is displayed below the inputcell. By
double-clicking on the cell marker in the tree view, the inputcell can be collapsed causing the result to
be hidden.
• Latexcell – This cell type has support for evaluation of latex scripts. It is intended to be mainly used for
writing mathematical equations and formulas for advanced documentation in OMNotebook. Each La-
texcell supports a maximum of one page document output.To evaluate this cell, latex must be installed
in your system.The users can copy and paste the latex scripts and start the evaluation.Evaluation is
done by pressing the key combination Shift+Return or Shift+Enter or the green color eval button
present in the toolbar. The script in the cell is sent to latex compiler, where it is evaluated and the
output is displayed hiding the latex source. By double-clicking on the cell marker in the tree view,the
latex source is displayed for further modification.
• Groupcell – This cell type is used to group together other cell. A groupcell can be opened or closed.
When a groupcell is opened all the cells inside the groupcell are visible, but when the groupcell is
closed only the first cell inside the groupcell is visible. The state of the groupcell is changed by the
user double-clicking on the cell marker in the tree view. When the groupcell is closed the marker is
changed and the marker has an arrow at the bottom.
10.4.2 Cursors
An OMNotebook document contains cells which in turn contain text. Thus, two kinds of cursors are needed for
positioning, text cursor and cell cursor:
• Textcursor – A cursor between characters in a cell, appearing as a small vertical line. Position the cur-
sor by clicking on the text or using the arrow buttons.
• Cellcursor – This cursor shows which cell currently has the input focus. It consists of two parts. The
main cellcursor is basically just a thin black horizontal line below the cell with input focus. The
cellcursor is positioned by clicking on a cell, clicking between cells, or using the menu item Cell-
>Next Cell or Cell->Previous Cell. The cursor can also be moved with the key combination Ctrl+Up
or Ctrl+Down. The dynamic cellcursor is a short blinking horizontal line. To make this visible, you
must click once more on the main cellcursor (the long horizontal line). NOTE: In order to paste cells
at the cellcursor, the dynamic cellcursor must be made active by clicking on the main cellcursor (the
horizontal line).
• 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 se-
lected 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.
• Paste cell – To paste copied or cut cells the cell cursor must be selected in the location where the cells
should be pasted. This is done by clicking on the cell cursor. Pasteing cells is done from the menu
Edit->Paste or the key combination Ctrl+V. If the cell cursor is selected the paste function will always
paste cells. OMNotebook share the same application-wide clipboard. Therefore cells that have been
copied from one document can be pasted into another document. Only pointers to the copied or cut
cells are added to the clipboard, thus the cell that should be pasted must still exist. Consequently a cell
can not be pasted from a document that has been closed.
• Find – Find text string in the current notebook, with the options match full word, match cell, search
within closed cells. Short command Ctrl+F.
• Replace – Find and replace text string in the current notebook, with the options match full word,
match cell, search+replace within closed cells. Short command Ctrl+H.
• View expression – Text in a cell is stored internally as a subset of HTML code and the menu item Edit-
>View Expression let the user switch between viewing the text or the internal HTML representation.
Changes made to the HTML code will affect how the text is displayed.
• Evaluate several cells – Several inputcells can be evaluated at the same time by selecting them in the
treeview and then pressing the key combination Shift+Enter or Shift+Return. The cells are evalu-
ated in the same order as they have been selected. If a groupcell is selected all inputcells in that
groupcell are evaluated, in the order they are located in the groupcell.
• Moving and Reordering cells in a Notebook – It is possible to shift cells to a new position and change the
hierarchical order of the document.This can be done by clicking the cell and press the Up and Down
arrow button in the tool bar to move either Up or Down. The cells are moved one cell above or below.It
is also possible to move a cell directly to a new position with one single click by pressing the red color
bidirectional UpDown arrow button in the toolbar. To do this the user has to place the cell cursor to
a position where the selected cells must be moved. After selecting the cell cursor position, select the
cells you want to shift and press the bidirectional UpDown arrow button. The cells are shifted in the
same order as they are selected.This is especially very useful when shifting a group cell.
• Command completion – Inputcells have command completion support, which checks if the user is typ-
ing a command (or any keyword defined in the file commands.xml) and finish the command. If the user
types the first two or three letters in a command, the command completion function fills in the rest. To
use command completion, press the key combination Ctrl+Space or Shift+Tab. The first command that
matches the letters written will then appear. Holding down Shift and pressing Tab (alternative holding
down Ctrl and pressing Space) again will display the second command that matches. Repeated request
to use command completion will loop through all commands that match the letters written. When a
command is displayed by the command completion functionality any field inside the command that
should be edited by the user is automatically selected. Some commands can have several of these fields
and by pressing the key combination Ctrl+Tab, the next field will be selected inside the command. >
Active Command completion: Ctrl+Space / Shift+Tab > Next command: Ctrl+Space / Shift+Tab >
Next field in command: Ctrl+Tab’
• Generated plot – When plotting a simulation result, OMC uses the program Ptplot to create a plot.
From Ptplot OMNotebook gets an image of the plot and automatically adds that image to the out-
put part of an inputcell. Like all other images in a document, the plot is saved in the document file
when the document is saved.
• Stylesheet –OMNotebook follows the style settings defined in stylesheet.xml and the correct style is ap-
plied to a cell when the cell is created.
• Automatic Chapter Numbering – OMNotebook automatically numbers different chapter, subchapter,
section and other styles. The user can specify which styles should have chapter numbers and which
level the style should have. This is done in the stylesheet.xml file. Every style can have a <chapter-
Level> tag that specifies the chapter level. Level 0 or no tag at all, means that the style should not have
any chapter numbering.
• Scrollarea – Scrolling through a document can be done by using the mouse wheel. A document can
also be scrolled by moving the cell cursor up or down.
• Syntax highlighter – The syntax highlighter runs in a separated thread which speeds up the loading of
large document that contains many Modelica code cells. The syntax highlighter only highlights when
letters are added, not when they are removed. The color settings for the different types of keywords
are stored in the file modelicacolors.xml. Besides defining the text color and background color of
keywords, whether or not the keywords should be bold or/and italic can be defined.
• Change indicator – A star (*) will appear behind the filename in the title of notebook window if the
document has been changed and needs saving. When the user closes a document that has some un-
saved change, OMNotebook asks the user if he/she wants to save the document before closing. If the
document never has been saved before, the save-as dialog appears so that a filename can be choosen
for the new document.
• Update menus – All menus are constantly updated so that only menu items that are linked to actions
that can be performed on the currently selected cell is enabled. All other menu items will be dis-
abled. When a textcell is selected the Format menu is updated so that it indicates the text settings for
the text, in the current cursor position.
10.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.
ELEVEN
The following facilities for model-based optimization are provided with OpenModelica:
• Builtin Dynamic Optimization with OpenModelica and IpOpt using dynamic optimization is the recom-
mended 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.
11.3 An Example
In this section, a simple optimal control problem will be solved. When formulating the optimization problems,
models are expressed in the Modelica language and optimization specifications. The optimization language spec-
ification allows users to formulate dynamic optimization problems to be solved by a numerical algorithm. It
includes several constructs including a new specialized class optimization, a constraint section, startTime, final-
Time etc. See the optimal control problem for batch reactor model below.
129
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Create a new file named BatchReactor.mo and save it in you working directory. Notice that this model contains
both the dynamic system to be optimized and the optimization specification.
Once we have formulated the undelying optimal control problems, we can run the optimization by using OMShell,
OMNotebook, MDT, OMEdit using command line terminals similar to the options described below:
>>> setCommandLineOptions("-g=Optimica");
optimization nmpcBatchReactor(objective=-x2)
extends BatchReactor;
end nmpcBatchReactor;
˓→= ''",
Optimizer Variables
========================================================
State[0]:x1(start = 1, nominal = 1, min = 0, max = 1, init = 1)
State[1]:x2(start = 0, nominal = 1, min = 0, max = 1, init = 0)
Input[2]:u(start = 0, nominal = 5, min = 0, max = 5)
--------------------------------------------------------
number of nonlinear constraints: 0
========================================================
******************************************************************************
This program contains Ipopt, a library for large-scale nonlinear optimization.
Ipopt is released as open source code under the Eclipse Public License (EPL).
For more information visit http://projects.coin-or.org/Ipopt
******************************************************************************
5
u
4.5
3.5
2.5
1.5
0.5
0 0.2 0.4 0.6 0.8 1
Figure 11.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 11.2: Optimization results for Batch Reactor model – state variables.
Table 11.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
11.5.2 An example
In this section, a simple optimal control problem will be solved. When formulating the optimization problems,
models are expressed in the Modelica language and optimization specifications. The optimization language spec-
ification allows users to formulate dynamic optimization problems to be solved by a numerical algorithm. It
includes several constructs including a new specialized class optimization, a constraint section, startTime, final-
Time etc. See the optimal control problem for batch reactor model below.
Create a new file named BatchReactor.mo and save it in you working directory. Notice that this model contains
both the dynamic system to be optimized and the optimization specification.
>>> list(BatchReactor)
model BatchReactor
Real x1(start = 1, fixed = true, min = 0, max = 1);
Real x2(start = 0, fixed = true, min = 0, max = 1);
input Real u(min = 0, max = 5);
equation
der(x1) = -(u + u ^ 2 / 2) * x1;
der(x2) = u * x1;
end BatchReactor;
One we have formulated the undelying optimal control problems, we can export the XML by using OMShell,
OMNotebook, MDT, OMEdit or command line terminals which are described in Section XML Import to CasADi
via OpenModelica Python Script.
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 11.2) that contains a symbolic representation of
the optimal control problem and can be inspected in a standard XML editor.
<VendorAnnotations>
<Tool name="OpenModelica Compiler OMCompiler v1.14.2-v1.14.2.6+g5c52d52477"> </
˓→Tool>
</VendorAnnotations>
<ModelVariables>
<ScalarVariable name="x1" valueReference="0" variability="continuous"
˓→causality="internal" alias="noAlias">
<Real />
<QualifiedName>
<exp:QualifiedNamePart name="x1"/>
</QualifiedName>
<isLinearTimedVariables>
<TimePoint index="0" isLinear="true"/>
</isLinearTimedVariables>
<VariableCategory>derivative</VariableCategory>
</ScalarVariable>
<equ:BindingEquations>
</equ:BindingEquations>
<equ:DynamicEquations>
<equ:Equation>
<exp:Sub>
<exp:Der>
<exp:Identifier>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
</exp:Der>
(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>
(continues on next page)
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
</exp:Sub>
</equ:Equation>
<equ:Equation>
<exp:Sub>
<exp:Identifier>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
<exp:Identifier>
<exp:QualifiedNamePart name="$START"/>
<exp:QualifiedNamePart name="x2"/>
</exp:Identifier>
</exp:Sub>
</equ:Equation>
</equ:InitialEquations>
<fun:Algorithm>
</fun:Algorithm>
<fun:RecordsList>
</fun:RecordsList>
<fun:FunctionsList>
</fun:FunctionsList>
<opt:Optimization>
<opt:TimePoints>
<opt:TimePoint >
</opt:TimePoint>
</opt:TimePoints>
<opt:PathConstraints>
</opt:PathConstraints>
</opt:Optimization>
</OpenModelicaModelDescription>
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
1. 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:
Parameters
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 con-
stant during all simulation time.
• The corresponding variable should play an input role in the model i.e. its modification influences
model simulation results.
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.
Objectives
As parameters, objectives are picked up from model variables. Objectives’ values are considered by the optimizer
at the final time.
Launch OMOptim
Load models
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.
Dependencies
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 11.3.
Problem->Add Problem->Optimization
A dialog should appear. Select the model you want to optimize. Only Model can be selected (no Package,
Component, Block. . . ).
A new form will be displayed. This form has two tabs. One is called Variables, the other is called Optimization.
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.
Select objectives
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 maximum equals to “-“ : it will
then
• Define whether objective should be minimized or maximized.
Figure 11.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 generations, 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 optimization is finished.
• ReinitStdDev: this is a specific parameter of EAAdapt1. It defines whether standard deviation of vari-
ables should be reinitialized. It is used only if you start optimization from previously obtained con-
figurations (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.
Use start file
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.
Launch
Stopping Optimization
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.
11.6.3 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).
TWELVE
This section describes the use of OpenModelica to compute parameter sensitivities using forward sensitivity anal-
ysis together with the Sundials/IDA solver.
Note: this is a very short preliminary description which soon will be considerably improved, since this a rather
new feature and will continuous improved.
Note: OpenModelica version 1.10 or newer is required.
12.1 Background
Parameter sensitivity analysis aims at analyzing the behavior of the corresponding model states w.r.t. model
parameters.
Formally, consider a Modelica model as a DAE system:
𝐹 (𝑥, 𝑥,
˙ 𝑦, 𝑝, 𝑡) = 0 𝑥(𝑡0 ) = 𝑥0 (𝑝)
12.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:
145
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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.
| quoted string, starting with ’ ending with ’})} Dict:(Group:({{{W:(ABCD...,ABCD...) | quoted string, start-
ing with ’ ending with ’} Suppress:("=")} Forward: {{{{{{{{{quoted string, starting with " ending with
" | Combine:({{{["-"] {"0" | W:(1234...,0123...)}} [{"." W:(0123...)}]} [{W:(eE) W:(0123...,0123...)}]})}
| Forward: None} | Group:({{Suppress:("{") [Forward: None [, Forward: None]...]} Suppress:("}")})} |
Group:({{Suppress:("(") [Forward: None [, Forward: None]...]} Suppress:(")")})} | {{{Suppress:("SOME")
Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"} | {{"NONE" Suppress:("(")} Sup-
press:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with
’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "."} Forward:
...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | {W:(ABCD...,ABCD...) |
quoted string, starting with ’ ending with ’}})}}) [, Group:({{{W:(ABCD...,ABCD...) | quoted string, start-
ing with ’ ending with ’} Suppress:("=")} Forward: {{{{{{{{{quoted string, starting with " ending with
" | Combine:({{{["-"] {"0" | W:(1234...,0123...)}} [{"." W:(0123...)}]} [{W:(eE) W:(0123...,0123...)}]})}
| Forward: None} | Group:({{Suppress:("{") [Forward: None [, Forward: None]...]} Suppress:("}")})} |
Group:({{Suppress:("(") [Forward: None [, Forward: None]...]} Suppress:(")")})} | {{{Suppress:("SOME")
Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"} | {{"NONE" Suppress:("(")} Sup-
press:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ end-
ing with ’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with
’} "."} Forward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} |
{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})}})]...)} Suppress:("end")} Sup-
press:(Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." For-
ward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." Forward: ...} |
{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | W:(ABCD...,ABCD...) | quoted
string, starting with ’ ending with ’})} Suppress:(";")})} | Group:({{Suppress:("{") [Forward: None [, For-
ward: None]...]} Suppress:("}")})} | Group:({{Suppress:("(") [Forward: None [, Forward: None]...]} Sup-
press:(")")})} | {{{Suppress:("SOME") Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"} |
{{"NONE" Suppress:("(")} Suppress:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted string,
starting with ’ ending with ’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ end-
ing with ’} "."} Forward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} |
{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})} Suppress:(")")} | "true" | "false"
| {"NONE" Suppress:("(") Suppress:(")")} | Combine:(Forward: {{{W:(ABCD...,ABCD...) | quoted string,
starting with ’ ending with ’} "." Forward: ...} | W:(ABCD...,ABCD...) | quoted string, starting with ’ end-
ing with ’})} (at char 1), (line:2, col:1) Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-
packages/pyparsing.py", line 1562, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions
) File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 3235, in parseImpl result = instring[loc] ==
self.firstQuoteChar and self.re.match(instring,loc) or None IndexError: string index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/var/lib/jenkins/ws/OpenModelica_maintenance_v1.14/doc/UsersGuide/source/sphinxcontr
line 173, in run filename = os.path.abspath(self.options.get(’filename’) or
omc.sendExpression("currentSimulationResult")) File "/usr/local/lib/python3.6/dist-
packages/OMPython/__init__.py", line 606, in sendExpression answer = OMTypedParser.parseString(result)
File "/usr/local/lib/python3.6/dist-packages/OMPython/OMTypedParser.py", line 120, in parseString return
omcGrammar.parseString(string)[0] File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1828, in
parseString raise exc File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1818, in parseString loc,
tokens = self._parse( instring, 0 ) File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1562, in
_parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/usr/local/lib/python3.6/dist-
packages/pyparsing.py", line 3735, in parseImpl loc, resultlist = self.exprs[0]._parse( instring, loc,
doActions, callPreParse=False ) File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1562, in
_parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/usr/local/lib/python3.6/dist-
packages/pyparsing.py", line 4098, in parseImpl return self.expr._parse( instring, loc, doActions, call-
PreParse=False ) File "/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1562, in _parseNo-
Cache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/usr/local/lib/python3.6/dist-
packages/pyparsing.py", line 3917, in parseImpl raise maxException File "/usr/local/lib/python3.6/dist-
packages/pyparsing.py", line 3902, in parseImpl ret = e._parse( instring, loc, doActions ) File
"/usr/local/lib/python3.6/dist-packages/pyparsing.py", line 1564, in _parseNoCache raise ParseException( in-
string, len(instring), self.errmsg, self ) pyparsing.ParseException: Expected {quoted string, starting with " end-
ing with " | Combine:({["-"] {"0" | W:(1234...,0123...)} [{"." W:(0123...)}] [{W:(eE) W:(0123...,0123...)}]})
’ ending with ’}}} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})}}) [,
Group:({{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} Suppress:("=")} Forward:
{{{{{{{{{quoted string, starting with " ending with " | Combine:({{{["-"] {"0" | W:(1234...,0123...)}} [{"."
W:(0123...)}]} [{W:(eE) W:(0123...,0123...)}]})} | Forward: None} | Group:({{Suppress:("{") [Forward:
None [, Forward: None]...]} Suppress:("}")})} | Group:({{Suppress:("(") [Forward: None [, Forward:
None]...]} Suppress:(")")})} | {{{Suppress:("SOME") Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"}
| "false"} | {{"NONE" Suppress:("(")} Suppress:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...)
| quoted string, starting with ’ ending with ’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string,
starting with ’ ending with ’} "."} Forward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with
’ ending with ’}}} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})}})]...)}
Suppress:("end")} Suppress:(Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with
’} "." Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." Forward: ...} |
{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | W:(ABCD...,ABCD...) | quoted
string, starting with ’ ending with ’})} Suppress:(";")}) | Group:({Suppress:("{") [Forward: None [, Forward:
None]...] Suppress:("}")}) | Group:({Suppress:("(") [Forward: None [, Forward: None]...] Suppress:(")")})
| {Suppress:("SOME") Suppress:("(") Forward: {{{{{{{{{quoted string, starting with " ending with " |
Combine:({["-"] {"0" | W:(1234...,0123...)} [{"." W:(0123...)}] [{W:(eE) W:(0123...,0123...)}]})} | Forward:
Group:({{{{{Suppress:("record") Suppress:(Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with
’ ending with ’} "." Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." For-
ward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | W:(ABCD...,ABCD...)
| quoted string, starting with ’ ending with ’})} Dict:(Group:({{{W:(ABCD...,ABCD...) | quoted string,
starting with ’ ending with ’} Suppress:("=")} Forward: {{{{{{{{{quoted string, starting with " ending with
" | Combine:({{{["-"] {"0" | W:(1234...,0123...)}} [{"." W:(0123...)}]} [{W:(eE) W:(0123...,0123...)}]})}
| Forward: None} | Group:({{Suppress:("{") [Forward: None [, Forward: None]...]} Suppress:("}")})} |
Group:({{Suppress:("(") [Forward: None [, Forward: None]...]} Suppress:(")")})} | {{{Suppress:("SOME")
Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"} | {{"NONE" Suppress:("(")} Sup-
press:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with
’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "."} Forward:
...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | {W:(ABCD...,ABCD...)
| quoted string, starting with ’ ending with ’}})}}) [, Group:({{{W:(ABCD...,ABCD...) | quoted
string, starting with ’ ending with ’} Suppress:("=")} Forward: {{{{{{{{{quoted string, starting
with " ending with " | Combine:({{{["-"] {"0" | W:(1234...,0123...)}} [{"." W:(0123...)}]} [{W:(eE)
W:(0123...,0123...)}]})} | Forward: None} | Group:({{Suppress:("{") [Forward: None [, Forward: None]...]}
Suppress:("}")})} | Group:({{Suppress:("(") [Forward: None [, Forward: None]...]} Suppress:(")")})} |
{{{Suppress:("SOME") Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"} | {{"NONE"
Suppress:("(")} Suppress:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting
with ’ ending with ’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending
with ’} "."} Forward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}}
| {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})}})]...)} Suppress:("end")}
Suppress:(Forward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." For-
ward: {{{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’} "." Forward: ...} |
{W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}} | W:(ABCD...,ABCD...) | quoted
string, starting with ’ ending with ’})} Suppress:(";")})} | Group:({{Suppress:("{") [Forward: None [,
Forward: None]...]} Suppress:("}")})} | Group:({{Suppress:("(") [Forward: None [, Forward: None]...]}
Suppress:(")")})} | {{{Suppress:("SOME") Suppress:("(")} Forward: ...} Suppress:(")")}} | "true"} | "false"}
| {{"NONE" Suppress:("(")} Suppress:(")")}} | Combine:(Forward: {{{{W:(ABCD...,ABCD...) | quoted
string, starting with ’ ending with ’} "."} Forward: {{{{W:(ABCD...,ABCD...) | quoted string, starting with
’ ending with ’} "."} Forward: ...} | {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}}}
| {W:(ABCD...,ABCD...) | quoted string, starting with ’ ending with ’}})} Suppress:(")")} | "true" | "false"
| {"NONE" Suppress:("(") Suppress:(")")} | Combine:(Forward: {{{W:(ABCD...,ABCD...) | quoted string,
starting with ’ ending with ’} "." Forward: ...} | W:(ABCD...,ABCD...) | quoted string, starting with ’ ending
with ’})} (at char 1), (line:2, col:1)
THIRTEEN
PDEMODELICA1
PDEModelica1 is nonstandardised experimental Modelica language extension for 1-dimensional partial differen-
tial extensions (PDE).
It is enabled using compiler flag --grammar=PDEModelica. Compiler flags may be set e.g. in OMEdit
(Tools->Options->Simulation->OMC Flags) or in the OpenModelica script using command
Error:
[<interactive>:4:14-4:14:writable] Error: Missing token: SEMICOLON
The domain omega represents the geometrical domain where the PDE holds. The domain is defined using the
built-in record DomainLineSegment1D. This record contains among others L – the length of the domain, N –
the number of grid points, x – the coordinate variable and the regions left, right and interior, representing
the left and right boundaries and the interior of the domain.
The field variable u is defined using a new keyword field. The domain is a mandatory attribute to specify the
domain of the field.
The indomain operator specifies where the equation containing the field variable holds. It is utilised in the initial
conditions (IC) of the fields, in the PDE and in the boundary conditions (BC). The syntax is
If the region is omitted, interior is the default (e.g. the PDE in the example above).
The IC of the field variable u is written using an expression containing the coordinate variable omega.x.
153
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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.
13.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.
FOURTEEN
14.1 Introduction
The Modelica Development Tooling (MDT) Eclipse Plugin as part of OMDev – The OpenModelica Development
Environment integrates the OpenModelica compiler with Eclipse. MDT, together with the OpenModelica com-
piler, provides an environment for working with Modelica and MetaModelica development projects. This plugin
is primarily intended for tool developers rather than application Modelica modelers.
The following features are available:
• Browsing support for Modelica projects, packages, and classes
• Wizards for creating Modelica projects, packages, and classes
• Syntax color highlighting
• Syntax checking
• Browsing of the Modelica Standard Library or other libraries
• Code completion for class names and function argument lists
• Goto definition for classes, types, and functions
• Displaying type information when hovering the mouse over an identifier.
14.2 Installation
The installation of MDT is accomplished by following the below installation instructions. These instructions
assume that you have successfully downloaded and installed Eclipse (http://www.eclipse.org).
The latest installation instructions are available through the OpenModelica Trac.
1. Start Eclipse
2. Select Help->Software Updates->Find and Install... from the menu
3. Select ‘Search for new features to install’ and click ‘Next’
4. Select ‘New Remote Site...’
5. Enter ‘MDT’ as name and http://www.ida.liu.se/labs/pelab/modelica/OpenModelica/MDT as URL and click
‘OK’
6. Make sure ‘MDT’ is selected and click ‘Finish’
7. In the updates dialog select the ‘MDT’ feature and click ‘Next’
8. Read through the license agreement, select ‘I accept...’ and click ‘Next’
9. Click ‘Finish’ to install MDT
155
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
156 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
158 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Figure 14.3: Eclipse Setup – disable automatic build for the projects.
160 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Figure 14.7: Eclipse – Switching to another perspective – e.g. the Java Perspective.
162 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
164 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
The second variant is useful when typing a call to a function. It shows the function signature (formal param-
eter names and types) in a popup when typing the parenthesis after the function name, here the signature Real
sin(SI.Angle u) of the sin function:
Figure 14.12: Code completion at a function call when typing left parenthesis.
Figure 14.14: Code assistance when writing cases with records in MetaModelica.
166 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
168 Chapter 14. MDT – The OpenModelica Development Tooling Eclipse Plugin
CHAPTER
FIFTEEN
The algorithmic code debugger, used for the algorithmic subset of the Modelica language as well as the Meta-
Modelica language is described in Section The Eclipse-based Debugger for Algorithmic Modelica. Using this
debugger replaces debugging of algorithmic code by primitive means such as print statements or asserts which
is complex, time-consuming and error- prone. The usual debugging functionality found in debuggers for proce-
dural or traditional object-oriented languages is supported, such as setting and removing breakpoints, stepping,
inspecting variables, etc. The debugger is integrated with Eclipse.
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:
169
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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 15.6: Eclipse will ask if the user wants to switch to the debugging perspective.
SIXTEEN
A common problem when simulating models in an equation-based language like Modelica is that the model may
contain non-linear equation systems. These are solved in each time-step by extrapolating an initial guess and
running a non-linear system solver. If the simulation takes too long to simulate, it is useful to run the performance
analysis tool. The tool has around 5~25% overhead, which is very low compared to instruction-level profilers
(30x-100x overhead). Due to being based on a single simulation run, the report may contain spikes in the charts.
When running a simulation for performance analysis, execution times of user-defined functions as well as linear,
non-linear and mixed equation systems are recorded.
To start a simulation in this mode, turn on profiling with the following command line flag >>>
setCommandLineOptions("–profiling=all")
The generated report is in HTML format (with images in the SVG format), stored in a file modelname_prof.html,
but the XML database and measured times that generated the report and graphs are also available if you want to
customize the report for comparison with other tools.
Below we use the performance profiler on the simple model A:
model ProfilingTest
function f
input Real r;
output Real o = sin(r);
end f;
String s = "abc";
Real x = f(x) "This is x";
Real y(start=1);
Real z1 = cos(z2);
Real z2 = sin(z1);
equation
der(y) = time;
end ProfilingTest;
>>> setCommandLineOptions("--profiling=blocks+html")
true
>>> simulate(ProfilingTest)
record SimulationResult
resultFile = "«DOCHOME»/ProfilingTest_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'ProfilingTest', options =
175
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
˓→details)
",
timeFrontend = 0.008441926000000001,
timeBackend = 0.010859481,
timeSimCode = 0.001484616,
timeTemplates = 0.002825918,
timeCompile = 0.5331640989999999,
timeSimulation = 0.08051813000000001,
timeTotal = 0.637411992
end SimulationResult;
"Warning: There are nonlinear iteration variables with default zero start
˓→attribute found in NLSJac0. For more information set -d=initialization. In
˓→setCommandLineOptions("-d=initialization").
Warning: The initial conditions are not fully specified. For more information set -
˓→d=initialization. In OMEdit Tools->Options->Simulation->OMCFlags, in OMNotebook
˓→call setCommandLineOptions("-d=initialization").
"
16.1.1 Information
All times are measured using a real-time wall clock. This means context switching produces bad worst-case
execution times (max times) for blocks. If you want better results, use a CPU-time clock or run the command
using real-time priviliges (avoiding context switches).
Note that for blocks where the individual execution time is close to the accuracy of the real-time clock, the
maximum measured time may deviate a lot from the average.
For more details, see ProfilingTest_prof.xml.
16.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
16.1.3 Summary
Equations
Name Variables
eq0
eq1 y
eq2 s
eq3
eq4 z2
eq5
eq6 ‘ <#var0>‘__
eq7 ‘ <#var0>‘__
eq8 ‘ <#var0>‘__
eq9 ‘ <#var0>‘__
eq10 z1
eq11
eq12 x
eq13 der(y)
eq14 z2
eq15
eq16 ‘ <#var0>‘__
eq17 ‘ <#var0>‘__
eq18 ‘ <#var0>‘__
eq19 ‘ <#var0>‘__
eq20 z1
eq21
eq22 x
eq23
Variables
Name Comment
y
der(y)
x This is x
z1
z2
s
When profiling the DoublePendulum example from MSL, the following output in Figure 16.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 16.2: Profiling results of the Modelica standard library DoublePendulum example, sorted by execution
time.
SEVENTEEN
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.
181
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
EIGHTEEN
Below is information and examples about the OpenModelica external C interfaces, as well as examples of Python
interoperability.
model ExternalLibraries
function ExternalFunc1
input Real x;
output Real y;
external y=ExternalFunc1_ext(x) annotation(Library="ExternalFunc1.o",
˓→LibraryDirectory="modelica://ExternalLibraries", Include="#include \
˓→"ExternalFunc1.h\"");
end ExternalFunc1;
function ExternalFunc2
input Real x;
output Real y;
external "C" annotation(Library="ExternalFunc2", LibraryDirectory="modelica://
˓→ExternalLibraries");
end ExternalFunc2;
These C (.c) files and header files (.h) are needed (note that the headers are not needed since OpenModelica will
generate the correct definition if it is not present; using the headers it is possible to write C-code directly in the
Modelica source code or declare non-standard calling conventions):
183
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
The following script file ExternalLibraries.mos will perform everything that is needed, provided you have gcc
installed in your path:
>>> system(getCompiler() + " -c -o ExternalFunc1.o ExternalFunc1.c")
0
>>> system(getCompiler() + " -c -o ExternalFunc2.o ExternalFunc2.c")
0
>>> system("ar rcs libExternalFunc2.a ExternalFunc2.o")
0
>>> simulate(ExternalLibraries)
record SimulationResult
resultFile = "«DOCHOME»/ExternalLibraries_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500,
˓→tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'ExternalLibraries',
˓→= ''",
2
x
1.8 y
1.6
1.4
1.2
0.8
0.6
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
function pyRunString
input String s;
external "C" annotation(Include="
#include <Python.h>
model CallExternalPython
algorithm
pyRunString("
print 'Python says: simulation time',"+String(time)+"
");
end CallExternalPython;
˓→= ''",
In the following Python (.py) files the above Modelica model is simulated via the OpenModelica scripting inter-
face:
mos_file.write('simulate(CalledbyPython,stopTime=10);\n')
mos_file.close()
A second option of simulating the above Modelica model is to use the command buildModel instead of the simulate
command and setting the parameter value in the initial parameter file, CalledbyPython_init.txt instead of using the
command setComponentModifierValue. Then the file CalledbyPython.exe is just executed.
The third option is to use the Corba interface for invoking the compiler and then just use the scripting interface to
send commands to the compiler via this interface.
The fourth variant is to use external function calls to directly communicate with the executing simulation process.
NINETEEN
189
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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:
>>> from OMPython import OMCSessionZMQ
>>> omc = OMCSessionZMQ()
>>> omc.sendExpression("getVersion()")
OMCompiler v1.14.2-v1.14.2.6+g5c52d52477
>>> 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("getConnectionCount(BouncingBall)")
0
>>> omc.sendExpression("getInheritanceCount(BouncingBall)")
(continues on next page)
˓→'SYSTEM_PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
˓→May 15 14:27:21 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux\n', 'RTLIBS': ' -Wl,--no-
˓→srcdir=.'"}
The common combination of a simulation followed by getting a value and doing a plot:
Import As Library
To use the module from within another python program, simply import OMCSessionZMQ from within the using
program.
For example:
# test.py
from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
cmds = [
'loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/
˓→BouncingBall.mo")',
"simulate(BouncingBall)",
"plot(h)"
]
for cmd in cmds:
answer = omc.sendExpression(cmd)
print("\n{}:\n{}".format(cmd, answer))
19.1.3 Implementation
Client Implementation
The OpenModelica Python API Interface – OMPython, attempts to mimic the OMShell’s style of operations.
OMPython is designed to,
• Initialize the CORBA/ZeroMQ communication.
• Send commands to the OMC server via the CORBA/ZeroMQ interface.
• Receive the string results.
• Use the Parser module to format the results.
• Return or display the results.
The object constructor requires a minimum of 2 input arguments which are strings, and may need a third string
input argument.
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory of Python, then the file path must also
be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument is used to specify the list of dependent libraries or dependent Modelica files e.g.,
• By default ModelicaSystem uses OMCSessionZMQ but if you want to use OMCSession then pass the
argument useCorba=True to the constructor.
19.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()
• 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
(-1.825929609047952, 0.65907039052943617)
>>> mod.getInputs()
{}
>>> mod.getOutputs()
{}
>>> mod.getSolutions(["time","height"],resultfile="c:/tmpbouncingBall.mat") //
˓→return list of array
19.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}
And then finally we can simulate the model using, The simulate() API can be used in two methods
1) without any arguments
2) resultfile names provided by user (only filename is allowed and not the location)
19.2.7 Linearization
The following methods are proposed for linearization.
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> mod.setLinearizationOptions(["stopTime=2.0","tolerance=1e-06"])
19.3 PySimulator
PySimulator provides a graphical user interface for performing analyses and simulating different model types
(currently Functional Mockup Units and Modelica Models are supported), plotting result variables and applying
simulation result analysis tools like Fast Fourier Transform.
Read more about the PySimulator at https://github.com/PySimulator/PySimulator.
TWENTY
OMMatlab – the OpenModelica Matlab API is a free, open source, highly portable Matlab-based interactive
session handler for Modelica scripting. It provides the modeler with components for creating a complete Modelica
modeling, compilation and simulation environment based on the latest OpenModelica library standard available.
OMMatlab is architectured to combine both the solving strategy and model building. So domain experts (people
writing the models) and computational engineers (people writing the solver code) can work on one unified tool
that is industrially viable for optimization of Modelica models, while offering a flexible platform for algorithm
development and research. OMMatlab is not a standalone package, it depends upon the OpenModelica installation.
OMMatlab is implemented in Matlab and depends on ZeroMQ - high performance asynchronous messaging li-
brary and it supports the Modelica Standard Library version 3.2 that is included in starting with OpenModelica
1.9.2.
To install OMMatlab follow the instructions at https://github.com/OpenModelica/OMMatlab
197
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
The object constructor requires a minimum of 2 input arguments which are strings, and third input argument which
is optional .
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory, then the file path must also be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument (optional) is used to specify the list of dependent libraries or dependent Modelica
files The argument can be passed as a string or array of strings e.g.,
>>> omc.ModelicaSystem("BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"])
20.3 WorkDirectory
For each Matlab session a temporary work directory is created and the results are published in that working
directory, Inorder to get the workdirectory the users can use the following API
>>> omc.getWorkDirectory()
'C:/Users/arupa54/AppData/Local/Temp/tp7dd648e5_5de6_4f66_b3d6_90bce1fe1d58'
20.4 BuildModel
The buildModel API can be used after ModelicaSystem(), in case the model needs to be updated or additional
simulationflags needs to be set using sendExpression()
>>> buildModel(mod)
+----------+------------+-------------------------+--------------+------------+----
˓→-------+---------------+-------+
>>> omc.getInputs()
struct with no fields
>>> omc.getOutputs()
struct with no fields
>>> omc.setSimulationOptions(["stopTime=2.0","tolerance=1e-08"])
>>> omc.getParameters()
struct with fields:
e: '0.7'
g: '9.810000000000001'
>>> omc.setParameters(["e=0.9","g=9.83"])
To check whether new values are updated to model , we can again query the getParameters().
>>> omc.getParameters()
struct with fields:
e: "0.9"
g: "9.83"
Similary we can also use setInputs() to set a value for the inputs during various time interval can also be done
using the following.
>>> omc.setInputs("cAi=1")
And then finally we can simulate the model using, The simulate() API can be used in two methods
1) without any arguments
2) resultfile names provided by user (only filename is allowed and not the location)
20.10 Linearization
The following methods are available for linearization of a modelica model
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> omc.setLinearizationOptions(["stopTime=2.0","tolerance=1e-08"])
TWENTYONE
OMJulia – the OpenModelica Julia API is a free, open source, highly portable Julia based interactive session han-
dler for Julia scripting of OpenModelica API functionality. It provides the modeler with components for creating
a complete Julia-Modelica modeling, compilation and simulation environment based on the latest OpenModelica
implementation and Modelica library standard available. OMJulia is architectured to combine both the solving
strategy and model building. Thus, domain experts (people writing the models) and computational engineers (peo-
ple writing the solver code) can work on one unified tool that is industrially viable for optimization of Modelica
models, while offering a flexible platform for algorithm development and research. OMJulia is not a standalone
package, it depends upon the OpenModelica installation.
OMJulia is implemented in Julia and depends on ZeroMQ - high performance asynchronous messaging library
and it supports the Modelica Standard Library version 3.2 that is included in starting with OpenModelica 1.9.2.
To install OMJulia follow the instructions at https://github.com/OpenModelica/OMJulia.jl
205
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
The object constructor requires a minimum of 2 input arguments which are strings, and third input argument which
is optional .
• The first input argument must be a string with the file name of the Modelica code, with Modelica file
extension ".mo". If the Modelica file is not in the current directory, then the file path must also be included.
• The second input argument must be a string with the name of the Modelica model including the namespace
if the model is wrapped within a Modelica package.
• The third input argument (optional) is used to specify the list of dependent libraries or dependent Modelica
files The argument can be passed as a string or array of strings e.g.,
>>> ModelicaSystem(mod,"BouncingBall.mo","BouncingBall",["Modelica",
˓→"SystemDynamics", "dcmotor.mo"])
21.3 WorkDirectory
For each OMJulia session a temporary work directory is created and the results are published in that working
directory, Inorder to get the workdirectory the users can use the following API
>>> getWorkDirectory(mod)
"C:/Users/arupa54/AppData/Local/Temp/jl_5pbewl"
21.4 BuildModel
The buildModel API can be used after ModelicaSystem(), in case the model needs to be updated or additional
simulationflags needs to be set using sendExpression()
>>> buildModel(mod)
["-1.825929609047952", "0.65907039052943617"]
>>> getInputs(mod)
{}
>>> getOutputs(mod)
{}
>>> setSimulationOptions(mod,["stopTime=2.0","tolerance=1e-08"])
>>> getParameters(mod)
{"c": "0.9", "radius": "0.1"}
>>> setParameters(mod,["radius=14","c=0.5"])
To check whether new values are updated to model , we can again query the getParameters().
>>> getParameters(mod)
{"c": "0.5", "radius": "14"}
Similary we can also use setInputs() to set a value for the inputs during various time interval can also be done
using the following.
>>> setInputs(mod,"cAi=1")
And then finally we can simulate the model using, The simulate() API can be used in two methods
1) without any arguments
2) resultfile names provided by user (only filename is allowed and not the location)
21.10 Linearization
The following methods are available for linearization of a modelica model
• linearize()
• getLinearizationOptions()
• setLinearizationOptions()
• getLinearInputs()
• getLinearOutputs()
• getLinearStates()
>>> setLinearizationOptions(mod,["stopTime=2.0","tolerance=1e-06"])
21.13 Usage
With the above list of API calls implemented, the users can have more control over the result types, returned as
Julia data structures.
TWENTYTWO
JUPYTER-OPENMODELICA
An OpenModelica Kernel for Jupyter Notebook. All commands are interpreted by OMPython which communi-
cates with OpenModelica Compiler and the results are presented to user.
The project is available at https://github.com/OpenModelica/jupyter-openmodelica.
Follow the Readme file to install and start running modelica models directly in Jupyter Notebook
211
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
TWENTYTHREE
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.
23.1.1 interactiveDumpAbsynToJL
function interactiveDumpAbsynToJL
output String res;
end interactiveDumpAbsynToJL;
23.1.2 relocateFunctions
function relocateFunctions
input String fileName;
input String names[:, 2];
output Boolean success;
end relocateFunctions;
23.1.3 toJulia
function toJulia
output String res;
end toJulia;
213
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
23.1.4 GC_expand_hp
function GC_expand_hp
input Integer size;
output Boolean success;
end GC_expand_hp;
23.1.5 GC_gcollect_and_unmap
23.1.6 GC_get_prof_stats
function GC_get_prof_stats
output GC_PROFSTATS gcStats;
end GC_get_prof_stats;
23.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;
23.1.8 addClassAnnotation
function addClassAnnotation
input TypeName class_;
input ExpressionOrModification annotate;
output Boolean bool;
end addClassAnnotation;
23.1.9 addInitialState
function addInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end addInitialState;
23.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;
23.1.11 alarm
23.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;
23.1.13 basename
function basename
input String path;
output String basename;
end basename;
23.1.14 buildEncryptedPackage
function buildEncryptedPackage
input TypeName className "the class that should encrypted";
input Boolean encrypt = true;
output Boolean success;
end buildEncryptedPackage;
23.1.15 buildLabel
builds Lable.
function buildLabel
input TypeName className "the class that should be built";
input Real startTime = 0.0 "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String method = "dassl" "integration method used for simulation. <default>
˓→= dassl";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.1.16 buildModel
˓→[cflags], [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 Real numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.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)";
˓→"=current platform, statically link everything. Else, use a host triple, e.g. \
˓→"x86_64-linux-gnu\" or \"x86_64-w64-mingw32\"";
output String generatedFileName "Returns the full path of the generated FMU.";
end buildModelFMU;
23.1.18 buildOpenTURNSInterface
function buildOpenTURNSInterface
input TypeName className;
input String pythonTemplateFile;
input Boolean showFlatModelica = false;
output String outPythonScript;
end buildOpenTURNSInterface;
23.1.19 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;
23.1.20 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;
23.1.21 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;
23.1.22 checkInterfaceOfPackages
function checkInterfaceOfPackages
input TypeName cl;
input String dependencyMatrix[:, :];
output Boolean success;
end checkInterfaceOfPackages;
23.1.23 checkModel
function checkModel
input TypeName className;
output String result;
end checkModel;
23.1.24 checkSettings
function checkSettings
output CheckSettingsResult result;
end checkSettings;
23.1.25 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;
23.1.26 classAnnotationExists
function classAnnotationExists
input TypeName className;
input TypeName annotationName;
output Boolean exists;
end classAnnotationExists;
23.1.27 clear
function clear
output Boolean success;
end clear;
23.1.28 clearCommandLineOptions
function clearCommandLineOptions
output Boolean success;
end clearCommandLineOptions;
23.1.29 clearDebugFlags
function clearDebugFlags
output Boolean success;
end clearDebugFlags;
23.1.30 clearMessages
function clearMessages
output Boolean success;
end clearMessages;
23.1.31 clearProgram
Clears loaded .
function clearProgram
output Boolean success;
end clearProgram;
23.1.32 clearVariables
function clearVariables
output Boolean success;
end clearVariables;
23.1.33 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;
23.1.34 codeToString
function codeToString
input $Code className;
output String string;
end codeToString;
23.1.35 compareFiles
23.1.36 compareFilesAndMove
23.1.37 compareSimulationResults
function compareSimulationResults
input String filename;
input String reffilename;
input String logfilename;
input Real relTol = 0.01;
input Real absTol = 0.0001;
input String[:] vars = fill("", 0);
output String[:] result;
end compareSimulationResults;
23.1.38 convertUnits
function convertUnits
input String s1;
input String s2;
output Boolean unitsCompatible;
output Real scaleFactor;
output Real offset;
end convertUnits;
23.1.39 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;
23.1.40 copyClass
function copyClass
input TypeName className "the class that should be copied";
input String newClassName "the name for new class";
input TypeName withIn = $Code(TopLevel) "the with in path for new class";
output Boolean result;
end copyClass;
23.1.41 countMessages
function countMessages
output Integer numMessages;
output Integer numErrors;
output Integer numWarnings;
end countMessages;
23.1.42 deleteFile
function deleteFile
input String fileName;
output Boolean success;
end deleteFile;
23.1.43 deleteInitialState
function deleteInitialState
input TypeName cl;
input String state;
output Boolean bool;
end deleteInitialState;
23.1.44 deleteTransition
function deleteTransition
input TypeName cl;
input String from;
input String to;
input String condition;
input Boolean immediate;
input Boolean reset;
input Boolean synchronize;
input Integer priority;
output Boolean bool;
end deleteTransition;
23.1.45 deltaSimulationResults
function deltaSimulationResults
input String filename;
input String reffilename;
input String method "method to compute then error. choose 1norm, 2norm, maxerr";
input String[:] vars = fill("", 0);
output Real result;
end deltaSimulationResults;
23.1.46 diffModelicaFileListings
function diffModelicaFileListings
input String before, after;
input DiffFormat diffFormat = DiffFormat.color;
output String result;
end diffModelicaFileListings;
23.1.47 diffSimulationResults
function diffSimulationResults
input String actualFile;
input String expectedFile;
input String diffPrefix;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between
˓→the maximum and minimum of the signal";
23.1.48 diffSimulationResultsHtml
function diffSimulationResultsHtml
input String var;
input String actualFile;
input String expectedFile;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between
˓→the maximum and minimum of the signal";
23.1.49 directoryExists
function directoryExists
input String dirName;
output Boolean exists;
end directoryExists;
23.1.50 dirname
function dirname
input String path;
output String dirname;
end dirname;
23.1.51 disableNewInstantiation
function disableNewInstantiation
output Boolean success;
end disableNewInstantiation;
23.1.52 dumpXMLDAE
function dumpXMLDAE
input TypeName className;
input String translationLevel = "flat" "flat, optimiser, backEnd, or stateSpace";
input Boolean addOriginalIncidenceMatrix = false;
input Boolean addSolvingInfo = false;
input Boolean addMathMLCode = false;
input Boolean dumpResiduals = false;
(continues on next page)
input String rewriteRulesFile = "" "the file from where the rewiteRules are read,
˓→ default is empty which means no rewrite rules";
23.1.53 echo
function echo
input Boolean setEcho;
output Boolean newEcho;
end echo;
23.1.54 enableNewInstantiation
function enableNewInstantiation
output Boolean success;
end enableNewInstantiation;
23.1.55 escapeXML
function escapeXML
input String inStr;
output String outStr;
end escapeXML;
23.1.56 exit
function exit
input Integer status;
end exit;
23.1.57 exportToFigaro
function exportToFigaro
input TypeName path;
input String directory = cd();
input String database;
input String mode;
input String options;
input String processor;
output Boolean success;
end exportToFigaro;
23.1.58 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;
23.1.59 filterSimulationResults
function filterSimulationResults
input String inFile;
input String outFile;
input String[:] vars;
input Integer numberOfIntervals = 0 "0=Do not resample";
input Boolean removeDescription = false;
output Boolean success;
end filterSimulationResults;
23.1.60 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;
23.1.61 generateEntryPoint
function generateEntryPoint
input String fileName;
input TypeName entryPoint;
input String url = "https://trac.openmodelica.org/OpenModelica/newticket";
end generateEntryPoint;
23.1.62 generateHeader
function generateHeader
input String fileName;
output Boolean success;
end generateHeader;
23.1.63 generateJuliaHeader
function generateJuliaHeader
input String fileName;
output Boolean success;
end generateJuliaHeader;
23.1.64 generateScriptingAPI
function generateScriptingAPI
input TypeName cl;
input String name;
output Boolean success;
output String moFile;
output String qtFile;
output String qtHeader;
end generateScriptingAPI;
23.1.65 generateSeparateCode
function generateSeparateCode
input TypeName className;
input Boolean cleanCache = false "If true, the cache is reset between each
˓→generated package. This conserves memory at the cost of speed.";
23.1.66 generateSeparateCodeDependencies
function generateSeparateCodeDependencies
input String stampSuffix = ".c" "Suffix to add to dependencies (often .c.stamp)";
output String[:] dependencies;
end generateSeparateCodeDependencies;
23.1.67 generateSeparateCodeDependenciesMakefile
function generateSeparateCodeDependenciesMakefile
input String filename "The file to write the makefile to";
input String directory = "" "The relative path of the generated files";
input String suffix = ".c" "Often .stamp since we do not update all the files";
output Boolean success;
end generateSeparateCodeDependenciesMakefile;
23.1.68 generateVerificationScenarios
function generateVerificationScenarios
input TypeName path;
output Boolean success;
end generateVerificationScenarios;
23.1.69 getAlgorithmCount
function getAlgorithmCount
input TypeName class_;
output Integer count;
end getAlgorithmCount;
23.1.70 getAlgorithmItemsCount
function getAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getAlgorithmItemsCount;
23.1.71 getAllSubtypeOf
Returns the list of all classes that extend from class_ given a parentClass where
˓→the lookup for class_ should start
function getAllSubtypeOf
input TypeName parentClass = $Code(AllLoadedClasses);
input TypeName class_;
input Boolean qualified = false;
input Boolean includePartial = false;
input Boolean sort = false;
output TypeName classNames[:];
end getAllSubtypeOf;
23.1.72 getAnnotationCount
function getAnnotationCount
input TypeName class_;
output Integer count;
end getAnnotationCount;
23.1.73 getAnnotationModifierValue
function getAnnotationModifierValue
input TypeName name;
input String vendorannotation;
input String modifiername;
output String modifiernamevalue;
end getAnnotationModifierValue;
23.1.74 getAnnotationNamedModifiers
function getAnnotationNamedModifiers
input TypeName name;
input String vendorannotation;
output String[:] modifiernamelist;
end getAnnotationNamedModifiers;
23.1.75 getAnnotationVersion
function getAnnotationVersion
output String annotationVersion;
end getAnnotationVersion;
23.1.76 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;
23.1.77 getAvailableIndexReductionMethods
function getAvailableIndexReductionMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableIndexReductionMethods;
23.1.78 getAvailableLibraries
function getAvailableLibraries
output String[:] libraries;
end getAvailableLibraries;
23.1.79 getAvailableMatchingAlgorithms
function getAvailableMatchingAlgorithms
output String[:] allChoices;
output String[:] allComments;
end getAvailableMatchingAlgorithms;
23.1.80 getAvailableTearingMethods
function getAvailableTearingMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableTearingMethods;
23.1.81 getBooleanClassAnnotation
function getBooleanClassAnnotation
input TypeName className;
input TypeName annotationName;
output Boolean value;
end getBooleanClassAnnotation;
23.1.82 getBuiltinType
function getBuiltinType
input TypeName cl;
output String name;
end getBuiltinType;
23.1.83 getCFlags
CFLAGS
function getCFlags
output String outString;
end getCFlags;
23.1.84 getCXXCompiler
CXX
function getCXXCompiler
output String compiler;
end getCXXCompiler;
23.1.85 getClassComment
function getClassComment
input TypeName cl;
output String comment;
end getClassComment;
23.1.86 getClassInformation
function getClassInformation
input TypeName cl;
output String restriction, comment;
output Boolean partialPrefix, finalPrefix, encapsulatedPrefix;
output String fileName;
output Boolean fileReadOnly;
(continues on next page)
23.1.87 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
˓→";
23.1.88 getClassRestriction
function getClassRestriction
input TypeName cl;
output String restriction;
end getClassRestriction;
23.1.89 getClassesInModelicaPath
function getClassesInModelicaPath
output String classesInModelicaPath;
end getClassesInModelicaPath;
23.1.90 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;
23.1.91 getCompileCommand
function getCompileCommand
output String compileCommand;
end getCompileCommand;
23.1.92 getCompiler
CC
function getCompiler
output String compiler;
end getCompiler;
23.1.93 getComponentModifierNames
function getComponentModifierNames
input TypeName class_;
input String componentName;
output String[:] modifiers;
end getComponentModifierNames;
23.1.94 getComponentModifierValue
function getComponentModifierValue
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValue;
23.1.95 getComponentModifierValues
function getComponentModifierValues
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValues;
23.1.96 getComponentsTest
function getComponentsTest
input TypeName name;
output Component[:] components;
record Component
String className;
// when building record the constructor. Records are allowed to contain only
˓→components of basic types, arrays of basic types or other records.
String name;
String comment;
Boolean isProtected;
Boolean isFinal;
Boolean isFlow;
(continues on next page)
23.1.97 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;
23.1.98 getConnectionCount
function getConnectionCount
input TypeName className;
output Integer count;
end getConnectionCount;
23.1.99 getDefaultOpenCLDevice
function getDefaultOpenCLDevice
output Integer defdevid;
end getDefaultOpenCLDevice;
23.1.100 getDerivedClassModifierNames
function getDerivedClassModifierNames
input TypeName className;
output String[:] modifierNames;
end getDerivedClassModifierNames;
23.1.101 getDerivedClassModifierValue
function getDerivedClassModifierValue
input TypeName className;
input TypeName modifierName;
output String modifierValue;
end getDerivedClassModifierValue;
23.1.102 getDerivedUnits
function getDerivedUnits
input String baseUnit;
output String[:] derivedUnits;
end getDerivedUnits;
23.1.103 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;
23.1.104 getEnvironmentVar
function getEnvironmentVar
input String var;
output String value "returns empty string on failure";
end getEnvironmentVar;
23.1.105 getEquationCount
function getEquationCount
input TypeName class_;
output Integer count;
end getEquationCount;
23.1.106 getEquationItemsCount
function getEquationItemsCount
input TypeName class_;
output Integer count;
end getEquationItemsCount;
23.1.107 getErrorString
23.1.108 getImportCount
function getImportCount
input TypeName class_;
output Integer count;
end getImportCount;
23.1.109 getIndexReductionMethod
function getIndexReductionMethod
output String selected;
end getIndexReductionMethod;
23.1.110 getInheritedClasses
function getInheritedClasses
input TypeName name;
output TypeName inheritedClasses[:];
end getInheritedClasses;
23.1.111 getInitialAlgorithmCount
function getInitialAlgorithmCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmCount;
23.1.112 getInitialAlgorithmItemsCount
function getInitialAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmItemsCount;
23.1.113 getInitialEquationCount
function getInitialEquationCount
input TypeName class_;
output Integer count;
end getInitialEquationCount;
23.1.114 getInitialEquationItemsCount
function getInitialEquationItemsCount
input TypeName class_;
output Integer count;
end getInitialEquationItemsCount;
23.1.115 getInitialStates
function getInitialStates
input TypeName cl;
output String[:, :] initialStates;
end getInitialStates;
23.1.116 getInstallationDirectoryPath
function getInstallationDirectoryPath
output String installationDirectoryPath;
end getInstallationDirectoryPath;
23.1.117 getInstantiatedParametersAndValues
function getInstantiatedParametersAndValues
input TypeName cls;
output String[:] values;
end getInstantiatedParametersAndValues;
23.1.118 getLanguageStandard
function getLanguageStandard
output String outVersion;
end getLanguageStandard;
23.1.119 getLinker
function getLinker
output String linker;
end getLinker;
23.1.120 getLinkerFlags
function getLinkerFlags
output String linkerFlags;
end getLinkerFlags;
23.1.121 getLoadedLibraries
function getLoadedLibraries
output String[:, 2] libraries;
end getLoadedLibraries;
23.1.122 getMatchingAlgorithm
function getMatchingAlgorithm
output String selected;
end getMatchingAlgorithm;
23.1.123 getMemorySize
function getMemorySize
output Real memory(unit = "MiB");
end getMemorySize;
23.1.124 getMessagesString
see getErrorString()
function getMessagesString
output String messagesString;
end getMessagesString;
23.1.125 getModelicaPath
function getModelicaPath
output String modelicaPath;
end getModelicaPath;
23.1.126 getNoSimplify
function getNoSimplify
output Boolean noSimplify;
end getNoSimplify;
23.1.127 getNthAlgorithm
function getNthAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithm;
23.1.128 getNthAlgorithmItem
function getNthAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithmItem;
23.1.129 getNthAnnotationString
function getNthAnnotationString
input TypeName class_;
input Integer index;
output String result;
end getNthAnnotationString;
23.1.130 getNthConnection
function getNthConnection
input TypeName className;
input Integer index;
output String[:] result;
end getNthConnection;
23.1.131 getNthEquation
function getNthEquation
input TypeName class_;
input Integer index;
output String result;
end getNthEquation;
23.1.132 getNthEquationItem
function getNthEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthEquationItem;
23.1.133 getNthImport
function getNthImport
input TypeName class_;
input Integer index;
output String out[3] "{\"Path\",\"Id\",\"Kind\"}";
end getNthImport;
23.1.134 getNthInitialAlgorithm
function getNthInitialAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithm;
23.1.135 getNthInitialAlgorithmItem
function getNthInitialAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithmItem;
23.1.136 getNthInitialEquation
function getNthInitialEquation
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquation;
23.1.137 getNthInitialEquationItem
function getNthInitialEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquationItem;
23.1.138 getOrderConnections
function getOrderConnections
output Boolean orderConnections;
end getOrderConnections;
23.1.139 getPackages
function getPackages
input TypeName class_ = $Code(AllLoadedClasses);
output TypeName classNames[:];
end getPackages;
23.1.140 getParameterNames
function getParameterNames
input TypeName class_;
output String[:] parameters;
end getParameterNames;
23.1.141 getParameterValue
function getParameterValue
input TypeName class_;
input String parameterName;
output String parameterValue;
end getParameterValue;
23.1.142 getSettings
function getSettings
output String settings;
end getSettings;
23.1.143 getShowAnnotations
function getShowAnnotations
output Boolean show;
end getShowAnnotations;
23.1.144 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";
23.1.145 getSourceFile
function getSourceFile
input TypeName class_;
output String filename "empty on failure";
end getSourceFile;
23.1.146 getTearingMethod
function getTearingMethod
output String selected;
end getTearingMethod;
23.1.147 getTempDirectoryPath
function getTempDirectoryPath
output String tempDirectoryPath;
end getTempDirectoryPath;
23.1.148 getTimeStamp
function getTimeStamp
input TypeName cl;
output Real timeStamp;
output String timeStampAsString;
end getTimeStamp;
23.1.149 getTransitions
function getTransitions
input TypeName cl;
output String[:, :] transitions;
end getTransitions;
23.1.150 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;
23.1.151 getUses
function getUses
input TypeName pack;
output String[:, :] uses;
end getUses;
23.1.152 getVectorizationLimit
function getVectorizationLimit
output Integer vectorizationLimit;
end getVectorizationLimit;
23.1.153 getVersion
function getVersion
input TypeName cl = $Code(OpenModelica);
output String version;
end getVersion;
23.1.154 help
function help
input String topic = "topics";
output String helpText;
end help;
23.1.155 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;
23.1.156 importFMU
function importFMU
input String filename "the fmu file name";
input String workdir = "<default>" "The output directory for imported FMU files.
˓→<default> will put the files to current working directory.";
input Boolean fullPath = false "When true the full output path is returned
˓→otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
23.1.157 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.
˓→";
output String generatedFileName "Returns the full path of the generated file.";
end importFMUModelDescription;
23.1.158 inferBindings
function inferBindings
input TypeName path;
output Boolean success;
end inferBindings;
23.1.159 instantiateModel
function instantiateModel
input TypeName className;
output String result;
end instantiateModel;
23.1.160 isBlock
function isBlock
input TypeName cl;
output Boolean b;
end isBlock;
23.1.161 isClass
function isClass
input TypeName cl;
output Boolean b;
end isClass;
23.1.162 isConnector
function isConnector
input TypeName cl;
output Boolean b;
end isConnector;
23.1.163 isEnumeration
function isEnumeration
input TypeName cl;
output Boolean b;
end isEnumeration;
23.1.164 isExperiment
function isExperiment
input TypeName name;
output Boolean res;
end isExperiment;
23.1.165 isFunction
function isFunction
input TypeName cl;
output Boolean b;
end isFunction;
23.1.166 isModel
function isModel
input TypeName cl;
output Boolean b;
end isModel;
23.1.167 isOperator
function isOperator
input TypeName cl;
output Boolean b;
end isOperator;
23.1.168 isOperatorFunction
function isOperatorFunction
input TypeName cl;
output Boolean b;
end isOperatorFunction;
23.1.169 isOperatorRecord
function isOperatorRecord
input TypeName cl;
output Boolean b;
end isOperatorRecord;
23.1.170 isOptimization
function isOptimization
input TypeName cl;
output Boolean b;
end isOptimization;
23.1.171 isPackage
function isPackage
input TypeName cl;
output Boolean b;
end isPackage;
23.1.172 isPartial
function isPartial
input TypeName cl;
output Boolean b;
end isPartial;
23.1.173 isProtectedClass
function isProtectedClass
input TypeName cl;
input String c2;
output Boolean b;
end isProtectedClass;
23.1.174 isRecord
function isRecord
input TypeName cl;
output Boolean b;
end isRecord;
23.1.175 isShortDefinition
function isShortDefinition
input TypeName class_;
output Boolean isShortCls;
end isShortDefinition;
23.1.176 isType
function isType
input TypeName cl;
output Boolean b;
end isType;
23.1.177 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 Real numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file.
˓→<default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.1.178 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;
23.1.179 listFile
function listFile
input TypeName class_;
input Boolean nestedClasses = true;
output String contents;
end listFile;
23.1.180 listVariables
function listVariables
output TypeName variables[:];
end listVariables;
23.1.181 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.";
23.1.182 loadFile
function loadFile
input String fileName;
input String encoding = "UTF-8";
input Boolean uses = true;
output Boolean success;
end loadFile;
23.1.183 loadFileInteractive
function loadFileInteractive
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractive;
23.1.184 loadFileInteractiveQualified
function loadFileInteractiveQualified
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractiveQualified;
23.1.185 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();
output Boolean success;
end loadFiles;
23.1.186 loadModel
function loadModel
input TypeName className;
input String[:] priorityVersion = {"default"};
input Boolean notify = false "Give a notification of the libraries and versions
˓→that were loaded";
input String languageStandard = "" "Override the set language standard. Parse
˓→with the given setting, but do not change it permanently.";
˓→match it.";
23.1.187 loadModelica3D
function loadModelica3D
input String version = "3.2.1";
output Boolean status;
end loadModelica3D;
23.1.188 loadOMSimulator
function loadOMSimulator
output Integer status;
end loadOMSimulator;
23.1.189 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
(continues on next page)
function loadString
input String data;
input String filename = "<interactive>";
input String encoding = "UTF-8";
input Boolean merge = false "if merge is true the parsed AST is merged with the
˓→existing AST, default to false which means that is replaced, not merged";
23.1.190 mkdir
function mkdir
input String newDirectory;
output Boolean success;
end mkdir;
23.1.191 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;
23.1.192 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;
23.1.193 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;
23.1.194 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;
23.1.195 numProcessors
function numProcessors
output Integer result;
end numProcessors;
23.1.196 oms_RunFile
function oms_RunFile
input String filename;
output Integer status;
end oms_RunFile;
23.1.197 oms_addBus
function oms_addBus
input String cref;
output Integer status;
end oms_addBus;
23.1.198 oms_addConnection
function oms_addConnection
input String crefA;
input String crefB;
output Integer status;
end oms_addConnection;
23.1.199 oms_addConnector
function oms_addConnector
input String cref;
input oms_causality causality;
input oms_signal_type type_;
output Integer status;
end oms_addConnector;
23.1.200 oms_addConnectorToBus
function oms_addConnectorToBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_addConnectorToBus;
23.1.201 oms_addConnectorToTLMBus
function oms_addConnectorToTLMBus
input String busCref;
input String connectorCref;
input String type_;
output Integer status;
end oms_addConnectorToTLMBus;
23.1.202 oms_addDynamicValueIndicator
function oms_addDynamicValueIndicator
input String signal;
input String lower;
input String upper;
input Real stepSize;
output Integer status;
end oms_addDynamicValueIndicator;
23.1.203 oms_addEventIndicator
function oms_addEventIndicator
input String signal;
output Integer status;
end oms_addEventIndicator;
23.1.204 oms_addExternalModel
function oms_addExternalModel
input String cref;
input String path;
input String startscript;
output Integer status;
end oms_addExternalModel;
23.1.205 oms_addSignalsToResults
function oms_addSignalsToResults
input String cref;
input String regex;
output Integer status;
end oms_addSignalsToResults;
23.1.206 oms_addStaticValueIndicator
function oms_addStaticValueIndicator
input String signal;
input Real lower;
input Real upper;
input Real stepSize;
output Integer status;
end oms_addStaticValueIndicator;
23.1.207 oms_addSubModel
function oms_addSubModel
input String cref;
input String fmuPath;
output Integer status;
end oms_addSubModel;
23.1.208 oms_addSystem
function oms_addSystem
input String cref;
input oms_system type_;
output Integer status;
end oms_addSystem;
23.1.209 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;
23.1.210 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;
23.1.211 oms_addTimeIndicator
function oms_addTimeIndicator
input String signal;
output Integer status;
end oms_addTimeIndicator;
23.1.212 oms_cancelSimulation_asynchronous
function oms_cancelSimulation_asynchronous
input String cref;
output Integer status;
end oms_cancelSimulation_asynchronous;
23.1.213 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;
23.1.214 oms_copySystem
function oms_copySystem
input String source;
input String target;
output Integer status;
end oms_copySystem;
23.1.215 oms_delete
function oms_delete
input String cref;
output Integer status;
end oms_delete;
23.1.216 oms_deleteConnection
function oms_deleteConnection
input String crefA;
input String crefB;
output Integer status;
end oms_deleteConnection;
23.1.217 oms_deleteConnectorFromBus
function oms_deleteConnectorFromBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromBus;
23.1.218 oms_deleteConnectorFromTLMBus
function oms_deleteConnectorFromTLMBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromTLMBus;
23.1.219 oms_export
function oms_export
input String cref;
input String filename;
output Integer status;
end oms_export;
23.1.220 oms_exportDependencyGraphs
function oms_exportDependencyGraphs
input String cref;
input String initialization;
input String simulation;
output Integer status;
end oms_exportDependencyGraphs;
23.1.221 oms_extractFMIKind
function oms_extractFMIKind
input String filename;
output Integer status;
output Integer kind;
end oms_extractFMIKind;
23.1.222 oms_faultInjection
function oms_faultInjection
input String signal;
input oms_fault_type_enu_t faultType;
input Real faultValue;
output Integer status;
end oms_faultInjection;
23.1.223 oms_getBoolean
function oms_getBoolean
input String cref;
output Integer status;
output Boolean value;
end oms_getBoolean;
23.1.224 oms_getFixedStepSize
function oms_getFixedStepSize
input String cref;
output Integer status;
output Real stepSize;
end oms_getFixedStepSize;
23.1.225 oms_getInteger
function oms_getInteger
input String cref;
output Integer status;
input Integer value;
end oms_getInteger;
23.1.226 oms_getModelState
function oms_getModelState
input String cref;
output Integer status;
output Integer modelState;
end oms_getModelState;
23.1.227 oms_getReal
function oms_getReal
input String cref;
output Integer status;
output Real value;
end oms_getReal;
23.1.228 oms_getSolver
function oms_getSolver
input String cref;
output Integer status;
output Integer solver;
end oms_getSolver;
23.1.229 oms_getStartTime
function oms_getStartTime
input String cref;
output Integer status;
output Real startTime;
end oms_getStartTime;
23.1.230 oms_getStopTime
function oms_getStopTime
input String cref;
output Integer status;
output Real stopTime;
end oms_getStopTime;
23.1.231 oms_getSubModelPath
function oms_getSubModelPath
input String cref;
output Integer status;
output String path;
end oms_getSubModelPath;
23.1.232 oms_getSystemType
function oms_getSystemType
input String cref;
output Integer status;
output Integer type_;
end oms_getSystemType;
23.1.233 oms_getTolerance
function oms_getTolerance
input String cref;
output Integer status;
output Real absoluteTolerance;
output Real relativeTolerance;
end oms_getTolerance;
23.1.234 oms_getVariableStepSize
function oms_getVariableStepSize
input String cref;
output Integer status;
output Real initialStepSize;
output Real minimumStepSize;
output Real maximumStepSize;
end oms_getVariableStepSize;
23.1.235 oms_getVersion
function oms_getVersion
output String version;
end oms_getVersion;
23.1.236 oms_importFile
function oms_importFile
input String filename;
output Integer status;
output String cref;
end oms_importFile;
23.1.237 oms_initialize
function oms_initialize
input String cref;
output Integer status;
end oms_initialize;
23.1.238 oms_instantiate
function oms_instantiate
input String cref;
output Integer status;
end oms_instantiate;
23.1.239 oms_list
function oms_list
input String cref;
output Integer status;
output String contents;
end oms_list;
23.1.240 oms_listUnconnectedConnectors
function oms_listUnconnectedConnectors
input String cref;
output Integer status;
output String contents;
end oms_listUnconnectedConnectors;
23.1.241 oms_loadSnapshot
function oms_loadSnapshot
input String cref;
input String snapshot;
output Integer status;
end oms_loadSnapshot;
23.1.242 oms_newModel
function oms_newModel
input String cref;
output Integer status;
end oms_newModel;
23.1.243 oms_parseModelName
function oms_parseModelName
input String contents;
output Integer status;
output String cref;
end oms_parseModelName;
23.1.244 oms_removeSignalsFromResults
function oms_removeSignalsFromResults
input String cref;
input String regex;
output Integer status;
end oms_removeSignalsFromResults;
23.1.245 oms_rename
function oms_rename
input String cref;
input String newCref;
output Integer status;
end oms_rename;
23.1.246 oms_reset
function oms_reset
input String cref;
output Integer status;
end oms_reset;
23.1.247 oms_setBoolean
function oms_setBoolean
input String cref;
input Boolean value;
output Integer status;
end oms_setBoolean;
23.1.248 oms_setCommandLineOption
function oms_setCommandLineOption
input String cmd;
output Integer status;
end oms_setCommandLineOption;
23.1.249 oms_setFixedStepSize
function oms_setFixedStepSize
input String cref;
input Real stepSize;
output Integer status;
end oms_setFixedStepSize;
23.1.250 oms_setInteger
function oms_setInteger
input String cref;
input Integer value;
output Integer status;
end oms_setInteger;
23.1.251 oms_setLogFile
function oms_setLogFile
input String filename;
output Integer status;
end oms_setLogFile;
23.1.252 oms_setLoggingInterval
function oms_setLoggingInterval
input String cref;
input Real loggingInterval;
output Integer status;
end oms_setLoggingInterval;
23.1.253 oms_setLoggingLevel
function oms_setLoggingLevel
input Integer logLevel;
output Integer status;
end oms_setLoggingLevel;
23.1.254 oms_setReal
function oms_setReal
input String cref;
input Real value;
output Integer status;
end oms_setReal;
23.1.255 oms_setRealInputDerivative
function oms_setRealInputDerivative
input String cref;
input Real value;
output Integer status;
end oms_setRealInputDerivative;
23.1.256 oms_setResultFile
function oms_setResultFile
input String cref;
input String filename;
input Integer bufferSize;
output Integer status;
end oms_setResultFile;
23.1.257 oms_setSignalFilter
function oms_setSignalFilter
input String cref;
input String regex;
output Integer status;
end oms_setSignalFilter;
23.1.258 oms_setSolver
function oms_setSolver
input String cref;
input oms_solver solver;
output Integer status;
end oms_setSolver;
23.1.259 oms_setStartTime
function oms_setStartTime
input String cref;
input Real startTime;
output Integer status;
end oms_setStartTime;
23.1.260 oms_setStopTime
function oms_setStopTime
input String cref;
input Real stopTime;
output Integer status;
end oms_setStopTime;
23.1.261 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;
23.1.262 oms_setTLMSocketData
function oms_setTLMSocketData
input String cref;
input String address;
input Integer managerPort;
input Integer monitorPort;
output Integer status;
end oms_setTLMSocketData;
23.1.263 oms_setTempDirectory
function oms_setTempDirectory
input String newTempDir;
output Integer status;
end oms_setTempDirectory;
23.1.264 oms_setTolerance
function oms_setTolerance
input String cref;
input Real absoluteTolerance;
input Real relativeTolerance;
output Integer status;
end oms_setTolerance;
23.1.265 oms_setVariableStepSize
function oms_setVariableStepSize
input String cref;
input Real initialStepSize;
input Real minimumStepSize;
input Real maximumStepSize;
output Integer status;
end oms_setVariableStepSize;
23.1.266 oms_setWorkingDirectory
function oms_setWorkingDirectory
input String newWorkingDir;
output Integer status;
end oms_setWorkingDirectory;
23.1.267 oms_simulate
function oms_simulate
input String cref;
output Integer status;
end oms_simulate;
23.1.268 oms_stepUntil
function oms_stepUntil
input String cref;
input Real stopTime;
output Integer status;
end oms_stepUntil;
23.1.269 oms_terminate
function oms_terminate
input String cref;
output Integer status;
end oms_terminate;
23.1.270 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 Real numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file.
˓→<default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.1.271 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.";
23.1.272 parseFile
function parseFile
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end parseFile;
23.1.273 parseString
function parseString
input String data;
input String filename = "<interactive>";
output TypeName names[:];
end parseString;
23.1.274 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 = "detailed" "Sets the grid for the plot i.e simple, detailed,
˓→none.";
input Boolean logX = false "Determines whether or not the horizontal axis is
˓→logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is
˓→logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in
˓→the diagram.";
input String yLabel = "" "This text will be used as the vertical label in the
˓→diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e left,
˓→right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call
˓→callback function even if it is defined.";
23.1.275 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 = "detailed" "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.";
(continues on next page)
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.";
23.1.276 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 = "detailed" "Sets the grid for the plot i.e simple, detailed,
˓→none.";
input Boolean logX = false "Determines whether or not the horizontal axis is
˓→logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is
˓→logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in
˓→the diagram.";
input String yLabel = "" "This text will be used as the vertical label in the
˓→diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the vertical interval that is
˓→visible in the diagram. {0,0} will select a suitable range.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e left,
˓→right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call
˓→callback function even if it is defined.";
23.1.277 readFile
23.1.278 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;
23.1.279 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";
23.1.280 readSimulationResultSize
function readSimulationResultSize
input String fileName;
output Integer sz;
end readSimulationResultSize;
23.1.281 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;
23.1.282 realpath
function realpath
input String name "Absolute or relative file or directory name";
output String fullName "Full path of 'name'";
end realpath;
23.1.283 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";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.1.284 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
˓→";
23.1.285 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;
23.1.286 regularFileExists
function regularFileExists
input String fileName;
output Boolean exists;
end regularFileExists;
23.1.287 reloadClass
function reloadClass
input TypeName name;
input String encoding = "UTF-8";
output Boolean success;
end reloadClass;
23.1.288 remove
function remove
input String path;
output Boolean success "Returns true on success.";
end remove;
23.1.289 removeComponentModifiers
function removeComponentModifiers
input TypeName class_;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeComponentModifiers;
23.1.290 removeExtendsModifiers
function removeExtendsModifiers
input TypeName className;
input TypeName baseClassName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeExtendsModifiers;
23.1.291 reopenStandardStream
function reopenStandardStream
input StandardStream _stream;
input String filename;
output Boolean success;
end reopenStandardStream;
23.1.292 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;
23.1.293 runOpenTURNSPythonScript
runs OpenTURNS with the given python script returning the log file
function runOpenTURNSPythonScript
input String pythonScriptFile;
output String logOutputFile;
end runOpenTURNSPythonScript;
23.1.294 runScript
23.1.295 runScriptParallel
function runScriptParallel
input String scripts[:];
input Integer numThreads = numProcessors();
input Boolean useThreads = false;
output Boolean results[:];
end runScriptParallel;
23.1.296 save
function save
input TypeName className;
output Boolean success;
end save;
23.1.297 saveAll
function saveAll
input String fileName;
output Boolean success;
end saveAll;
23.1.298 saveModel
function saveModel
input String fileName;
input TypeName className;
output Boolean success;
end saveModel;
23.1.299 saveTotalModel
function saveTotalModel
input String fileName;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
output Boolean success;
end saveTotalModel;
23.1.300 saveTotalSCode
23.1.301 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;
23.1.302 setAnnotationVersion
function setAnnotationVersion
input String annotationVersion;
output Boolean success;
end setAnnotationVersion;
23.1.303 setCFlags
CFLAGS
function setCFlags
input String inString;
output Boolean success;
end setCFlags;
23.1.304 setCXXCompiler
CXX
function setCXXCompiler
input String compiler;
output Boolean success;
end setCXXCompiler;
23.1.305 setCheapMatchingAlgorithm
example input: 3
function setCheapMatchingAlgorithm
input Integer matchingAlgorithm;
output Boolean success;
end setCheapMatchingAlgorithm;
23.1.306 setClassComment
function setClassComment
input TypeName class_;
input String filename;
output Boolean success;
end setClassComment;
23.1.307 setCommandLineOptions
function setCommandLineOptions
input String option;
output Boolean success;
end setCommandLineOptions;
23.1.308 setCompileCommand
function setCompileCommand
input String compileCommand;
output Boolean success;
end setCompileCommand;
23.1.309 setCompiler
CC
function setCompiler
input String compiler;
output Boolean success;
end setCompiler;
23.1.310 setCompilerFlags
function setCompilerFlags
input String compilerFlags;
output Boolean success;
end setCompilerFlags;
23.1.311 setCompilerPath
function setCompilerPath
input String compilerPath;
output Boolean success;
end setCompilerPath;
23.1.312 setDebugFlags
function setDebugFlags
input String debugFlags;
output Boolean success;
end setDebugFlags;
23.1.313 setDefaultOpenCLDevice
function setDefaultOpenCLDevice
input Integer defdevid;
output Boolean success;
end setDefaultOpenCLDevice;
23.1.314 setDocumentationAnnotation
function setDocumentationAnnotation
input TypeName class_;
input String info = "";
input String revisions = "";
output Boolean bool;
end setDocumentationAnnotation;
23.1.315 setEnvironmentVar
function setEnvironmentVar
input String var;
input String value;
output Boolean success;
end setEnvironmentVar;
23.1.316 setIndexReductionMethod
function setIndexReductionMethod
input String method;
output Boolean success;
end setIndexReductionMethod;
23.1.317 setInitXmlStartValue
function setInitXmlStartValue
input String fileName;
input String variableName;
input String startValue;
input String outputFile;
(continues on next page)
23.1.318 setInstallationDirectoryPath
function setInstallationDirectoryPath
input String installationDirectoryPath;
output Boolean success;
end setInstallationDirectoryPath;
23.1.319 setLanguageStandard
function setLanguageStandard
input String inVersion;
output Boolean success;
end setLanguageStandard;
23.1.320 setLinker
function setLinker
input String linker;
output Boolean success;
end setLinker;
23.1.321 setLinkerFlags
function setLinkerFlags
input String linkerFlags;
output Boolean success;
end setLinkerFlags;
23.1.322 setMatchingAlgorithm
function setMatchingAlgorithm
input String matchingAlgorithm;
output Boolean success;
end setMatchingAlgorithm;
23.1.323 setModelicaPath
function setModelicaPath
input String modelicaPath;
output Boolean success;
end setModelicaPath;
23.1.324 setNoSimplify
function setNoSimplify
input Boolean noSimplify;
output Boolean success;
end setNoSimplify;
23.1.325 setOrderConnections
function setOrderConnections
input Boolean orderConnections;
output Boolean success;
end setOrderConnections;
23.1.326 setPlotCommand
function setPlotCommand
input String plotCommand;
output Boolean success;
end setPlotCommand;
23.1.327 setPostOptModules
function setPostOptModules
input String modules;
output Boolean success;
end setPostOptModules;
23.1.328 setPreOptModules
function setPreOptModules
input String modules;
output Boolean success;
end setPreOptModules;
23.1.329 setShowAnnotations
function setShowAnnotations
input Boolean show;
output Boolean success;
end setShowAnnotations;
23.1.330 setSourceFile
function setSourceFile
input TypeName class_;
input String filename;
output Boolean success;
end setSourceFile;
23.1.331 setTearingMethod
function setTearingMethod
input String tearingMethod;
output Boolean success;
end setTearingMethod;
23.1.332 setTempDirectoryPath
function setTempDirectoryPath
input String tempDirectoryPath;
output Boolean success;
end setTempDirectoryPath;
23.1.333 setVectorizationLimit
function setVectorizationLimit
input Integer vectorizationLimit;
output Boolean success;
end setVectorizationLimit;
23.1.334 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.
˓→[cflags], [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 Real numberOfIntervals = 500 "number of intervals in the result file.
˓→<default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default>
˓→= 1e-6";
input String variableFilter = ".*" "Filter for variables that should store in
˓→result file. <default> = \".*\"";
23.1.335 solveLinearSystem
function solveLinearSystem
input Real[size(B, 1), size(B, 1)] A;
input Real[:] B;
input LinearSystemSolver solver = LinearSystemSolver.dgesv;
input Integer[:] isInt = {-1} "list of indices that are integers";
output Real[size(B, 1)] X;
output Integer info;
end solveLinearSystem;
23.1.336 sortStrings
function sortStrings
input String arr[:];
output String sorted[:];
end sortStrings;
23.1.337 stat
23.1.338 stringReplace
function stringReplace
input String str;
input String source;
input String target;
output String res;
end stringReplace;
23.1.339 stringSplit
function stringSplit
input String string;
input String token "single character only";
output String[:] strings;
end stringSplit;
23.1.340 stringTypeName
function stringTypeName
input String str;
output TypeName cl;
end stringTypeName;
23.1.341 stringVariableName
function stringVariableName
input String str;
output VariableName cl;
end stringVariableName;
23.1.342 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;
(continues on next page)
23.1.343 system
output Integer retval "Return value of the system call; usually 0 on success";
end system;
23.1.344 system_parallel
Similar to system(3). Executes the given commands in the system shell, in parallel
˓→if omc was compiled using OpenMP.
23.1.345 testsuiteFriendlyName
function testsuiteFriendlyName
input String path;
output String fixed;
end testsuiteFriendlyName;
23.1.346 threadWorkFailed
23.1.347 translateGraphics
function translateGraphics
input TypeName className;
output String result;
end translateGraphics;
23.1.348 translateModelFMU
Example command:
translateModelFMU(className, version="2.0");
function translateModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 1.0 or 2.0.";
input String fmuType = "me" "FMU type, me (model exchange), cs (co-simulation),
˓→me_cs (both model exchange and co-simulation)";
output String generatedFileName "Returns the full path of the generated FMU.";
end translateModelFMU;
23.1.349 typeNameString
function typeNameString
input TypeName cl;
output String out;
end typeNameString;
23.1.350 typeNameStrings
function typeNameStrings
input TypeName cl;
output String out[:];
end typeNameStrings;
23.1.351 typeOf
function typeOf
input VariableName variableName;
output String result;
end typeOf;
23.1.352 unloadOMSimulator
function unloadOMSimulator
output Integer status;
end unloadOMSimulator;
23.1.353 updateConnection
function updateConnection
input TypeName className;
input String from;
input String to;
input ExpressionOrModification annotate;
output Boolean result;
end updateConnection;
23.1.354 updateConnectionNames
function updateConnectionNames
input TypeName className;
input String from;
input String to;
input String fromNew;
input String toNew;
output Boolean result;
end updateConnectionNames;
23.1.355 updateInitialState
function updateInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end updateInitialState;
23.1.356 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;
23.1.357 uriToFilename
function uriToFilename
input String uri;
output String filename = "";
end uriToFilename;
23.1.358 val
function val
input VariableName var;
input Real timePoint = 0.0;
(continues on next page)
23.1.359 verifyCompiler
function verifyCompiler
output Boolean compilerWorks;
end verifyCompiler;
23.1.360 writeFile
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 contain-
ing different start value for e i.e., 1.7, 2.7, 3.7.
23.3 Examples
The following is an interactive session with the OpenModelica environment including some of the abovemen-
tioned commands and examples. First we start the system, and use the command line interface from OMShell,
OMNotebook, or command window of some of the other tools.
We type in a very small model:
>>> 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.002725486,
timeBackend = 0.001844857,
timeSimCode = 0.0005510480000000001,
timeTemplates = 0.002250845,
timeCompile = 0.527192949,
timeSimulation = 0.05297594100000001,
timeTotal = 0.587729837
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()
>>> 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
a[j,k] := a[j,k]-0.3*j;
end if;
end for;
(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.104622125411205,-1.104622125411205,0.0,0.0,0.0,0.0,0.0},0.
˓→0,8,1)
TWENTYFOUR
24.1 Options
-d, –debug
Sets debug flags. Use –help=debug to see available flags.
String list (default empty).
-h, –help
Displays the help text. Use –help=topics for more information.
String (default empty).
–v, –version
Print the version and exit.
Boolean (default false).
–target
Sets the target compiler to use.
String (default gcc). Valid options:
• gcc
• msvc
• msvc10
• msvc12
• msvc13
• msvc15
• msvc19
• vxworks69
• debugrt
-g, –grammar
Sets the grammar and semantics to accept.
String (default Modelica). Valid options:
• Modelica
• MetaModelica
• ParModelica
287
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
• 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
• latest
–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)
• 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
constraints. This module requires -d=reduceDynOpt.)
• 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.)
Redirect the dump to file. If the file ends with .html HTML code is generated.
String (default empty).
–delayBreakLoop
Enables (very) experimental code to break algebraic loops using the delay() operator. Probably messes with
initialization.
Boolean (default true).
–tearingMethod
Sets the tearing method to use. Select no tearing or choose tearing method.
String (default cellier). Valid options:
• noTearing (Skip tearing.)
• minimalTearing (Minimal tearing method based on a brute force approuch.)
• 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)
–disableLinearTearing
Disables the tearing of linear systems. That might improve the performance of large linear systems(N>1000) in
combination with a sparse solver (e.g. umfpack) at runtime (usage with: -ls umfpack). Deprecated flag: Use
–maxSizeLinearTearing=0 instead.
Boolean (default false).
–scalarizeMinMax
Scalarizes the builtin min/max reduction operators if true.
Boolean (default false).
–scalarizeBindings
Always scalarizes bindings if set.
Boolean (default false).
–corbaObjectReferenceFilePath
Sets the path for corba object reference file if -d=interactiveCorba is used.
–gDynOpt
Generate dynamic optimization problem based on annotation approach.
Boolean (default false).
–maxSizeSolveLinearSystem
Max size for solveLinearSystem.
Integer (default 0).
–cppFlags
Sets extra flags for compilation with the C++ compiler (e.g. +cppFlags=-O3,-Wall)
String list (default ).
–removeSimpleEquations
Specifies method that removes simple equations.
String (default default). Valid options:
• none (Disables module)
• default (Performs alias elimination and removes constant variables. Default case uses in preOpt phase the
fastAcausal and in postOpt phase the causal implementation.)
• causal (Performs alias elimination and removes constant variables. Causal implementation.)
• fastAcausal (Performs alias elimination and removes constant variables. fastImplementation fastAcausal.)
• allAcausal (Performs alias elimination and removes constant variables. Implementation allAcausal.)
• new (New implementation (experimental))
–dynamicTearing
Activates dynamic tearing (TearingSet can be changed automatically during runtime, strict set vs. casual set.)
String (default false). Valid options:
• false (No dynamic tearing.)
• true (Dynamic tearing for linear and nonlinear systems.)
• linear (Dynamic tearing only for linear systems.)
• nonlinear (Dynamic tearing only for nonlinear systems.)
–symSolver
Activates symbolic implicit solver (original system is not changed).
String (default none). Valid options:
• none
• impEuler
• expEuler
–loop2con
Specifies method that transform loops in constraints. hint: using initial guess from file!
String (default none). Valid options:
• none (Disables module)
• lin (linear loops –> constraints)
• noLin (no linear loops –> constraints)
• all (loops –> constraints)
–forceTearing
Use tearing set even if it is not smaller than the original component.
Boolean (default false).
–simplifyLoops
Simplify algebraic loops.
Integer (default 0). Valid options:
• 0 (do nothing)
• 1 (special modification of residual expressions)
• 2 (special modification of residual expressions with helper variables)
–recursiveTearing
Inline and repeat tearing.
Integer (default 0). Valid options:
• 0 (do nothing)
• 1 (linear tearing set of size 1)
• 2 (linear tearing)
–flowThreshold
Sets the minium threshold for stream flow rates
Real (default 1e-07).
–matrixFormat
Sets the matrix format type in cpp runtime which should be used (dense | sparse ). Default: dense.
String (default dense).
–partlintorn
Sets the limit for partitionin of linear torn systems.
Integer (default 0).
–initOptModules
Sets the initialization optimization modules to use in the back end. See –help=optmodules for more info.
String list (default simplifyComplexFunction,tearingSystem,solveSimpleEquations,calculateStrongComponentJacobians,simplifyAl
Valid options:
• calculateStrongComponentJacobians (Generates analytical jacobian for torn linear and non-linear strong
components. By default linear components and non-linear components with user-defined function calls are
skipped. See also debug flags: LSanalyticJacobian, NLSanalyticJacobian and forceNLSanalyticJacobian)
• collapseArrayExpressions (Simplifies {x[1],x[2],x[3]} → x for arrays of whole variable references (simpli-
fies code generation).)
• constantLinearSystem (Evaluates constant linear systems (a*x+b*y=c; d*x+e*y=f; a,b,c,d,e,f are constants)
at compile-time.)
• extendDynamicOptimization (Move loops to constraints.)
• generateHomotopyComponents (Finds the parts of the DAE that have to be handled by the homotopy solver
and creates a strong component out of it.)
• inlineHomotopy (Experimental: Inlines the homotopy expression to allow symbolic simplifications.)
• inputDerivativesUsed (Checks if derivatives of inputs are need to calculate the model.)
• recursiveTearing (inline and repeat tearing)
• reduceDynamicOptimization (Removes equations which are not needed for the calculations of cost and
constraints. This module requires -d=reduceDynOpt.)
-r, –alarm
Sets the number seconds until omc timeouts and exits. Used by the testing framework to terminate infinite running
processes.
Integer (default 0).
–totalTearing
Activates total tearing (determination of all possible tearing sets) for the specified components. Use ’-
d=tearingdump’ to find out the relevant indexes.
Unknown default valueFlags.FlagData.INT_LIST_FLAG(data = {NIL})
–ignoreSimulationFlagsAnnotation
Ignores the simulation flags specified as annotation in the class.
Boolean (default false).
–dynamicTearingForInitialization
Enable Dynamic Tearing also for the initialization system.
Boolean (default false).
–preferTVarsWithStartValue
Prefer tearing variables with start value for initialization.
Boolean (default true).
–equationsPerFile
Generate code for at most this many equations per C-file (partially implemented in the compiler).
Integer (default 2000).
–evaluateFinalParameters
Evaluates all the final parameters in addition to parameters with annotation(Evaluate=true).
Boolean (default false).
–evaluateProtectedParameters
Evaluates all the protected parameters in addition to parameters with annotation(Evaluate=true).
Boolean (default false).
–replaceEvaluatedParameters
Replaces all the evaluated parameters in the DAE.
Boolean (default true).
–condenseArrays
Sets whether array expressions containing function calls are condensed or not.
Boolean (default true).
–wfcAdvanced
wrapFunctionCalls ignores more then default cases, e.g. exp, sin, cos, log, (experimental flag)
Boolean (default false).
–tearingStrictness
Sets the strictness of the tearing method regarding the solvability restrictions.
String (default strict). Valid options:
• casual (Loose tearing rules using ExpressionSolve to determine the solvability instead of considering the
partial derivative. Allows to solve for everything that is analytically possible. This could lead to singularities
during simulation.)
• strict (Robust tearing rules by consideration of the partial derivative. Allows to divide by parameters that
are not equal to or close to zero.)
• veryStrict (Very strict tearing rules that do not allow to divide by any parameter. Use this if you aim at
overriding parameters after compilation with values equal to or close to zero.)
–interactive
Sets the interactive mode for omc.
String (default none). Valid options:
• none (do nothing)
• corba (Starts omc as a server listening on the socket interface.)
• tcp (Starts omc as a server listening on the Corba interface.)
• zmq (Starts omc as a ZeroMQ server listening on the socket interface.)
-z, –zeroMQFileSuffix
Sets the file suffix for zeroMQ port file if –interactive=zmq is used.
String (default empty).
–homotopyApproach
Sets the homotopy approach.
String (default equidistantGlobal). Valid options:
• equidistantLocal (Local homotopy approach with equidistant lambda steps. The homotopy parameter only
effects the local strongly connected component.)
• adaptiveLocal (Local homotopy approach with adaptive lambda steps. The homotopy parameter only effects
the local strongly connected component.)
• equidistantGlobal (Default, global homotopy approach with equidistant lambda steps. The homotopy pa-
rameter effects the entire initialization system.)
• adaptiveGlobal (Global homotopy approach with adaptive lambda steps. The homotopy parameter effects
the entire initialization system.)
–ignoreReplaceable
Sets whether to ignore replaceability or not when redeclaring.
Boolean (default false).
–postOptModulesDAE
Sets the optimization modules for the DAEmode in the back end. See –help=optmodules for more info.
String list (default lateInlineFunction,wrapFunctionCalls,simplifysemiLinear,simplifyComplexFunction,removeConstants,simplifyT
–evalLoopLimit
The loop iteration limit used when evaluating constant function calls.
Integer (default 100000).
–evalRecursionLimit
The recursion limit used when evaluating constant function calls.
Integer (default 256).
–singleInstanceAglSolver
Sets to instantiate only one algebraic loop solver all algebraic loops
Boolean (default false).
–showStructuralAnnotations
Show annotations affecting the solution process in the flattened code.
Boolean (default false).
–initialStateSelection
Activates the state selection inside initialization to avoid singularities.
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.
checkSimplify (default: off) Enables checks for expression simplification and prints a notification whenever an
undesirable transformation has been performed.
constjac (default: off) solves linear systems with constant Jacobian and variable b-Vector symbolically
convertAnalyticalDump (default: off) Dumps the conversion process of analytical to structural singularities.
countOperations (default: off) Count operations.
daedumpgraphv (default: off) Dumps the DAE in graphviz format.
debugAlgebraicLoopsJacobian (default: off) Dumps debug output while creating symbolic jacobians for non-
linear systems.
debugAlias (default: off) Dumps some information about the process of removeSimpleEquations.
debugDAEmode (default: off) Dump debug output for the DAEmode.
debugDifferentiation (default: off) Dumps debug output for the differentiation process.
debugDifferentiationVerbose (default: off) Dumps verbose debug output for the differentiation process.
disableColoring (default: off) Disables coloring algorithm while spasity detection.
disableComSubExp (default: off) Deactivates module ’comSubExp’ Deprecated flag: Use –preOptModules-
=comSubExp instead.
disableDirectionalDerivatives (default: on) For FMI 2.0 only dependecy analysis will be perform.
disableFMIDependency (default: off) Disables the dependency analysis and generation for FMI 2.0.
disableJacsforSCC (default: off) Disables calculation of jacobians to detect if a SCC is linear or non-linear. By
disabling all SCC will handled like non-linear.
disablePartitioning (default: off) Deactivates partitioning of entire equation system. Deprecated flag: Use –
preOptModules-=clockPartitioning instead.
disableRecordConstructorOutput (default: off) Disables output of record constructors in the flat code.
disableSimplifyComplexFunction (default: off) disable simplifyComplexFunction Deprecated flag: Use –
postOptModules-=simplifyComplexFunction/–initOptModules-=simplifyComplexFunction instead.
disableSingleFlowEq (default: off) Disables the generation of single flow equations.
disableStartCalc (default: off) Deactivates the pre-calculation of start values during compile-time.
disableWindowsPathCheckWarning (default: off) Disables warnings on Windows if OPENMODELICA-
HOME/MinGW is missing.
discreteinfo (default: off) Enables dumping of discrete variables. Extends -d=backenddaeinfo.
dummyselect (default: off) Dumps information from dummy state selection heuristic.
dump (default: off) Dumps the absyn representation of a program.
dumpBackendInline (default: off) Dumps debug output while inline function.
shortOutput (default: off) Enables short output of the simulate() command. Useful for tools like OMNotebook.
showDaeGeneration (default: off) Show the dae variable declarations as they happen.
showEquationSource (default: off) Display the element source information in the dumped DAE for easier de-
bugging.
showExpandableInfo (default: off) Show information about expandable connector handling.
showInstCacheInfo (default: off) Prints information about instantiation cache hits and additions. Defaults to
false.
showStartOrigin (default: off) Enables dumping of the DAE startOrigin attribute of the variables.
showStatement (default: off) Shows the statement that is currently being evaluated when evaluating a script.
skipInputOutputSyntacticSugar (default: off) Used when bootstrapping to preserve the input output parsing of
the code output by the list command.
stateselection (default: off) Enables dumping of selected states. Extends -d=backenddaeinfo.
static (default: off) Enables extra debug output from the static elaboration.
stripPrefix (default: on) Strips the environment prefix from path/crefs. Defaults to true.
susanDebug (default: off) Makes Susan generate code using try/else to better debug which function broke the
expected match semantics.
symJacConstantSplit (default: off) Generates all symbolic Jacobians with splitted constant parts.
symjacdump (default: off) Dumps information about symbolic Jacobians. Can be used only with postOptMod-
ules: generateSymbolicJacobian, generateSymbolicLinearization.
symjacdumpeqn (default: off) Dump for debug purpose of symbolic Jacobians. (deactivated now).
symjacdumpverbose (default: off) Dumps information in verbose mode about symbolic Jacobians. Can be used
only with postOptModules: generateSymbolicJacobian, generateSymbolicLinearization.
symjacwarnings (default: off) Prints warnings regarding symoblic jacbians.
tail (default: off) Prints out a notification if tail recursion optimization has been applied.
tearingdump (default: off) Dumps tearing information.
tearingdumpV (default: off) Dumps verbose tearing information.
totaltearingdump (default: off) Dumps total tearing information.
totaltearingdumpV (default: off) Dumps verbose total tearing information.
tplPerfTimes (default: off) Enables output of template performance data for rendering text to file.
transformsbeforedump (default: off) Applies transformations required for code generation before dumping flat
code.
types (default: off) Prints extra failtrace from Types.
uncertainties (default: off) Enables dumping of status when calling modelEquationsUC.
updmod (default: off) Prints information about modification updates.
useMPI (default: off) Add MPI init and finalize to main method (CPPruntime).
vectorize (default: off) Activates vectorization in the backend.
visxml (default: off) Outputs a xml-file that contains information for visualization.
warnMinMax (default: on) Makes a warning assert from min/max variable attributes instead of error.
warnNoNominal (default: off) Prints the iteration variables in the initialization and simulation DAE, which do
not have a nominal value.
writeToBuffer (default: off) Enables writing simulation results to buffer.
TWENTYFIVE
This chapter contains a short overview of simulation flags as well as additional details of the numerical integration
methods.
309
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
-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 ho-
motopy path (default: system size * 100).
-homMaxNewtonSteps=value or -homMaxNewtonSteps value Maximum newton steps in the homotopy cor-
rector step (default: 20).
-homMaxTries=value or -homMaxTries value Maximum number of tries for one homotopy lambda step (de-
fault: 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 initialization problem. Without this flag, the solver first tries to solve the initialization problem without
homotopy and only uses homotopy as fallback option.
-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 (de-
fault: 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))
-jacobianThreads=value or -jacobianThreads value Value specifies the number of threads for jacobian evalua-
tion in dassl or ida. The value is an Integer with default value 1.
-l=value or -l value Value specifies a time where the linearization of the model should be performed.
-l_datarec Emit data recovery matrices with model linearization.
-logFormat=value or -logFormat value Value specifies the log format of the executable:
• text (default)
• xml
• xmltcp (required -port flag)
-ls=value or -ls value Value specifies the linear solver method
• lapack (method using LAPACK LU factorization)
• lis (method using iterative solver Lis)
• klu (method using KLU sparse linear solver)
• umfpack (method using UMFPACK sparse linear solver)
• totalpivot (method using a total pivoting LU factorization for underdetermination systems)
• default (default method - LAPACK with total pivoting as fallback)
-ls_ipopt=value or -ls_ipopt value Value specifies the linear solver method for Ipopt, default mumps. Note: Use
if you build ipopt with other linear solver like ma27
-lss=value or -lss value Value specifies the linear sparse solver method
• default (the default sparse linear solver (or a dense solver if there is none available) )
• lis (method using iterative solver Lis)
• klu (method using klu sparse linear solver)
• umfpack (method using umfpack sparse linear solver)
-lssMaxDensity=value or -lssMaxDensity value Value specifies the maximum density for using a linear sparse
solver. The value is a Double with default value 0.2.
-lssMinSize=value or -lssMinSize value Value specifies the minimum system size for using a linear sparse
solver. The value is an Integer with default value 4001.
-lv=value or -lv value Value (a comma-separated String list) specifies which logging levels to enable. Multiple
options can be enabled at the same time.
• stdout (this stream is always active, can be disabled with -lv=-stdout)
• assert (this stream is always active, can be disabled with -lv=-assert)
• LOG_DASSL (additional information about dassl solver)
• LOG_DASSL_STATES (outputs the states at every dassl call)
• LOG_DEBUG (additional debug information)
• LOG_DSS (outputs information about dynamic state selection)
• LOG_DSS_JAC (outputs jacobian of the dynamic state selection)
• LOG_DT (additional information about dynamic tearing)
• LOG_DT_CONS (additional information about dynamic tearing (local and global constraints))
• LOG_EVENTS (additional information during event iteration)
• LOG_EVENTS_V (verbose logging of event system)
• LOG_INIT (additional information during initialization)
• LOG_IPOPT (information from Ipopt)
• LOG_IPOPT_FULL (more information from Ipopt)
• LOG_IPOPT_JAC (check jacobian matrix with Ipopt)
-optDebugJac=value or -optDebugJac value Value specifies the number of iterations from the dynamic opti-
mization, which will be debugged, creating .csv and .py files.
-optimizerNP=value or -optimizerNP value Value specifies the number of points in a subinterval. Currently
supports numbers 1 and 3.
-optimizerTimeGrid=value or -optimizerTimeGrid value Value specifies external file with time points.
-output=value or -output value Output the variables a, b and c at the end of the simulation to the standard output:
time = value, a = value, b = value, c = value
-outputPath=value or -outputPath value Value specifies a path for writing the output files i.e., model_res.mat,
model_prof.intdata, model_prof.realdata etc.
-override=value or -override value Override the variables or the simulation settings in the XML setup file For
example: var1=start1,var2=start2,par3=start3,startTime=val1,stopTime=val2
-overrideFile=value or -overrideFile value Will override the variables or the simulation settings in the XML
setup file with the values from the file. Note that: -overrideFile CANNOT be used with -override. Use when
variables for -override are too many. overrideFileName contains lines of the form: var1=start1
-port=value or -port value Value specifies the port for simulation status (default disabled).
-r=value or -r value Value specifies the name of the output result file. The default file-name is based on the model
name and output format. For example: Model_res.mat.
-reconcile Run the DataReconciliation algorithm for constrained equation
-rt=value or -rt value Value specifies the scaling factor for real-time synchronization (0 disables). A value > 1
means the simulation takes a longer time to simulate.
-s=value or -s value Value specifies the integration method. For additional information see the User’s Guide
• euler - Euler - explicit, fixed step size, order 1
• heun - Heun’s method - explicit, fixed step, order 2
• rungekutta - classical Runge-Kutta - explicit, fixed step, order 4
• impeuler - Euler - implicit, fixed step size, order 1
• trapezoid - trapezoidal rule - implicit, fixed step size, order 2
• imprungekutta - Runge-Kutta methods based on Radau and Lobatto IIA - implicit, fixed step size,
order 1-6(selected manually by flag -impRKOrder)
• irksco - own developed Runge-Kutta solver - implicit, step size control, order 1-2
• dassl - default solver - BDF method - implicit, step size control, order 1-5
• ida - SUNDIALS IDA solver - BDF method with sparse linear solver - implicit, step size control, order
1-5
• rungekuttaSsc - Runge-Kutta based on Novikov (2016) - explicit, step size control, order 4-5 [experi-
mental]
• symSolver - symbolic inline Solver [compiler flag +symSolver needed] - fixed step size, order 1
• symSolverSsc - symbolic implicit Euler with step size control [compiler flag +symSolver needed] -
step size control, order 1
• qss - A QSS solver [experimental]
• optimization - Special solver for dynamic optimization
-single Output results in single precision (mat-format only).
-steps Dumps the number of integration steps into the result file.
-steadyState Aborts the simulation if steady state is reached.
-steadyStateTol=value or -steadyStateTol value This relative tolerance is used to detect steady state:
max(|d(x_i)/dt|/nominal(x_i)) < steadyStateTol
-sx=value or -sx value Value specifies an csv-file with inputs as covariance matrix Sx for DataReconciliation
-keepHessian=value or -keepHessian value Value specifies the number of steps, which keep Hessian matrix con-
stant.
-w Shows all warnings even if a related log-stream is inactive.
TWENTYSIX
TECHNICAL DETAILS
This chapter gives an overview of some implementation details that might be interesting when building tools
around OpenModelica.
317
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
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).
TWENTYSEVEN
DATARECONCILIATION
The objective of data reconciliation is to use physical models to decrease measurement uncertainties on physical
quantities. Data reconciliation is possible only when redundant measurements are available for a given physical
quantity.
319
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
After defining the modelica model, the users must define the dataReconciliation Input File.
27.1.1 DataReconciliationInputFile
The dataReconciliation Input file is a csv file with the the following headers,
• Variable Names - names of the Uncertainty variables, given in the modelica model
• Measured Value-x – Values given by the users
• HalfWidthConfidenceInterval – Values given by the users, which computes Covariance Matrix Sx
• xi – co-relation- coefficients
• xk - co-relation- coefficients
• rx_ik- value associated with co-relation coefficients
The first 3 column, Variable Names, Measured Value-x and HalfWidthConfidenceInterval are mandatory The
remaining column xi, xk, rx_ik are correlation-coefficients which are optional. An example csv file is given below
The ordering of variables in the csv files should be defined in correct order on how it is declared in the model,
for example in the above example we have uncertain variables defined in the following order Q1,Q2 and Q3
and the same order should be followed for the csv file in order to match the jacobian columns generated for
dataReconciliation Otherwise the dataReconciliation procedure computes wrong results.
Now we are ready to run the DataReconciliation procedure in OpenModelica.
setCommandLineOptions("--preOptModules+=dataReconciliation");
getErrorString();
loadFile("DataReconciliationSimpleTests/package.mo");
getErrorString();
simulate(DataReconciliationTests.Splitter1,simflags="-reconcile -sx=./Splitter1_Sx.
˓→csv -eps=0.0023 -lv=LOG_JAC");
getErrorString();
To start the dataReconciliation procedure via command line interface, the users have to enable the dataReconcil-
iation module which is done via setCommandLineOptions("–preOptModules+=dataReconciliation") which runs
the extraction algorithm for dataReconciliation procedure. And finally the users must specify 3 runtime simulation
flags given below
1. reconcile – runtime flag which starts the dataReconciliation Procedure
2. sx – csv file Input
3. eps – small value given by users
The Flag -lv=LOG_JAC is optional and can be used for debugging.
And finally run the mos script(a.mos) with omc
>> omc a.mos
The HTML Reports, the Csv files and the debugging log are generated in the current directory see DataRecon-
cilation Results.
next time when running the dataReconciliation for the same model, we can directly set the input file and run the
DataReconciliation procedure.
This is done in 2 steps.
• Setting the TranslationFlag defined in TranslationFlag Tab. and press the Ok button.
And then from the plotting window variable browser, right click on the model and select the “re-simulate Setup”
as shown below
Which opens the simulation set-up dialog window and select the simulation Flag tab defined in SimulationFlag
Tab. and load the csv file and fill in the epsilon value and press the “Ok” button to start the Data Reconciliation
Procedure.
TWENTYEIGHT
Below are some frequently asked questions in three areas, with associated answers.
28.2 OMNotebook
• Q: OMNotebook hangs, what to do?
• A: It is probably waiting for the omc.exe (compiler) process. (Under windows): Kill the processes
omc.exe, g++.exe (C-compiler), as.exe (assembler), if present. If OMNotebook then asks whether
to restart OMC, answer yes. If not, kill the process OMNotebook.exe and restart manually.
• Q: After a previous session, when starting OMNotebook again, I get a strange message.
• A: You probably quit the previous OpenModelica session in the wrong way, which left the process
omc.exe running. Kill that process, and try starting OMNotebook again.
• Q: I copy and paste a graphic figure from Word or some other application into OMNotebook, but the
graphic does not appear. What is wrong?
• A: OMNotebook supports the graphic picture formats supported by Qt 4, including the .png, .bmp
(bitmap) formats, but not for example the gif format. Try to convert your picture into one of the
supported formats, (e.g. in Word, first do paste as bitmap format), and then copy the converted version
into a text cell in OMNotebook.
• Q: I select a cell, copy it (e.g. Ctrl-C), and try to paste it at another place in the notebook. However,
this does not work. Instead some other text that I earlier put on the clipboard is pasted into the nearest
text cell.
• A: The problem is wrong choice of cursor mode, which can be text insertion or cell insertion. If you
click inside a cell, the cursor become vertical, and OMNotebook expects you to paste text inside
327
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
the cell. To paste a cell, you must be in cell insertion mode, i.e., click between two cells (or after a
cell), you will get a vertical line. Place the cursor carefully on that vertical line until you see a small
horizontal cursor. Then you should past the cell.
• Q: I am trying to click in cells to place the vertical character cursor, but it does not seem to react.
• A: This seems to be a Qt feature. You have probably made a selection (e.g. for copying) in the output
section of an evaluation cell. This seems to block cursor position. Click again in the output section to
disable the selection. After that it will work normally.
• Q: I have copied a text cell and start writing at the beginning of the cell. Strangely enough, the font be-
comes much smaller than it should be.
• A: This seems to be a Qt feature. Keep some of the old text and start writing the new stuff inside the
text, i.e., at least one character position to the right. Afterwards, delete the old text at the beginning of
the cell.
TWENTYNINE
This Appendix lists the most important OpenModelica releases and a brief description of their contents. Right
now versions from 1.3.1 to 1.16.0 are described.
329
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
components and annotations. • GUI for data reconciliation – a method for increasing sensor data precision • Im-
proved 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 . • Auto-
complete 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.
Backend enhancements
‘‘ * Only warn about non-linear iteration variables with default start attribute.‘‘
‘‘ * Other variables have no influence on simulation at all.‘‘
Backend bugfixes
errors during matching and differentiation. • 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.
• 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
directly. 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‘).
29.7.4 Optimization
29.9.4 Optimization
Several improvements of the Dynamic Optimization module with collocation, using Ipopt:
• Better performance due to smart treatment of algebraic loops for optimization.
• Improved formulation of optimization problems with an annotation approach which also allows graphical
problem formulation.
• Proper handling of constraints at final time.
• Better initialization.
• Improved tearing.
• Improved non-linear, linear and mixed system solving.
• Common subexpression elimination support - drastically increases performance of some models.
29.10.3 Optimization
Some smaller improvements of the Dynamic Optimization module with collocation, using Ipopt.
• Support for model rewriting expressions via rewriting rules in an external file.
• Reject more bad code (r19986, consider records with different components type-incompatible)
29.11.3 OMPython
The interface was changed to version 2.0, which uses one object for each OpenModelica instance you want active.
It also features a new and improved parser that returns easier to use datatypes like maps and lists.
29.11.4 Optimization
A builtin integrated Dynamic Optimization module with collocation, using Ipopt, is now available.
29.12.6 ModelicaML
• Enhanced ModelicaML version with support for value bindings in
requirements-driven modeling available for the latest Eclipse and Papyrus versions. GUI specific adaptations.
Automated model composition workflows (used for model-based design verification against requirements) are
modularized and have improved in terms of performance.
THIRTY
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.
355
OpenModelica User’s Guide, Release v1.14.2-6-g5c52d52477
Eric Meyers, Pratt & Whitney Rocketdyne, Palm City, Florida, USA.
Tuomas Miettinen, VTT, Espoo, Finland.
Afshin Moghadam, PELAB, Linköping University, Linköping, Sweden.
Maroun Nemer, CEP Paristech, Ecole des Mines, Paris, France.
Hannu Niemistö, VTT, Espoo, Finland.
Peter Nordin, IEI, Linköping University, Linköping, Sweden.
Arunkumar Palanisamy, PELAB, Linköping University, Linköping, Sweden.
Karl Pettersson, IEI, Linköping University, Linköping, Sweden.
Pavol Privitzer, Institute of Pathological Physiology, Praha, Czech Republic.
Jhansi Remala, PELAB, Linköping University, Linköping, Sweden.
Reino Ruusu, VTT, Espoo, Finland.
Per Sahlin, Equa Simulation AB, Stockholm, Sweden.
Wladimir Schamai, EADS, Hamburg, Germany.
Gerhard Schmitz, University of Hamburg, Hamburg, Germany.
Alachew Shitahun, PELAB, Linköping University, Linköping, Sweden.
Anton Sodja, University of Ljubljana, Ljubljana, Slovenia
Ingo Staack, IEI, Linköping University, Linköping, Sweden.
Kristian Stavåker, PELAB, Linköping University, Linköping, Sweden.
Sonia Tariq, PELAB, Linköping University, Linköping, Sweden.
Hubert Thierot, CEP Paristech, Ecole des Mines, Paris, France.
Mohsen Torabzadeh-Tari, PELAB, Linköping University, Linköping, Sweden.
Parham Vasaiely, EADS, Hamburg, Germany.
Niklas Worschech, Bosch-Rexroth, Lohr am Main, Germany.
Robert Wotzlaw, Goettingen, Germany.
Azam Zia, PELAB, Linköping University, Linköping, Sweden.
[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.
[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.
[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.
[Pet82] L.R. Petzold. Description of dassl: a differential/algebraic system solver. 1982.
[Axe05] Ingemar Axelsson. OpenModelica Notebook for interactive structured Modelica documents. Master’s
thesis, Linköping University, Department of Computer and Information Science, October 2005. LITH-
IDA-EX–05/080–SE.
[Fernstrom06] Anders Fernström. Extending OpenModelica Notebook – an interactive notebook for structured
Modelica documents. Master’s thesis, Linköping University, Department of Computer and Informa-
tion Science, September 2006. LITH-IDA-EX–06/057—SE.
[Fri04] Peter Fritzson. Principles of Object-Oriented Modeling and Simulation with Modelica 2.1. Wiley-
IEEE Press, February 2004. ISBN 0-471-471631.
[Knu84] Donald E. Knuth. Literate programming. The Computer Journal, 27:97–111, 1984.
[Wol96] Stephen Wolfram. The Mathematica Book. Wolfram Media/Cambridge University Press, third edition,
1996.
[BOR+12] Bernhard Bachmann, Lennart Ochel, Vitalij Ruge, Mahder Gebremedhin, Peter Fritzson, Vaheed
Nezhadali, Lars Eriksson, and Martin Sivertsson. Parallel multiple-shooting and collocation Op-
timization with OpenModelica. In Martin Otter and Dirk Zimmer, editors, Proceedings of the
9th International Modelica Conference. Linköping University Electronic Press, September 2012.
doi:10.3384/ecp12076659.
[RBB+14] Vitalij Ruge, Willi Braun, Bernhard Bachmann, Andrea Walther, and Kshitij Kulshreshtha. Effi-
cient implementation of collocation methods for optimization using openmodelica and adol-c. In
Hubertus Tummescheit and Karl-Erik Årzén, editors, Proceedings of the 10th International Mod-
elica Conference. Modelica Association and Linköping University Electronic Press, March 2014.
doi:10.3384/ecp140961017.
371