Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

Modeling and Optimization with Modelica and Optimica Using the JModelica.org Open Source Platform

Johan Åkessona,b Tove Bergdahla Magnus Gäfverta Hubertus Tummescheita a Modelon AB, Sweden b Department of Automatic Control, Lund University, Sweden

Abstract devoted to encapsulating expert knowledge in model libraries encoded in domain specific languages such This paper reports a new Modelica-based open source as VHDL-AMS [30] and Modelica [44]. While such project entitled JModelica.org, targeted towards dy- model libraries have been primarily intended for sim- namic optimization. The objective of the project is ulation, it is desirable to enable also other usages, in- to bridge the gap between the need for high-level de- cluding optimization. From a user’s perspective, it scription languages and the details of numerical opti- is desirable that the optimization specification is ex- mization algorithms. JModelica.org is also intended pressed in a high-level language in order to provide a as an extensible platform where algorithm developers, comprehensive description both of the dynamic model particularly in the academic community, may integrate to be optimized and of the optimization problem. An- new and innovative methods. In doing so, researchers other aspect that requires attention is that of enabling gain access to a wealth of industrially relevant opti- flexible use of the wealth of numerical algorithms mization problems based on existing Modelica mod- for dynamic optimization, based on the high-level de- els, while at the same time facilitating industrial use scriptions specified by the user. of state of the art algorithms. In this contribution, an Several common engineering tasks are conveniently overview of the platform is presented and the main fea- cast as optimization problems. This includes param- tures of JModelica.org are highlighted. eter estimation problems to obtain models that match Keywords: Modelica; Optimica; Optimization; plant data, design optimization for improving product Model Predictive Control performance, and controller parameter tuning. In ad- dition, dynamic optimization is a key to implementing for example model predictive controllers and receding 1 Introduction horizon state estimators. Optimization is becoming a standard methodology in This contribution reports a new Modelica-based many engineering disciplines to improve products and open source initiative targeted at dynamic optimiza- processes. The need for optimization is driven by tion entitled JModelica.org. JModelica.org [36] is a factors such as increased costs for raw materials and novel open source project with the mission: stricter environmental regulations as well as a general “To offer a community-based, free, open source, ac- need to meet increased competition. As model-based cessible, user and application oriented Modelica en- design processes are being used increasingly in indus- vironment for optimization and simulation of complex try, the prerequisites for optimization are often ful- dynamic systems, built on well-recognized technology filled. However, current tools and languages used to and supporting major platforms.” model dynamic systems are not always well suited for integration with state of the art numerical optimization JModelica.org is primarily focused on dynamic opti- algorithms. As a result, optimization is not used as fre- mization of Modelica models. To meet this end, JMod- quently as it could, or less efficient, but easier to use, elica.org supports Optimica, which is an extension to algorithms are employed. the Modelica language that offers language constructs More often than not, systems to be optimized are for encoding of cost functions, constraints and the op- complex and dynamic. Such problems offer several timization interval with fixed or free end points. The challenges at different levels. Much effort has been platform consists of compilers for translating Model-

© The Modelica Association, 2009 29 DOI: 10.3384/ecp09430057 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

