45
Modeling, Identification and Control, Vol. 41, No. 4, 2020, pp. 241–285, ISSN 1890–1328 The OpenModelica Integrated Environment for Modeling, Simulation, and Model-Based Development Peter Fritzson 1 Adrian Pop 1 Karim Abdelhak 2 Adeel Asghar 1 Bernhard Bachmann 2 Willi Braun 2 Daniel Bouskela 9 Robert Braun 1 Lena Buffoni 1 Francesco Casella 3 Rodrigo Castro 5 udiger Franke 6 Dag Fritzson 1 Mahder Gebremedhin 1 Andreas Heuermann 1 Bernt Lie 7 Alachew Mengist 1 Lars Mikelsons 1 Kannan Moudgalya 4 Lennart Ochel 1 Arunkumar Palanisamy 1 Vitalij Ruge 2 Wladimir Schamai 8 MartinSj¨olund 1 Bernhard Thiele 1 John Tinnerholm 1 Per ¨ Ostlund 1 1 PELAB – Programming Environment Lab, Dept. of Computer and Information Science Link¨ oping University, SE-581 83 Link¨ oping, Sweden. E-mail: {peter.fritszon,adrian.pop}@liu.se 2 FH Bielefeld, Bielefeld, Germany 3 Dip. Elettronica, Informazione e Bioingegneria, Politecnico di Milano, Milano, Italy 4 Dept. of Chemical Engineering, IIT Bombay, Mumbai, India 5 Dept. Computer Science, Universidad de Buenos Aires, Argentina 6 ABB AG, DE-68309 Mannheim, Germany 7 University of South-Eastern Norway, Porsgrunn, Norway 8 Danfoss Power Solutions GmbH & Co. OHG, Offenbach, Germany 9 Electricit´ e de France, (EDF Lab), Chatou, France Abstract OpenModelica is a unique large-scale integrated open-source Modelica- and FMI-based modeling, simu- lation, optimization, model-based analysis and development environment. Moreover, the OpenModelica environment provides a number of facilities such as debugging; optimization; visualization and 3D ani- mation; web-based model editing and simulation; scripting from Modelica, Python, Julia, and Matlab; efficient simulation and co-simulation of FMI-based models; compilation for embedded systems; Modelica- UML integration; requirement verification; and generation of parallel code for multi-core architectures. The environment is based on the equation-based object-oriented Modelica language and currently uses the MetaModelica extended version of Modelica for its model compiler implementation. This overview paper gives an up-to-date description of the capabilities of the system, short overviews of used open source sym- bolic and numeric algorithms with pointers to published literature, tool integration aspects, some lessons learned, and the main vision behind its development. Keywords: Modelica, OpenModelica, MetaModelica, FMI, modeling, simulation, optimization, develop- ment, environment, numeric, symbolic, compilation, embedded system, real-time doi:10.4173/mic.2020.4.1 2020 Norwegian Society of Automatic Control

