OpenModelicaUsersGuide
OpenModelicaUsersGuide
September 2006
Peter Fritzson
Peter Aronsson, Adrian Pop,
David Akhvlediani, Bernhard Bachmann, David Broman,
Anders Fernström, Daniel Hedberg, Elmir Jagudin,
Håkan Lundvall, Kaj Nyström, Andreas Remar, Anders Sandholm
Copyright by:
Programming Environment Laboratory – PELAB
Department of Computer and Information Science
Linköping University, Sweden
3
Copyright © 1998-2006, PELAB, Department of Computer and Information Science, Linköpings universitet.
All rights reserved.
This document is part of OpenModelica: www.ida.liu.se/projects/OpenModelica
Contact: [email protected]
Table of Contents
Preface
This users guide provides documentation and examples on how to use the OpenModelica system, both for
the Modelica beginners and advanced users.
10
11
Chapter 1
Introduction
The OpenModelica system described in this document has both short-term and long-term goals:
• The short-term goal is to develop an efficient interactive computational environment for the Modelica
language, 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 longer-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
generating code for parallel hardware.
• Improved debugging support for equation based languages such as Modelica, to make them even easier
to use.
• Easy-to-use specialized high-level (graphical) user interfaces for certain application domains.
• Visualization and animation techniques for interpretation and presentation of results.
• Application usage and model library development by researchers in various application areas.
The OpenModelica environment provides a test bench for language design ideas that, if successful, can be
submitted to the Modelica Association for consideration regarding possible inclusion in the official Modelica
standard.
12
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. An external function library interfacing a LAPACK subset and other
basic algorithms is under development.
Interactive
Emacs session handler Textual
Editor/Browser Model Editor
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
interactive 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. The
graphical model editor is not really part of OpenModelica but integrated into the system and available from
MathCore without cost for academic usage.
The following subsystems are currently integrated in the OpenModelica environment:
• An interactive session handler, that parses and interprets commands and Modelica expressions for
evaluation, simulation, plotting, etc. The session handler also contains simple history facilities, and
completion of file names and certain identifiers in commands.
• A Modelica compiler subsystem, translating Modelica to C code, with a symbol table containing
definitions of classes, functions, and variables. Such definitions can be predefined, user-defined, or
obtained from libraries. The compiler also includes a Modelica interpreter for interactive usage and
constant expression evaluation. The subsystem also includes facilities for building simulation
executables linked with selected numerical ODE or DAE solvers.
• An execution and run-time module. This module currently executes compiled binary code from
translated expressions and functions, as well as simulation code from equation based models, linked
with numerical solvers. In the near future event handling facilities will be included for the discrete and
hybrid parts of the Modelica language.
13
• Emacs textual model editor/browser. In principle any text editor could be used. We have so far
primarily employed Gnu Emacs, which has the advantage of being programmable for future extensions.
A Gnu Emacs mode for Modelica has previously been developed. The Emacs mode hides Modelica
graphical annotations during editing, which otherwise clutters the code and makes it hard to read. A
speedbar browser menu allows to browse a Modelica file hierarchy, and among the class and type
definitions in those files.
• Eclipse plugin editor/browser. The Eclipse plugin called MDT (Modelica Development Tooling)
provides file and class hierarchy browsing and text editing capabilities, rather analogous to previously
described Emacs editor/browser. Some syntax highlighting facilities are also included. The Eclipse
framework has the advantage of making it easier to add future extensions such as refactoring and cross
referencing support.
• OMNotebook DrModelica model editor. This subsystem provides a lightweight notebook editor,
compared to the more advanced Mathematica notebooks available in MathModelica. This basic
functionality still allows essentially the whole DrModelica tutorial to be handled. Hierarchical text
documents with chapters and sections can be represented and edited, including basic formatting. Cells
can contain ordinary text or Modelica models and expressions, which can be evaluated and simulated.
However, no mathematical typesetting or graphic plotting facilities are yet available in the cells of this
notebook editor.
• Graphical model editor/browser. This is a graphical connection editor, for component based model
design by connecting instances of Modelica classes, and browsing Modelica model libraries for reading
and picking component models. The graphical model editor is not really part of OpenModelica but
integrated into the system and provided by MathCore without cost for academic usage. The graphical
model editor also includes a textual editor for editing model class definitions, and a window for
interactive Modelica command evaluation.
• Modelica debugger. The current implementation of debugger provides debugging for an extended
algorithmic subset of Modelica, excluding equation-based models and some other features, but
including some meta-programming and model transformation extensions to Modelica. This is
conventional full-feature debugger, using Emacs 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.
We enter an assignment of a vector expression, created by the range construction expression 1:12, to be stored
in the variable x. The value of the expression is returned.
>> x := 1:12
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
The function bubblesort is called below to sort the vector x in descending order. The sorted result is returned
together with its type. Note that the result vector is of type Real[:], instantiated as Real[12], since this is
the declared type of the function result. The input Integer vector was automatically converted to a Real
vector according to the Modelica type coercion rules. The function is automatically compiled when called if
this has not been done before.
>> bubblesort(x)
{12.0,11.0,10.0,9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0}
Another call:
15
>> bubblesort({4,6,2,5,8})
{8.0,6.0,5.0,4.0,2.0}
It is also possible to give operating system commands via the system utility function. A command is provided
as a string argument. The example below shows the system utility applied to the UNIX command cat, which
here outputs the contents of the file bubblesort.mo to the output stream. However, the cat command does not
boldface Modelica keywords – this improvement has been done by hand for readability.
>> cd("C:/OpenModelica1.4.2/testmodels")
>> system("cat 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;
Another built-in command is cd, the change current directory command. The resulting current directory is
returned as a string.
>> cd()
"C:\OpenModelica1.4.2\testmodels"
>> cd("..")
"C:\OpenModelica1.4.2"
>> cd("C:\\OpenModelica1.4.2\\testmodels")
"C:\OpenModelica1.4.2\testmodels"
16
It is simulated:
>> simulate(dcmotor,startTime=0.0,stopTime=10.0)
record
resultFile = "dcmotor_res.plt"
end record
equation
connect(v.p,r1.p);
connect(v.n,g.p);
connect(r1.n,i1.p);
connect(i1.n,emf1.p);
connect(emf1.n,g.p);
connect(emf1.flange_b,load.flange_a);
end dcmotor;
"
v.p.v = r1.p.v;
load.flange_b.tau = 0.0;
end dcmotor;
"
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:
loadFile("BouncingBall.mo");
simulate(BouncingBall, stopTime=3.0);
plot({h,flying});
We enter a switch model, to test if-equations (e.g. copy and paste from another file and push enter):
>> 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;
20
Ok
>> simulate(Switch, startTime=0, stopTime=1);
We note that the variable open switches from false (0) to true (1), causing itot to increase from 1.0 to 2.0.
It is simulated:
>> simulate(VanDerPol)
record
resultFile = "VanDerPol_res.plt"
21
end record
It is plotted:
plotParametric(x,y);
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
A simple if-statement. By putting the variable last, after the semicolon, its value is returned after evaluation:
>> if 5>2 then a := 77; end if; a
77
>> 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;
Ok
Clear again:
>> clear()
true
function ExternalFunc2
24
input Real x;
output Real y;
external "C" annotation(Library="libExternalFunc2.a",
Include="#include \"ExternalFunc2.h\"");
end ExternalFunc2;
/* file: ExternalFunc2.c */
double ExternalFunc2(double x)
{
double res;
res = (x-1.0)*(x+2.0);
return res;
}
The following script file ExternalLibraries.mos will perform everything that is needed, provided you
have gcc installed in your path:
loadFile("ExternalLibraries.mo");
system("gcc -c -o libExternalFunc1_ext.o ExternalFunc1.c");
system("gcc -c -o libExternalFunc2.a ExternalFunc2.c");
simulate(ExternalLibraries);
simulate(modelname[,startTime=<Real>][,stopTime=<Real>][,numberOfIntervals
=<Integer>]) 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. Many steps will give higher time
resolution, but occupy more space and take longer to compute. The default
number of intervals is 500.
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.
plotParametric(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.
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.
help() Print this helptext (returned as a string).
quit() Leave and quit the OpenModelica environment
28
Chapter 2
This chapter just presents a very simple example of using graphical modeling of Modelica models. A model is
built using the graphical model editor by using drag-and-drop of already developed and freely available model
components from the Modelica Standard Library.
NOTE: This chapter is just a short sample of using the graphical model editor. See www.mathcore.com
for the current manual and the complete MathModelica System Designer Graphic Model Editor Users Guide.
As mentioned previously, the graphic editor is not part of OpenModelica, but a MathModelica Lite Edition of
the GraphicEditor that works together with OpenModelica can be downloaded from the OpenModelica web
site. (The MathModelica Lite edition of the editor is free for non-commercial usage and commercial
evaluation).
The Modelica Standard Library can be loaded into the OpenModelica environment when the model editor is
started and can be browsed using the class browser visible at the left of Figure 2-1 below.
Figure 2-1. The Graphical Model Editor with the class browser to the left, the graphic editing area in the middle
and the instance component browser to the right.
29
To open the library, click on the Browse libraries button in the class browser to the left. As shown by
Figure 2-2, the Modelica Standard Library is hierarchically structured into sublibraries.
Figure 2-2. The Graphical Model Editor with the class browser showing the Modelica Standard library opened
up into sublibraries.
The following list briefly mentions some of the most important sublibraries in the Modelica standard library, as
well as the Users Guide:
Blocks Continuous and discrete input/output blocks for use in block diagrams.
Constants Common constants from mathematics, physics, etc.
Electrical Common electrical components, such as resistors and transistors.
Icons Graphical layout for many component icons
Math Definitions of common mathematical functions, such as sin, cos, and log.
Mechanics Mechanical rotational and translational components.
SIunits Type definitions with SI standard names and units.
UsersGuide Browse the Users Guide.
Figure 2-4. The Graphical Model Editor with the new Motor model appearing as a question mark icon in the
class browser window to the left.
Now you can assemble the DC motor by drag-and-drop of components from the class browser to the diagram
view window to the right. The constant voltage source component can be found in the
31
Figure 2-5. Several components dragged into the diagram view of the Graphic Model Editor.
When the components have been placed on the drawing area, similar to the figure above, you have to draw the
lines that connect the components. This is done using the connector tool from the toolbar:
To connect two components, select the connector tool and place the mouse cursor over a connector, i.e., the
square symbol on either side of the component. When you are close enough, the mouse cursor will change into
a cross. Click and a hold down the left mouse button, drag the cursor to the other connector and then release the
mouse button when the mouse cursor turns into a cross. Continue to connect all components until the model
diagram resembles the one in Figure 2-6 below.
32
2.1.3 Plotting
After the model has been translated and simulated, any of its variables can be plotted (Figure 2-8). Such
plotting from the Graphic Model Editor is not available in the MathModelica Lite Edition. Instead, plotting can
be made from the command line through the plot command, as in the examples shown in Section 1.2.
Figure 2-8. MathModelica plot window created after a simulation of the Motor model, using the full version of
the MathModelica System Designer Graphic Editor (plotting not available in the MathModelica Lite version).
35
Chapter 3
This chapter covers the OpenModelica electronic notebook subsystem, called OMNotebook, together with the
DrModelica tutoring system for teaching Modelica, which is using such notebooks.
3.1.2 OMNotebook
The OMNotebook software (Axelsson 2005, Fernström 2006) is a new open source free software that gives an
interactive WYSIWYG (What-You-See-Is-What-You-Get) 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 (What-You-See-Is-What-You-Get)
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 3-1.
36
Figure 3-1. Examples of Mathematica notebooks in the MathModelica modeling and simulation environment.
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..
Understanding programs is hard, especially code written by someone else. For educational purposes it is
essential to be able to show the source code and to give an explanation of it at the same time.
Moreover, it is important to show the result of the source code’s execution. In modeling and simulation it is
also important to have the source code, the documentation about the source code, the execution results of the
simulation model, and the documentation of the simulation results in the same document. The reason is that the
problem solving process in computational simulation is an iterative process that often requires a modification
of the original mathematical model and its software implementation after the interpretation and validation of
the computed results corresponding to an initial model.
Most of the environments associated with equation-based modeling languages focus more on providing
efficient numerical algorithms rather than giving attention to the aspects that should facilitate the learning and
teaching of the language. There is a need for an environment facilitating the learning and understanding of
Modelica. These are the reasons for developing the DrModelica teaching material for Modelica and for
teaching modeling and simulation.
37
An earlier version of DrModelica was developed using the MathModelica environment. The rest of this
chapter is concerned with the OMNotebook version of DrModelica and on the OMNotebook tool itself.
DrModelica has a hierarchical structure represented as notebooks. The front-page notebook is similar to a
table of contents that holds all other notebooks together by providing links to them. This particular notebook is
the first page the user will see (Figure 3-2).
Figure 3-2. The front-page notebook of the OMNotebook version of the DrModelica tutoring system.
38
In each chapter of DrModelica the user is presented a short summary of the corresponding chapter of the book
“Principles of Object-Oriented Modeling and Simulation with Modelica 2.1” by Peter Fritzson. The summary
introduces some keywords, being hyperlinks that will lead the user to other notebooks describing the keywords
in detail.
Figure 3-3. The HelloWorld class simulated and plotted using the OMNotebook version of DrModelica.
Now, let us consider that the link “HelloWorld” in DrModelica Section is clicked by the user. The new
HelloWorld notebook (see Figure 3-3), to which the user is being linked, is not only a textual description but
39
also contains one or more examples explaining the specific keyword. In this class, HelloWorld, a differential
equation is specified.
No information in a notebook is fixed, which implies that the user can add, change, or remove anything in a
notebook. Alternatively, the user can create an entirely new notebook in order to write his/her own programs or
copy examples from other notebooks. This new notebook can be linked from existing notebooks.
Figure 3-4. DrModelica Chapter on Algorithms and Functions in the main page of the OMNotebook version of
DrModelica.
40
When a class has been successfully evaluated the user can simulate and plot the result, as previously depicted
in Figure 3-3 for the simple HelloWorld example model..
After reading a chapter in DrModelica the user can immediately practice the newly acquired information by
doing the exercises that concern the specific chapter. Exercises have been written in order to elucidate language
constructs step by step based on the pedagogical assumption that a student learns better “using the strategy of
learning by doing”. The exercises consist of either theoretical questions or practical programming assignments.
All exercises provide answers in order to give the user immediate feedback.
Figure 3-4 shows part of Chapter 9 of the DrModelica teaching material. Here the user can read about
language constructs, like algorithm sections, when-statements, and reinit equations, and then practice
these constructs by solving the exercises corresponding to the recently studied section.
3.3.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 are used to display ordinary text and images. Each textcell has a style that
specifies how text is displayed. The cell´s style can be changed in the menu Format->Styles,
example of different styles are: Text, Title, and Subtitle. The Textcell type also has support
for following links to other notebook documents.
• Inputcell – This cell type has support for syntax highlighting and evaluation. It is intended to be
used for writing program code, e.g. Modelica code. Evaluation is done by pressing the key
combination Shift+Return or Shift+Enter. All the text in the cell is sent to OMC (OpenModelica
Compiler/interpreter), where the text is evaluated and the result is displayed below the inputcell. By
double-clicking on the cell marker in the tree view, the inputcell can be collapsed causing the result
to be hidden.
• 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.
3.3.2 Cursors
An OMNotebook document contains cells which in turn contain text. Thus, two kinds of cursors are needed
for positioning, text cursor and cell cursor:
• Textcursor – A cursor between characters in a cell, appearing as a small vertical line. Position the
cursor by clicking on the text or using the arrow buttons.
• Cellcursor – This cursor shows which cell currently has the input focus. It consists of two parts.
The main cellcursor is basically just a thin black horizontal line below the cell with input focus. The
cellcursor is positioned by clicking on a cell, clicking between cells, or using the menu item Cell-
>Next Cell or Cell->Previous Cell. The cursor can also be moved with the key combination
Ctrl+Up or Ctrl+Down. The dynamic cellcursor is a short blinking horisontal 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 horisontal line).
between last selected cell and the cell clicked on. This only works if both cells belong to the same
groupcell.
• Copy cell – Cells can be copied from a document with the menu item Edit->Copy or the key
combination Ctrl+C. The copy function will always copy cells if cells have been selected in the tree
view, otherwise the copy function copy text.
• 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.
• Text manipulation – There are a number of different text manipulations that can be done to change
the appearance of the text. These manipulations include operations like: changing font, changing
color and make text bold, but also operations like: changing the alignment of the text and the
margin inside the cell. All text manipulations inside a cell can be done on single letters, words or
the entire text. Text settings are found in the Format menu. The following text manipulations are
available in OMNotebook:
> Font family
> Font face (Plain, Bold, Italic, Underline)
> Font size
> Font stretch
> Font color
> Text horizontal alignment
> Text vertical alignment
> Border thickness
> Margin (outside the border)
> Padding (inside the border)
• 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
disabled. 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.
3.5 References
Eric Allen, Robert Cartwright, Brian Stoler. DrJava: A lightweight pedagogic environment for Java. In
Proceedings 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).
Ingemar Axelsson. OpenModelica Notebook for Interactive Structured Modelica Documents. Final thesis, LITH-
IDA-EX–05/080–SE, Linköping University, Linköping, Sweden, October 21, 2005.
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.
Anders Fernström. Extending OMNotebook – An Interactive Notebook for Structured Modelica
Documents.Final thesis to be presented spring 2006, Dept. Computer and Information Science, Linköping
University, Sweden.
Peter Fritzson. Principles of Object Oriented Modeling and Simulation with Modelica 2.1, 940 pages, ISBN 0-
471-471631, Wiley-IEEE Press. Feb. 2004.
Knuth, Donald E. Literate Programming. The Computer Journal, NO27(2), pp. 97–111, May 1984.
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.
The Modelica Association. The Modelica Language Specification Version 2.2, March 2005.
http://www.modelica.org.
Stephen Wolfram. The Mathematica Book. Wolfram Media Inc, 1997.
48
Chapter 4
An Emacs Modelica mode provides facilities for keyword highlighting, suppressing annotations, etc. It can
be downloaded from the OMDevelopers part of the OpenModelica web page
www.ida.liu.se/projects/OpenModelica.
(?? Need to describe those facilities, including how the Modelica mode is started).
Another quite useful facility is the Speedbar menu, depicted in Figure 4-1. (?? This Screendump shows the
same facility used for RML code, not Modelica code. Needs to be updated. Currently not included in the
Modelica mode.)
Figure 4-1. Emacs with a speedbar menu to the left, which allows clicking on file names (for expansion or
closing the file contents menu). An expanded file shows all function, class, and type declarations. By clicking
on one of those, you can position the editor at the appropriate definition.
Give the command M-x speedbar to start the Speedbar menu. See Section 6.1 for an explanation to the
notation M-x, etc.
49
When you open files the speedbar menu will automatically update itself. You can double-click with the
left mouse button or single-click with the middle button to expand trees, and jump between files and
program definitions.
At the top you see the search path to the current directory, where you can click on the directory names
at different levels to jump back and forth in the hierarchy. Subdirectories are visible in the tree as
expandable nodes.
It is also possible to right-click in the speedbar window to have a menu appear.
50
Chapter 5
5.1 Introduction
The Modelica Development Tooling (MDT) Eclipse Plug-In integrates the OpenModelica compiler with
Eclipse. MDT, together with the OpenModelica compiler, provides an environment for working with
Modelica development projects.
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
• Code completion for class names and function argument lists.
5.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).
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
51
The second variant is useful when typing a call to a function. It shows the function signature (formal
parameter 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:
57
Chapter 6
This chapter presents a comprehensive Modelica debugger for an extended algorithmic subset of the
Modelica language. This replaces debugging of algorithmic code using primitive means such as print
statements or asserts which is complex, time-consuming and error- prone.
Note: This Debugger is not yet released for general usage.There is current ongoing work in integrating
the Debugger into the MDT/Eclipse plugin for Modelica. This chapter has not yet been updated for the
Eclipse plugin release of the debugger in OpenModelica 1.4.2.
The debugger is portable since it is based on transparent source code instrumentation techniques that are
independent of the implementation platform.
The usual debugging functionality found in debuggers for procedural or traditional object-oriented
languages is supported, such as setting and removing breakpoints, single-stepping, inspecting variables,
back-trace of stack contents, tracing, etc.
We presents the debugger functionality by a debugging session on a short Modelica example. The
functionality of the debugger is shown using pictures from the Emacs debugging mode for Modelica
(modelicadebug-mode).
Note 1: The current (August 2006) implementation of the debugger only works together with the
Modelica compiler version that supports an extended algorithmic subset of Modelica, without equations
and simulation, but including meta-programming support. Both compiler versions will be merged into a
single version in the near future. It is not yet released for general usage.
Note 2: when applying the debugger to debug the OpenModelica compiler itself, give the make debug
command to compile the code with debugging turned on, or just the command: make, to compile it without
debugging support.
C-c C-r
C-x C-a C-r
mdb@> ru|run <RET>
at the debugger prompt. The debugger will try to connect to the ModelicaDataViewer and send the
contents of the variable. The external data browser has to be started a priori. If the debugger cannot connect
to the external viewer within a specified timeout a warning message will be displayed. A picture of the
external ModelicaDataViewer tool is presented in Figure 6-3.
Figure 6-3. Modelica Data Viewer (Browser) for data structures, here a small abstract syntax tree.
If the variable which one tries to print does not exist in the current scope (not a live variable) a notifying
warning message will be displayed.
Automatic printing of variables at every step or breakpoint can be specified by adding a variable to a
display list:
mdb@> di|display variable_name <RET>
Instructing the debugger to print or to disable the print of the live variable names at each step/breapoint:
mdb@> [set] li|live|livevars [on|off]<RET>
Figure 6-4 shows examples of some of these commands within a debugging session:
61
Figure 6-4. Examining variable values using print and display commands.
Because the contents of the stack can be quite large, one can print a filtered view of it:
mdb@> fbt|fbacktrace filter_string <RET>
Also, one can restrict the numbers of entries the debugger is storing using:
mdb@> maxbt|maxbacktrace integer <RET>
The status of the extended Modelica runtime comprises information regarding the garbage collector,
allocated memory, stack usage, etc.
The current debugging settings can be displayed using:
mdb@> stg|settings <RET>
The settings printed are: the maximum remembered backtrace entries, the depth of variable printing, the
current breakpoints, the live variables, the list of the display variables and the status of the runtime system.
One can invoke the debugging help by issuing:
mdb@> he|help <RET>
[set] de|depth integer Set the depth of variable printing. (0=full, default=10)
[set] ms|maxstring integer Set how may chars we print from long strings. (0=full,
default=60)
set st|step [on|off] Set the execution mode.
st|step|<ENTER>|<CR> Perform one step.
ne|next Jump over next statement.
ru|run Run the program.
stg|settings Print the current settings.
he|help Showing help.
sts|stat|status Printing the status of Modelica runtime.
li|live|livevars Print the names of live variables.
[set] li|live|livevars [on|off] On/Off printing names of livevars each step.
pr|print var_name Print the live variable.
sz|size|sizeof var_name Print sizeof the live variable.
di|display var_name Display the live variable each step.
ud|undisplay var_name Un-display the live variable.
di|display Show display variables.
ud|undisplay Un-display ALL display variables.
gr|graph var_name Send the live variable to external viewer.
pty|printtype identifier Print type info on any Modelica id.
fa|fast FAST debugging: no backtrace, callchain, livevars.
qu|quit|ex|exit|by|bye Exiting the debugger/program.
64
Chapter 7
Below are some frequently asked questions in three areas, with associated answers.
7.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.
65
• 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: Plotting does not work in OMNotebook.
• A: You probably have an old version of Java installed. Update your installation, and try again.
(Another known problem, soon to be fixed, is that plotting of parameters and constants does not yet
work).
• 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 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
becomes 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.
Appendix A
This Appendix lists the most important OpenModelica releases and a brief description of their contents.
However, right now only the versions from 1.3.1 to 1.4.2 are described. (The earlier releases will be
described in a future update of the Users Guide).
Modelica code, including the MetaModelica extensions. Many bug fixes. The Eclipse plug-in is now in use
for OpenModelica development at PELAB and MathCore Engineering AB since approximately one month.
Appendix B
Contributors to OpenModelica
This Appendix lists the individuals who have made significant contributions to OpenModelica, in the form
of software development, design, documentation, project leadership, tutorial material, 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.
Index