ica and Optimica models into C and XML code, a complexity of the target models, models are usually C API for evaluation of model equations and Python treated as black boxes, i.e. the result of a computation bindings to enable scripting and custom algorithm de- is propagated to the tool, but the structure of a par- velopment. The software is distributed freely under ticular model is not explored. Accordingly, heuristic the GPL license. optimization algorithms which do not require deriva- The paper is outlined as follows. In Section 2, a tive information or detailed structural information, are review of optimization tools and the Optimica exten- usually employed. In addition, model integration tools sion are given. Section 3 describes the JModelica.org often have sophisticated features supporting model ap- platform. Previous case studies performed based on proximation and visualization. JModelica.org, and the opportunities provided by ab- Several Simulation tools comes with optimization stract syntax tree access are discussed in Section 4. In add-ons, e.g., [14], gPROMS [42] and Jaco- Section 5, an example of a model predictive control bian [37]. Such tools typically offer strong support application is given. The paper ends with a summary for modeling of physical systems and simulation. The and comments on future work in Section 6. level of support for optimization in this category dif- fers between different tools. Dymola, for example, offers add-ons for parameter identification and design 2 Background optimization, [18]. gPROMS, on the other hand, also offers support for solution of optimal control prob- It is typical that numerical algorithms for dynamic op- lems. Tools in this category are usually limited to a timization is written in C or Fortran. Often, the user predefined set of optimization algorithms. Integration is required to encode the dynamic model and the opti- of new algorithms may be difficult if the tools do not mization specification in the same languages. While C provide the necessary API:s. and Fortran enables efficient compilation to executable code, such languages are not well suited for encoding In the third category we have numerical packages of dynamic models and optimization problems. In par- for dynamic optimization, often developed as part of ticular, it is difficult to write the code in a modular way research programs. Examples are ACADO [39], Mus- that enables reuse. This observation was made several cod II [46], and DynoPC [33], which is based on decades ago in the context of modeling and simulation Ipopt [48]. Such packages are typically focused on and resulted in high-level modeling languages, includ- efficient implementation of an optimization algorithm ing ACSL and later Omola, [4], VHDL-AMS [30], and for a particular class of dynamic systems. Also, de- Modelica [44]. See [5] for a comprehensive overview tailed information about the model to optimize is gen- of the evolution of continuous-time simulation lan- erally required in order for such algorithms to work, guages and tools. including accurate derivatives and in some cases also sparsity patterns. Some of the packages in this cate- gory are also targeting optimal control and estimation 2.1 Optimization Tools problems in real-time, e.g., non-linear model predic- There are several tools for optimization on the market, tive control, which require fast convergence. While offering different features. In essence, three different these packages offer state of the art algorithms, they categories of tools can be distinguished, although the typically come with simple or no user interface. Their functionality is sometimes overlapping. Model inte- usage is therefore limited due to the effort required to gration tools addresses the problem of interfacing sev- code the model and optimization descriptions. eral design tools into a a single computation environ- The JModelica.org platform is positioned to fill the ment, where analysis, simulation and optimization can gap left between simulation tools offering optimiza- be performed. Examples are ModelCenter, [41], Op- tion capabilities and state of the art numerical algo- tiY, [40], modeFRONTIER [21], and iSIGHT, [11]. rithms. Primarily, target algorithms are gradient based Typically, such tools are dedicated to design opti- methods offering fast convergence. Never the less, mization of extremely complex systems which may JModelica.org is well suited for use also with heuristic be composed from subsystems encoded in different direct search methods; the requirements with respect tools. Accordingly, model integration tools typically to execution interface is typically a subset of the re- offers interfaces to CAD and finite element software as quirements for gradient based methods. The problems well as simulation tools for, e.g., mechanical and hy- addressed by model integration tools is currently be- draulic systems. As a result of the heterogeneity and yond the scope of JModelica.org, even though its in-

© The Modelica Association, 2009 30 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

model VDP The dynamic model (2) of the problem is a van Der Real x1(start=0); Pol oscillator, and the optimization problem corre- Real x2(start=1); sponds to bringing the system from initial conditions input Real u; x1(0)= 0, x2(0)= 1 to the origin in minimum time. In equation addition, the transition is to be performed with limited der(x1) = (1•x2^2)*x1 • x2 + u; control authority. der(x2) = x1; A Modelica model corresponding to the dynamic end VDP; system (2) is given in Listing 1. Based on this model, Listing 1: A Modelica model of a van Der Pol oscilla- an Optimica specification can be formulated, see List- tor. ing 2. Since Optimica is an extension of Modelica, language elements valid in Modelica are also valid in optimization VDP_Opt Optimica. In addition Optimica also contains new con- “(objective=cost(finalTime), structs not valid in Modelica. startTime=0, The Optimica program corresponding to the van finalTime(free=true, Der Pol example can be seen in Listing 2. In order initialGuess=1)) to specify an optimization problem in Optimica, the Œ VDP vdp(u(free=true, new specialized class optimization is used. Inside initialGuess=0.0)); such a class, Optimica constructs, as well as Model-  Real cost (start=0); equation ica constructs may be used. An instance of the VDP Ž der(cost) = 1; model is created by declaring a corresponding compo- constraint nent, Œ. In order to express that the input u is to be  vdp.x1(finalTime) = 0; tuned in the optimization, the Optimica-specific vari-  vdp.x2(finalTime) = 0; able attribute free is set to true, and in addition, ‘ vdp.u >= •1; an initial guess for u is provided. In order to define ’ vdp.u <= 1; the cost function, a variable, cost , is introduced end VDP_Opt; along with a defining equation, Ž. Further, the con- Listing 2: An Optimica optimization specification straints are given in the constraint section, which is based on the van Der Pol Oscillator. a new Optimica construct. In this section, – cor- respond to the terminal constraints, whereas ‘–’ cor- respond to the control variable bounds. Notice how tegration with Python offers extensive possibilities to the value of a variable at a particular time instant is develop custom applications based on the solution of accessed using an Optimica-specific function call-like simulation and optimization problems. syntax. finalTime is a built-in variable of the special- ized class optimization and is used to refer to the 2.2 Optimica time at the end of the optimization interval. Finally, the objective and the optimization interval is specified, The Optimica extension is discussed in detail [1, 2]. In “. The construct introduced in Optimica to meet this this paper, a brief overview of Optimica is given and end can be viewed as built-in class attributes which the extension is illustrated by means of an example. are given values through class arguments. Here the We consider the following dynamic optimization variable representing the cost function is bound to the problem: t f built-in class attribute objective and it is specified min 1dt (1) that finalTime is to be free in the optimization. u(t) Z0 The Modelica and Optimica specifications are then subject to the dynamic constraint typically translated by a compiler into a format suit- able for compilation with a numerical solver in order x˙ (t) = (1 − x (t)2)x (t) − x (t)+ u(t), x (0)= 0 1 2 1 2 1 to obtain the solution. x˙2(t)= x1(t), x2(0)= 1 (2) and 3 The JModelica.org platform x1(t f )= 0

