optimica—an extension of modelica supporting dynamic

11
Optimica—An Extension of Modelica Supporting Dynamic Optimization Åkesson, Johan 2008 Link to publication Citation for published version (APA): Åkesson, J. (2008). Optimica—An Extension of Modelica Supporting Dynamic Optimization. Paper presented at 6th International Modelica Conference, 2008, Bielefeld, Germany. Total number of authors: 1 General rights Unless other specific re-use rights are stated the following general rights apply: Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights. • Users may download and print one copy of any publication from the public portal for the purpose of private study or research. • You may not further distribute the material or use it for any profit-making activity or commercial gain • You may freely distribute the URL identifying the publication in the public portal Read more about Creative commons licenses: https://creativecommons.org/licenses/ Take down policy If you believe that this document breaches copyright please contact us providing details, and we will remove access to the work immediately and investigate your claim.

Upload: others

Post on 23-Mar-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

LUND UNIVERSITY

PO Box 117221 00 Lund+46 46-222 00 00

Optimica—An Extension of Modelica Supporting Dynamic Optimization

Åkesson, Johan

2008

Link to publication

Citation for published version (APA):Åkesson, J. (2008). Optimica—An Extension of Modelica Supporting Dynamic Optimization. Paper presented at6th International Modelica Conference, 2008, Bielefeld, Germany.

Total number of authors:1

General rightsUnless other specific re-use rights are stated the following general rights apply:Copyright and moral rights for the publications made accessible in the public portal are retained by the authorsand/or other copyright owners and it is a condition of accessing publications that users recognise and abide by thelegal requirements associated with these rights. • Users may download and print one copy of any publication from the public portal for the purpose of private studyor research. • You may not further distribute the material or use it for any profit-making activity or commercial gain • You may freely distribute the URL identifying the publication in the public portal

Read more about Creative commons licenses: https://creativecommons.org/licenses/Take down policyIf you believe that this document breaches copyright please contact us providing details, and we will removeaccess to the work immediately and investigate your claim.

Optimica—An Extension of Modelica

Supporting Dynamic Optimization

Johan ÅkessonDepartment of Automatic Control

Faculty of EngineeringLund University

BOX 118, SE-221 00 Lund

Abstract

In this paper, an extension of Modelica, entitled Opti-mica, is presented. Optimica extends Modelica withlanguage constructs that enable formulation of dy-namic optimization problems based on Modelica mod-els. There are several important design problemsthat can be addressed by means of dynamic optimiza-tion, in a wide range of domains. Examples include,minimum-time problems, parameter estimation prob-lems, and on-line optimization control strategies. TheOptimica extension is supported by a prototype com-piler, the Optimica compiler, which has been used suc-cessfully in case studies.Keywords: Optimica, Language extension, Dynamic

optimization, The JModelica compiler

1 Introduction

Modelica is becoming a standard format for describ-ing and communicating high-fidelity models of large-scale dynamic systems. Expert knowledge is being en-coded into Modelica libraries, both in industry and inacademia. The growing body of Modelica models alsorepresents significant capital investments, and accord-ingly, Modelica models and libraries represent valu-able assets for many companies. As a consequence,Modelica models are turning into legacy code, whichcannot easily be replaced, simply because the cost ofre-encoding the models in a different format is toolarge.While the primary usage of Modelica models today issimulation, several other usages are emerging. Sinceit is not feasible, for the reasons mentioned above,to re-encode models for each new model usage, fu-ture Modelica tools, and also the Modelica languageitself, should accommodate and promote new usages

of Modelica models. This requirement has profoundconsequences for software design of Modelica tools,and also for the language design itself. In particular,some new usages may require new constructs, at thelanguage level, in order to enable modeling of particu-lar design problems.

One example of an emerging usage of Modelica mod-els is dynamic optimization. A characteristic featureof realistic dynamic optimization problems is that theprocedure of formulating such problems is highly iter-ative. It is common that extensive tuning of the costfunction and constraints is required in order to ob-tain an acceptable solution. If a numerical algorithmis used to solve the dynamic optimization problem,there is an additional dimension that requires attention:the design of the transcription scheme. The schemeused to discretize the control and state variables oftenstrongly influences the properties of the resulting solu-tion. The choice of discretization method also affectsthe execution time for solving the problem, which is animportant aspect in on-line applications. For these rea-sons, dynamic optimization problems are very rich inthe sense that there are several aspects that require at-tention. Also, the user needs, and should be enabled to,model, using high-level language constructs, the opti-mization problem both in terms of cost functions andconstraints and at the transcription level.

