modelica - a domain-specific language - implementation and...

54
Modelica - A Domain-Specific Language Implementation and Overview of the OpenModelica Compiler Martin Sjölund Department of Computer and Information Science Linköping University 2016-11-10

Upload: others

Post on 13-May-2020

26 views

Category:

Documents


0 download

TRANSCRIPT

Modelica - A Domain-Specific LanguageImplementation and Overview of the OpenModelica Compiler

Martin Sjölund

Department of Computer and Information ScienceLinköping University

2016-11-10

Overview

Part I BackgroundPart II Implementation of a Modelica CompilerPart III Conclusion

Part I

Background

Classic Compiler

I Very structured.I Translates from one intermediate representation to another.I Assumes it is straight-forward to translate code from one

representation to another.I Usually statement-based code (maybe some object

orientation).I Taught in courses TDDB44 and TDDD55.

The Phases of the Compiler

Lexical analysis

Syntactic analysis

Semantic

source program

sequence of tokens:’IF’ ’sum’ ’=’ ’5’

sequence of chars: ’IF sum=5 THEN..’

parse tree, derivation tree

TDDD55/B44, P Fritzson, IDA, LIU, 2011.

Error Management

Table management

Semanticanalysis andIntermediate

code gen

Code optimization

Code generation

object program

internal form, intermediate code

internal form

Systems Engineering

I Handling large, complex projects.I Combining requirements, modeling,

simulation, deployment, support,etc.

I Inter-disciplinary.I You often end up with many

different tools because differentdomains traditionally used differenttools.

Systems Engineering – Example Tools

I Early stage – Administrators and managers emailaround Word (contracts) and Excel(requirements) sheets

I Requirements are formalized and stored in adatabase somewhere

I Requirements are mapped to UML modelsI UML is mapped to a design (empty classes)I The actual code is written (perhaps C)I The code is adapted/generated to run on a

certain platform (MISRA C perhaps?)I The code tested/certified, etc

Domain-Specific Languages

I Many are similar to classic, general-purpose programminglanguages (e.g. PHP).

I Examples include unix shells, SQL, HTML, regular expressions,parser generators, some XML schemas, and many more.

I Compilers are usually implemented partially usingdomain-specific languages (grammars, special languages todescribe architectures, etc).

I Why? It is easier to program and maintain such code.

DSLs: Markup Languages

Listing 1: HTML is markup code (some of which is interpreted)<!DOCTYPE html><html><body>

<h1>My first HTML page</h1>

<p>Hello, world!</p>

</body></html>

DSLs: Template Languages

Listing 2: PHP code in-between pieces of code or markup<!DOCTYPE html><html><body>

<h1>My first PHP page</h1><?phpecho $_SERVER["REMOTE_ADDR"];?></body></html>

DSLs: Embedded Scripting Languages

Listing 3: JavaScript is interpreted code that was fast enough to beembedded in web-browsers back in 1997<!DOCTYPE html><html><body>

<p id="demo"></p>

<script>document.getElementById("demo").innerHTML = "Hello World!";</script>

</body></html>

DSLs: Shell Scripting Languages

Listing 4: Bash is either an interactive shell or interpreted codesuitable for running system commands#!/bin/bash

if test -f testsuite/Makefile; thencd testsuitefor test in *.test; do

grep "status: *correct" "$test"done

fi

DSLs: Regular expressions

Listing 5: Regular expressions appear almost everywhere from texteditors to the venerable grepgrep "status: *correct" "$test"grep -R "openmodelica[.]org" /etc/apache2

DSLs: Build configuration