The OpenModelica Integrated Environment for Modeling ...for OpenModelica is an integrated and modular model-ing, simulation, model-based development environment with additional capabilities

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

  • Modeling, Identification and Control, Vol. 41, No. 4, 2020, pp. 241–285, ISSN 1890–1328

    The OpenModelica Integrated Environment forModeling, Simulation,

    and Model-Based Development

    Peter Fritzson 1 Adrian Pop 1 Karim Abdelhak 2 Adeel Asghar 1

    Bernhard Bachmann 2 Willi Braun 2 Daniel Bouskela 9 Robert Braun 1

    Lena Buffoni 1 Francesco Casella 3 Rodrigo Castro 5 Rüdiger Franke 6

    Dag Fritzson 1 Mahder Gebremedhin 1 Andreas Heuermann 1 Bernt Lie 7

    Alachew Mengist 1 Lars Mikelsons 1 Kannan Moudgalya 4 Lennart Ochel 1

    Arunkumar Palanisamy 1 Vitalij Ruge 2 Wladimir Schamai 8 Martin Sjölund 1

    Bernhard Thiele 1 John Tinnerholm 1 Per Östlund 1

    1PELAB – Programming Environment Lab, Dept. of Computer and Information Science Linköping University,SE-581 83 Linköping, Sweden. E-mail: {peter.fritszon,adrian.pop}@liu.se2FH Bielefeld, Bielefeld, Germany

    3Dip. Elettronica, Informazione e Bioingegneria, Politecnico di Milano, Milano, Italy

    4Dept. of Chemical Engineering, IIT Bombay, Mumbai, India

    5Dept. Computer Science, Universidad de Buenos Aires, Argentina

    6ABB AG, DE-68309 Mannheim, Germany

    7University of South-Eastern Norway, Porsgrunn, Norway

    8Danfoss Power Solutions GmbH & Co. OHG, Offenbach, Germany

    9Electricité de France, (EDF Lab), Chatou, France

    Abstract

    OpenModelica is a unique large-scale integrated open-source Modelica- and FMI-based modeling, simu-lation, optimization, model-based analysis and development environment. Moreover, the OpenModelicaenvironment provides a number of facilities such as debugging; optimization; visualization and 3D ani-mation; web-based model editing and simulation; scripting from Modelica, Python, Julia, and Matlab;efficient simulation and co-simulation of FMI-based models; compilation for embedded systems; Modelica-UML integration; requirement verification; and generation of parallel code for multi-core architectures.The environment is based on the equation-based object-oriented Modelica language and currently uses theMetaModelica extended version of Modelica for its model compiler implementation. This overview papergives an up-to-date description of the capabilities of the system, short overviews of used open source sym-bolic and numeric algorithms with pointers to published literature, tool integration aspects, some lessonslearned, and the main vision behind its development.

    Keywords: Modelica, OpenModelica, MetaModelica, FMI, modeling, simulation, optimization, develop-ment, environment, numeric, symbolic, compilation, embedded system, real-time

    doi:10.4173/mic.2020.4.1 © 2020 Norwegian Society of Automatic Control

    http://dx.doi.org/10.4173/mic.2020.4.1

  • Modeling, Identification and Control

    1 Introduction

    The OpenModelica environment was the first opensource Modelica environment supporting equation-based object-oriented modeling and simulation usingthe Modelica modeling language (Fritzson and Engel-son, 1998; Modelica Association, 2017; Fritzson, 2014).Its development started in 1997 resulting in the releaseof a flattening frontend for a core subset of Model-ica 1.0 in 1998 (Fritzson and K̊agedal, 1998). Aftera pause of four years, the open source developmentresumed in 2002. A very early version of OpenModel-ica is described in (Fritzson et al., 2005). Since thenthe capabilities of OpenModelica have expanded enor-mously. The Open Source Modelica Consortium whichsupports the long-term development of OpenModelicawas created in 2007, initially with seven founding orga-nizations. The scope and intensity of the open sourcedevelopment has gradually increased. At the time ofthis writing the consortium has more than fifty sup-porting organizational members. The long-term visionfor OpenModelica is an integrated and modular model-ing, simulation, model-based development environmentwith additional capabilities such as optimization, sen-sitivity analysis, requirement verification, etc., whichare described in the rest of this paper. Fritzson et al.(2005, 2018c) are two less detailed and now partly outof date overview papers about OpenModelica.

    The current overview paper gives an up-to-dategreatly expanded description of the capabilities of thesystem, short overviews of used open source symbolicand numeric algorithms with pointers to published sci-entific literature, tool integration aspects, some lessonslearned, and the main vision behind its development.

    This paper is organized as follows. Section 2 presentsthe idea of integrated environment, Section 3 detailsthe goals for OpenModelica, Section 4.1 presents a de-tailed overview of the OpenModelica environment, Sec-tion 5 describes selected open source applications, Sec-tion 6 presents related work, and Section 7 the conclu-sions.

    2 Integrated Interactive Modelingand Simulation Environments

    An integrated interactive modeling and simulation en-vironment is a special case of programming environ-ments with applications in modeling and simulation.Thus, it should fulfill the requirements both from gen-eral integrated interactive environments and from theapplication area of modeling and simulation mentionedin the previous section.

    The main idea of an integrated programming envi-ronment in general is that a number of programming

    support functions should be available within the sametool in a well-integrated way. This means that thefunctions should operate on the same data and pro-gram representations, exchange information when nec-essary, resulting in an environment that is both power-ful and easy to use. An environment is interactive andincremental if it gives quick feedback, e.g., without re-computing everything from scratch, and maintains adialogue with the user, including preserving the stateof previous interactions with the user. Interactive envi-ronments are typically both more productive and morefun to use than non-interactive ones.

    There are many things that one wants a program-ming environment to do for the programmer or mod-eler, particularly if it is interactive. Comprehensivesoftware development environments are expected toprovide support for the major development phases,such as:

    Requirements analysis

    Design

    Implementation

    Maintenance

    A pure programming environment can be somewhatmore restrictive and need not necessarily support earlyphases such as requirements analysis, but it is an ad-vantage if such facilities are also included. The mainpoint is to provide as much computer support as pos-sible for different aspects of systems development, tofree the developer from mundane tasks so that moretime and effort can be spent on the essential issues.

    Our vision for an integrated interactive modeling andsimulation environment is to fulfill essentially all the re-quirements for general integrated interactive environ-ments combined with the specific needs for modelingand simulation environments, e.g.:

    Specification of requirements, expressed as docu-mentation and/or mathematics

    Design of the mathematical model

    Symbolic transformations of the mathematicalmodel

    A uniform general language for model design,mathematics, and transformations

    Automatic generation of efficient simulation code

    Execution of simulations

    Debugging of models

    Design optimization and parameter studies

    242

  • Fritzon et al., “OpenModelica Integrated Environment”

    Export/import of models to/from other tools

    Evaluation and documentation of numerical ex-periments

    Graphical presentation

    Model and system structure parameterization

    Variant and version handling, traceability

    3 Goals for OpenModelica

    Providing a complete open source Modelica-basedindustrial-strength implementation of the Model-ica language, including modeling and simulation ofequation-based models, system optimization, andadditional facilities in the programming/modelingenvironment.

    Providing an interactive computational environ-ment for the Modelica language. It turns out thatwith support of appropriate tools and libraries,Modelica is very well suited as a computationallanguage for development and execution of numer-ical algorithms, e.g. for control system design andfor solving nonlinear equation systems.

    The research related goals and issues of the Open-Modelica open source implementation of a Modelicaenvironment include, but are not limited to, the fol-lowing:

    Development of a complete formal specificationand reference implementation of Modelica, includ-ing both static and dynamic semantics. Such aspecification can be used to assist current and fu-ture Modelica implementers by providing a seman-tic reference, as a kind of reference implementa-tion.

    Language design, e.g. to further extend the scopeof the language, e.g. for use in diagnosis, struc-tural analysis, system identification, integratedproduct development with requirement verifica-tion, etc., as well as modeling problems that re-quire partial differential equations.

    Language design to improve abstract propertiessuch as expressiveness, orthogonality, declarativ-ity, reuse, configurability, architectural properties,etc.

    Improved implementation techniques, e.g. to en-hance the performance of compiled Modelica codeby generating code for parallel hardware.

    Improved debugging support for equation-basedlanguages such as Modelica, to make them eveneasier to use.

    Improved optimization support, with integratedoptimization and modeling/simulation. Twokinds: parameter-sweep optimization based onmultiple simulations; direct dynamic optimizationof a goal function without lots of simulations, e.g.,using collocation or multiple shooting.

    Easy-to-use specialized high-level (graphical) userinterfaces for certain application domains.

    Visualization and animation techniques for inter-pretation and presentation of results.

    Integrated requirement modeling and verificationsupport. This includes the ability to enter require-ments formalized in a kind of Modelica style, andto verify that the requirements are fulfilled for se-lected models under certain usage scenarios.

    High-performance simulation, e.g., of large-scalemodels, generating simulations to efficiently utilizemulti-core computers for high performance.

    3.1 History and System Architecture

    The OpenModelica effort started by developing arather complete formal specification of the Modelicalanguage. This specification was developed in Opera-tional Semantics, which still is the most popular andwidely used semantics specification formalism in theprogramming language community. It was initiallyused as input for automatic generation of the Mod-elica translator implementations which are part of theOpenModelica environment. The RML compiler gen-eration tool (our implementation of Operational Se-mantics) (Fritzson et al., 2009a) was used for this task.

    However, inspired by our vision of integrated inter-active environments with self-specification of programsand data, and integrated modeling and simulation en-vironments), in 2005 we designed and implemented anextension to Modelica called MetaModelica (Pop et al.,2006; Fritzson et al., 2011, 2019), see also Section 4.1.3.This was done in order to support language modelingand specification (including modeling the language it-self), in addition to the usual physical systems model-ing applications, as well as applications requiring com-bined symbolic-numeric capabilities. Modeling the se-mantics in Modelica itself was also inspired by func-tional languages such as Standard ML (Milner et al.,1997), and OCaml (OCaml, 2018). Moreover, it wasan investment into a future Modelica becoming a com-bined symbolic-numeric language such as Mathemat-ica, but more efficient and statically strongly typed.

    243

  • Modeling, Identification and Control

    This language extension has a backwards compatibleModelica-style syntax but was initially implementedon top of the RML compiler kernel. The declara-tive specification language primitives in RML withsingle-assignment pattern equations, potentially recur-sive uniontypes of records and match expressions, fitwell into Modelica since it is a declarative equation-based language. In 2006 our whole formal specificationof Modelica static and translational semantics, at thattime about 50 000 lines, was automatically translatedinto MetaModelica. After that, all further developmentof the symbolic processing parts of the OpenModelicacompiler (the run-time parts were mainly written inC), was done in MetaModelica.

    At the same time we embarked on an effort to com-pletely integrate the MetaModelica language exten-sion into the Modelica language and the OpenModelicacompiler. This would enable us to support both Mod-elica and MetaModelica by the same compiler. Thiswould allow modeling the Modelica tool and the Open-Modelica compiler using its own language. This wouldget rid of the limitations of the RML compiler kerneland the need to support two compilers. Moreover, ad-ditional tools such as our Modelica debugger can bebased on a single compiler.

    Such an ability of a compiler to compile itself is calledcompiler bootstrapping. This development turned outto be more difficult and time-consuming than initiallyexpected; moreover, developers were not available fora few years due resource limitations and other prior-ities. Finally, bootstrapping of the whole OpenMod-elica compiler was achieved in 2011. Two years later,in 2013, all our OpenModelica compiler developmentwas shifted to the new bootstrapped compiler (Sjölundet al., 2014; Sjölund, 2015), after automatic memoryreclamation (garbage collection), separate compilation,and a new efficient debugger had been achieved for ournew compiler platform.

    4 The OpenModelica Environment

    At the time of this writing, the OpenModelica environ-ment primarily consists of the following functionalitiesand subsystems:

    OMC – The OpenModelica Model Compiler

    The new OpenModelica Compiler frontend

    Symbolic Programming and Meta Modeling withMetaModelica

    Numeric-symbolic solver modules

    OMEdit – the OpenModelica Graphic Model Ed-itor and Simulator GUI

    3D Animation and Visualization

    Debugging and Performance Optimization

    Interactive Electronic Notebooks

    Interactive Scripting using Modelica, Python, Ju-lia, and Matlab

    Audio-Video Tutorials

    FMI – Functional Mockup Interface

    Multi-Parameter Sensitivity Analysis

    Parameter System Identification

    Embedded System Support

    Model-based Control Design with Dynamic Opti-mization

    Model-based Fault and Dependability Analysis

    Data Reconciliation for Enhanced Sensor Data

    Using Artificial Neural Networks for Model Cali-bration

    Embedded System Support

    MDT Eclipse Plug-in

    ModelicaML UML Profile and Eclipse Plug-in

    Requirement Verification

    Design Optimization

    Parallelization and Multi-Core

    The relationships between the main OpenModelicasubsystems are briefly depicted above in Figure 1.Their functionality and selected applications are de-scribed in the rest of this article. An example of us-ing OpenModelica to perform simulations and plot-ting simulation results is depicted in Figure 2 for theV6Engine model.

    4.1 OMC – The OpenModelica ModelCompiler

    OMC is the OpenModelica compiler which translatesModelica models into simulation code, which is com-piled and executed to perform simulations. The Open-Modelica compiler is generated from formal specifica-tions in RML (earlier) or MetaModelica (currently).At the time of this writing the OpenModelica compiler(OMC) is generated from a specification of about threehundred thousand lines of MetaModelica. Moreover,OMC is able to compile itself, i.e., it is bootstrapped(Sjölund et al., 2014). There is also a compilation modeto generate low-footprint code for embedded systems(Section 4.20).

    244

  • Fritzon et al., “OpenModelica Integrated Environment”

    Simulation

    Execution

    OMEdit Graphic

    and Textual

    Model Editor

    OMNotebook

    Interactive

    Notebooks

    Debugger

    OMC

    Interactive Compiler

    Server

    ModelicaML

    UML/Modelica

    and requirement

    verification

    MDT

    Eclipse Plugin

    OMOptim

    Optimization

    3D

    Visualization

    OMShell

    Modelica

    Scripting

    OMPython

    Python

    Scripting

    OMSimulator

    FMI Simulation

    OMJulia

    Julia

    Scripting

    OMWebbook

    Interactive

    Notebooks

    OMMatlab

    Matlab

    Scripting

    OMSens

    sensitivity

    analysisOMSysident

    Figure 1: The architecture of the OpenModelica environment. Arrows denote data and control flow.

    Figure 2: OpenModelica simulation of the V6Engine model with 11000 equations. Plotting simulation resultsusing OMEdit. Left : Model browser. Right : Plot variable browser. Bottom: message browser window.

    245

  • Modeling, Identification and Control

    1. Lexical AnalysisKeywords, operators and identifiers are ex-tracted from the model.

    2. ParsingAn abstract syntax tree represented in Meta-Modelica is created from the operators andidentifiers.

    3. Semantic AnalysisThe abstract syntax tree gets tested for se-mantic errors.

    4. Intermediate RepresentationTranslation of the abstract syntax tree to anintermediate representation (IR) called SCodein MetaModelica. This is further processed bythe frontend (Section 4.1.2) producing DAEIR code.

    5. Symbolic Optimization BackendThe intermediate representation gets opti-mized and preprocessed (Section 4.2).

    6. Code GenerationExecutable code gets generated from the lowlevel intermediate representation.

    Figure 3: OpenModelica compiler workflow – from model to executable simulation code.

    4.1.1 OMC Compiler Structure

    The compilation of Modelica models with the Open-Modelica Compiler (OMC) can be divided into sixphases (Figure 3) to get an executable simulation. Ina nutshell the Frontend performs lexical and seman-tic analysis and the Backend performs symbolic opti-mization on the provided DAE-model-representation.From the optimized MetaModelica intermediate repre-sentation an executable simulation program in a targetlanguage (C, C++ and some others) is generated andcompiled.

    4.1.2 New Compiler Frontend

    As previously mentioned in Section 3.1, a new Open-Modelica compiler frontend has been developed. Thislarge effort has been made in order to provide completelanguage coverage as well as much faster compilationincluding efficient support for compilation of very largemodels. The first usable version was released in Open-Modelica 1.14.0, in December 2019. The new fron-tend (Pop et al., 2019) uses model-centric and multiplephases design principles and is about 10 to 100 timesfaster than the old frontend. A few highlights:

    The new front-end was carefully designed withperformance and scalability in mind.

    References (pointers) are used to link componentreferences to their definition scope via lookup andusage scope via application.

    Constant evaluation and expression simplificationare more restricted compared to the old frontend.

    Arrays of basic types and arrays of models are notexpanded until the scalarization phase.

    Expansion of arrays is currently needed becausethe backend currently cannot handle all the casesof non-expanded arrays, but will be eliminated inthe future (Section 4.2.8) to give increased perfor-mance for array computations.

    One of the design principles of the new frontend hasbeen to find ways to break dependencies between thevarious frontend phases. Instead of being component-focused like the old compiler frontend it has been de-signed to be model-focused, meaning that each fron-tend phase processes the whole model before the modelis passed on to the next phase. The result is the design

    246

  • Fritzon et al., “OpenModelica Integrated Environment”

    seen in Figure 4, which shows the flow of the modelthrough the different phases of the new frontend.

    The symbolic instantiation phase builds the instancetree and constructs all the nodes, and the expressioninstantiation phase instantiates all expressions in thatinstance tree. This involves looking up the names usedin expressions and associating them with the correctnodes in the instance tree. The lookup tree for a class isonly constructed once and then reused for all instancesof that particular class, unlike the old frontend wherea new lookup tree is constructed for each instance.

    The typing phase traverses the instance tree and de-termines the type of all variables and expressions. Theflattening phase of the new frontend traverses the in-stance tree and flattens the tree into a flat model thatconsists of a list of variables, a list of equations, anda list of algorithms. It also expands connect-equationsand for-equations into basic equations.

    The new frontend is implemented in modern Meta-Modelica 3.0 which combines Modelica features withfunctional languages features. The implementationcurrently consists of 65 MetaModelica packages oruniontypes defining encapsulated data structures andfunctions that operate on the defined data.

    4.1.3 MetaModelica for Symbolic Programmingand Meta-Programming

    The need for integrating system modeling with ad-vanced tool capabilities is becoming increasingly pro-nounced. For example, a set of simulation experimentsmay give rise to new data that is used to systemati-cally construct a series of new models, e.g. for furthersimulation and design optimization.

    Such combined symbolic-numeric capabilities havebeen pioneered by dynamically typed interpreted lan-guages such as Lisp (Teitelman, 1974) and Mathemat-ica (Wolfram, 2003). Such capabilities are also relevantfor advanced modeling and simulation applications butlacking in the standard Modelica language. Therefore,this is a topic of long-running design discussions in theModelica Design group.

    One contribution in this direction is the MetaModel-ica language extension (Pop and Fritzson, 2006; Fritz-son et al., 2011, 2019) that has been developed to ex-tend Modelica with symbolic operations and advanceddata structures in a backwards-compatible way, whilepreserving safe engineering practices through statictype checking and a compilation-based efficient imple-mentation.

    The MetaModelica language is an efficiently com-piled language that provides symbolic programming us-ing tree and list data structures. This is similar to whatis provided by the rather young language Julia (Bezan-son et al., 2017; Julialang, 2018) which has recently ap-

    Figure 4: The OMC new frontend phases.

    peared, Julia 1.0 was released in August 2018. A com-parison between MetaModelica and Julia is presentedby Fritzson et al. (2019). MetaModelica is also usedfor modeling/specification of languages (including theModelica language) and for Modelica-style program-ming of model transformations, where the OpenMod-elica compiler itself is the currently largest application.

    The research contributions of MetaModelica are notabout inventing new language constructs since theyhave already been well proven in several other lan-guages. However, in the context of Modelica there arecontributions on integrating such constructs into theModelica language including the Modelica type systemin a backwards compatible way. The following is a verybrief overview of the most important language exten-sions:

    Overloading of user-defined operators and func-tions. Note: overloading is called multiple dis-

    247

  • Modeling, Identification and Control

    patch in Julia.

    Uniontype construct to define unions of possiblyrecursive record types. This is used to create treedata structures. Syntax example:

    uniontype Exp

    record RCONST

    Real rval;

    end RCONST;

    record INTconst

    Integer exp1;

    end INTconst;

    end Exp;

    Uniontypes are also present in Julia.

    The predefined type Any is a supertype of anyother MetaModelica type, i.e., all other MetaMod-elica types are subtypes of Any. Used e.g. in re-placeable,

    replaceable type TypeParam =

    Any constrainedby Any;

    The predefined Option uniontype provides a typesafe way of representing optional values.

    Built-in list and tuple data types. List of inte-gers: list(2,3,4) is a list of integers. A tuple:(a,b,"cc")

    Match-expressions for traversing and transform-ing complex data structures. This supports pat-tern matching specified by pattern expressions,and building data structures such as trees, lists,etc.

    Exception handling using

    try

    // ...

    else

    // ...

    end try;

    Also a fail() function to cause an exception.

    The following recent enhancements available inMetaModelica 3.0 were found to be quite useful in theimplementation of the new frontend:

    Flexible pattern matching specified by (), thatdoes not require verbose listing of all record fields(or named field access) of the record in the patternmatching, e.g., UNTYPED BINDING().

    Record field access via dot notation inside the case,e.g., binding.bindingExp.

    Definition of functions inside uniontypes.

    Definition and usage of parameterized uniondatatypes such as trees using redeclare/replace-able types.

    4.1.4 Experimental Just-in-Time Compilation

    Just-in-Time Compilation (JIT) allows compilationand executing code during runtime. Such a facilityopens up new flexible strategies for handling the com-pilation and execution of Modelica code and even go-ing beyond Modelica to general variable structure sys-tems. The following work is currently ongoing relatedto OpenModelica.

    The OpenModelica LLVM backend (OMLB)The OpenModelica LLVM backend (OMLB) is an ex-perimental OpenModelica prototype backend to inves-tigate just-in-time compilation using the LLVM com-piler framework (Tinnerholm, 2019). The goal was toinvestigate the advantages and disadvantages of hav-ing OMC target LLVM instead of C. The investiga-tion was also performed to examine if targeting LLVMwould be a viable option to achieve efficient Just-in-time compilation (JIT). Another approach with similargoals was conducted by (Agosta et al., 2019). WhileOMLB currently is not complete enough for bootstrap-ping, it demonstrates the benefits of having an LLVMbased backend and JIT. OMLB is presently able tocompile the algorithmic subsets of MetaModelica andModelica interactively. Inspired by the design goalsof the Julia programming language and the successfuluse of Julia for equation-based modeling as done byElmqvist et al. (2017), an investigation was conductedin 2018 comparing MetaModelica and Julia (Fritzsonet al., 2019).

    This investigation highlighted the similarities anddifferences between the two languages, both in terms ofdesign goals and programming paradigm. The conclu-sions were that there are similarities both with regardsto the indented audience and the design goals of thetwo. These similarities prompted another investigation(Tinnerholm et al., 2019) regarding the possibility ofautomatically translating the existing OpenModelicafrontend into Julia. Such an OpenModelica frontendin Julia could provide a framework for experimenta-tion with variable structured systems while at the sametime adhering to the Modelica standard.

    An Experimental Julia-based Modelica Compiler Pro-totypeTo empirically investigate the advantages, disadvan-tages, and challenges of providing a Modelica com-piler in Julia, an OpenModelica to Julia translator

    248

  • Fritzon et al., “OpenModelica Integrated Environment”

    was developed together with an extension of the Meta-Modelica runtime initially described in (Fritzson et al.,2019). From our preliminary experiments in (Tinner-holm et al., 2019) we observed that automatically gen-erated Julia code may outperform hand-written Meta-Modelica code in some cases. However, the compilationtime was overall slower compared to OMLB, due toOMLB making use of precompiled runtime functionsin contrast with the overhead imposed by the Juliacompiler due to type specialization.

    Prototyping a Standards Compliant Modelica Compilerwith Run-time Just-in-Time CompilationRegarding just-in-time compilation (JIT), the statusin the fall of 2019 was that there are still two op-tions to provide a JIT in the OpenModelica compilerenvironment. One is via OMCompiler.jl – an experi-mental standards compliant prototype subset Model-ica compiler in Julia, the other is to increase the scopeof OMLB with its associated JIT. However, since theMetaModelica to Julia translator is capable of trans-lating the existing OMC frontend, it is also capable ofconverting the OMLB code-generator into Julia. Thus,further development of OMCompiler.jl will not invali-date the possibility of having LLVM as a final backendtarget for OMC.

    4.1.5 Template-Based Code Generation

    The OMC code generation uses a text-template basedapproach. The Susan text template language (Fritzsonet al., 2009b) based on MetaModelica was developedfor this purpose. It facilitates generation of code formultiple target platforms from the low-level intermedi-ate code in and enables writing concise code generationspecifications. Several alternative regular code genera-tors are available to produce the simulation code as Cor C++ code (or Java or C# code using experimentalcode generators), which is compiled and executed toperform simulations or to export FMUs.

    4.2 OMC Backend with Numeric-SymbolicSolver Modules

    In the following we briefly present four of the mostimportant numeric-symbolic modules inside the OMCBackend that perform symbolic optimization (Fig-ure 3).

    4.2.1 Removal of Simple Equations

    Some variables in the equation system correlate, be-cause they are connected by so-called simple equations.The most elementary equation is equality, e.g.: x = y.In this equation it is possible to declare either x or y

    as an alias variable and replace it in every equationit occurs with the corresponding other variable. Theequation can be removed from the system and is laterused to reconstruct the value of the removed alias vari-able if necessary. Even more complex, but still simpleequations can be extracted such that the resulting sys-tem will be much smaller (e.g. any linear equationconnecting two variables). More information for thisprocess regarding a specific model can be gained usingthe compiler flag -d=debugAlias.

    4.2.2 BLT-Transformation (Matching/Sorting)

    The transformation of a system of differential-algebraicequations to Block-Lower-Triangular form is funda-mental to the simulation. The first step is to assignevery variable to an equation such that the equationcan be solved (explicitly or implicitly) for the assignedvariable. This step is called Matching and is unique ifthere are no algebraic loops in the system. Afterwardsthe equations are sorted into blocks, such that an evalu-ation sequence is achieved (Sorting). If a block containsmore than one equation, it forms an algebraic loop,where all variables assigned to those equations have tobe solved simultaneously. Further information on BLT-Transformation can be found in Duff et al. (2017, chap-ter 6). More information regarding a specific model canbe gained using the compiler flag -d=backenddaeinfo.

    4.2.3 Index Reduction

    The differential index of a system of differential-algebraic equations is defined as the maximum num-ber of differentiations of all equations such that allunknowns of the system can be solved by integrat-ing an ordinary differential equation. Most solvers aredesigned to work with systems of index zero or one,so an efficient reduction is necessary. The equationsthat have to be differentiated and the correspondingnumber of differentiations can be obtained with Pan-telides (1988) algorithm. The index reduction algo-rithm with dummy-states, described in Söderlind andMattsson (1993), reduces the system to index one,so that it can be simulated with common solvers.Alternative methods to handle index reduction havebeen proposed in Qin et al. (2016, 2018). Simula-tion without index reduction is also possible, but lessreliable. The process of index reduction identifiesa set of state variables which are algebraically con-nected. Some of those states will be treated as reg-ular algebraic variables (dummy states) to simulatethe system correctly. One can influence this processof state selection by providing stateSelect attributesfor states, e.g., x(stateSelect=StateSelect.avoid),see Table 1. More information for this process regard-

    249

  • Modeling, Identification and Control

    Table 1: StateSelect Attributes

    Attribute Description Strictness

    always Always pick as continuous state (never pick as dummy state) Forced

    prefer Prefer to pick as continuous state Suggestion

    default Default value, no special treatment No Influence

    avoid Try to avoid picking this as a continuous state Suggestion

    never Never pick as continuous state (always pick as dummy state) Mostly Forced

    Table 2: TearingSelect Annotation

    Attribute Description Strictness

    always Always pick as tearing variable Mostly Forced

    prefer Prefer to pick as tearing variable Suggestion

    default Default value, no special treatment No Influence

    avoid Try to avoid picking this as a tearing variable Suggestion

    never Never pick as tearing variable Forced

    ing a specific model can be gained using the compilerflags {d=bltdump or {d=stateselection (extends {d=backenddaeinfo).

    4.2.4 Tearing

    For every algebraic loop some of the assigned variablesare chosen as tearing-variables, such that all other vari-ables can be evaluated explicitly on the basis of thosevariables. The goal is to efficiently find small sets oftearing-variables. Many algorithms are already imple-mented in the OpenModelica Compiler and publishedin Cellier and Kofman (2006). One can influence thisprocess by providing tearingSelect annotations, sim-ilar to the stateSelect attribute. Since this is notpart of the Modelica language and specific to Open-Modelica, it must be provided as an annotation (e.g. xannotation(tearingSelect = prefer); see Table 2.Discrete variables can never be tearing variables. Moreinformation for this process regarding a specific modelcan be gained using the compiler flags -d=dumpLoopsor -d=iterationVars.

    4.2.5 Simulation using Numeric Solvers

    After code generation for specified target languageand linking with the OpenModelica Simulation Run-time, the model can be simulated. For the simu-lation OpenModelica offers multiple numeric integra-tion/solver methods for ODE systems as well as DAE-mode (Section 4.2.6) for direct solution of DAE sys-tems. Mostly DASSL (Petzold, 1982) respectively IDA(Hindmarsh et al., 2005) are used to integrate the sys-tems, but there are more solvers for specific problems

    (Table 3). For models containing algebraic loops thereare multiple linear (Table 4) and non-linear (Table 5)algebraic solvers to choose from. There are generalpurpose solvers like LAPACK for linear problems anda combination of a Newton method with the total pivotmethod as fallback.

    4.2.6 DAEMode

    A recent extension of the numeric solver module is theDAEMode which is used for solving very large mod-els. DAE-mode can be accessed using the compiler flag{daeMode. This is part of an emerging trend in Model-ica tools of handling large-scale models, with hundredsof thousands or possibly millions of equations, (Casella,2015). OpenModelica has pioneered this field by in-troducing sparse solvers in the solution chain: KLUfor linear algebraic equations, Kinsol for nonlinear al-gebraic equations, and IDA for causalized differentialequations. It also introduced the direct use of IDA asdifferential-algebraic equation solver, skipping the tra-ditional causalization step, which is computationallymore efficient for certain classes of systems. The largestsystem handled so far is an electro-mechanical powersystem model with about 600 000 differential-algebraicequations (Braun et al., 2017).

    4.2.7 Homotopy-based Initialization

    In many cases, solving the initialization problem ofModelica models requires solving nonlinear system bymeans of iterative methods, whose convergence maybe critical if the provided initial guesses are not closeenough to the solution. To mitigate this problem,

    250

  • Fritzon et al., “OpenModelica Integrated Environment”

    Table 3: Available numeric solver methods

    Integrator Method Explicit or Implicit Step Size Order

    euler Forward Euler method Explicit Fixed 1

    impeuler Backward Euler method Implicit Fixed 1

    irksco Own developed Runge-Kutta solver Implicit Variable 1-2

    heun Heun’s method Explicit Fixed 2

    trapezoid Trapezoid rule Implicit Fixed 2

    rungekutta Classic Runge-Kutta method Explicit Fixed 4

    imprungekutta Runge-Kutta methods based on Radau andLobatto IIA-method

    Implicit Variable 1-6

    rungekuttaSsc Runge-Kutta based on Novikov Explicit Variable 4-5

    Dassl (default) BDF method Implicit Variable 1-5

    ida BDF method with sparse linear solver Implicit Variable 1-5

    symSolver Symbolic inline solver - Fixed 1

    symSolverSsc Symbolic implicit Euler - Variable 1

    qss Quantized state systems method (Migoniet al., 2011)

    Implicit Variable 1

    dassl + daeMode Solves the DAE system instead of ODE sys-tem

    Implicit Variable 1-5

    ida + daeMode Solves the DAE system instead of ODE sys-tem

    Implicit Variable 1-5

    optimization Special solver for dynamic optimization - - -

    Table 4: Available linear solvers for algebraic loops

    Solver Method

    default Lapack with totalpivot as fallback (Anderson et al., 1999)

    lapack Non-Sparse LU factorization using LAPACK (Anderson et al., 1999)

    lis Iterative linear solver (Nishida, 2010)

    klu Sparse LU factorization (Natarajan, 2005)

    umfpack Sparse unsymmetric multifrontal LU factorization (Davis, 2004)

    totalpivot Total pivoting LU factorization for underdetermined systems

    Table 5: Available non-linear solvers for algebraic loops

    Solver Method

    hybrid Modified Powell hybrid method from MINPACK (Dennis Jr. and Schnabel, 1996)

    kinsol Combination of Newton-Krylov, Picard and fixed-pointsolver

    (Taylor and Hindmarsh, 1998)

    newton Newton-Raphson method (Cellier and Kofman, 2006)

    mixed Homotopy with hybrid as fallback (Keller, 1978; Bachmann et al., 2015)

    homotopy Damped Newton solver with fixed-point solver andNewton homotopy solver as fallbacks

    251

  • Modeling, Identification and Control

    OpenModelica implements the homotopy() operator ofthe language, which allows to replace some key expres-sions in model equations with simplified counterparts,to make the initialization problem less sensitive to anaccurate choice of initial guesses. Once the solutionof the simplified problem has been found, a homotopytransformation is performed from the simplified to theactual formulation of the expression in the homotopyoperators. If the simplified expression is chosen appro-priately, the homotopy path followed by the solutionis continuous and allows to reliably reach the solutionof the actual initialization problem (Sielemann et al.,2011; Bachmann et al., 2015; Keller, 1978). See alsoCasella et al. (2011b) for an application.

    4.2.8 New OMC Backend

    The current OMC backend is lacking in modularity,efficiency, and does not support non-expanded arraysin a general way. The latter functionality is neededto support compilation and simulation of large-scalemodels with large arrays. Therefore an effort hasbeen started spring of 2020 of re-designing and re-implementing the backend to improve modularizationand enable efficient handling of general non-expandedarrays.

    4.3 OMEdit – the OpenModelica GraphicModel Editor and Simulator GUI

    OMedit is the OpenModelica graphical model edi-tor (Asghar et al., 2011) for component-based modeldesign by connecting instances of Modelica classes.The editor also provides text editing. Moreover, theOMEdit GUI provides a graphical user interface tosimulation and plotting (Figure 2). Also, it also pro-vides browsing, parameter update, 3D animation (Sec-tion 4.4), debugging and performance analysis (Sec-tion 4.5), and FMI composite editing (Section 4.10).

    Figure 5 depicts the connection editing view ofOMEdit in the center. The model browsing windowis to the left and a model documentation window isshown at the upper right.

    A typical usage of OMEdit is to first create a modelusing the connection editor, then simulate, and finallyplot by selecting which variables should be plotted inthe variable plot selection window (Figure 5, lowerright).

    A model can be created by opening a new emptymodel and dragging/dropping model components fromthe model browsing window to the left into the centralconnection editing area and creating a new model byconnecting those components. Alternatively an exist-ing model can be opened by double clicking the modelin the model browser window to the left. A model can

    also be created textually by clicking the text buttonand typing in Modelica text.

    A simulation is performed by clicking on the greenright-arrow at the top. After a successful simulationthe plot selection window will appear at the right. Onerather unusual example of how a plot can appear is vis-ible in Figure 2). There are also variants of the simu-lation green arrows at the top that combine simulationwith debugging or 3D visualization.

    4.4 3D Animation and Visualization

    The OpenModelica 3D animation and visualization isa built-in feature of OMEdit to animate based on 3Dshapes defined by the MSL Multi-Body library. It pro-vides visualization of simulation results and animationof geometric primitives and CAD-files. OpenModel-ica generates a scene description XML-file which as-signs model variables to visualization shape attributes.The scene description file can also be used to gen-erate a visualization controlled by an FMU either inOMEdit or in an external visualization tool as Unity3D (Waurich and Weber, 2017). In combination withthe Modelica DeviceDrivers Library, interactive simu-lations with visual feedback and 3D-interactions canbe implemented for training, development and testingpurposes.

    4.5 Debugging and Performance Analysis

    4.5.1 The Algorithm Debugger

    The OpenModelica algorithm debugger (Figure 7),(Pop, 2008; Sjölund, 2015) is available for use eitherfrom OMEdit or from the MDT Eclipse plug-in. Thedebugger provides traditional debugging of the algo-rithmic part of Modelica, such as setting breakpoints,starting and stopping execution, single-stepping, in-specting and changing variables, inspecting all kindsof standard Modelica data structures as well as Meta-Modelica data structures such as trees and lists.

    4.5.2 The Equation Model Debugger

    The OpenModelica equation model debugger (Fig-ure 8) (Pop et al., 2014; Sjölund, 2015) is availablefor use from OMEdit. It provides capabilities for de-bugging equation-based models, such as showing andexplaining the symbolic transformations performed onselected equations on the way to executable simulationcode. It can locate the source code position of an equa-tion causing a problem such as a run-time error, tracedbackwards via the symbolic transformations.

    In February 2020, new functionality was demon-strated to perform “backward” trace of which variables

    252

  • Fritzon et al., “OpenModelica Integrated Environment”

    Figure 5: OMEdit on the Modelica.Electrical.Analog.Examples.ChuaCircuit model.Center : Model connection diagram. Upper right : Information window. Lower right : Plot variablebrowser with a small popup re-simulate menu on top.

    Figure 6: OpenModelica 3D animation of a simulated excavator in OMEdit and in unity 3D.

    253

  • Modeling, Identification and Control

    Figure 7: The OpenModelica algorithmic code debugger viewed from the MDT Eclipse plug-in. The OMEditversion of the debugger looks about the same. A breakpoint has been set in the function which iscalled from the small model called SimulationModel.

    Figure 8: The OpenModelica equation model debugger. Left : Equations view where equations and symbolictransformations can be viewed. Right : Source view where the erroneous equation is pointed out.

    254

  • Fritzon et al., “OpenModelica Integrated Environment”

    (a) Left : Turn on the menu choice.

    (b) Right : List of variables directly influencing thechosen variable.

    Figure 9: Debugger tracing variables or equations influence of a variable.

    or equations that directly influence a chosen variable(Figure 9). This can be useful to understand the de-pendencies causing a faulty variable value.

    4.5.3 The Performance Profiler/Analyzer

    By using performance profiling analysis it is possibleto detect which equations or functions cause low per-formance during a simulation.

    The OpenModelica profiler (Sjölund, 2015) usescompiler-assisted source code instrumentation. Thereis one call to a real-time clock before executing theequation block or function call and one call to the clockafter execution of the block. Associated with each callis a counter that keeps track of how many times thisfunction was triggered for the given time step. Simi-larly, each call is associated with clock data – one vari-able for the total time spent in the block for all timesteps and one variable for the total time spent in theblock for the current time step. The time measurementuses the best real-time clock available on the used plat-form.

    With profiling enabled only for equation blocks(strongly connected equation sets) and functions, theoverhead cost is low compared to the cost of solvingmost nonlinear systems of equations. The profiler isintegrated with the equation debugger, which enables

    Figure 10: The OpenModelica performance profilershowing which sets of equations use thebiggest fraction of the simulation time.

    the tool to directly point out the equations using alarge fraction of the simulation time (Figure 10).

    4.6 Teaching with Interactive ElectronicNotebooks

    Electronic notebooks provide an executable electronicbook facility supporting chapters, sections, executionof simulation models, plotting. The first versions ofOpenModelica used the proprietary Mathematica note-book facility. Later versions include a simple opensource implementation called OMNotebook describedbelow. More recently, a web-based notebook has beendeveloped as well as a plug-in to the Jupyter notebookfacility.

    255

  • Modeling, Identification and Control

    (a) Left : The DrModelica document start page. (b) Right : The VanDerPol sub-document showing acell with a Modelica model, simulation commands,and plot results.

    Figure 11: The OMNotebook electronic notebook showing part of the DrModelica document (course-material)for learning Modelica.

    4.6.1 OMNotebook and DrModelica

    OMNotebook (Figure 11) (Fernström et al., 2006) isa book-like interactive user interface to OpenModelicaprimarily intended for teaching and course material. Itsupports sections and subsections to any level, hidingand showing sections and cells, interactive evaluationand simulation of Modelica models as well as plottingresults. The user can define his/her own books. Thistool is useful for developing interactive course mate-rial. The DrModelica (Sandelin et al., 2003) interac-tive Modelica teaching course was the first main appli-cation, at that time based on Mathematica notebooks,later translated to use interactive Modelica scripting inOMNotebook.

    4.6.2 OMWebbook – Interactive Web-basedEditable and Executable Book

    OMWebbook (Figure 12) (Moudgalya et al., 2017;Fritzson et al., 2018b) is an interactive web-based elec-tronic book. This is similar to OMNotebook, but tex-tual model editing and simulation is performed in aweb-browser. Simulation is performed by a dedicatedsimulation server. Thus, the user need not installOpenModelica on a computer. Editing and simulationcan even be done from smartphones or tablets.

    Figure 12: OMWebbook with editable models, simula-tions, and plots, here simulating the bounc-ing ball.

    4.6.3 Jupyter Notebook for OpenModelica

    More recently, the Python-based Jupyter notebooksoftware (Project Jupyter, 2016) has appeared, sup-porting a number of scripting languages. Therefore,based on user demand, we have also developed aJupyter notebook plug-in for OpenModelica (2020)supporting Modelica scripting. However, Pythonscripting together with the OMPython package wasalready available and used in the Jupyter notebooks

    256

  • Fritzon et al., “OpenModelica Integrated Environment”

    presented in Lie et al. (2016).

    4.7 Self-Learning Audio-Video Tutorials

    A number of interactive audio-video tutorials, calledspoken tutorials, have been developed to provide step-by-step teaching about how to use OpenModelica anddevelop simple Modelica models (Moudgalya et al.,2017; FOSSEE-Modelica, 2020). The audio parts ofthe tutorials are dubbed in many languages and aresuitable for on-line usage (Moudgalya et al., 2017). Atotal of 14 short Spoken Tutorials of 10 minutes eachare available, and a total of 10,000 students have beentrained using these tutorials at the time of writing thisarticle.

    4.8 Text-book Companions for Teachingand Prototyping

    Most open source software projects rely on contribu-tions from the user community. Students form a sub-stantial fraction of this community. One of the short-comings of Free and Open Source Software is inade-quate documentation, and the lack of contributions toit by students aggravate this problem: Students of-ten lack motivation to document or are not capable ofcreating good documents. The converse is often true:Students are much better coders and they often enjoycoding. We addressed the above mentioned problemby solving the inverse problem: Ask students to writecode for existing documents. For students, documentsare textbooks.

    A textbook companion comprises a collection ofcode for all relevant solved problems in a textbook(Moudgalya, 2018). A student who has understoodthe concepts in a textbook may be motivated to learnan appropriate open source software and code thesolved examples, verifying the correctness at everystep. There is no document containing the code andhence there is very little chance of copyright violations.

    The student community has already created a largenumber of textbook companions for OpenModelica(Moudgalya, 2018; FOSSEE-OM-Textbook, 2020). Atthe time of this writing, we have OpenModelica text-book companions for 56 books. Textbook companionsare extremely useful as documents. Anyone who needsto know the syntax and semantics for a command couldlocate a solved example that has the underlying calcu-lation and the corresponding code. A textbook com-panion can also be used by course instructors to carryout what-if studies on solved examples. Finally, if alarge number of textbook companions are created, acourse instructor can use a database of such documentsto set problems.

    4.9 Interactive Scripting APIs usingModelica, Python, Julia, and Matlab

    Interactive scripting APIs (Application ProgrammingInterfaces) are provided for several scripting languagesusing interactive read-eval-print loops.

    There is an interactive session handler, OMShell,that parses and interactively interprets commands andexpressions in Modelica for evaluation, thus providingModelica scripting. The session handler also containssimple history facilities, and completion of file namesand certain identifiers in commands.

    Interactive sessions handlers with scripting APIsto OpenModelica are also provided for the languagesPython (Python Software Foundation, 2018), Julia(Julialang, 2018), and Matlab (MathWorks, 2018),through the subsystems OMPython (Lie et al., 2016),OMJulia (Lie et al., 2019) and OMMatlab (OpenMod-elica, 2020). This gives the user the possibility to useModelica together with the rich set of facilities and li-braries in these languages, e.g. for tasks such as controldesign and post processing of simulation results.

    More precisely, the scripting language APIs(OMPython, OMJulia, OMMatlab) provide methodsfor

    (i) establishing objects of Modelica code within thescripting language,

    (ii) getting and setting Modelica model parameters,

    (iii) getting and setting piece-wise constant inputs overa time interval,

    (iv) getting and setting simulation options,

    (v) carrying out simulation and getting solutions,

    and more. Initial states can be set via parameters.

    4.10 FMI – Functional Mockup Interface

    4.10.1 FMI Import and Export

    The FMI (Functional Mockup Interface) standard de-scribes a way of describing and packaging causal mod-els in either binary or source-code form. Many tools(including Modelica tools) support exporting modelsfrom their native modeling representation into FMIform. The standard is widely used in industry, es-pecially the automotive industry which initially drovethe development. Today, the Modelica Association ismaintaining the standard and continuously developingit further. A model or simulation unit is called FMU(Functional Mockup Unit) according to the standard.Regarding export from Modelica tools, compared to aModelica model which is usually acausal, an exportedmodel in FMU form is less general since it is causal

    257

  • Modeling, Identification and Control

    Figure 13: The OpenModelica OMSimulator composite model editor (left) and simulator right.

    – the causality of ports has to be fixed. The Open-Modelica toolset can be used to both export any givenModelica model as an FMU and import FMUs to cre-ate a composite model.

    4.10.2 OMSimulator – FMI and TLM-basedSimulation/Co-simulation and CompositeModel Editor

    Simulation according to the FMI standard can be doneusing model-exchange FMUs (exported models with-out a solver), co-simulation FMUs (exported mod-els including an embedded solver), or tool-to-tool co-simulation. Standard Modelica simulation uses thesame solver for all included model components, whichis the approach used for model-exchange FMUs. Co-simulation mechanisms that synchronize several solvershave to be used for co-simulation FMUs, which some-times may cause numerical stability issues.

    OMSimulator (2020) is an OpenModelica subsystemthat provides efficient simulation and co-simulation ofFMUs. Thus, models from non-Modelica tools com-piled into FMUs can also be utilized and simulated.Furthermore, models that cannot be exported as FMUscan be integrated in a simulation using tool-to-tool co-simulation. This is provided via wrappers to mod-els in tools such as ADAMS (MSCSoftware, 2020),Beast (Fritzson et al., 2014; Fritzson, 2018), Simulink(MathWorks, 2019a), Hopsan (Axin et al., 2010), or co-simulation of FMUs with embedded solvers. The sys-tem can optionally be used with TLM (TransmissionLine Modeling) connectors, which provide numericallymore stable co-simulation.

    The previous version, OMSimulator 1.0 (2017) wasalready made available in OpenModelica 1.12.0 (Fritz-son et al., 2018a). However, it was strictly restrictedto TLM-connections between components.

    OMSimulator is provided together with a compos-ite model editor integrated in OMEdit (Figure 13),that allows combining external models (e.g. FMUsfor both model-exchanged and co-simulation) into newcomposite models, simulating them and in some cases(for the TLM version) perform 3D animation. Com-posite models can be imported and exported by usingthe SSP standard (Systems and Structure Parameter-ization) standard (Modelica Association, 2018; Open-Modelica, 2020).

    4.11 Parameter System Identification

    OMSysIdent (2020) is a system parameter identifica-tion module built on top of the OMSimulator (2020)API. For estimating the sought parameter values, asystem model needs to be provided as FMU, as well asrespective measurement data of the system. The APIof OMSysIdent is integrated with the scripting inter-faces of OMSimulator and OpenModelica (using Luaor Python scripting). Internally, the module uses theCeres Solver (Agarwal et al., 2018) library for the op-timization task.

    4.12 Parameter Search-Based DesignOptimization

    An important use for modeling and simulation is toimprove a system design, usually before it is physi-cally realized and manufactured. In this process it iscustomary to perform a number of simulations for dif-ferent values of the design parameters, until a designhas been obtained that best fulfills a given set of designcriteria.

    The traditional parameter sweep based design opti-mization performs many simulation runs while sweep-ing, i.e., performing a linear search, of the desired pa-

    258

  • Fritzon et al., “OpenModelica Integrated Environment”

    (a) Selecting variables, objectives, parameters.

    (b) A result plot with a Pareto optimization of two goalfunctions.

    Figure 14: The OpenModelica OMOptim tool for pa-rameter sweep optimization.

    rameters over an interval in order to find an optimalvalue of a goal function or goal variable. The drawbackis the very large number of simulations that might berequired. For example, three parameters each with aninterval that is subdivided into 100 steps would requireone million simulations to cover all combinations forthese parameters.

    4.12.1 The OMOptim Tool with GeneticAlgorithms for Parameter Search

    The OMOptim OpenModelica tool (Figure 14),(Thieriot et al., 2011) provides a GUI and uses ge-netic algorithms (simulated annealing) during parame-ter exploration as a search heuristic to find an optimalparameter setting.

    Figure 15: Sensitivity of reactor temperature to ran-domly varied heat transfer coefficient UA.Nominal parameters (solid) for increase incooling temperature Tc (red) and decreasein cooling temperature Tc (blue).

    4.12.2 Parameter Sweep Optimization based onPython, Julia, or Matlab Scripting

    With a simulation model expressed in Modelica, anda cost function either expressed in Modelica or thescripting language, for-loops in a scripting language,Section 4.9, such as Python, Julia, Matlab, and tosome extent Modelica can be used to compute how thecost function varies with changing values of parame-ters. Typical scripting language code for carrying outthis operation is as follows (Julia syntax):

    # mod -- model object

    # sweep over np parameter values

    np = 20

    # parameter vector

    par = range (1.0, 10.0, length =np)

    # vector for storing resulting cost

    cost = zeros(np)

    for i in par

    setParameters(mod ,"p = $(par [i])")

    simulate(mod)

    cost[i] = getSolutions(" cost ")[end]

    end

    This idea can trivially be extended to multi parame-ter problems, including parameterization of inputs. Tofind parameters which, say, minimize the cost, one canthen simply search for minimal point in the cost ar-ray, or by fitting the cost array data to some analyticparametric function, and then find the minimum of theanalytic function.

    To illustrate the idea of parameter sweep, Figure 15shows how the solution of a reactor model (Seborget al., 2011) changes for a randomly drawn heat trans-fer coefficient within a range.

    259

  • Modeling, Identification and Control

    Figure 16: Dynamic optimization formulates the wholetrajectory in terms of trajectory segmentswhose shapes are adjusted during optimiza-tion.

    4.13 Dynamic Optimization UsingCollocation

    Another approach, dynamic optimization using collo-cation (Figure 16), (Bachmann et al., 2012; Åkesson,2008; Ruge et al., 2014; Houska et al., 2011), avoidsthe combinatorial explosion of multiple simulation runssince only a single model evaluation is required to findan optimal trajectory. This is at the cost of being verysensitive to the model – the methods may typically notconverge except for small models, i.e., not at all robust.

    A collocation method formulates an optimizationproblem directly on a whole trajectory which is dividedinto trajectory segments (Figure 16) whose shapes aredetermined by coefficients which are initially not de-termined.

    During the optimization process these coefficientsare gradually assigned values which make the trajec-tory segments adjust shape and join into a single tra-jectory with a shape that optimizes the goal functionunder the constraints of fulfilling the model equations.

    The systems to be optimized are typically describedusing differential-algebraic equations (DAEs), whichcan be conveniently formulated in Modelica. The cor-responding optimization problem can be expressed us-ing graphical or textual formulation based on annota-tions.

    Solution algorithms based on collocation methodsare highly suitable for discretizing the underlying dy-namic model formulation. Thereafter, the correspond-ing discretized optimization problem can be solved,e.g. by the interior-point optimizer Ipopt (Wächterand Biegler, 2006). The performance of the optimizerheavily depends on the availability of derivative infor-mation for the underlying optimization problem. Typ-ically, the gradient of the objective function, the Jaco-

    bian of the DAEs as well as the Hessian matrix of thecorresponding Lagrangian formulation need to be de-termined. If only some or none of these derivatives areprovided, usually numerical approximations are used.The generation of symbolic Jacobian is already avail-able in OpenModelica (Braun et al., 2012; Shitahunet al., 2013) and the generation of symbolic Hessian iscurrently under development.

    The main symbolic transformation steps during com-pile time and the dynamic optimization tool chain forOpenModelica with Ipopt are visualized in Figure 17.

    The optimization can be called via a batch processusing the following commands:

    setCommandLineOptions("+gDynOpt");

    loadFile("...");

    optimize(nmpcProblem,

    numberOfIntervals =20,

    tolerance =1e-8);

    The implementation has been tested with several ap-plications and is demonstrated in the following using acombined cycle power plant model, see Figure 18. Themodel contains equation-based implementations of thethermodynamic functions for water and steam, whichin turn are used in the components corresponding topipes and the boiler. The model also contains compo-nents for the economizer, the super heater, as well asthe gas and steam turbines. The model has one input,10 states, and 131 equations. Additional details on themodel are presented in (Casella et al., 2011a).

    The optimization problem is set up to use 50 collo-cation points that result in 1651 variables for the non-linear optimal control problem and was solved on aPC with a 3.2GHz Intel(R) Core(TM) i7. The algo-rithm requires an initial trajectory of all problem vari-ables, which is provided by a simulation where the rateof change of the gas turbine load is set to a constantvalue. The optimization results are shown in Figure 18and correspond with the results that are discussed indetail in (Casella et al., 2011a). Here, the trajectoriesare smoother, and the performance has been improvedsubstantially.

    4.14 Parameter Sensitivity Analysis Basedon Optimization

    The sensitivity of non-linear models in the form ofordinary differential equations is understood as thetendency to undergo qualitatively noticeable changesin response to shifts in the parameters used for themodel setup (Khalil, 2002). Given a nonlinear modelthere exists an interest in automatically and effi-ciently detecting small sets of parameters that can pro-duce strong changes in state variables when perturbedwithin ranges smaller than the uncertainty bounds.

    260

  • Fritzon et al., “OpenModelica Integrated Environment”

    (a) Symbolic preprocessing and transformation.

    (b) Optimization tool chain.

    Figure 17: OpenModelica with Ipopt

    (a) Combined cycle power plant displayed withOMEdit

    (b) Optimal start-up trajectories. The upper curveshows the live steam temperature, the middle andlow curves show the turbine rotor surface and meantemperatures.

    (c) Optimal start-up trajectories. The upper curveshows the pressure in the evaporator, the middlecurve shows the thermal stress in the steam tur-bine shaft and the lower curve shows the controlinput represented by the load.

    Figure 18: Combined cycle power plant model in OpenModelica

    261

  • Modeling, Identification and Control

    Object-oriented modeling languages such as Modelica(Modelica Association, 2017; Fritzson, 2014) facilitatea systematic treatment of the problem by exposing aclear and unambiguous access to model parameters,state variables, and simulation configuration. This pro-motes the design of reusable frameworks that treat themodels as black boxes (not excluding exploiting inter-nal knowledge on the model structure) The OpenMod-elica (2020) tool also includes a Sundials/IDA solverthat calculates parameter sensitivities using forwardsensitivity analysis. Yet, this approach cannot be ap-plied to models that are not fully differentiable. Theoption of picking several values within a parameterinterval and sweep all possible combinations quicklyleads to a combinatorial explosion that renders the ap-proach unfeasible. In the simultaneous approach, afterdefining the parameters and their intervals, an algo-rithm (typically an optimization-based strategy) findsa vector of smallest perturbation values that producesthe largest impact on the state variables. The OM-Sens OpenModelica (2020, ch. Paremeter Sensitivititeswith OpenModelica) sub-system is a tool to assess thesensitivity of Modelica models (Danós et al., 2017).OMSens uses different methods for sensitivity analy-sis including robust, derivate-free non-linear optimiza-tion techniques based on the CURVI family (Dennis Jr.et al., 1991).

    4.14.1 Sensitivity Analysis of Modelica models

    Unlike most previous approaches, OMSens offers awide choice of computational methods for sensitivityanalysis. Elsheikh (2012) uses automatic differentia-tion to augment the model with the sensitivity equa-tions. This is similar to the IDA Solver approach inOpenModelica (2020, ch. Paremeter Sensitivitites withOpenModelica) which is simpler to employ since it nu-merically computes sensitivities directly. Wolf et al.(2008) compares several methods including parameter-sweep and solver-based approaches using the DASPKsolver (Petzold et al., 2006). Many optimization meth-ods can be employed for sensitivity analysis. For exam-ple, Ipopt (Wächter and Biegler, 2006) is a well-knownnon-linear optimization routine. Other methods arementioned in Section 4.12 and Section 4.13, some ofwhich are time consuming or not at all robust.

    4.14.2 Optimization-driven Sensitivity Analysis

    Numerical aspects of the optimization algorithms needto be considered carefully, as they affect their efficiency,robustness and scope of applicability. A correct analy-sis should consider the combined, simultaneous effectsof many perturbations of the parameters, somethingthat is unmanageable due to the number of combina-

    tions and the impossibility of determining beforehandthe size of those perturbations. Nonlinear optimizationcan be used to solve the problem by reformulating itas a model stability problem (Danós et al., 2017).

    In the current version OMSens implements a deriva-tive–free optimization algorithm named CURVI –curvilinear search method, Dennis Jr. et al. (1991)which is able to solve very difficult problems while al-lowing for custom interval constraints. There are threeversions: CURVIF, CURVIG, CURVIH that use, re-spectively, function values, function values plus gra-dients, and the latter plus Hessians. All versions areglobally convergent.

    CURVIF is the flavor currently adopted in OMSens,and does not necessarily employ the least number offunction evaluations. It can be seen as a trade-off be-tween robustness and efficiency. Moreover, global opti-mization functionality is currently being added to OM-Sens.

    4.14.3 OMSens Architecture

    OMSens provides a flexible experimentation arena ofdifferent sensitivity analysis strategies for Modelicamodels. It provides modularity by being split into de-coupled backend and frontend modules. It also pro-vides flexibility since the backend is subdivided intomodules that encapsulate responsibilities and exposeclear invocation interfaces.

    The OMSens modules can be divided in two groups:simultaneous sensitivity analysis and individual sensi-tivity analysis. In Figure 19 we find six main modules.In the simultaneous scenario, module 3 (Optimization)leads the workflow, invoking modules 1, 2 and 4 to per-form an exploration of the parameter space. This needssuccessive simulations requested from module 2 (Mod-elica) depending on the simulation results of previousinvocations, following a closed loop strategy. In the in-dividual scenario modules 5 and 6 lead their own work-flows, invoking single simulations with no dependencyon the results of previous runs (open loop). Module6 (Parameter sweeping) invokes simulations while se-quentially picking values from a parameter space de-fined by the user.

    A summary of the presented sensitivity analysismethods can be found in Table 6.

    A sensitivity method measures the change of a cho-sen variable/state variable with respect to changes inone or more parameters. OpenModelica (2020, ch.Paremeter Sensitivitites with OpenModelica) can cal-culate sensitivities using the Sundials/IDA solver usingthe derivatives of each state variable with respect toeach top-level parameter during a simulation (IDAsensmethod) defined for all values of time. OMSens canlaunch experiments using the IDASens method. OM-

    262

  • Fritzon et al., “OpenModelica Integrated Environment”

    Table 6: Summary of sensitivity methods for a generic state variable x with respect to the i-th parameter pi.

    Method Formula Input Type

    IDAsense ṡi(t) =∂x(t)∂pi

    Single year

    Rel srel(t) =σ(t)std(t) Single year

    RMS srms(t0, tf ) =√

    1n (σ

    20 + · · · + σ2n) Range of years

    Figure 19: OMSens high level architectural view.

    sens allows defining custom methods for comparisonsof perturbed vs. unperturbed runs. For example, weuse a Relative (Rel) method defined as

    srel(tk) =σ(tk)

    x(tk)with σ = xper − x,

    i.e. the difference in a state variable with and withoutperturbation of a parameter (xper vs. x).

    It can be used to rank the parameters affecting avariable the most at a target year. We also define theRoot Mean Square (RMS) method sRMS(t0, tf ) thatcalculates the root mean square of the differences σ(tk)for integer years t0 ≤ tk ≤ tf . It can be used torank the most relevant parameters impacting a vari-able throughout a range of years.

    4.14.4 Case Study – Sensitivity Analysis of aComplex Socio-Economic Model

    World3 is a world-level socio-economic model availableas a Modelica library (Cellier, 2008), here referred toas W3-Mod. It implements the World3 model as de-scribed in Meadows et al. (2004, Limits to Growth, 3rdedition) meant to forecast critical global aspects (popu-lation, pollution, natural resources) as far as year 2100.W3-Mod subdivides the model into 13 socio-economic

    sectors, with a total of 41 state variables, 245 algebraicvariables, and 70 parameters (including bivariate tablefunctions) representing many facets of human life andecological factors.

    In a separate earlier book by Meadows et al. (1974),simplistic sensitivity experiments were considered, butW3-Mod lacks a comprehensive sensitivity study. Themodel has long been characterized as strongly nonlin-ear and unstable with regards to parameter changes(Castro, 2012; Scolnik, 1979; Vermeulen and de Jongh,1976).

    Applying optimization-based analysis, we used OM-Sens to analyze the state variable Population of W3-Mod at year 2100, perturbing the top-12 most influ-encing parameters found using the Rel analysis methodfor that state variable. We allowed all parameters tochange within a ±5% interval (conservative bounds forsocio-economic indicators). CURVI found three non-intuitive perturbation values compared to the resultsobtained with the Rel method alone, not shown here.

    Parameters p land yield fact 1 andp avg life ind cap 1 (Default land yield factorand Default average life of industrial capital) wereperturbed in opposite directions compared to what anindividual parameter-based approach would indicate.With these differences the impact is noticeable. InFigure 20 we observe several simulations to interpretthe results, all extended up to the year 2500 for thesake of readability. The black curve is the unperturbedrun. The red curve is the run perturbed with theindividual parameter-based strategy (Rel method)and the green curve represents perturbations foundby CURVI. We can see that for the target year 2100CURVI found a parameter combination that takes thepopulation way up compared to what was achievedrelying solely on the Rel method.

    Verification with multi-parameter sweeping is avail-able to automate the simulation and analysis of ar-bitrary combinations in a parameter space. Theoptimization-based method yields a substantial im-provement compared to an individual parameter-basedstudy. We now assess whether other perturbations offerextra insights. We create a space for both parameters

    263

  • Modeling, Identification and Control

    Figure 20: Population in W3-Mod.Standard Run and OMSens perturbations: Rel method, multi-parameter sweep and CURVI.

    using the same perturbation vector [−5%, 0%,+5%]and launch the analysis. The results in Figure 20 aredenoted with (0) and (1) for values of land yield and in-dustrial capital parameters. We observe that the popu-lation variable converges smoothly from the individualparameter-based to the simultaneous parameter-basedstudy.

    4.15 Model-based Control with DynamicOptimization

    Modelica has been applied to the formulation of dy-namic optimization problems for complex physical sys-tems since many years (Franke et al., 2003). Theoptimization methods of control vector parameteriza-tion and multiple shooting enable the efficient use ofsimulation models with numerical optimization solversand the treatment of large-scale problems with paral-lel computing. Many successful industrial applicationsto model-based control of power systems underline thesuitability. The Modelica technology and the imple-mentation in OpenModelica evolved continuously.

    FMI 2.0 for model exchange standardizes the solverinterface to simulation models. It covers executablemodel code, an XML interface description, sparsemodel structures and analytic Jacobian matrices. Mul-tiple FMI instances of one and the same model enableparallel optimization. The OpenModelica C++ run-time was developed with focus on the export of simu-

    lation models to real-time control applications. C++provides for improved type safety, deterministic mem-ory management and compiler optimizations resultingin best in class execution times (Franke et al., 2015).

    4.15.1 Synchronous Modelica for Model-BasedControl

    Continuous-time physical models are treated with dis-crete sample times in digital control applications. Mod-elica’s synchronous language elements extension wasintroduced for precisely defining and synchronizingsampled-data systems with different sampling rates(Modelica Association, 2017). OpenModelica was thesecond Modelica tool which supported this extension,implemented both on top of the OpenModelica C run-time and the C++ run-time. This can be used formodel-based control, using Modelica and FMI (Frankeet al., 2017).

    4.15.2 Control and Optimization of Electric PowerSystem as Exported FMUs

    Figure 21 shows OMEdit with an example model ofan electric power system, covering an off-shore inter-connector combined with wind farms and a back-to-back HVDC coupling. The object-oriented model com-prises 4 722 variables. 788 of those variables are non-trivial. OMEdit exports the model as FMU 2.0 usingthe OpenModelica C++ runtime.

    264

  • Fritzon et al., “OpenModelica Integrated Environment”

    Figure 21: Model of an electric power system.

    The control task is to maximize the transfer capacityof the interconnector on top of collected wind power,considering active and reactive power flows subject togrid and voltage limitations. The prediction horizonspans 96 sample intervals. This results in 76 436 (97 ·788) non-trivial optimization variables.

    Table 7 shows speedups achieved with different FMUfeatures and optimization solver configurations. Thereference configuration uses multiple shooting with 1CPU, exploiting sparsity that results from the timestaggering structure over 96 intervals, but neglectingsparsity inside model Jacobians at each time point.The Jacobians are obtained with the method of finitedifferences. A speedup of 1.9 is achieved with sparseJacobians by exploiting information in the XML inter-face description. The speedup increases to 3.9 whenadditionally enabling OpenModelica’s algorithmic dif-ferentiation and re-use of numerical factors of equationsystems inside the model.

    Parallel multiple shooting using a separate FMU in-stance for each CPU further increases the speedup to6.3 with 5 CPUs and up to 7.6 with 20 CPUs. Thespeedup is still 7.0 with finite differences and 20 CPUs.This is at the cost of twice the CPU usage though,whereas algorithmic differentiation leaves more CPUcapacity for other tasks running at the same time.

    4.16 Model-based Control System Design

    In addition to the scripting API commands mentionedin Section 4.9, the APIs OMPython (Lie et al., 2016),OMJulia (Lie et al., 2019), OMMatlab (OpenModelica,2020) also allow for getting and setting linearizationoptions, and carrying out linearization. The linearizemethod returns a tuple of linear, time invariant (LTI)matrices (A,B,C,D), which can be further used in var-ious control tools, e.g., the MATLAB Control SystemToolbox (MathWorks, 2019b), the Python Control Sys-tems Library (Murray and Livingston, 2019), or theJulia Control Systems Toolbox (JuliaControl, 2019).

    We consider a liquid reactor (Figure 22) taken from(Seborg et al., 2011), where we seek to control the efflu-ent temperature by manipulating the influent coolingtemperature.

    The model is implemented in Modelica, and an ob-ject is created in a scripting language (here: Julia, us-ing OMJulia). At the operating point, the linearizemethod is used to find an LTI approximation. Based onthis LTI approximation, Julia’s ControlSystems pack-age can be used to do a root locus plot (Figure 23) onhow the closed loop eigenvalues vary with proportionalgain in a Proportional controller (P-controller),

    Based on the root locus plot, a suitable controllergain for the P-controller can be found, and like-wise a suitable reset time/integral time in a Propor-tional+Integral controller (PI controller). The result-

    265

  • Modeling, Identification and Control

    Table 7: Speedup achieved with different FMU features and parallel computing.

    Speedup for different solver configurations Finite Differ-ences

    AD withrefactoring

    AD with fac-tor reuse

    Sequential shooting, Dense model blocks, no AD, 1 CPI 1.0 - -

    Sequential shooting, Sparse model blocks, 1 CPU 1.9 1.3 3.9

    Parallel multiple shooting, Sparse model blocks, 2 CPUs 2.8 2.2 4.6

    Parallel multiple shooting, Sparse model blocks, 5 CPUs 4.6 3.7 6.3

    Parallel multiple shooting, Sparse model blocks, 20 CPUs 7.0 6.5 7.6

    Figure 22: Cooled liquid reactor.

    Figure 23: Root locus plot of Seborg reactor. A modi-fied plotting routine has been used, insteadof the root locus method of the ControlSys-tems package.

    ing PI controller gives quite good control of the reactortemperature.

    However, the resulting cooling temperature inputdips down to minus twenty Celcius, which is unreal-istic. Constraining the cooling temperature to lie inthe range of liquid water, together with integral anti-windup leads to the results in Figure 24a and Fig-ure 24b for output T and controller Tc, respectively.

    (a) Reactor temperature controlled with a constrained PIcontroller with anti-windup. A continuous controller isused, implemented in Modelica.

    (b) PI control signals — cooling temperature, with con-strained PI controller with anti-windup. A continuouscontroller is used, implemented in Modelica.

    Figure 24: Results for output T and controller Tc

    More details of this example can be found in Khaliliand Lie (2018), with other examples including stateestimation and Linear Quadratic control.

    266

  • Fritzon et al., “OpenModelica Integrated Environment”

    4.17 Model-based Fault and DependabilityAnalysis

    The purpose of reliability, and more generally, of de-pendability studies is to evaluate non-functional per-formances, that is, to calculate probabilities of un-desirable events such as the failure of the missionof a system, or to estimate the probability distribu-tion of quantities like: total production on a giventime interval, maintenance cost, number of repairsetc. Usually, dependability studies are performedwith dedicated methods and tools, based on discrete(and often even Boolean) models of systems: faulttrees, Markov chains, Petri nets, BDMP (Boolean logicDriven Markov Processes) etc. EDF (Electricité duFrance) designed the Figaro modeling language in 1990(Bouissou et al., 1991). This language generalizes allthe above cited models, and allows casting knowledgein categories of systems in libraries. It is the basis ofKB3 which is the reference tool used for building faulttrees and dynamic models for probabilistic safety anal-yses of nuclear power plants and most other reliabilityanalyses at EDF.

    In order to benefit from this type of analysis a pro-totype for coupling Modelica models with their Figarocounterpart has been developed (Bouissou et al., 2016).This coupling presented two main issues:

    The systems are modeled with different degrees ofgranularity in the two languages.

    Links are explicit objects in the Figaro world thatcan have properties and behavior, whereas the de-fault port connections in Modelica are not objects.When mapping Figaro to Modelica this is handledby letting connections go through intermediary ob-jects that contain that information.

    Therefore, the mapping between Modelica and Fi-garo components is not one-to-one. Instead compo-nent types with a Figaro counterpart are identified inModelica through special interfaces and this informa-tion is then used to export the Figaro model from thecorresponding Modelica model.

    The reliability analysis performed on the Figaromodel can be then used to identify potential issues (forexample, critical components) and this information canbe fed back into the Modelica simulation (for example,investigate in more details the effect of the failure of acritical component).

    Another approach has been to use Monte Carlo sim-ulation on Modelica models. In order to do this, ran-dom failures (and possibly repairs) are added to theoriginal simulation model, which is slightly modifiedin order to propagate the effects of failures. The ar-ticle by Bouissou et al. (2014) explains how standard

    Modelica solvers can be used to simulate systems withfailure rates that depend on continuous variables (liketemperature, etc.). This was tested with a well-knownbenchmark that was first published in (Aldemir, 1987)and since then has been solved with many differentmethods and tools.

    In the OpenModelica setting, scripting is used to runthe simulation a large number of times (10 000 timesin this example), which allows to calculate by simplestatistical estimators the probability of various unde-sirable events over time, and quantities such as averageproduction, life-cycle cost etc.

    4.18 Data Reconciliation for EnhancedAccuracy of Sensor Data

    The operation of power plants requires a good qualityof the process data obtained through sensor measure-ments. Unfortunately, sensor measurements such asflow rates, temperatures, and pressures are subject toerrors that lead to uncertainties in the assessment ofthe system’s state. Operational margins are thereforeset to take into account uncertainties on the system’sstate. Their effect is to decrease production becausesafety regulations put stringent limits on the thermalpower of the plants. It is therefore important to com-pute the best estimates of the measurement uncertain-ties in order to increase power production by reducingoperational margins as much as possible while still pre-serving system safety.

    The best estimates can be obtained by combiningdata statistics with a knowledge a priori of the sys-tem in the form of a physical model. Data reconcilia-tion is a technique that has been conceived in the pro-cess industry for that purpose. It is fully described inthe VDI 2048 standard (VDI – Verein Deutscher Inge-nieure, 2012, 2017, 2018) for the “Control and qualityimprovement of process data and their uncertaintiesby means of correction calculation for operation andacceptance tests”. Up to now, it was only availablein dedicated tools such as VALI from Belsim (2019)that require to develop a specific model of the sys-tem under consideration. The main drawbacks are thatsuch models are costly to develop and difficult to vali-date. A natural answer to this problem is to performdata reconciliation on Modelica models. However, un-der the current state-of-the-art of Modelica tools, suchtask is not possible because an appropriate subset ofthe Modelica model of the system under considerationmust be considered for data reconciliation. This sub-set contains the (presumably) exact physical laws thatconstrain the variables of interest to be reconciled. Allother equations such as boundary conditions or approx-imated equations that affect the variables of interest

    267

  • Modeling, Identification and Control

    must be removed. This subset is called the “auxiliaryconditions” in VDI 2048. The auxiliary conditions aretherefore underdetermined (more unknowns than equa-tions) and cannot form a valid Modelica model for sim-ulation.

    OpenModelica is currently being extended to per-form data reconciliation on regular Modelica models.To that end the following is developed:

    New annotations are introduced to tag the vari-ables of interest and the approximated equations.

    An algorithm is being developed to automaticallyextract the auxiliary conditions.

    The data reconciliation procedure taking as inputsthe variables of interest as tagged by the user, theirmeasured values (mean values and statistical con-fidence intervals) as provided by the user and theautomatically extracted auxiliary conditions fromthe Modelica model provided by the user, is beingimplemented. It produces as outputs the recon-ciled values and their reduced confidence intervals.

    The GUI is being extended to handle inputs andoutputs.

    The main benefit is to be able to perform data recon-ciliation on existing validated model without having tomodify them for that purpose. This is a considerableimprovement with respect to the current state-of-the-art.

    4.19 Artificial Neural Networks for ModelCalibration and Augmentation

    The pursuit of both model accuracy and simplicity ingeneral results in conflict. Ultimately, a model shouldmeet its accuracy requirements whilst remaining assimple as possible. To validate a model, measurementstaken from the original system can be used (Zhu et al.,2007). As an example, the trajectories from simula-tions of the model can be compared to the actual mea-surement data to validate the model behavior.

    A more sophisticated approach may involve the ex-traction of high-level features from said trajectories.For example, a good model of a pendulum should ex-hibit frequency and amplitude of oscillation similar tothose of the original pendulum.

    Inherently, after the modeling process, there are dif-ferences between the measurements of the model andthe original system that, by magnitude or trend overtime, cannot purely originate from measurement noise.Assuming negligible numer