Sophisticated numerical optimization algorithms oftenhave cumbersome APIs, which do not always matchthe engineering need for high-level description for-mats. For example, it is not uncommon for such nu-merical packages to be written in C, or in Fortran, andthat they require the dynamic system to be modeledas an ODE/DAE, which is also encoded in C or For-tran. In addition, it may be required to also encodefirst and second order derivatives. Although there areefficient tools for automatic differentiation, encoding

of dynamic optimization problems in low-level lan-guages1 like C or FORTRAN is often cumbersome anderror-prone. An important goal of developing high-level languages for dynamic optimization is thereforeto bridge the gap between the engineering need forhigh-level descriptions and the APIs of numerical al-gorithms.

There are several software packages supporting dy-namic optimization, for example Dymola [6] andgPROMS [12]. However, most available softwaretools are restricted in the sense that they usually onlysupport a particular optimization algorithm. While aparticular algorithm may work well in some cases, theappropriate choice of numerical algorithm is usuallydependent on the particular problem at hand. An anal-ogy with differential equation solvers can be made.Stiff systems call for sophisticated, but potentiallycomputationally demanding solvers, whereas less dif-ficult systems may be more efficiently solved by a sim-pler algorithm. An additional goal in the developmentof tools supporting high-level formulation of dynamicoptimization problems is therefore to provide an openarchitecture, where several different algorithms can beintegrated.

In this paper, an extension of Modelica, entitled Opti-mica, will be presented. Optimica consists of a num-ber of new language elements, which enable high-levelformulation of dynamic optimization problems basedon Modelica models. The syntax as well as the se-mantics of Optimica will be described. In addition,a prototype implementation of an Optimica compiler,which is a modular extension of the JModelica com-piler [2, 1], will be presented.

The paper is organized as follows. In Section 2, issuesrelated to extensions of languages are discussed. Dif-ferent options regarding language extensions in Mod-elica are also treated. In Section 3, the scope of Opti-mica is discussed, i.e., the class of optimization prob-lems that can be expressed using Optimica is defined.In Section 4 the syntax and the semantics of the Optim-ica extension are presented. Implementation issues re-lated to the modular Optimica extension of the JMod-elica compiler are discussed in Section 5. The paperends with a summary and conclusions in Section 6.

1The term low-level is relative, but is here used in relation todomain-specific languages like Modelica.

2 Motivation of the Optimica Exten-

sion

2.1 Isn’t Modelica Enough?

Although being a very rich language in terms of ex-pressive power for describing complex hybrid dynam-ical systems, Modelica lacks important features de-sirable for expressing optimization problems. Thisis quite natural, since Modelica was not developedwith optimization in mind. For example, the notionof cost functions, constraints, variable bounds and ini-tial guesses are not included in the Modelica language.Some of these quantities may indeed be modeled us-ing standard Modelica, to some extent. For example, aparticular variable may be given the meaning of cost,and the min and max attributes may be interpreted asvariable bounds. However, while this approach maywork in simple cases, it becomes intractable for morecomplex optimization problems. For example, com-plicated constraints, several use cases, and tailoringof the transcription method would be difficult to ex-press. Further, the min and max attributes are usuallyused to express regions of validity for a model, andgiving them a new semantic meaning would be poten-tially misleading.

2.2 What About Annotations?

Modelica offers a mechanism for adding informationto model, which may not be part of the actual math-ematical description, but which is convenient to storein the model. Typical examples include graphical an-notations and documentation. Annotations can also beused to supply information that can be used by a par-ticular tool, for example, in order to influence proper-ties of the translation process. In principle, it wouldbe possible to specify parts of an optimization prob-lem by introducing suitable annotations. For example,a variable could be marked as a cost function, and thesemantic meaning of the equality operator in an equa-tion could be changed to that of the inequality opera-tor. There are two reasons why it is not a good ideato strictly use this approach. Firstly, and most impor-tantly, annotations are designed to supply complemen-tary information, whereas in this case, the elements ofan optimization problem are rather primary informa-tion, that is essential for solving the actual problem.Also, since annotations are not intended for formula-tion of design problems, they do not provide a con-venient modeling environment for the user. Secondly,annotations cannot currently be changed by means of

modifications. Since modification is one of the corner-stones of Modelica, this is a severe restriction. Also,it is not currently well defined how annotations aretreated in the case of inheritance. Since one of themain objectives of the Optimica extension is to enableconvenient formulation of dynamic optimization prob-lems using high-level constructs, using only annota-tions does not seem to be a feasible alternative.

Whereas the above arguments are applicable to coreelements of an optimization problem, such as costfunction and constraints, annotations may well be usedto specify a solution algorithm, and associated param-eters. This type of information is not part of the actualoptimization formulation, but it might still be essentialin order to efficiently solve the problem numerically.By introducing annotations for specifying, for exam-ple, the collocation scheme used in a direct method,the user is able to model both the actual optimizationproblem at hand and the transcription method in a uni-fied high-level description language. This approach isalso in line with the intentions of Modelica annota-tions, because of the separation between formulationof the actual problem (by means of dedicated languageconstructs), and specification of the solution technique(by means of annotations).