x2(t f )= 0 (3) In order to demonstrate the feasibility and effective- −1 ≤u(t) ≤ 1 ness of the proposed Optimica extension, a prototype

© The Modelica Association, 2009 31 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

model M Real x; equation x = 1; end M;

Figure 2: A simple Modelica model (left) and its cor- responding abstract syntax tree (right). The dashed ar- row represents the reference attribute myDecl which binds an identifier to its declaration. Figure 1: Overview of the JModelica.org platform ar- chitecture. larations corresponding to identifiers, type analysis, i.e., verifying the type correctness of a program, and code generation. compiler was developed, [1]. Currently, the initial pro- totype compiler is being developed with the objective The JastAdd way of building compilers involves of creating a Modelica-based open source platform fo- specification of attributes and equations based on the cused on dynamic optimization. abstract syntax specification. This feature is very simi- The architecture of the JModelica.org platform is il- lar to ordinary Knuth-style attribute grammars [32] but lustrated in Figure 1. The platform consists essentially enhanced with reference attributes. Accordingly, at- of two main parts: the compiler and the JModelica.org tributes may be used to specify, declaratively, links be- Model Interface (JMI) runtime library. The compiler tween different nodes in the AST. For example, iden- transforms Modelica and Optimica source code into a tifier nodes can be bound to their declaration nodes. flat model description and then generates C and XML In Figure 2, an example of a small Modelica program code. The generated C code contains the actual model and its corresponding AST is shown. Notice how the equations in a format suitable for efficient evaluation, reference attribute myDecl links an identifier (IdUse) whereas the XML code contains model meta data, to its declaration (CompDecl). such as variable names and parameter values. The JMI JastAdd attributes and equations are organized into runtime library provides a C interface which in turn separate aspects, which form a convenient abstrac- can be interfaced with numerical algorithms. There is tion for encoding of cross cutting behavior. Typically, also an Eclipse plug-in and a Python integration mod- implementation of a semantic function, for example ule under development. In this section, the key parts type analysis, involves adding code to large number of the JModelica.org platform will be described. of classes in the AST specification. Using aspects, much like in AspectJ [31], cross cutting behavior can be modularized in a natural way. In addition, this ap- 3.1 Compiler Development—JastAdd proach is the basis for one of the distinguishing fea- Compiler construction has traditionally been associ- tures of JastAdd: it enables development of modularly ated with intricate programming techniques within the extensible compilers. This means that it is feasible to area of computer science. Recent research effort has, develop, with a comparatively moderate effort, modu- however, resulted in new compiler construction frame- lar extensions of an existing JastAdd compiler without works that are easier to use and where it is feasible changing the core compiler. This feature has been used to develop compilers with a comparatively reasonable in the implementation of the JModelica.org Modelica effort. One such framework is JastAdd [28, 17]. Jas- and Optimica compilers, where the Optimica compiler tAdd is a Java-based compiler construction framework is a fully modular extension of the core Modelica com- based on concepts such as object-orientation, aspect- piler. orientation and reference attributed grammars [15]. At The JastAdd compiler transforms the JastAdd spec- the core of JastAdd is an abstract syntax specification, ification into pure Java code, where the definition of which defines the structure of a computer program. the abstract grammar translates into Java classes corre- Based on an abstract syntax tree (AST), the compiler sponding to Modelica classes, components, functions, performs tasks such as name analysis, i.e, finding dec- and equations. The JastAdd attributes are woven into