Listing 6: autoconf translates a description of possible build config-urations and generates a shell script to run thisAC_PREREQ([2.63])AC_INIT([OMCompiler],[dev],[https://trac.openmodelica.org/

OpenModelica],[openmodelica],[https://openmodelica.org])AC_LANG([C])AC_PROG_CCAC_SEARCH_LIBS(dlopen,dl)

DSLs: Build systems

Listing 7: make interprets build dependencies and build rules to runshell commandslibOpenModelicaRuntimeC.so: $(BASE_OBJS) $(GCOBJPATH_MINIMAL)

@rm -f $@$(CC) -shared -o $@ $(BASE_OBJS) $(GCOBJPATH_MINIMAL)

$(LDFLAGS)

Modelica

I An equation-based object-orientedmodeling language (a DSL).

I Modeling using a graphical userinterface (or the equivalent textualrepresentation).

I Used for simulation and/or controlof multi-domain (physical) systems.

I Centered around making it easy fora (mechanical, electrical, etc)engineer to use Modelica.

pv

+-

C=1e-6

c

R=1e6

r

g

Figure: An RC-circuitimplemented in Modelica.

Simulating the RC-circuit

0

50

100

150

200

250

0 1 2 3 4 5

Volt

ag

e [

V]

time [s]

Figure: Result of simulating the RC-circuit.

Equations

Physics is described by equations, not statements. Thus, Modelicaprimarily uses equations instead of imperative programming (likeC).

I Equations look like VR = I

However, code needs to be translated to imperative programming(or similar) in order to run numerical solvers on a CPU. So it couldbe solved as either of:

I V := R ∗ II I := V

RI R := V

I

Ordinary Differential Equations (ODEs)

The numerical solvers we use require an ODE formulation. Forexample:

∂x∂t = y (1)

d = 2.0 ∗ t (2)∂y∂t = −d ∗ x (3)

Where these equations can be solved sequentially and the startvalue for each state variable is known or can be solved duringinitialization.

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00x 3.00y 2.00∂x∂t = yd = 2.0 ∗ t∂y∂t = −d ∗ x

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00x 3.00y 2.00∂x∂t = y 2.00d = 2.0 ∗ t∂y∂t = −d ∗ x

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00x 3.00y 2.00∂x∂t = y 2.00d = 2.0 ∗ t 0.00∂y∂t = −d ∗ x

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00x 3.00y 2.00∂x∂t = y 2.00d = 2.0 ∗ t 0.00∂y∂t = −d ∗ x 0.00

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25x 3.00 3.50y 2.00∂x∂t = y 2.00d = 2.0 ∗ t 0.00∂y∂t = −d ∗ x 0.00

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25x 3.00 3.50y 2.00 2.00∂x∂t = y 2.00d = 2.0 ∗ t 0.00∂y∂t = −d ∗ x 0.00

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25x 3.00 3.50y 2.00 2.00∂x∂t = y 2.00 2.00d = 2.0 ∗ t 0.00 0.50∂y∂t = −d ∗ x 0.00 -1.75

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25 0.50x 3.00 3.50 4.00y 2.00 2.00 1.5625∂x∂t = y 2.00 2.00d = 2.0 ∗ t 0.00 0.50∂y∂t = −d ∗ x 0.00 -1.75

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25 0.50x 3.00 3.50 4.00y 2.00 2.00 1.5625∂x∂t = y 2.00 2.00 1.5625d = 2.0 ∗ t 0.00 0.50 1.00∂y∂t = −d ∗ x 0.00 -1.75 -4.00

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25 0.50 0.75x 3.00 3.50 4.00 4.390625y 2.00 2.00 1.5625 0.5625∂x∂t = y 2.00 2.00 1.5625d = 2.0 ∗ t 0.00 0.50 1.00∂y∂t = −d ∗ x 0.00 -1.75 -4.00

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25 0.50 0.75x 3.00 3.50 4.00 4.390625y 2.00 2.00 1.5625 0.5625∂x∂t = y 2.00 2.00 1.5625 0.5625d = 2.0 ∗ t 0.00 0.50 1.00 1.50∂y∂t = −d ∗ x 0.00 -1.75 -4.00 -6.5859375

Solving the Ordinary Differential Equation

Solving the ODE from t=0 to t=1 using a step size of 0.25 withexplicit (forward) Euler, using x(t = 0) = 3 and y(t = 0) = 2:t 0.00 0.25 0.50 0.75 1.00x 3.00 3.50 4.00 4.390625 4.53125y 2.00 2.00 1.5625 0.5625 -1.083984375∂x∂t = y 2.00 2.00 1.5625 0.5625d = 2.0 ∗ t 0.00 0.50 1.00 1.50∂y∂t = −d ∗ x 0.00 -1.75 -4.00 -6.5859375

Better Solutions for the Ordinary Differential EquationModelica tools need to know about ODEs, andcan solve them better than the explicit Euler.The end values for different solvers:

I Euler stepSize=0.25, x=4.531, y=-1.084, 4 rhs calls

I Euler stepSize=0.10, x=4.087, y=-1.600, 10 rhs calls

I RK4 stepSize=1.00, x=3.667, y=-1.667, 4 rhs calls

I RK4 stepSize=0.25, x=3.747, y=-1.841, 16 rhs calls

I DASSL, tolerance=1e-3, x=3.745, y=-1.838, 15 rhscalls

I DASSL, x=3.747, y=-1.842, 67 rhs calls

I Euler stepSize=1e-5, x=3.747, y=-1.842, 10000 rhscalls

Ability to choose numerical solver based on needs(predictable execution time, fast execution time, oraccurate).

model ODEReal d=2*time;Real x(start

=3.0, fixed=true);

Real y(start=2.0, fixed=true);

equationder(x) = y;der(y) = -d*x;

end ODE;

Better Solutions for the Ordinary Differential EquationModelica tools need to know about ODEs, andcan solve them better than the explicit Euler.The end values for different solvers:

I Euler stepSize=0.25, x=4.531, y=-1.084, 4 rhs calls

I Euler stepSize=0.10, x=4.087, y=-1.600, 10 rhs calls

I RK4 stepSize=1.00, x=3.667, y=-1.667, 4 rhs calls

I RK4 stepSize=0.25, x=3.747, y=-1.841, 16 rhs calls

I DASSL, tolerance=1e-3, x=3.745, y=-1.838, 15 rhscalls

I DASSL, x=3.747, y=-1.842, 67 rhs calls

I Euler stepSize=1e-5, x=3.747, y=-1.842, 10000 rhscalls

Ability to choose numerical solver based on needs(predictable execution time, fast execution time, oraccurate).

model ODEReal d=2*time;Real x(start

=3.0, fixed=true);

Real y(start=2.0, fixed=true);

equationder(x) = y;der(y) = -d*x;

end ODE;

Multi-Domain Approach: Systems Engineering

Modelica is a multi-domain approach based on math:I It is suitable to simulate different physical domains

independently or multiple domains in the same model.I Can be used to simulate full systems or synthesize parts of a

system (such as digital controllers).I The language fulfills the requirements of Systems Engineering.

Part II

Implementation of a ModelicaCompiler

User in the Focus

Modelica is designed around the user of the language being thefocus:

I This makes implementation of the compiler harder.I NP-hard problems need to be solved at compile-time.I Compilation time is unbounded and includes interpretation of

arbitrary code.I Certain language features are a little weird when you consider

the textual representation, but make sense when for thegraphical user interface.

OpenModelica

OpenModelica is an open sourceModelica tool

I Open Source ModelicaConsortium (OSMC)

I 46 org members Mar 2014I Founded Dec 4, 2007I Open-source community

servicesI Website and Support

ForumI Development coursesI Main development at

Linköping UniversityI Used for research prototypes

and industrial products www.openmodelica.org

OpenModelica

I Version-controlled source base (git)I Bug database (Trac)I Continuous integration (Hudson)I Interactive Modelica compiler (OMC)

I Compiles the Modelica LanguageI Modelica and Python scriptingI Efficient C-code, simulation run-time systemI Extensive Modelica test suite

I Environment for creating modelsI OMShell – scripting commandsI OMNotebook – interactive notebookI OMOptim parameter optimization toolI OpenModelica dynamic optimizer with collocationI MDT – Eclipse plug-inI ModelicaML UML-Modelica-Requirements ProfileI OMEdit graphic connection Editor

I Debugger – finding model errors

OpenModelica

I Version-controlled source base (git)I Bug database (Trac)I Continuous integration (Hudson)I Interactive Modelica compiler (OMC)

I Compiles the Modelica LanguageI Modelica and Python scriptingI Efficient C-code, simulation run-time systemI Extensive Modelica test suite

I Environment for creating modelsI OMShell – scripting commandsI OMNotebook – interactive notebookI OMOptim parameter optimization toolI OpenModelica dynamic optimizer with collocationI MDT – Eclipse plug-inI ModelicaML UML-Modelica-Requirements ProfileI OMEdit graphic connection Editor

I Debugger – finding model errors

OpenModelica

I Version-controlled source base (git)I Bug database (Trac)I Continuous integration (Hudson)I Interactive Modelica compiler (OMC)

I Compiles the Modelica LanguageI Modelica and Python scriptingI Efficient C-code, simulation run-time systemI Extensive Modelica test suite

I Environment for creating modelsI OMShell – scripting commandsI OMNotebook – interactive notebookI OMOptim parameter optimization toolI OpenModelica dynamic optimizer with collocationI MDT – Eclipse plug-inI ModelicaML UML-Modelica-Requirements ProfileI OMEdit graphic connection Editor

I Debugger – finding model errors

OpenModelica

I Version-controlled source base (git)I Bug database (Trac)I Continuous integration (Hudson)I Interactive Modelica compiler (OMC)

I Compiles the Modelica LanguageI Modelica and Python scriptingI Efficient C-code, simulation run-time systemI Extensive Modelica test suite

I Environment for creating modelsI OMShell – scripting commandsI OMNotebook – interactive notebookI OMOptim parameter optimization toolI OpenModelica dynamic optimizer with collocationI MDT – Eclipse plug-inI ModelicaML UML-Modelica-Requirements ProfileI OMEdit graphic connection Editor

I Debugger – finding model errors

User in the Focus – OMEdit / OMWebBook Demo

The Compiler Design

A Modelica compiler needs to have lots of domain knowledge. Italso depends on heuristics to translate equations into ODEs (themain job of a Modelica compiler), which are translated toexecutable code.

I The heuristics may fail to create an ODE from the given codeeven when a solution exists.

I Solutions do not necessarily exist.I Numerical solvers may fail to solve the model (require infinite

resolution).I Solution: good error messages and debuggers.

In practice, this works very well.

OpenModelica Overview

I Written in MetaModelica (general-purpose programmingextension to Modelica).

I The code generator uses our own DSL Susan for textgeneration (which translates Susan code to MetaModelica).

I ANTLR parser which translates an ANTLR grammar with aC-code target, which uses the C interface to MetaModelica tocreate data types.

I Kernel written in Modelica, MetaModelica, C, C++, Susan,ANTLR. DSL’s almost everywhere.

OpenModelica Parts

I Parser (using the ANTLR parser generator).I Front-end (semantic analysis, like a traditional compiler).I Equation back-end (symbolic math, outputs imperative code

from equations).I Code generator (takes imperative code and generates of

C-code, skipping middle-end and back-end of a traditionalcompiler).

I Utilities.I Front-end + code generator handles MetaModelica

(functions).I The compiler is also written in Modelica (bootstrapping).

Compiler Bootstrapping

The compiler needs a working copy of itself in order to compile itscode (because there exist no other MetaModelica compilers). Thissounds annoying but has some benefits:

I Can implement language extensions in order to write a moreefficient compiler.

I Performance improvements to the Modelica compiler alsoimproves the MetaModelica compiler.

I The language looks similar to Modelica.

Testing a Modelica Compiler

I Testing a C-compiler is easier because the exact translationsemantics are specified.

I In Modelica, a compiler needs to decide by itself how togenerate code.

I Numerical differences depending on how an equation is solved.I Compare result-files with a relative+absolute tolerance and

some magic to align discrete event times.

Testing a Modelica Compiler

How is Everything Developed?

I The Modelica language is developed by committee.I OpenModelica developers implement new Modelica language

features and create pull requests on github.I The pull request is reviewed and automatically tested before it

is merged into the main repository.I Weekly meetings to coordinate between the Swedish and

German teams.I Infrequent developer weeks for larger changes to the compiler.

Part III

Conclusion

Software used by OpenModelicaOpenModelica is a huge project that combines many pieces ofsoftware. You need software engineers to manage everything, aswell as mathematicians and mechanical engineers to helpimplementing the symbolic and numerical solvers. The projectincludes:

I A lexer/parser generator.I Its own symbolic processing libraries.I Numerical solvers:

I Linear algebra (dense / sparse).I Non-linear solvers (optimization/minimization formulations).I ODE solvers (euler, RK4, dassl, radau, lobatto).I Dynamic optimization.

I DSL for code (text) generation.I C compilers.I GUI toolkits.

OpenModelica and Systems Engineering

There are additional ways to useOpenModelica to integrate it with productdevelopment (although some is ongoingresearch):

I SysML-Modelica or ModelicaML (UMLprofiles) converting UML to Modelica

I The Modelica tool itself to do modelingI Generating multi-core code for simulation

on clustersI Generating code for embedded systemsI Generating FMUs (for co-simulation or

simulation in other simulation tools)

More Reading

I https://modelica.orgI https://openmodelica.org

www.liu.se