2.3 Tool-oriented Support for Optimization?

Another potential strategy for enabling dynamic op-timization of Modelica models is to develop tool-oriented solutions, for example Graphical User Inter-faces (GUIs), within a simulation-based software tool.This approach is used, for example, to enable opti-mization of Modelica models in Dymola. The userwould then set up the optimization problem by enter-ing information in dedicated fields in the GUI. Usingthis approach, the software tool needs to maintain aninternal model of the optimization problem, as spec-ified by the user. While this solution may be an at-tractive choice for interfacing a particular optimizationmethod with existing simulation-based tools, it doesnot offer the flexibility, or portability, which is inher-ent in the Modelica language. It is therefore desirableto define, at the language level, a generic extension,which has a well defined syntax and semantics. Nev-ertheless, it may still be desirable to offer GUIs, inorder to increase productivity in the design process, inthe same way as current Modelica tools typically offerGUIs to simplify critical modeling tasks.

2.4 To Extend or to Complement?

A key issue is whether to extend Modelica by introduc-ing new language constructs, or to define a new, sep-arate, language which complements Modelica. By in-troducing a new language, the syntax and semantics ofModelica would be kept entirely intact, which may beadvantageous since it makes design and maintenanceof the language simpler. Also, if several extensions areintroduced, defining the interaction between the ex-tensions, both at a syntactic and semantic level, maybe difficult. On the other hand, Modelica has manygeneric built-in constructs, e.g., classes, functions anddeclarative equations, which are widely applicable inmany contexts. Reinventing such constructs in newlanguages does not seem to be an attractive alterna-tive. Another argument in favor of language extensionis that Modelica offers strong support for modulariza-tion of models. In the case of dynamic optimization,the user may construct the model separately from theformulation of the optimization problem, in which themodel is used. In this way, the same model may stillbe used for other purposes than optimization, such as,for example, simulation.It is essential, however, that language extensions tar-geted at particular usages of Modelica models donot interfere unnecessarily with the original language.Preferably, extensions should be modular, in the sensethat the new constructs are only allowed in a well de-fined language environment.

3 Scope of Optimica

3.1 Information Structure

In order to formulate a dynamic optimization prob-lem, to be solved by a numerical algorithm, the usermust supply different kinds of information. It is natu-ral to categorize this information into three levels, cor-responding to increasing levels of detail.

• Level I. At the mathematical level, a canonicalformulation of a dynamic optimization problemis given. This include variables and parameters tooptimize, cost function to minimize, constraints,and the Modelica model constituting the dynamicconstraint. The optimization problem formulatedat this level is in general infinite dimensional, andis thereby only partial in the respect that it cannotbe directly used by a numerical algorithm withoutadditional information, for example, concerningtranscription of continuous variables.

• Level II. At the transcription level, a method fortranslating the problem from an infinite dimen-sional problem to a finite dimensional problemneeds to be provided. This might include dis-cretization meshes as well as initial guesses foroptimization parameters and variables. It shouldbe noticed that the information required at thislevel is dependent on the numerical algorithm thatis used to solve the problem.

• Level III. At the algorithm level, informationsuch as tolerances and algorithm control parame-ters may be given. Such parameters are often crit-ical in order to achieve acceptable performance interms of convergence, numerical reliability, andspeed.

An important issue to address is whether informationassociated with all levels should be given in the lan-guage extension. In Modelica, only information cor-responding to Level I is expressed in the actual modeldescription. Existing Modelica tools then typically useautomatic algorithms for critical tasks such as state se-lection and calculation of consistent initial conditions,although the algorithms can be influenced by the uservia the Modelica code, by means of annotations, orattributes, such as StateSelect. Yet other informa-tion, such as choice of solver, tolerances and simula-tion horizon is provided directly to the tool, either bymeans of a graphical user interface, a script language,or alternatively, in annotations.For dynamic optimization, the situation is similar, butthe need for user input at the algorithm level is moreemphasized. Automatic algorithms, for example formesh selection, exist, but may not be suitable for allkinds of problems. It is therefore desirable to include,in the language, means for the user to specify mostaspects of the problem in order to maintain flexibil-ity, while allowing for automatic algorithms to be usedwhen possible and suitable.Relating to the three levels described above, the ap-proach taken in the design of Optimica is to extendthe Modelica language with a few new language con-structs corresponding to the elements of the mathemat-ical description of the optimization problem (level I).The information included in levels II and III, however,may rather be specified by means of annotations.