© The Modelica Association, 2009 32 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

the Java classes as methods. In addition, methods for The JModelica.org platform contains two code gen- traversing an AST and query properties of a particular eration modules, one for C and one for XML. The AST class, e.g., obtain a list of variables contained in a generated C code contains the model equations and is class declaration, are automatically generated. As a re- intended to be compiled and linked with the JModel- sult of this approach, compilers produced by JastAdd ica.org Model Interface (see below) in order to offer are in the form of standard Java packages, which in efficient evaluation of the model equations. The XML turn can be integrated in other applications. It is there- output consists of model meta data such as specifica- fore not necessary to know the particular details of tions of variables, including their names, attributes and how to write JastAdd specifications in order to use the type. Also, the XML output includes a separate file for JModelica.org compilers, knowledge of Java is gener- parameter values. The XML output is similar to what ally sufficient. is discussed within the FMI initiative [12], and the intention is for the JModelica.org XML output to be 3.2 The Modelica and Optimica Compilers compliant with FMI once finalized. In addition, there is on-going work aimed to develop an XML specifica- At the core of the JModelica.org platform is a Mod- tion for flattened Modelica models, including variable elica compiler that is capable of transforming Mod- declarations, functions, and equations [9]. The objec- elica code into a flat representation and of generat- tive is for JModelica.org to be compliant also with this ing C code. In the Modelica compiler, several design specification. strategies, for example name look-up, developed for a Java compiler developed using JastAdd [16], were reused. For additional details on the implementation of the compiler, see [3]. 3.4 CAPI In order to support also the Optimica extension, a modular extension of the core Modelica compiler has The JModelica.org platform offers a C API, entitled been developed. The extended compiler is capable of the JModelica.org Model Interface (JMI1), suitable for translating standard Modelica enhanced with the new integration with numerical algorithms. The interface Optimica syntax presented in Section 2.2. The Optim- provides functions for accessing and setting parame- ica extension is reported in more detail in [27]. ter and state values, for evaluation of the DAE residual The JModelica.org Modelica compiler currently function and for evaluation of cost functions and con- supports a subset of Modelica version 3.0. The Mod- straints specified in an Optimica model. In addition, elica Standard Library version 3.0.1 can be parsed Jacobians and sparsity patterns can be obtained for all and the corresponding source AST can be constructed. functions in the interface. To meet this end, a package Flattening support is more limited, but is being contin- for automatic differentiation, CppAD [6], has been in- uously improved. tegrated into JMI. The JMI code is intended to be com- piled with the C code that is generated by the compiler 3.3 Code Generation into an executable, or into a shared object file. The JModelica.org offers a code generation frame- The JMI interface consists of four parts: the ODE work implemented in Java as part of the compil- interface, the DAE interface, the DAE initialization ers. The framework facilitates development of custom interface, and the Optimization interface. These in- code generation modules and is based on templates terfaces provide access to functions relevant for differ- and tags. A template is used to specify the structure ent parts of the optimization specification. The ODE of the generated code and tags are used to define ele- and DAE interfaces provide evaluation functions for ments of the template which is to be replaced by gen- the right hand side of the ODE and the DAE residual erated code. In order to develop a custom code gener- function respectively. The DAE initialization problem ation module, the user needs to define a template and provides functions for solving the DAE initialization a set of tags, and then implement the actual code gen- problem, whereas the Optimization interface provides eration behavior corresponding to each tag. In order to functions for evaluation of the cost functions and the perform the latter, the AST for the flattened Modelica constraints. model is typically used, where objects corresponding to declarations, equations and functions are queried for 1Notice that this acronym is unrelated to Java Metadata inter- information used to generate the target code. face

© The Modelica Association, 2009 33 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

3.5 Interactive Environment—Python 3.6 Optimization Algorithms