3.2 Dynamic System Model

The scope of Optimica can be separated into two parts.The first part is concerned with the class of modelsthat can be described in Modelica. Arguably, this

class is large, since very complex, non-linear and hy-brid behavior can be encoded in Modelica. From adynamic optimization perspective, the inherent com-plexity of Modelica models is a major challenge. Typ-ically, different algorithms for dynamic optimizationsupport different model structures. In fact, the key todeveloping efficient algorithms lies in exploiting thestructure of the model being optimized. Consequently,there are different algorithms for different model struc-tures, such as linear systems, non-linear ODEs, gen-eral DAEs, and hybrid systems. In general, an algo-rithm can be expected to have better performance, interms of convergence properties and shorter executiontimes, if the model structure can be exploited. For ex-ample, if the model is linear, and the cost function isquadratic, the problem can be obtained very efficientlyby solving a Riccati equation. On the other hand, op-timization of general non-linear and hybrid DAEs isstill an area of active research, see for example [3].As a result, the structure of the model highly affectsthe applicability of different algorithms. The Optim-ica compiler presented in this paper relies on a directcollocation algorithm in order to demonstrate the pro-posed concept. Accordingly, the restrictions imposedon model structure by this algorithm apply when for-mulating the Modelica model, upon which the opti-mization problem is based. For example, this excludesthe use of hybrid constructs, since the right hand sideof the dynamics is assumed to be twice continuouslydifferentiable. Obviously, this restriction excludes op-timization of many realistic Modelica models. On theother hand, in some cases, reformulation of disconti-nuities to smooth approximations may be possible inorder to enable efficient optimization. This is particu-larly important in on-line applications. The Optimicaextension, as presented in this paper, could also be ex-tended to support other algorithms, which are indeedapplicable to a larger class of models.

3.3 The Dynamic Optimization Problem

The second part of the scope of Optimica is concernedwith the remaining elements of the optimization prob-lem. This includes cost functions, constraints and vari-able bounds. Consider the following formulation of adynamic optimization problem:

minu(t),p

ψ(z, p) (1)

subject to the dynamic system

F(x(t),x(t),y(t),u(t), p, t) = 0, t ∈ [t0, t f ] (2)

and the constraints

cineq(x(t),y(t),u(t), p) ≤ 0 t ∈ [t0, t f ] (3)

ceq(x(t),y(t),u(t), p) = 0 t ∈ [t0, t f ] (4)

cpineq(z, p) ≤ 0 (5)

cpeq(z, p) = 0 (6)

where x(t) ∈ Rnx are the dynamic variables, y(t) ∈ Rny

are the algebraic variables, u(t) ∈ Rnu are the con-trol inputs, and p ∈ Rnp are parameters which arefree in the optimization. In addition, the optimiza-tion is performed on the interval t ∈ [t0, t f ], where t0and t f can be fixed or free, respectively. In addi-tion, the initial values of the dynamic and algebraicvariables may be fixed or free in the optimization.The vector z is composed from discrete time pointsof the states, controls and algebraic variables; z =[x(t1), ..,x(tNp ),y(t1), ..,y(tNp ),u(t1), ..,u(tNp )]

T , ti ∈[t0, t f ], where Np denotes the number of time pointsincluded in the optimization problem.

The constraints include inequality and equality pathconstraints, (3)-(4). In addition, inequality and equal-ity point constraints, (5)-(6), are supported. Point con-straints are typically used to express initial or terminalconstraints, but can also be used to specify constraintsfor time points in the interior of the interval.

The cost function (1) is a generalization of a terminalcost function, φ(t f ), in that it admits inclusion of vari-able values at other time instants. This form includessome of the most commonly used cost function formu-lations. A Lagrange cost function can be obtained byintroducing an additional state variable, xL(t), with theassociated differential equation xL(t) = L(x(t),u(t)),and the cost function ψ(t f ) = xL(t f ). The need to in-clude variable values at discrete points in the interiorof the optimization interval in the cost function arisesfor example in parameter estimation problems. In suchcases, a sequence of measurements, yd(ti), obtained atthe sampling instants ti, i ∈ 1 . . .Nd is typically avail-able. A cost function candidate is then:

Nd

∑i=1

(y(ti)− yd(ti))TW (y(ti)− yd(ti)) (7)

where y(ti) is the model response at time ti andW is aweighting matrix.

Another important class of problems is static optimiza-

tion problems on the form:

minu,p

ϕ(x,y,u, p)

subject to

F(0,x,y,u, p, ts) = 0

cineq(x,u, p) ≤ 0

ceq(x,u, p) = 0

(8)

In this case, a static optimization problem is derivedfrom a, potentially, dynamic Modelica model by set-ting all derivatives to zero. Since the problem is static,all variables are algebraic and accordingly, no tran-scription procedure is necessary. The variable ts de-notes the time instant at which the static optimizationproblem is defined.

3.4 Transcription

In this paper a direct collocation method (see for ex-ample [4]) will be used to illustrate how also the tran-scription step can be encoded in the Optimica exten-sion. The information that needs to be provided bythe user is then a mesh specification, the collocationpoints, and the coefficients of the interpolation poly-nomials.

4 The Optimica Extension

In this section, the Optimica extension will be pre-sented and informally defined. The presentation willbe made using the following dynamic optimizationproblem, based on a double integrator system, as anexample:

minu(t)

∫ t f01dt (9)

subject to the dynamic constraint

x(t) = v(t), x(0) = 0

v(t) = u(t), v(0) = 0(10)

andx(t f ) = 1, v(t f ) = 0

v(t) ≤ 0.5, −1≤ u(t) ≤ 1(11)

In this problem, the final time, t f , is free, and the ob-jective is thus to minimize the time it takes to transferthe state of the double integrator from the point (0,0)to (1,0), while respecting bounds on the velocity v(t)and the input u(t). A Modelica model for the doubleintegrator system is shown in Listing 1.In summary, the Optimica extension consists of thefollowing elements:

model DoubleIntegrator

Real x(start=0);

Real v(start=0);

input Real u;

equation

der(x)=v;

der(v)=u;

end DoubleIntegrator;

Listing 1: A Modelica model of a double integratorsystem.

• A new specialized class: optimization

• New attributes for the built-in type Real: freeand initialGuess.

• A new function for accessing the value of a vari-able at a specified time instant

• Class attributes for the specialized classoptimization: objective, startTime,finalTime and static

• A new section: constraint

• Inequality constraints

• An annotation for providing transcription infor-mation

4.1 A New Specialized Class

It is convenient to introduce a new specializedclass, called optimization, in which the proposedOptimica-specific constructs are valid. This approachis consistent with the Modelica language, since thereare already several other specialized classes, e.g.,record, function and model. By introducing anew specialized class, it also becomes straightfor-ward to check the validity of a program, since theOptimica-specific constructs are only valid inside anoptimization class. The optimization class cor-responds to an optimization problem, static or dy-namic, as specified in Section 3.3. Apart from theOptimica-specific constructs, an optimization classcan also contain component and variable declarations,local classes, and equations.It is not possible to declare components fromoptimization classes in the current version of Op-timica. Rather, the underlying assumption is that anoptimization class defines an optimization problem,that is solved off-line. An interesting extension would,however, be to allow for optimization classes to be

instantiated. With this extension, it would be possibleto solve optimization problems, on-line, during sim-ulation. A particularly interesting application of thisfeature is model predictive control, which is a controlstrategy that involves on-line solution of optimizationproblems during execution.As a starting-point for the formulation of the optimiza-tion problem (9)-(11), consider the optimization

class:

optimization DIMinTime

DoubleIntegrator di;

end DIMinTime;

This class contains only one component representingthe dynamic system model, but will be extended in thefollowing to incorporate also the other elements of theoptimization problem.

4.2 Attributes for the Built-in Type Real

In order to superimpose information on variable decla-rations, two new attributes are introduced for the built-in type Real2. Firstly, it should be possible to spec-ify that a variable, or parameter, is free in the opti-mization. Modelica parameters are normally consid-ered to be fixed after the initialization step, but in thecase of optimization, some parameters may rather beconsidered to be free. In optimal control formulations,the control inputs should be marked as free, to indi-cate that they are indeed optimization variables. Forthese reasons, a new attribute for the built-in type Real,free, of boolean type is introduced. By default, thisattribute is set to false.Secondly, an attribute, initialGuess, is introducedto enable the user to provide an initial guess for vari-ables and parameters. In the case of free optimiza-tion parameters, the initialGuess attribute providesan initial guess to the optimization algorithm for thecorresponding parameter. In the case of variables, theinitialGuess attribute is used to provide the numer-ical solver with an initial guess for the entire optimiza-tion interval. This is particularly important if a simul-taneous or multiple-shooting algorithm is used, sincethese algorithms introduce optimization variables cor-responding to the values of variables at discrete pointsover the interval. Notice that such initial guesses maybe needed both for control and state variables. Forsuch variables, however, the proposed strategy for pro-viding initial guesses may sometimes be inadequate.

2The same attributes may be introduced for the built-in typeInteger, in order to support also variables of type Integer in theoptimization formulation

In some cases, a better solution is to use simulationdata to initialize the optimization problem. This ap-proach is also supported by the Optimica compiler. Inthe double integrator example, the control variable u isa free optimization variable, and accordingly, the freeattribute is set to true. Also, the initialGuess at-tribute is set to 0.0.