The JModelica.org platform offers two different al- Solution of engineering problems typically involves gorithms for solving dynamic optimization problems. atomization of tasks in the form of user scripts. The first is a simultaneous optimization method based Common examples are batch simulations, parameter on orthogonal collocation on finite elements [7]. Us- sweeps, post processing of simulation results and plot- ing this method, state and input profiles are parame- ting. Given that JModelica.org is directed towards sci- terized by Lagrange polynomials which are based on entific computing, Python, see [23], is an attractive op- Radau points. This method corresponds to a fully im- tion. Python is a free open-source highly efficient and plicit Runge-Kutta method, and accordingly it pos- mature scripting language with strong support in the sesses well known and strong stability properties. By scientific community. Packages such as NumPy [38] parameterizing the variable profiles by polynomials, and SciPy [20], and bindings to state-of-the art numer- the dynamic optimization problem is translated into ical codes implemented in C and Fortran make Python a non-linear programming (NLP) problem which may a convenient glue between JModelica.org and numeri- be solved by a numerical NLP solver. This NLP is, cal algorithms. In addition, IPython [19] with the visu- however, very large. In order to efficiently find a solu- alization package matplotlib [29] and the PyLab mode tion to the NLP, derivative information as well as the offer an interactive numerical environment similar to sparsity patterns of the constraint Jacobians need to be the ones offered by Matlab and . provided to the solver. The simultaneous optimization The JModelica.org Pyhon package includes sub algorithm has been interfaced with the large-scale NLP packages for running the compilers, for managing solver Ipopt [48], which has been developed particu- file input/output of simulation/optimization results and larly to solved NLP problems arising in simultaneous for accessing the function provided by the JMI inter- dynamic optimization methods. The algorithm is im- face. The compilers are run in a Java Virtual Machine plemented in C as an extension of JMI, and provides (JVM) which is connected to the Python environment an example of how to implement algorithms based on by the package JPype, [35]. One of JPype’s main fea- the JMI functions. In particular, Jacobians computed tures is to enable direct access to Java objects from a by CppAD is used, including sparsity patterns. Python shell or script. This feature is used to com- In addition to the simultaneous optimization algo- municate with the compilers, but can also be used to rithm, JModelica.org contains a multiple shooting al- retrieve the ASTs generated by the compilers. The lat- gorithm, [8]. The algorithm is based on an integra- ter feature enables the user to traverse and query the tor which is used to simulate the system dynamics and ASTs interactively, see 4.2 for a discussion on exam- thereby evaluate the cost function, and an optimiza- ple usages of this feature. tion algorithm which modifies the optimization vari- The integration of the JMI is based on the ctypes ables. Typically, the optimization variables are Mod- package [22]. Using ctypes, a dynamically linked li- elica parameters in the case of a design or parame- brary (DLL) can be loaded into Python, All the con- ter optimization problem, or parameters resulting from tained functions of the DLL are then exposed and can discretization of a control input. The multiple shoot- be called directly from the Python shell. In order to en- ing algorithm is implemented in Python, and relies on able use of Numpy arrays and matrices as arguments the integrator SUNDIALS [34], its Python interface to the JMI functions, the argument types has been ex- PySUNDIALS [47], and the optimization algorithm plicitly encoded using standard features of ctypes. In scipy_slsqp, which is included in Scipy. In order to im- order to provide a more convenient interface to the prove the convergence of the optimization algorithm JMI functions, a Python class, Model has been created. sensitivities are computed and propagated to the op- This class encapsulates loading of a DLL and typing timization algorithm. The sensitivities are computed of the JMI functions, and also provides wrapper func- using SUNDIALS. The implementation serves also as tions supporting Python exceptions. In addition, upon an example of how to develop algorithms based on the creation of a Model class, the generated XML meta JModelica.org Python interface. The multiple shoot- data files are loaded and parameter values and start at- ing algorithm is described in more detail in [43]. tributes are set in the loaded model instance. Model The above algorithms are both based on the avail- objects can then be manipulated, e.g., by setting new ability of derivatives. For some optimization prob- parameter values, or passed as an argument to a simu- lems, it is not possible to reliably compute derivatives, lation or optimization algorithm. and accordingly, numerical optimization algorithms

© The Modelica Association, 2009 34 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