optimization DIMinTime

DoubleIntegrator di(u(free=true,

initialGuess=0.0));

end DIMinTime;

4.3 A Function for Accessing Instant Values

of a Variable

An important component of some dynamic optimiza-tion problems, in particular parameter estimation prob-lems where measurement data is available, is variableaccess at discrete time instants. For example, if a mea-surement data value, yi, has been obtained at time ti, itmay be desirable to penalize the deviation between yiand a corresponding variable in the model, evaluatedat the time instant ti. In Modelica, it is not possible toaccess the value of a variable at a particular time in-stant in a natural way, and a new construct thereforehas to be introduced.All variables in Modelica are functions of time. Thevariability of variables may be different—some arecontinuously changing, whereas others can changevalue only at discrete time instants, and yet others areconstant. Nevertheless, the value of a Modelica vari-able is defined for all time instants within the simula-tion, or optimization, interval. The time argument ofvariables are not written explicitly in Modelica, how-ever. One option for enabling access to variable val-ues at specified time instants is therefore to associatean implicitly defined function with a variable declara-tion. This function can then be invoked by the stan-dard Modelica syntax for function calls, y(t_i). Thename of the function is identical to the name of thevariable, and it has one argument; the time instant atwhich the variable is evaluated. This syntax is alsovery natural since it corresponds precisely to the math-ematical notation of a function. Notice that the pro-posed syntax y(t_i) makes the interpretation of suchan expression context dependent. In order for this con-struct to be valid in standard Modelica, y must refer toa function declaration. With the proposed extension,y may refer either to a function declaration or a vari-able declaration. A compiler therefore needs to clas-sify an expression y(t_i) based on the context, i.e.,

what function and variable declarations are visible. Analternative syntax would have been to introduce a newbuilt-in function, that returns the value of a variable ata specified time instant. While this alternative wouldhave been straightforward to implement, the proposedsyntax has the advantages of being easier to read andthat it more closely resembles the corresponding math-ematical notation. This feature of Optimica is used inthe constraint section of the double integrator example,and is described below.

4.4 Class Attributes

In the optimization formulations (1)-(6) and (8), thereare elements that occur only once, i.e., the cost func-tion and the optimization interval in (1)-(6), and in thestatic case (8), only the cost function. These elementsare intrinsic properties of the respective optimizationformulations, and should be specified, once, by theuser. In this respect the cost function and optimizationinterval differ from, for example, constraints, since theuser may specify zero, one or more of the latter.One option for providing this kind of information isto introduce a built-in class, call it Optimization,and require that all optimization classes inherit fromOptimization. Information about the cost functionand optimization interval may then be given as modi-fications of components in this built-in class:

optimization DIMinTime

extends Optimization(

objective=cost(finalTime),

startTime=0,

finalTime(free=true,initialGuess=1));

Real cost;

DoubleIntegrator di(u(free=true,

initialGuess=0.0));

equation

der(cost) = 1;

end DIMinTime;

Here, objective, startTime and finalTime are as-sumed to be components located in Optimization,whereas cost is a variable which is looked up in thescope of the optimization class itself. Notice alsohow the cost function, cost, has been introduced,and that the finalTime attribute is specified to befree in the optimization. This approach of inheritingfrom a built-in class has been used previously, in thetool Mosilab [11], where the Modelica language is ex-tended to support statecharts. In the statechart exten-sion, a new specialized class, state, is introduced,and properties of a state class (for example whetherthe state is an initial state) can be specified by inherit-

ing from the built-in class State and applying suitablemodifications.The main drawback of the above approach is its lackof clarity. In particular, it is not immediately clearthat Optimization is a built-in class, and that its con-tained elements represent intrinsic properties of theoptimization class, rather than regular elements, asin the case of inheritance from user or library classes.To remedy this deficiency, the notion of class at-tributes is proposed. This idea is not new, but has beendiscussed previously within the Modelica community.A class attribute is an intrinsic element of a specializedclass, and may be modified in a class declaration with-out the need to explicitly extend from a built-in class.In the Optimica extension, four class attributes areintroduced for the specialized class optimization.These are objective, which defines the cost function,startTime, which defines the start of the optimiza-tion interval, finalTime, which defines the end ofthe optimization interval, and static, which indicateswhether the class defines a static or dynamic optimiza-tion problem. The proposed syntax for class attributesis shown in the following optimization class:

optimization DIMinTime (

objective=cost(finalTime),

startTime=0,

finalTime(free=true,initialGuess=1))

Real cost;

DoubleIntegrator di(u(free=true,

initialGuess=0.0));

equation

der(cost) = 1;

end DIMinTime;