requiring derivative information may fail. This situ- in the JModelica.org org compilers consists of stan- ation may occur for certain classes of hybrid systems. dard Java objects instantiated from the AST classes In such cases, heuristic methods which do not require produced by the JastAdd compilers. Also, means to derivative methods may be better suited. Examples of traverse the AST are provided automatically, in addi- such methods are genetic algorithms, pattern match- tion to the methods corresponding to attributes defined ing, simulated annealing, and simplex (Nelder-Mead). in the compiler. Some methods of this class are freely available for The source AST results from parsing of a Model- Python, see the OpenOpt project [13] for more infor- ica source file. Its structure corresponds precisely to mation, and may be integrated with the JMI Python the actual structure of the code, but the details of the interface. concrete syntax has been removed. Given the source AST, a number of queries can be performed. For ex- ample, the AST may be traversed and for each class 4 Applications declaration, the documentation annotation and the sig- 4.1 Dynamic optimization natures of the public parameters may be extracted and pretty printed according to a HTML template. Another Prototype versions of the JModelica.org software has example would be to traverse the AST and output the been used successfully in applications in different do- default values of all parameters in XML format. mains. In [26], an application is reported where op- Based on a particular class declaration in the source timal start-up trajectories are computed for a plate re- AST, an instance AST may be constructed. The in- actor. The problem is challenging not only due to the stance AST differs from the source AST in that in the complexity of the model (approx. 130 differential and instance AST the components structurally contained algebraic equations), but also due to non-linear and in a component declaration is explicitly represented. in some conditions unstable dynamics. A main chal- Also, in the instance tree, modifications, e.g., class lenge in this project was to obtain trajectories robust and component redeclarations take effect. In fact, the to parameter variations. The procedure of finding ac- key to constructing the instance tree is to handle mod- ceptable solutions was highly iterative in that the cost ification environments consisting of an ordered set of function and the constraints required several redesigns. modifications applicable to a particular class or com- The high-level specification framework in combina- ponent instance. Construction of the instance AST is tion with automatic code generation offered by Optim- described in [3]. Access to the instance AST enables ica and the JModelica.org platform proved very useful several analyses to be performed. For example, the in- in this respect. stance AST may be traversed, and for each primitive The prototype software has as also been used in a variable encountered the corresponding modification number of other projects involving vehicle systems. environment may be retrieved and output to file. For example, in [10] optimal tracks for racing cars The flat AST, corresponding to a flattened Modelica were optimized, and in [45], optimal rail profiles were model, is constructed by traversing the instance AST computed for a novel mass transportation system, the and collecting all primitive variables, equations, algo- NoWait train concept. Other examples where Optim- rithms and functions. The flat AST offers a predefined ica has been used are reported in [25] where minimum API for retrieving variables of the primitive types. For time optimization for an industrial robot is considered example, Java methods are provided for retrieving all and in [24] where an optimal control application of a parameters of Real type, for retrieving all differenti- pendulum system is reported. ated variables, for querying if a variable occurs lin- early in the model equations etc. The flat AST is typi- 4.2 UsingASTs cally used as a basis for code generation. As described above, the JModelica.org compilers pro- vide direct access to abstract syntax trees (ASTs). The 5 An Example ASTs are abstract representations of Modelica mod- els, and provides a means to access the contents of a We consider the Continuously Stirred Tank Reactor Model in a structured and programmatic way. Three (CSTR) process depicted in Figure 3. The tempera- different types of ASTs are used during the procedure ture and the reactant concentration of the inlet flow are of producing a flat Modelica representation: the source constant and the control input of the process, u corre- AST, the instance AST, and the flat AST. The ASTs sponds to the coolant flow. The coolant temperature,

© The Modelica Association, 2009 35 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

in Tf , c = 1 T, c

Tc, u Tc, u

Figure 3: A schematic figure of the CSTR process.

Figure 5: Simulation result of the MPC.

The optimal control problem formulated above can also be used in conjunction with other algorithms available in Scipy. To demonstrate this, a simple model predictive controller (MPC) has been imple- mented. The MPC control strategy is based on the receding horizon principle, where an open loop opti- mal control problem is solved in each sample. Simu- lation of an MPC requires joint simulation of the plant Figure 4: Optimization result for the CSTR example. and solution of the optimal control problem. Such op- erations are easily encoded in Python. The result of executing the MPC is shown in Figure 5. Tc, is constant. A dynamic model for an exothermic reaction is then given by c˙ = β(1 − c) − ke−N/T c (4) 6 Summary and future work −N/T T˙ = β(Tf − T)+ ke c − α(T − Tc)u In this paper, the JModelica.org open source platform where c is the normalized concentration in the reactor, has been presented. The platform features compilers T is the normalized reactor temperature, and β, k, N, written in JastAdd/Java, Optimica support, a C model and α are physical parameters for the process. API, and XML export. The compilers and the C API Based on the CSTR model, the following dynamic for evaluation of the model equations have been inter- optimization problem can be formulated: faced with Python, in order to provide an environment t f 2 2 2 for scripting and development of custom applications. min q1(cr − c) + q2(Tr − T) + r(ur − u) dt (5) u(t) Z0 In addition, the abstract syntax trees representing the subject to the dynamics (4). The cost function penal- Modelica source code, the instance hierarchy and the izes deviations from a desired operating point given by flattened model are accessible. target values cr, Tr and ur for c, T and u respectively. Future plans include improvement of the Modelica Starting at fixed initial conditions, the optimal solu- compliance of the compiler front-end, integration of tion transfers the system from one operating point to additional numerical optimization algorithms, simu- another. lation support, and support for heuristic optimization In this case, the numerical solver IPOPT [48] is used methods such as simulated annealing and genetic algo- to solve the transcribed NLP resulting from direct col- rithms. Also, an Eclipse plug-in is under development location. The result of the optimization is shown in where current research on custom IDE development Figure 4. based on JastAdd is explored.

© The Modelica Association, 2009 36 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

References [11] Dassault Systèmes. iSIGHT Home Page, 2009. http://www.simulia.com/products/ [1] Johan Åkesson. Tools and Languages for Op- isight.html. timization of Large-Scale Systems. PhD thesis, Department of Automatic Control, Lund Univer- [12] DLR, Dynasim, ITI and QTronic. The functional sity, Sweden, November 2007. model interface. Draft.

[2] Johan Åkesson. Optimica—an extension of mod- [13] Dmitrey L. Kroshko. OpenOpt Home Page, elica supporting dynamic optimization. In In 6th 2009. http://openopt.org/Welcome. International Modelica Conference 2008. Mod- [14] Dynasim AB. Dynasim AB Home Page, 2008. elica Association, March 2008. http://www.dynasim.se.

[3] Johan Åkesson, Torbjörn Ekman, and Görel [15] T. Ekman and G. Hedin. Rewritable Reference Hedin. Implementation of a modelica com- Attributed Grammars. In Proceedings of ECOOP piler using jastadd attribute grammars. Sci- 2004, volume 3086 of LNCS, pages 144–169. ence of Computer Programming, July 2009. Springer-Verlag, 2004. doi:10.1016/j.scico.2009.07.003. [16] Torbjön Ekman and Görel Hedin. The jastadd ex- [4] Mats Andersson. Object-Oriented Modeling and tensible java compiler. In Proceedings of OOP- Simulation of Hybrid Systems. PhD thesis, De- SLA 2007, 2007. partment of Automatic Control, Lund Institute of [17] Torbjörn Ekman, Görel Hedin, and Eva Magnus- Technology, Sweden, December 1994. son. JastAdd, 2008. http://jastadd.cs.lth.se/web/. [5] Karl Johan Åström, Hilding Elmqvist, and [18] H. Elmqvist, H. Olsson, S.E. Mattsson, D. Brück, Sven Erik Mattsson. Evolution of continuous- C. Schweiger, D. Joos, and M. Otter. Optimiza- time modeling and simulation. In Proceedings tion for design and parameter estimation. In of the 12th European Simulation Multiconfer- In 7th International Modelica Conference 2009. ence, ESM’98, pages 9–18, Manchester, UK, Modelica Association, 2005. June 1998. Society for Computer Simulation In- ternational. [19] Inc. Enthought. IPython FrontPage, 2009. http: //ipython.scipy.org/moin/. [6] B. M. Bell. CppAD Home Page, 2008. http: //www.coin•or.org/CppAD/. [20] Inc. Enthought. SciPy, 2009. http://www. scipy.org/. [7] L.T. Biegler, A.M. Cervantes, and A Wächter. Advances in simultaneous strategies for dynamic [21] ESTECO. modeFRONTIER Home Page, 2009. optimization. Chemical Engineering Science, http://www.esteco.com/. 57:575–593, 2002. [22] Python Software Foundation. ctypes: A for- [8] H.G. Bock and K. J. Plitt. A multiple shooting eign function library for Python, 2009. http: algorithm for direct solution of optimal control //docs.python.org/library/ctypes.html. problems. In Ninth IFAC world congress, Bu- [23] Python Software Foundation. Python Program- dapest, 1984. ming Language – Official Website, 2009. http: //www.python.org/. [9] F. Casella, D. Filippo, and J. Åkesson. n XML Representation of DAE Systems Obtained from [24] P. Giselsson, J. Åkesson, and A. Robertsson. Op- Modelica Models. In In 7th International Mod- timization of a pendulum system using optimica elica Conference 2009. Modelica Association, and modelica. In In 7th International Modelica 2009. Conference 2009. Modelica Association, 2009.