The default value of the class attribute static isfalse, and accordingly, it does not have to be set inthis case. In essence, the keyword extends and thereference to the built-in class have been eliminated,and the modification construct is instead given directlyafter the name of the class itself. The class attributesmay be accessed and modified in the same way as ifthey were inherited.

4.5 Constraints

Constraints are similar to equations, and in fact, apath equality constraint is equivalent to a Model-ica equation. But in addition, inequality constraints,as well as point equality and inequality constraintsshould be supported. It is therefore natural to havea separation between equations and constraints. InModelica, initial equations, equations, and algorithmsare specified in separate sections, within a class

body. A reasonable alternative for specifying con-straints is therefore to introduce a new kind of section,constraint. Constraint sections are only allowed in-side an optimization class, and may contain equal-ity, inequality as well as point constraints. In the dou-ble integrator example, there are several constraints.Apart from the constraints specifying bounds on thecontrol input u and the velocity v, there are also termi-nal constraints. The latter are conveniently expressedusing the mechanism for accessing the value of a vari-able at a particular time instant; di.x(finalTime)=1and di.v(finalTime)=0. In addition, bounds mayhave to be specified for the finalTime class attribute.The resulting optimization formulation may now bewritten:

optimization DIMinTime (

objective=cost(finalTime),

startTime=0,

finalTime(free=true,initialGuess=1))

Real cost;

DoubleIntegrator di(u(free=true,

initialGuess=0.0));

equation

der(cost) = 1;

constraint

finalTime>=0.5;

finalTime<=10;

di.x(finalTime)=1;

di.v(finalTime)=0;

di.v<=0.5;

di.u>=­1; di.u<=1;

end DIMinTime;

4.6 Annotations for Specification of the Tran-

scription Scheme

The transcription scheme used to transform theinfinite-dimensional dynamic optimization probleminto a finite-dimensional approximate problem usu-ally influences the properties of the numerical solu-tion. Nevertheless, transcription information can beconsidered to be complimentary information, that isnot part of the mathematical definition of the optimiza-tion problem itself. Also, transcription information isclosely related to particular numerical algorithms. Itis therefore reasonable not to introduce new languageconstructs, but rather new annotations for specifica-tion of transcription schemes. This solution is alsomore flexible, which is important in order easily ac-commodate transcription schemes corresponding to al-gorithms other than the direct collocation method cur-rently supported.Following the guidelines for vendor-specific annota-

Figure 1: The transformation fromModelica/Optimicacode to optimization result.

tions in the specification of Modelica 3.0 [13, p. 147],a hierarchical annotation for supplying the informa-tion needed to specify a direct collocation methodbased on interpolation polynomials has been intro-duced. This annotation is defined by the followingModelica record:

record DirectCollocationInterpolationPolynomials

parameter Real mesh[:];

parameter Real collocationPoints[:];

parameter Real

polynomialCoefficientsAlgebraic[:];

parameter Real

polynomialCoefficientsDynamic[:];

end DirectCollocationInterpolationPolynomials;

This annotation enables the user to influence the par-ticular properties of the corresponding transcriptionscheme. For additional details, see [1].

5 The Optimica Compiler

A new Modelica compiler, entitled the JModelicacompiler is currently under development [2, 1]. Thecompiler is developed in the compiler constructionframework JastAdd, see [9], and in Java. One of theprimary targets of the JModelica compiler is to providean extensible compiler, which is suitable for modularimplementation of new language features. A funda-mental design concept is that of modular extensibility,which enables the core JModelica compiler to be keptintact, since new extensions may be implemented fullymodularized.A prototype implementation of the JModelica com-piler, that also supports the Optimica extension hasbeen developed. The extended compiler will be re-ferred to as the Optimica compiler in the following. Interms of the front-end, the compiler supports a subsetof Modelica, and an early version of Optimica. The

syntax of Optimica that is supported by this compileris different than the one presented in this paper, al-though the functionality is essentially the same. Thenew, improved syntax and semantics that have beenpresented in this paper, were defined based on thecomments and experiences from the users of the veryfirst version of Optimica. A new version of the Optim-ica compiler, supporting the revised Optimica syntaxis currently under development, with the intention ofreplacing the initial prototype.

5.1 Code Generation to AMPL