[10] Henrik Danielsson. Vehicle path optimisation. [25] M. Hast, J. Åkesson, and A. Robertsson. Optimal Master’s Thesis ISRN LUTFD2/TFRT--5797-- Robot Control using Modelica and Optimica. In SE, Department of Automatic Control, Lund In 7th International Modelica Conference 2009. University, Sweden, June 2007. Modelica Association, 2009.

© The Modelica Association, 2009 37 Proceedings 7th Modelica Conference, Como, Italy, Sep. 20-22, 2009

[26] Staffan Haugwitz, Johan Åkesson, and Per Ha- [38] T. Oliphant. Numpy Home Page, 2009. http: gander. Dynamic start-up optimization of a plate //numpy.scipy.org/. reactor with uncertainties. Journal of Process Control, 2009. doi:10.1016/j.jprocont. [39] OPTEC K.U. Leuven. ACADO Home Page, http://www.acadotoolkit.org/ 2008.07.005. 2009. .

[27] Görel Hedin, Johan Åkesson, and Torbjön Ek- [40] OptiY. OptiY Home Page, 2009. http://www. man. Building DSLs by leveraging base optiy.de/. compilers—from Modelica to Optimica. IEEE [41] Phoenix Integration. ModelCenter Home Software , 2009. Submitted for publication. Page, 2009. http://www.phoenix•int.com/ [28] Görel Hedin and Eva Magnusson. JastAdd: software/phx_modelcenter.php. an aspect-oriented compiler construction system. [42] Process Systems Enterprise. gPROMS Home Science of Computer Programming, 47(1):37– Page, 2009. http://www.psenterprise.com/ 58, 2003. gproms/index.html. [29] J. Hunter, D. Dale, and M. Droettboom. mat- [43] J. Rantil, J. Åkesson, C. Führer, and M. Gäfvert. plotlib: python plotting, 2009. http:// Multiple-Shooting Optimization using the JMod- matplotlib.sourceforge.net/. elica.org Platform. In In 7th International Mod- [30] IEEE. Standard VHDL Analog and Mixed- elica Conference 2009. Modelica Association, Singnal Extensions. Technical report, IEEE, 2009. 1997. [44] The Modelica Association. The Modelica As- [31] Gregor Kiczales, Erik Hilsdale, Jim Hugunin, sociation Home Page, 2007. http://www. Mik Kersten, Jeffrey Palm, and William G. modelica.org. Griswold. An overview of AspectJ. LNCS, [45] Jan Tuszynskia, Mathias Persson, Johan 2072:327–355, 2001. Åkesson, Johan Andreasson, and Magnus [32] Donald E. Knuth. Semantics of context- Gäfvert. Model-based approach for design and free languages. Mathematical Systems Theory, validation of a novel concept of public mass 2(2):127–145, June 1968. Correction: Mathe- transport. In 21st International Symposium on matical Systems Theory 5, 1, pp. 95-96 (March Dynamics of Vehicles on Roads and Tracks, 1971). 2009. Accepted for publication.

[33] Y.D. Lang and L.T. Biegler. A software en- [46] University of Heidelberg. MUSCOD-II vironment for simultaneous dynamic optimiza- Home Page, 2009. http://www.iwr. tion. Computers and Chemical Engineering, uni•heidelberg.de/~agbock/RESEARCH/ 31(8):931–942, 2007. muscod.php.

[34] Center for Applied Scientific Computing [47] Triple-J Group for Molecular Cell Physiol- Lawrence Livermore National Laboratory. ogy University of Stellenbosch. PySUNDI- SUNDIALS (SUite of Nonlinear and DIf- ALS: Python SUite of Nonlinear and DIfferen- ferential/ALgebraic equation Solvers), 2009. tial/ALgebraic equation Solvers, 2009. http: https://computation.llnl.gov/casc/ //pysundials.sourceforge.net/. sundials/main.html. [48] Andreas Wächter and Lorenz T. Biegler. On [35] S. Menard. JPype Home Page, 2009. http:// the implementation of an interior-point filter jpype.sourceforge.net/. line-search algorithm for large-scale nonlinear programming. Mathematical Programming, [36] Modelon AB. JModelica Home Page, 2009. 106(1):25–58, 2006. http://www.jmodelica.org.

[37] Numerica Technology. Jacobian Home Page, 2009. http://www.numericatech.com/ jacobian.htm.

© The Modelica Association, 2009 38