One of the main features of the Optimica compiler isthat it performs automatic transcription of continuousvariables, using a direct collocation method. The useris thus relieved from the burden of encoding the col-location equations, which is a tedious and error-proneprocedure. Whereas the prototype version of the Op-timica compiler supported one particular collocationscheme, future versions will support the annotation in-troduced above to specify the transcription method.In order to solve the transcribed optimization prob-lem by means of a numerical algorithm, the Optim-ica compiler generates AMPL [7] code. The tran-scribed problem is purely static, and can therefore beencoded using the constructs available in AMPL. TheAMPL representation of the optimization problem canbe viewed as an additional intermediate representa-tion format. The purpose of using AMPL is twofold.Firstly, AMPL provides an additional debugging level,that is very useful during compiler development. Inparticular, the AMPL tool offers a shell, where vari-ables and constraints can be inspected. Secondly, theAMPL solver interface provides solvers with sparsityinformation, as well as first and second order deriva-tives. This information may be essential for perfor-mance and convergence of a numerical optimizationalgorithm. The numerical algorithm IPOPT [14] hasbeen used to solve the non-linear program resultingfrom the transcription procedure. The result is thenwritten to file for further analysis or implementation.See Figure 1 for an illustration of the transformationsteps involved when using the Optimica compiler andAMPL to solve a dynamic optimization problem.

6 Summary and Conclusions

In this paper an extension of the Modelica language,Optimica, that enables high-level formulation of dy-namic optimization problems, has been presented. The

Optimica extension enables the user to specify impor-tant elements of a dynamic optimization problem suchas cost functions, constraints and optimization inter-val. The dynamic model, upon which the dynamic op-timization problem is based, is expressed using stan-dard Modelica. Optimica also supports an annotationthat enables the user to specify the properties of a tran-scription method, based on direct collocation. Becauseof these properties, Optimica supports formulation ofdynamic optimization problems, using high-level con-structs, both at the mathematical level and at the nu-merical transcription level.A prototype implementation of the Optimica compilerhas been used in the work on start-up optimization ofa plate reactor [8], in two master’s thesis projects (see[5] and [10]) and in the PhD course “Optimization-Based Methods and Tools in Control”, that was givenat the Department of Automatic Control, Lund Univer-sity in September 2007.An important objective of the JModelica compiler isto offer a modularly extensible Modelica compiler. Inthis respect, the experiences and results from devel-oping the Optimica extension are very promising. Inparticular, the coding effort needed to implement theextension of the compiler front-end, including exten-sion of the name analysis framework and the flatteningalgorithm, was very moderate.

References

[1] J. Åkesson. Tools and Languages for Opti-mization of Large-Scale Systems. PhD thesisISRN LUTFD2/TFRT--1081--SE, Departmentof Automatic Control, Lund University, Sweden,November 2007.

[2] J. Åkesson, T. Ekman, and G. Hedin. “Devel-opment of a Modelica compiler using JastAdd.”In Seventh Workshop on Language Descriptions,Tools and Applications, Braga, Portugal, March2007.

[3] P. Barton and C. K. Lee. “Modeling, simulation,sensitivity analysis, and optimization of hybridsystems.” ACM Transactions on Modeling andComputer Simulation, 12:4, 2002.

[4] L. Biegler, A. Cervantes, and A. Wächter. “Ad-vances in simultaneous strategies for dynamicoptimization.” Chemical Engineering Science,57, pp. 575–593, 2002.

[5] H. Danielsson. “Vehicle path optimisation.”Master’s Thesis ISRN LUTFD2/TFRT--5797--SE, Department of Automatic Control, LundUniversity, Sweden, June 2007.

[6] Dynasim AB. “Dynasim AB Home Page.” 2007.http://www.dynasim.se.

[7] R. Fourer, D. Gay, and B. Kernighan. AMPL – AModeling Language for Mathematical Program-ming. Brooks/Cole — Thomson Learning, 2003.

[8] S. Haugwitz, J. Åkesson, and P. Hagander. “Dy-namic optimization of a plate reactor start-upsupported by Modelica-based code generationsoftware.” In Proceedings of 8th InternationalSymposium on Dynamics and Control of ProcessSystems, Cancun, Mexico, June 2007.

[9] G. Hedin and E. Magnusson. “JastAdd:an aspect-oriented compiler construction sys-tem.” Science of Computer Programming, 47:1,pp. 37–58, 2003.

[10] H. Hultgren and H. Jonasson. “Automatic cal-ibration of vehicle models.” Master’s ThesisISRN LUTFD2/TFRT--5794--SE, Departmentof Automatic Control, Lund University, Sweden,June 2007.

[11] C. Nytsch-Geusen. “MosiLab Home Page.”2007. http://www.mosilab.de/.

[12] Process Systems Enterprise. “gPROMS HomePage.” 2007. http://www.psenterprise.

com/gproms/index.html.

[13] The Modelica Association. “Modelica – a uni-fied object-oriented language for physical sys-tems modeling, language specification, version3.0.” Technical Report, Modelica Association,2007.

[14] A.Wächter and L. T. Biegler. “On the implemen-tation of an interior-point filter line-search al-gorithm for large-scale nonlinear programming.”Mathematical Programming, 106:1, pp. 25–58,2006.