Linköping Studies in Science and Technology

Dissertation No. 1016

PDEModelica A High-Level Language for Modeling with Partial Differential

by

Levon Saldamli

Department of Computer and Information Science Linköpings universitet SE-581 83 Linköping, Sweden

Linköping 2006

“...toboldlygowhere no man has gone before.” James T. Kirk

Abstract

This thesis describes work on a new high-level mathematical modeling language and framework called PDEModelica for modeling with partial differential equa- tions. It is an extension to the current Modelica modeling language for object- oriented, -based modeling based on differential and algebraic equations. The language extensions and the framework presented in this thesis are consistent with the concepts of Modelica while adding support for partial differential equa- tions and space-distributed variables called fields. The specification of a partial problem consists of three parts: 1) the description of the definition domain, i.e., the geometric region where the equations are defined, 2) the initial and boundary conditions, and 3) the ac- tual equations. The known and unknown distributed variables in the equation are represented by field variables in PDEModelica. Domains are defined by a geo- metric description of their boundaries. Equations may use the Modelica derivative operator extended with support for partial derivatives, or vector differential opera- tors such as divergence and gradient, which can be defined for general curvilinear coordinates based on coordinate system definitions. The PDEModelica system also allows the partial differential equation models to be defined using a coefficient-based approach, where PDE models from a library are instantiated with different parameter values. Such a library contains both con- tinuous and discrete representations of the PDE model. The user can instantiate the continuous parts and define the parameters, and the discrete parts containing the equations are automatically instantiated and used to solve the PDE problem numerically. Compared to most earlier work in the area of mathematical modeling languages supporting PDEs, this work provides a modern object-oriented component-based approach to modeling with PDEs, including general support for hierarchical mod- eling, and for general, complex geometries. It is possible to separate the geometry definition from the model definition, which allows geometries to be defined sep- arately, collected into libraries, and reused in new models. It is also possible to separate the analytical continuous model description from the chosen discretization and numerical solution methods. This allows the model description to be reused, independent of different numerical solution approaches. The PDEModelica field concept allows general declaration of spatially distributed

v variables. Compared to most other approaches, the field concept described in this work affords a clearer abstraction and defines a new type of variable. Arrays of such field variables can be defined in the same way as arrays of regular, scalar variables. The PDEModelica language supports a clear, mathematical syntax that can be used both for equations referring to fields and explicit domain specifica- tions, used for example to specify boundary conditions. Hierarchical modeling and decomposition is integrated with a general connection concept, which allows connections between ODE/DAE and PDE based models. The implementation of a Modelica library needed for PDEModelica and a pro- totype implementation of field variables are also described in the thesis. The PDEModelica library contains internal and external solver implementations, and uses external software for mesh generation, requisite for numerical solution of the PDEs. Finally, some examples modeled with PDEModelica and solved using these implementations are presented.

vi Acknowledgments

First of all, I would like to thank my supervisor Peter Fritzson, for the inspiration and the motivation I needed to finish this thesis, and for commenting both my work and my language. I would also like to thank my co-supervisor Bernhard Bach- mann, for help with parts of the implementation in this work, and for his valuable comments on the contents of this thesis. Thanks also to Hansjürg Wiesmann for help with the implementation and for interesting discussions. Other colleagues at PELAB I would like to thank, who have contributed to the OpenModelica platform, where I could experiment with language extensions, are Peter Aronsson, Kaj Nyström, Adrian Pop, Peter Bunus, Håkan Lundvall, and David Broman. Thanks to the rest of the PELAB members for interesting dis- cussions about both work and other more or less relevant subjects, especially to Jens Gustavsson, Andreas Borg, and John Wilander for our very interesting work together on research methodology and computer science. Special thanks to An- drzej Bednarski for being both a colleague and a friend. Many thanks to Bodil Mattsson-Kihlström for her support in many ways, and to Lillemor Wallgren for her administrative help. Finally, I would like to thank my parents for enhancing my motivation, and my friends, for their company and support that helped me finish this work.

This work has been supported by the Swedish Foundation for Strategic Research in the ECSEL graduate school and the VISIMOD project, the European Commis- sion in the RealSim project, and by Vinnova in the VISP project.

vii viii Contents

1 Introduction 1 1.1PDE-basedModelExample...... 2 1.1.1 ConnectiontoODE/DAEmodels...... 4 1.2ResearchMethod...... 6 1.3Contributions...... 8 1.4OverviewoftheThesis...... 9

2 Background 11 2.1Modelica...... 11 2.1.1 Classes...... 12 2.1.2 VariableDeclarations...... 12 2.1.3 SubtypingandInheritance...... 13 2.1.4 Modifications...... 15 2.1.5 EquationsandAlgorithms...... 16 2.1.6 Replaceable Elements ...... 16 2.2DifferentialEquations...... 18 2.2.1 Fields...... 18 2.2.2 Ordinary Differential Equations and Differential and Alge- braicEquations...... 18 2.2.3 PartialDifferentialEquations...... 19 2.2.4 Boundary Conditions ...... 20 2.2.5 Initial Conditions ...... 21 2.2.6 Classification...... 21 2.3 Numerical Solution Methods ...... 22 2.3.1 Finite Difference Methods ...... 22 2.3.2 Finite Element Methods ...... 23 2.3.3 MethodofLines...... 25

3 A Modelica Library for PDE-based Modeling 27 3.1 Introduction ...... 27 3.1.1 Separation into Continuous and Discrete Parts ...... 28 3.2 Continuous Part Design ...... 28

ix Contents

3.2.1 Standard Boundaries ...... 30 3.3ThePackageDesign...... 31 3.4 Continuous Part ...... 34 3.4.1 Boundary Definition ...... 34 3.4.2 Domain Definition ...... 34 3.4.3 Fields...... 35 3.4.4 Included Boundaries ...... 36 3.4.5 EquationModels...... 42 3.4.6 Boundary Conditions ...... 44 3.5DiscretePartDesign...... 45 3.5.1 DomainDiscretization...... 46 3.5.2 ModelDiscretization...... 49 3.6TheFEMpackage...... 53 3.6.1 DiscreteDomain...... 54 3.6.2 DiscreteField...... 55 3.6.3 ThePoissonEquation...... 56 3.6.4 TheDiffusionEquation...... 56 3.6.5 PDELibraryInterface...... 56 3.7RheolefFiniteElementSolver...... 57 3.7.1 Forms...... 57 3.7.2 Boundary Conditions ...... 58 3.8TheFEMFormspackage...... 59 3.8.1 DiscreteField...... 59 3.8.2 Form...... 60 3.8.3 ThePoissonEquation...... 61 3.8.4 TheDiffusionEquation...... 61 3.8.5 PDELibraryInterface...... 61 3.9Example...... 62 3.10Discussion...... 67

4 Language Elements for Space-distributed Models 69 4.1 Introduction ...... 69 4.2Fields...... 70 4.2.1 FieldVariables...... 70 4.2.2 FieldConstructor...... 71 4.2.3 FieldTypeinExpressions...... 71 4.2.4 AccessingFieldValues...... 73 4.3 Future Language Extensions ...... 74 4.3.1 Domain Geometry Definition ...... 74 4.3.2 DifferentialOperators...... 78 4.3.3 DomainSpecifierinEquations...... 81 4.3.4 FieldReduction...... 82

x Contents

4.3.5 Discussion...... 83

5 Implementation 85 5.1ModelicaCompiler...... 85 5.1.1 ModelicaParser...... 86 5.1.2 ModelicaTranslator...... 88 5.2ThePDELibrary...... 94 5.2.1 TheFiniteElementPackage...... 95 5.3PDEModelicaSolverEnvironment...... 99 5.3.1 SpatialDiscretizationofEquations...... 99

6 Examples 105 6.1StationaryHeatTransfer...... 105 6.1.1 Neumann and Robin Boundary Conditions ...... 107 6.2Time-dependentHeatTransfer...... 108 6.2.1 HeatTransferwithController...... 109 6.3Discussion...... 110

7 Previous Approaches With Examples 113 7.1Mathematica-basedTranslator...... 113 7.1.1 SpaceVariables...... 113 7.1.2 DomainClasses...... 114 7.1.3 SolverGeneratorinMathematica...... 115 7.2Coefficient-BasedTranslator...... 116 7.2.1 Domains...... 116 7.2.2 Equations and Boundary Conditions ...... 117 7.2.3 ImplementationDetails...... 118 7.2.4 NumericalSolver...... 132 7.2.5 Issues with the Coefficient-Based Translator ...... 134

8 Related Work 137 8.1 Libraries and Programming Language-Based Packages ...... 137 8.1.1 Diffpack...... 138 8.1.2 Overture...... 138 8.1.3 Compose...... 138 8.2 High-Level Packages and Problem Solving Environments . . . . . 139 8.2.1 gPROMS...... 139 8.2.2 PELLPACK ...... 140 8.2.3 PDESpec...... 142 8.2.4 FEMLAB...... 142 8.3Discussion...... 143

xi Contents

9 Conclusion 145 9.1Summary...... 145 9.2Contributions...... 147 9.3FutureWork...... 148 9.3.1 ModelicaPDELibrary...... 148 9.3.2 Connectors...... 149 9.3.3 Language Implementation ...... 150

References 153

A UML Notation 159

B Plotting Simulation Results 161 B.1 Visualization of Domain Boundary ...... 161 B.2VisualizationofMeshes...... 161 B.3VisualizationofSteady-stateFields...... 161 B.4VisualizationofTime-dependentFields...... 162

xii Glossary

class A user-defined, reusable component type in Modelica, containing variables, instances of other classes, algorithms and equations. restricted class A specialized Modelica class, with some restrictions on the contents it may have, for example occurence of equations. extends Term used for subclassing of Modelica classes, for defining inheritance hierarchies of classes. modification In Modelica, a mechanism to change values of parameters, types of declared elements etc., while inheriting or instantiating a class. connector A specialized Modelica class to represent interfaces between compo- nents, that can be used with the connect operator to automatically generate equations. domain The definition domain of the independent variables. For time-dependent functions, the domain is the time interval where the variable is defined. For two or three-dimensional space-dependent functions, the domain is the two and three-dimensional geometric regions where the function is defined, re- spectively. boundary The bounding limit of the definition domain. field A function of independent variables, for example a space-dependent, two dimensional function f(x,y). field value Value of a field at a point in the definition domain. partial derivative Derivative of an expression or function with respect to one of the independent variables, e.g., one of the space coordinates. PDE Partial differential equation, i.e., an equation containing partial derivatives of functions. ODE Ordinary differential equation. containing functions of one independent variable and derivatives of functions and expressions with respect to that independent variable.

xiii Contents

DAE Differential and algebraic equations. An algebraic system of equations con- taining ordinary derivatives. boundary condition Conditions to determine a unique solution to a PDE, de- fined on the boundary of the definition domain where the PDE is solved. The PDE is usually valid only in the interior of the domain, while the boundary conditions give the values of the unknown or its derivatives on the boundary of the domain. initial condition In time-dependent equations, the starting values of the unknown variables, needed to determine a unique solution to the time-dependent prob- lem.

Dirichlet A type of boundary condition, specifying the value of the unknown vari- able on the boundary.

Newman A type of boundary condition, specifying the value of the derivative of the unknown variable on the boundary.

Robin A type of boundary condition, consisting of an equation containing both the unknown variable and its derivative. Also called mixed boundary condi- tion. elliptic Usually steady-state PDEs containing no time derivatives, e.g., the Pois- son equation. parabolic Usually time-dependent PDEs containing first-order time derivatives, e.g., the time-dependent heat transfer equation. hyperbolic Usually time-dependent PDEs containing second-order time deriva- tives, e.g., the . stationary (steady-state) The time-independent equation, corresponding to the time-dependent equation with the time elapsed enough long so that the solu- tion becomes time-independent, e.g., the transients have vanished.

finite difference An approximation of the derivative using the derivative defini- tion and the values of the unknown at discrete grid points and the distance between the grid points. central difference A finite difference method using discrete values from both previous and next discrete point. forward difference A finite difference method using discrete values from the next discrete point.

xiv Contents backward difference A finite difference method using discrete values from the previous discrete point. finite difference method A method to solve PDE problems using finite differ- ences to approximate partial derivatives and solve the resulting equation sys- tems. finite element method (FEM) A method to solve PDE problems by subdivid- ing the domain in for example triangles and expressing the unknown in terms of known basis functions and solving the resulting equation systems. method of lines A method to solve time-dependent PDE problems by replacing the time- or space-dependent parts of the equations with discrete formula- tions, resulting in a only time- or only space-dependent problem. In this work, spatial discretization is used, generating DAEs from time-dependent PDEs.

xv Contents

xvi Chapter 1 Introduction

“Its five year mission: To explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.” Captain Kirk, Starship Enterprise

In mathematical modeling of physical systems, the behavior of a system is typi- cally modeled using differential equations or a system of differential and algebraic equations, i.e. algebraic equations containing derivatives. For large scale models, some properties of the physical system that is modeled are often approximated; for example when controlling the temperature of a fluid in a container, the temperature can be assumed to be the same everywhere inside the container. This way, the space dependency is eliminated, resulting in models con- taining only ordinary differential equations (ODEs), or differential and algebraic equations (DAEs), i.e. equations where all derivatives are with respect to time only. This greatly simplifies the solution of the equations and the simulation. However, sometimes a more detailed model with explicit space dependency is needed for the whole or some part of the system. Such space-dependent models are used to study the behavior in more detail, and contain partial derivatives, i.e., derivatives with respect to space variables like x, y and z in a Cartesian coordinate system. Differential equations containing partial derivatives are called partial dif- ferential equations (PDEs), and are used in many fields to model physical behavior, for example structural mechanics, computational fluid dynamics, and electrostat- ics. There are many tools for modeling and simulation with ordinary differential equations as well as with partial differential equations. Most are however spe- cialized for certain application domains or special kinds of models.

1 Chapter 1 Introduction

An effort to define a general, application domain and tool-independent model- ing language is made by Modelica Association, with the Modelica language as a result. Modelica® [1, 2] is a standard language designed for component-based modeling, where previously defined models can be reused as components in new models. Object oriented constructs, equation-based and declarative modeling sup- port, as well as a connection concept make this possible. Currently, Modelica only supports models with ordinary differential equations, algebraic equations, discrete equations, hybrid (mixed time-discrete and time-continuous) equations but not par- tial differential equations. Several Modelica implementations and simulation tools exist [3,4]. Thanks to the progress in computer performance, the use of detailed models con- taining partial differential equations is becoming increasingly common. The aim of this work is to define a language based on Modelica, in order to handle partial differential equations in models in addition to differential and algebraic equations. This language is called PDEModelica, and this thesis discusses the initial language extensions needed for the desired support.

1.1 PDE-based Model Example

Consider a simplified model of heat distribution in a room where only the distri- butioninthex and y directions is studied and the temperature in the z direction is assumed to be constant. A heater is installed on one of the walls and there is a window on another wall. The domain of this problem, i.e., the region (including geometry) on which it is defined, can be seen in Figure 1.1. A heater is represented by assigning constant temperature boundary condition to the middle part of the upper wall. The window is modeled by non-zero heat flow through the left wall. The heat flow is proportional to the temperature difference between the inside tem- perature and the outside temperature. The rest of the walls are insulated, i.e., no heat flow occurs through these walls. The right wall is curved in order to illustrate modeling with complex geometries. Heat transfer by conduction in two dimensions can be modeled using Poisson’s equation:

∂2T (x, y) ∂2T (x, y) −( + )=g(x, y) on Ω ∂x2 ∂y2 The possible boundary conditions are the following:

• Dirichlet1 boundary condition for the heated wall:

T (x, y)=h1(x, y) on ∂Ω

1The value of the unknown variable is known on the boundary. See also Section 2.2.4.

2 1.1 PDE-based Model Example

Heater

top3top2 top1

h Window right left y

bottom x

w

Figure 1.1: Example of time-dependent heat transfer by conduction.

•Neumann2 boundary condition for insulated walls: ∂T(x, y) = h2(x, y) on ∂Ω ∂n

• Robin3 (also called mixed) boundary condition for the window which is not perfectly insulated: ∂T(x, y) + qT(x, y)=h3(x, y) on ∂Ω ∂n If heat distribution over time is studied, a time derivative is added to the Laplace equation which gives the heat diffusion equation: ∂T(x, y, t) ∂2T (x, y, t) ∂2T (x, y, t) ρC − k( + )=g(x, y, t) on Ω ∂t ∂x2 ∂y2 with ρ, C and k being material constants, and a given initial condition:

T (x, y, 0) = T0(x, y) on Ω

This problem can be modeled in PDEModelica with the geometry and the model description shown in Figure 1.2. The domain geometry is defined by describing

2The value of the outward normal derivative of the unknown variable is known on the boundary. The outward normal derivative is the space derivative in the outward normal direction. See also Section 2.2.4. 3A linear combination of the unknown variable and its outward normal derivative is known on the boundary. See also Section 2.2.4.

3 Chapter 1 Introduction its boundary in a specific direction in order to find out on what side of the bound- ary the actual domain is. The boundary is built up of several sections defined as named components in the domain description. Hence, when defining the PDE model, boundary conditions can be assigned to each section using the name of each boundary component. The definition of the boundary conditions and the PDE are not shown in this example; they can be defined as described in Chapter 4. The solution to a similar example can be found in Section 6.2.1.

1.1.1 Connection to ODE/DAE models

A system with active temperature control can be modeled using a time-dependent model as shown in the previous section. A temperature sensor can be approximated by reading the computed temperature at some point in the domain, and the temper- ature can be used as input to a heat controller. The model overview is illustrated in Figure 1.3, and the PDEModelica code is listed in Figure 1.4. The controller is a proportional, integrating controller (PI-controller), which contains an ordinary differential equation:

T = T − T error sensor goal

Theater(t)=kpTerror + ki Terror dt

The resulting problem consists of a PDE part modeling temperature distribution, and an ODE part modeling the controller. This can be compared to a simplified, lumped system where the temperature is assumed to be the same at all points, i.e. where the temperature distribution in the domain is instant. Temperature dis- tribution in such a system is modeled using an ODE-based model, resulting in a complete system with only ODEs. However, if a more realistic temperature model is used, involving PDEs, where spatial variation in temperature is studied as well, coupled ODE and PDE models are needed. Spatial dependency can then be re- moved by spatial discretization as a first step, using the method of lines, resulting in an equation system of ODEs also for the spatially distributed temperature model. Thus, the final discretized system will only contain ODEs which is solved using ex- isting ODE/DAE solvers. This example is simplified by the fact that the sensor is replaced with a simple field access to read the temperature value. The connection between the controller and the PDE model is accomplished manually by writing down the equations. In the future, the connection between PDE and ODE models can be more complex, using connectors and field reduction, see Section 4.3.4 and Section 9.3.2.

4 1.1 PDE-based Model Example

class CurvedRectangular "Geometry" extends Cartesian2D (boundary={bottom , right , top1 , top2 , top3 , left });

parameter Point p0; parameter Real w; parameter Real h; parameter Real cw;

parameter Real ch=h; parameter Point cc=p0 + {w,h/2};

Line2D bottom (p1=p0 , p2=p0 + {w,0}); Line2D top1 (p1=p0 + {w, h} , p2=p0 + {2*w/3 ,h }); Line2D top2 (p1=p0 + {2*w/3 ,h} , p2=p0 + {w/3 ,h }); Line2D top3 (p1=p0 + {w/3 , h} , p2=p0 + {0 ,h }); Line2D l e f t (p1=p0 + {0 ,h} , p2=p0 );

Bezier2D right (n=8, p= f i l l (cc , 8) + {{0.0,−0.5}, {0.0,−0.2}, {0.0 ,0.0} , { −0.85,−0.85}, { −0.85,0.85}, {0.0 ,0.0} , {0.0 ,0.2} , {0.0 ,0.5} } *{{cw,0},{0 ,ch}}); end CurvedRectangular ;

model Diffusion "Heat diffusion with heater" ... import Modelica . SIUnits . Temperature ; parameter Temperature heaterValue ; parameter Real h_3 ; parameter Real q; CurvedRectangular omega; Diffusion2D pde(domain=omega); equation der( pde .u , n) = 0 on omega . bottom ; der( pde .u , n) = 0 on omega . right ; der( pde .u , n) = 0 on omega . top1 ; pde.u = heaterValue on omega. top2 ; der( pde .u , n) = 0 on omega . top3 ; der( pde .u , n) + q* pde . u = h_3 on omega . l e f t ; end Diffusion ;

Figure 1.2: The PDEModelica code to define the heat diffusion problem in Sec- tion 1.1. Predefined PDE model Diffusion2D and detailed parameter declarations have been left out. The syntax is explained in Chapter 4.

5 Chapter 1 Introduction

PI-Controller

Heater

Glass layer Sensor

Figure 1.3: A coupled PDE and ODE model. Time dependent heat transfer model with a controller.

1.2 Research Method

The research method used in this work can be called explorative design [5]. The approach starts with a design hypothesis which is believed to be a possible solution to the problem. A prototype implementation of this design is developed. During implementation, flaws in the design are discovered and new knowledge about the problem is acquired. The implementation is modified to handle these issues. Thus, the system that is implemented differs from that in the original design. On the other hand, the implementation also differs from the one that would have been implemented from start using the new knowledge. For this reason, at some point, the prototype is discarded and a new design and prototype are developed. See Figure 1.5 for an illustration of the work flow when using this method.

Thus, important parts of the research results are the original design, the actual implemented prototype, and a proposed, improved design. In this thesis, we present the previous iterations of the design and implementation in Chapter 7. The final design of PDEModelica in this thesis work is presented in Chapter 4 and the final implementation is described in Chapter 3 and Chapter 5.

6 1.2 Research Method

class CurvedRectangular "Geometry" extends Cartesian2D (boundary={bottom , right , top1 , top2 , top3 , left });

parameter Point p0; parameter Real w; parameter Real h; parameter Real cw;

parameter Real ch=h; parameter Point cc=p0 + {w,h/2};

Line2D bottom (p1=p0 , p2=p0 + {w,0}); Line2D top1 (p1=p0 + {w, h} , p2=p0 + {2*w/3 ,h }); Line2D top2 (p1=p0 + {2*w/3 ,h} , p2=p0 + {w/3 ,h }); Line2D top3 (p1=p0 + {w/3 , h} , p2=p0 + {0 ,h }); Line2D l e f t (p1=p0 + {0 ,h} , p2=p0 );

Bezier2D right (n=8, p= f i l l (cc , 8) + {{0.0,−0.5}, {0.0,−0.2}, {0.0 ,0.0} , { −0.85,−0.85}, { −0.85,0.85}, {0.0 ,0.0} , {0.0 ,0.2} , {0.0 ,0.5} } *{{cw,0},{0 ,ch}}); end CurvedRectangular ;

model ControlledDiffusion "Heat diffusion with controlled heater" ... import Modelica . SIUnits . Temperature ; parameter Temperature goalValue ; parameter Real h_3 ; parameter Real q; // Use PI regulator from Standard Library Modelica . Blocks . Continuous . PI regulator ; CurvedRectangular omega; Diffusion2D pde(domain=omega); Temperature heaterValue ; Temperature sensorValue ; equation der( pde .u , n) = 0 on omega . bottom ; der( pde .u , n) = 0 on omega . right ; der( pde .u , n) = 0 on omega . top1 ; pde.u = heaterValue on omega. top2 ; der( pde .u , n) = 0 on omega . top3 ; der( pde .u , n) + q* pde . u = h_3 on omega . l e f t ; heaterValue = regulator .y[1]; regulator . inPort . signal [1] = goalValue − sensorValue ; sensorValue = pde.u(2.61, 2.33); end ControlledDiffusion ;

Figure 1.4: The PDEModelica code to define the heat diffusion problem with a con- trolled heater in Section 1.1.1. Predefined PDE model Diffusion2D and detailed parameter declarations have been left out. The syntax is explained in Chapter 4.

7 Chapter 1 Introduction

Iterations

Design Modified Improved Hyptohesis Design Design Hyptohesis Hyptohesis

New knowledge

Prototype implementation

Figure 1.5: Explorative design.

1.3 Contributions

The result of this work is two-fold. First, a design and implementation of a Model- ica library for PDEs is presented, which illustrates the concepts needed to specify and simulate PDE-based models. Second, a design and a partial implementation of language extensions for the Modelica language is presented, which integrates the concepts from the PDE library into the Modelica language. The proposed lan- guage design for an object-oriented modeling language, PDEModelica, supports the following: • Object-oriented, component-based modeling with PDEs. • General, complex geometry description with lines, polygons, parametric curves and a combination of these. • Component-based geometry definition, i.e., separation of geometry defini- tion from model definition. • Separation of analytical, continuous model description from discretization and numerical solution. • Field concept for general declaration of spatially distributed variables inte- grated in the language.

8 1.4 Overview of the Thesis

• Clear, mathematical syntax for equations containing fields and explicit do- main specification. • Hierarchical modeling and decomposition. • Modeling of combined ODE/DAE and PDE problems. We believe that the combination of these aspects in a single modeling language is rather new. See also the discussion and comparison to other related systems in Section 8.3. A prototype translator and solver environment is set up as well, with a basic PDE solver interface for adding new solvers and mesh generators. Some of the work discussed in this thesis has been published previously in the following publications:

1. L. Saldamli and P. Fritzson. Object-Oriented Modeling with Partial Differ- ential Equations. In Proceedings of the Modelica Workshop 2000, Lund, Sweden, October 2000 [6]. 2. L. Saldamli and P. Fritzson. A Modelica-Based Language for Object-Orient- ed Modeling with Partial Differential Equations. In Proceedings of the 4th International EUROSIM Congress, Delft, The Netherlands, June 2001 [7]. 3. L. Saldamli and P. Fritzson. Domains and Partial Differential Equations in Modelica. In Proceedings of the 42nd SIMS Conference, Porsgrunn, Norway, October 2001 [8]. 4. L. Saldamli, P. Fritzson and B. Bachmann. Extending Modelica for Partial Differential Equations. In Proceedings of the 2nd International Modelica Conference, Oberpfaffenhofen, Germany, March 2002 [9]. 5. L. Saldamli and P. Fritzson. Field Type and Field Constructor in Model- ica. In Proceedings of SIMS 2004, the 45th Conference on Simulation and Modelling, Copenhagen, Denmark, September 2004 [10]. 6. L. Saldamli, B. Bachmann, H Wiesmann and P. Fritzson. A Framework for Describing and Solving PDE Models in Modelica. In Proceedings of the 4th International Modelica Conference, Hamburg, Germany, March 2005 [11].

Section 4.3 contains material not previously published.

1.4 Overview of the Thesis

This thesis is organized as follows. Chapter 2 contains background information rel- evant for the thesis: a short overview of the Modelica language, a basic introduction

9 Chapter 1 Introduction to partial differential equations and some existing numerical solution methods for partial differential equations. Chapter 3 describes a PDE library consisting of Modelica packages written us- ing standard Modelica. The PDE library can be used to describe and solve PDE models on general domains using the finite element method and the method of lines discretization. Chapter 4 presents proposed extensions to the Modelica language for definition of space-distributed models, e.g. models containing fields and partial derivatives. Chapter 5 contains the implementation details. The PDE library, prototypes for language extensions and the interface to external solvers are described here. Chapter 6 contains examples to demonstrate the use of the PDE library and the language extensions. Chapter 7 discusses the previous design iterations that were implemented and tested. Chapter 8 presents an overview of related work. Different low- and high-level tools with varying modeling language support are summarized here. Finally, some conclusions and possible future work directions are discussed in Chapter 9.

10 Chapter 2 Background

“Logic is the beginning of wisdom; not the end.” Mr. Spock

The basic concepts of Modelica are presented in the first part of this chapter. In the second part, the topic of partial differential equations (PDEs) and classifica- tion of PDEs are briefly presented, and finally an overview of different numerical solution methods is given.

2.1 Modelica

Modelica [2, 12] is a modeling language for equation-based, object-oriented mod- eling and simulation of physical systems. Using object-oriented concepts, it allows hierarchical, component-based modeling which in turn makes reuse of existing models possible. The general modeling concepts in Modelica allow it to be used in different application domains and in multi-domain modeling, for example when defining a combined electrical and mechanical model. There is a free Modelica Standard Library [13] and other free Modelica libraries with packages of existing models from different domains that can be used as components in specific models. Acausal modeling, i.e., modeling using equations - not assignment statements, al- lows single models to be used in different data flow contexts since variables are not explicitly declared as input or output. This causality information is rather derived from the context where the model is used. In his PhD thesis [14], H. Tummescheit discusses design and implementation of modeling libraries using Modelica.

11 Chapter 2 Background

Models in Modelica are built hierarchically from sub-models that are defined separately, which in turn can be defined in the same way. Hence, a model can con- tain one or more instances of other models with a different set of parameter values for each instance, and a set of connections between these components/instances. Additionally, each model can have variables of built-in types, and equations that define the relationship between these variables as well as between variables in sub- models.

2.1.1 Classes The basic structural unit in Modelica is class. A class can contain other classes, variable declarations, equations, and algorithms. An example of a class can be seen in Figure 2.1. Other keywords can be used to denote classes, restricted classes that are special cases of classes with some restrictions. These are record, type, connector, model, block, package and function. Different restricted classes and restrictions that apply to them can be seen in Table 2.1.

model MyModel "Short description of this model" Real x,y; equation x+y=5; x + 2y = 11; end MyModel ;

Figure 2.1: Example of a Modelica class.

2.1.2 Variable Declarations Variable declarations consist of a type and a variable name. The type can be one of the primitive types or another class name. The primitive types are Real, In- teger, String, Boolean and Enumeration. Each declaration can also have type modifiers, such as the variability type prefix constant, discrete,orpa- rameter, or a causality prefix, input or output, used in function and block classes to declare the direction of a variable. Variables with the constant or parameter prefix keep their value constant during a simulation, i.e., they are constants. The difference between parameters and constants is that values of parameters can be changed before each simula- tion without needing to recompile the Modelica code. An exception is structural parameters , which require recompilation of the model because they change the model structure. A parameter used as number of components in an array declara- tion is an example of a structural parameter. Parameters also appear in tool menus

12 2.1 Modelica

Table 2.1: Restricted classes in Modelica. Restricted class Restrictions record No equations are allowed. type May only be used to extend primitive types, enumerations, or records. connector No equations are allowed. model Model instances may not be used in connections. block Fixed causality. Each variable must be declared as input or output. package May only contain classes and constants. Is allowed to import from. function Similar to block. No equations, at most one algorithm section. May be called using positional arguments. May be recursive. to allow the user to change them before simulation. Variables of type Real de- clared without the constant or parameter modifiers are implicitly time-dependent, i.e. functions of time. Time derivatives of variables can be represented using the der() operator. Using the time derivatives, ordinary differential equations can be expressed, and full systems of differential and algebraic equations (DAEs) can be specified.

2.1.3 Subtyping and Inheritance Modelica models can be defined using inheritance. The extends clause is used together with a class name to inherit that class. Multiple inheritance is allowed us- ing several extends clauses, one for each inherited class. Inheritance is equiva- lent to inserting the contents of the inherited class at the place where the extends clause resides. Type equivalence in Modelica is defined as follows: Two types T and U are equivalent if and only if

• they denote the same primitive type (see Section 2.1.2), or

• T and U are classes containing the same elements (according to their names) and the elements types are equivalent.

Subtypes in Modelica are defined independently from the inheritance mecha- nism. A class C is a subtype of a class S if

• S and C are type equivalent, or

13 Chapter 2 Background

• both of the following statements hold: – every public element of S also exists in C (according to its name). – the type of each such element in C is a subtype of the type of the corre- sponding element in S. If a class C is a subtype of a class S then S is called the supertype of C. Subtypes and supertypes do not necessarily need to be in an inheritance hierarchy, but a class that is inherited from, a base class, is a supertype of a class that inherits from it, a derived class. An example is shown in Figure 2.2.

partial model OnePort Pin p ,n; Voltage v "Voltage drop"; equation v=p.v− n.v; p.i + n.i = 0; end OnePort ;

model Resistor ; extends OnePort ; parameter Real R( unit="Ohm" ) "Resistance "; equation v=p.i * R; end Resistor ;

model TempResistor "Temperature dependent resistor " extends OnePort ; parameter Real R( unit="Ohm" ) "Resistance at reference temperature "; parameter Real RT( unit="Ohm/ degC" )=0 "Temperature dependent resistance "; parameter Real Tref ( unit="degC")=20"Reference temp . "; Real Temp = 20 "Actual temperature "; equation v=p.i * (R + RT * (Temp − Tref )); end TempResistor ;

Figure 2.2: Subtyping in Modelica. TempResistor does not inherit from Re- sistor, but it is a subtype of Resistor. They both inherit from OnePort.

The TempResistor class cannot extend the Resistor class because it has a different equation in the equation section, but it is still a subtype of Resistor because it contains all the elements in Resistor, and additional elements. Both classes inherit from the OnePort1 class, though.

1The term OnePort is used by specialists in the electrical modeling community to denote electrical

14 2.1 Modelica

2.1.4 Modifications

A modification in Modelica is a short-hand Modelica syntax for expressing class specialization. For example, the modification compa(pa=1) in ModelB in Figure 2.3 expresses that the equation pa=0 in ModelA should be replaced by the equation pa=1 to create a temporary, specialized class derived from ModelA and used for creation of the compa instance. Since models are built up hierarchically, modifications can be overridden, in which case the topmost (outermost) modification is applied. A modification can also be hierarchical, in order to modify a lower level parameter directly. Each modification consists of a component reference and an expression that is evaluated in the context where the declaration resides. Example of modifications can be seen in Figure 2.3. Declarations preceded by the final keyword are final elements and cannot be modified using modifications. The final keyword can also precede modifications, in which case it prevents further modifications of that variable in outer modifications.

model ModelA parameter Real pa = 0; // default value end ModelA ;

model ModelB ModelA compa ( pa =1); // modification parameter Real pb = 0; end ModelB ;

model MyModel parameter Real mypa=3 , mypb=4; // hierarchical modification ModelB compb ( pb=mypb , compa ( pa=mypa ) ) ; end MyModel ;

Figure 2.3: Modifications in Modelica. The resulting value of the variable compb- .compa.pa is mypa, i.e., 3.

Modifications can also be applied directly when extending a class, in the ex- tends clause. For example:

model MyNewModel extends MyModel(mypb =5);

When instantiating components of MyNewModel the default value of mypb will be 5.

components with two physical connection points, i.e., two physical ports.

15 Chapter 2 Background

2.1.5 Equations and Algorithms The keywords equation and algorithm denote equation and algorithm sec- tions, respectively. There can be several such sections of each kind in a class. During compilation, all equation sections are merged into a single equations sec- tion. Equation sections can contain standard equation clauses, connect equations, con- ditional equations, for equations and when equations. Standard equations consist of two expressions and the equality operator denoted by =. The assignment oper- ator := is not allowed in equation sections, whereas the equality operator = is not allowed in algorithm sections. Besides the common operators like arithmetic operators and function calls, Modelica has if-expressions, which can be used in situations like: equation x= if (z > 0) 2* z else (−2*z); Connect equations consist of the connect() operator with two arguments that are references to connectors. Connectors are instances of connector restricted classes and usually contain two kinds of variables, flow (e.g. current) and non-flow (e.g. potential) variables, the former being denoted by the flow keyword. Connect equations are translated into standard equations during compilation, where for each connection the non-flow variables of the involved connectors are set equal, and the sum of all the flow variables is set to be equal to zero. Figure 2.4 illustrates the use of connectors and connections, and the resulting equations. Conditional equations can be written using the if-elseif-else construct with equations in the body. for equations are useful for repetitive equation struc- tures involving arrays, whereas when equations and when statements are used for discrete event simulation. Algorithm section can contain assignments, conditional statements, for-loops, while-loops and when-statements. The difference from equation sections is that algorithm sections contain assignments instead of equations, and the contents of the algorithms are executed sequentially. An assignment consists of a variable reference as the left-hand side, the assignment operator := and an expression as the right-hand side.

2.1.6 Replaceable Elements Elements in classes in Modelica can be declared as replaceable, in which case they can be replaced by another type of element that is type compatible when the containing class is extended or instantiated. Generic classes with type parameters is supported in Modelica through the replaceable mechanism. The type restriction of a redeclaration is that the new declared type must be a subtype of the original declared type, a constraining type.

16 2.1 Modelica

A B

p p

p

C

(a) Visual view of a connector and connection example.

connector Pin "Electrical pin" flow Current i ; Voltage v; end Pin ;

model OnePin Pin p; end OnePin ;

model Test OnePin a , b , c ; equation connect (a.p, b.p); connect (b.p, c.p); end Test ;

(b) Textual view of a connector and connection example.

equation a.p.i + b.p.i + c.p.i = 0; a.p.v = b.p.v; b.p.v = c.p.v;

(c) Resulting equations

Figure 2.4: Example of connectors and connections and the resulting simple equa- tions after compilation.

17 Chapter 2 Background

2.2 Differential Equations

Differential equations are commonly used in mathematical models of physical phe- nomena that are distributed in time and/or space. Examples include heat transfer, fluid flow, structural mechanics, wave propagation, etc. Such mathematical models relate certain variables, called dependent variables, and their derivatives to other variables, called independent variables. For example the time variable or space coordinates occur commonly as independent variables.

2.2.1 Fields A field is a mapping from a domain to scalar or vector values. The geometrical region, i.e., the domain where the field is defined, is called the fields definition domain. A field can be seen as a continuous variable distributed in spatial coordi- nates. Example of a scalar field and a vector field can be seen in Figure 2.5. The scalar field is a mapping R2 → R while the vector field is a mapping R2 → R2, i.e. for each tuple (x, y), the fields give a value u and (u, v), respectively. u

v

u

y y

omega omega x x

Figure 2.5: Two examples of fields. A scalar field defined on two-dimensional do- main is depicted on the left. A vector field defined on the same domain can be seen on the right.

2.2.2 Ordinary Differential Equations and Differential and Algebraic Equations In some cases a variable that is distributed in space and/or time, e.g. a temperature field, can be approximated by a scalar variable. For example, when the temperature of a fluid in a container is studied, the temperature could be assumed to be the same throughout the entire container at each specific time instant, and one can study the temperature change as a function of time based on the incoming and outgoing fluid flow. Since the simplified model depends only on one variable, time, derivatives that occur are time derivatives, and the equations of the model

18 2.2 Differential Equations are ordinary differential equations (ODEs) or differential and algebraic equations (DAEs).

2.2.3 Partial Differential Equations In more detailed models when the temperature distribution over the container is studied, with different temperature values at different positions inside the container, the temperature is a function of the independent variables. representing the space coordinates inside the container, and also of the time variable if time-dependent be- havior is studied. Derivatives that occur in such models can be partial derivatives , i.e. derivatives with respect to one of the space variables or the time variable. Dif- ferential equations involving partial derivatives are thus called partial differential equations (PDEs). If the equations contain the time variable or any time-dependent variable, the problem is called time-dependent, otherwise it is called stationary. The order of a partial differential equation is defined as the highest differentia- tion order that occurs in that equation. The most commonly used PDEs in models of many practical systems are second-order PDEs, containing second order deriva- tives. A partial derivative can be stated in different ways. The first-order partial derivative of a dependent variable u with respect to the independent variable x is represented using the following three variants of mathematical notation:

∂u = ∂ u = u ∂x x x A second order derivative can be written accordingly as

∂2u = ∂ u = u ∂x2 xx xx The second differentiation can be done with respect to a different variable y than the first differentiation, e.g. ∂xyu = uxy, which is also a second order derivative, a mixed partial derivative. A general, second order PDE with an unknown dependent variable u and the independent variables x and y can be stated as

f(u, ux,uxx,uy,uyy,uxy,uyx,x,y)=0 (x, y) ∈ Ω (2.1)

The definition domain, i.e., the geometric region on which the PDE is defined, denoted Ω, is an open2 and in most cases bounded region in space as defined by the independent variables, see Figure 2.6.

2An open region is a region where any point in the region can be enclosed by a ball that is completely inside the region.

19 Chapter 2 Background

n

∂Ω Ω

Figure 2.6: The definition domain Ω, its boundary ∂Ω and the outward normal vec- tor n.

2.2.3.1 Vector notation The differential operators gradient and divergence are commonly used to express PDEs using vector notation. These operators are dimension and coordinate name independent. The gradient operator is defined as follows: ∂(u) ∂(u) ∇u = grad u(x1,...,xn)= ... ∂x1 ∂xn The divergence operator is defined as follows:

∂u1 ∂un ∇·u = div u(x1,...,xn)= + ...+ ∂x1 ∂xn

2.2.4 Boundary Conditions Boundary conditions in a PDE problem specify the behaviour of the model on the boundary of the domain Ω, denoted ∂Ω, and usually contain derivatives of one order less than the PDE. A general boundary condition corresponding to Equa- tion (2.1) can be expressed as

g(u, ux,uy,x,y)=0 (x, y) ∈ ∂Ω (2.2) Boundary conditions usually contain a directional derivative instead of the partial derivative with respect to one variable. A common directional derivative is the outward normal derivative, which is obtained by the scalar product of the outward normal on the domain boundary and a vector of the partial derivatives. The outward normal derivative is denoted ∂n and is commonly used in boundary conditions to specify e.g. heat flux through the boundary.

20 2.2 Differential Equations

Three kinds of boundary conditions that often occur have been given special names:

Dirichlet : u = h1 on ∂Ω

: ∂ = Ω Neumann ∂nu h2 on ∂

: ∂ + = Ω Robin ∂nu qu h3 on ∂

In cases where the right-hand side is zero, the corresponding condition is called homogeneous,otherwisenon-homogeneous.

2.2.5 Initial Conditions Initial conditions are needed in order to find a unique solution to a time-dependent differential equation. Due to the zero derivatives of constants, infinite number of solutions can satisfy a differential equation. Giving the value of the dependent vari- able at some point in time, usually time value where simulation starts, the constant can be determined and a unique solution can be found.

2.2.6 Classification PDEs are classified based on linearity properties. An equation expressed using the linear operator3 L() in the form

L(αu + βv)=f is linear if L(αu + βv)=αL(u)+βL(v) If a PDE with the dependent variable u and the independent variables x and y can be expressed in the following form:

auxx +2buxy + cuyy = d (2.3) where the coefficients a, b and c are constants, the PDE is linear. If the coefficients are functions of the independent variables only, x and y in this example, the PDE is semi-linear, and if the coefficients also depend on u or its first-order derivatives the PDE is quasi-linear. Equations that cannot be expressed linearly in the second order derivatives as in Equation (2.1) are nonlinear. In this text, semi-linear PDEs will be regarded as linear, while quasi-linear PDEs will be classified together with the nonlinear. 3An example of a linear operator is the derivative operator.

21 Chapter 2 Background

Equation (2.3) is classified further into three categories depending on the value of b2 − ac: Elliptic : b2 − ac < 0

Parabolic: b2 − ac =0

Hyperbolic : b2 − ac > 0

Elliptic equations typically occur in stationary heat conduction models, whereas parabolic equations arise in time-dependent models. The wave equation used for modeling propagation of waves such as sound waves in gas or electro-magnetic waves is an example of a hyperbolic equation.

2.3 Numerical Solution Methods

A very small number of PDE problems can be solved symbolically, and even fewer of these are solvable with practically useful boundary conditions. For this rea- son, much research has been done on numerical solution of PDEs and different methods have been developed. Unlike the case for solution of ordinary differential equations, there is no unified method for solution of general PDE problems, how- ever, and an appropriate numerical solver must be selected for the specific kind PDE being solved. The solution method depends on whether a stationary or a time-dependent PDE is solved. Only space discretization is needed for stationary problems, whereas time-dependent problems need both space and time discretization. The methods described below can be used for both these cases. Discretization of only time or space variables can be done as well. For example, an equation can be discretized with respect to space coordinates, leaving a system of algebraic equations contain- ing only time derivatives (the method of lines). Time-dependency can be removed similarly, replacing time derivatives with a finite difference, leaving a stationary PDE problem which can be solved iteratively at different time steps. Space discretization is performed in different ways, depending on the numerical solution method. The finite difference method requires a grid, which is usually regular, i.e., with equidistant discrete points. This also requires that the definition domain is rectangular. The finite element method can be used on more general domains, because the domain is discretized using a triangular mesh.

2.3.1 Finite Difference Methods In order to find the unknown function, the domain, i.e. the geometry on which the problem is defined is discretized into a set of grid points and the values of the

22 2.3 Numerical Solution Methods function at these points are calculated. When the domain is discretized, the partial derivatives can be approximated by equations using the values at the grid points. Using Taylor’s theorem, different approximations can be derived [15]. The first- order derivative of u with respect to x using a grid with the distance h between the points can be approximated by for instance: ∂u u(x + h) − u(x − h) = + O(h2) ∂x 2h Here, O(h2) represents the approximation error. This equation is called a central- difference approximation. Other approximations can be derived, for example ( + ) − ( ) ∂u  u x h u x ∂x h which is called a forward-difference formula, and ( ) − ( − ) ∂u  u x u x h ∂x h which is called a backward-difference formula. Higher-order derivatives can be ap- proximated similarly. The derivatives in the PDE are then replaced by the approx- imations and repeated for each grid point, generating an equation system with the values of u at the grid points as unknowns. The boundary conditions are applied at the grid points neighboring the boundary, depending on the kind of boundary con- ditions. With Dirichlet boundary conditions, the values on the boundary are known and can be used directly. With Neumann and Robin conditions, the derivative is ap- proximated in the same way as in the PDE and equations involving the grid points outside the domain are generated, that can be used to express the unknown values on the boundary. When solving time-dependent problems, the time derivatives can be approxi- mated with finite differences as well. Note however that especially when using finite difference methods, the discretization steps must be chosen according to cer- tain conditions in order to maintain numerical stability during simulation.

2.3.2 Finite Element Methods A common way of solving a PDE numerically is to approximate the dependent variable u with a function uˆ belonging to a finite dimensional space with known basis functions βk(x), also called trial functions. Using a vector space of dimen- sion N, the approximate function is defined as

N uˆ(x)= ckβk(x). (2.4) k=1

23 Chapter 2 Background

Each set of coefficients c1...cN is the coordinates of a function in this space. The problem is then reduced to finding the coefficients for a function uˆ that satisfy the equation as well as possible, i.e. minimizing the error u − uˆ. Because u is unknown, the error cannot be measured directly. Instead, the partial differential equation is used to measure the error introduced by using the approximation uˆ instead of u. Different measurements lead to different solution methods, such as the least squares method or the weighted residual method. Since there are a finite number of basis functions and finite number of unknown coefficients, it is possible to calculate the coefficients numerically, given the PDE and known values at some points, i.e. the boundary conditions. The Galerkin method is a basic method for calculating the unknown coefficients. For a partial differential equation of the form

L(u(x)) = g(x) where L() is a linear operator containing u and its derivatives, a residual error R of an approximation uˆ is defined by

R(ˆu(x)) = L(ˆu(x)) − g(x)

The residual error measures how well the approximation satisfies the partial differ- ential equation. If it is identical to zero, i.e. R(ˆu(x)) ≡ 0 for all x in the domain, then the approximation is the exact solution. A criterion for measuring how close a function is to being zero is to look at its orthogonality to a chosen set of functions. Orthogonality of two functions u(x) and v(x) is defined as u(x)v(x) dx =0 Ω

The residual of the exact solution R(u(x)) is orthogonal to all functions according to this definition. The residual of the approximation is checked against a set of test functions from an appropriate test space. It is sufficient to check the basis vectors of the test space to assure orthogonality to all functions in the test space. The Galerkin method uses the same space for both trial and test functions, so the basis functions βk are used as test functions as well:

R(ˆu(x))βk(x) dx =0 k =1..N Ω Substituting uˆ with its definition in Equation (2.4) and calculating the integrals gives an equation system of size N that can be solved to finally obtain the coeffi- cients to the trial functions and consequently the approximation to the solution. One problem with this method is to find basis functions that can be easily com- bined to approximate the unknown function. Basis functions like polynomials that

24 2.3 Numerical Solution Methods has global support, e.g. where each basis function contribute to the entire domain, have the problem that, in order to increase the accuracy of the approximation, the degree of the polynomials must be increased, leading to very high degree of poly- nomials. A more flexible method, called the finite element method, is to divide the domain into M subdomains, called partitions or elements, and use basis functions with only local contribution. Each basis function ϕk is zero in the entire domain except for a small number of elements. The hat function is an example of a basis function with local support, defined as:   0,x/∈ [xi−1,xi+1], x−xi−1 ( )= ,x∈ [x −1,x ], ϕi x  xi−xi−1 i i (2.5)  x−xi+1 ,x∈ [x ,x +1]. xi−xi+1 i i

With the finite element method, may smaller sized elements can be used for better approximation instead of polynomials of higher order. Element size and shape can be varied as well, using adaptive triangulation/subdivision to create smaller ele- ments for the parts of the domain where the error is too large, for example where the solution has steep changes. Subdivision of the domain in two or three dimen- sions can be performed in different ways, triangulation being a common method.

2.3.3 Method of Lines

The method of lines is a solution method that converts a PDE into a set of ODEs involving only time-dependent functions and time-derivatives. The conversion is done by discretizing the PDE in space, leaving a number of unknowns and their time derivatives. For the space discretization, any of the methods described earlier can be used. For example, if the finite difference method is used, the space dis- cretization leads to one unknown and its time derivative at each grid point on the domain, i.e. a set of ODEs. One advantage of the method of lines is that advanced numerical solution meth- ods exist for solving general ODEs that do not yet exist for PDEs. There are, for instance, solvers with automatic step adjustment to find a solution with required accuracy. Another advantage is that coupled systems containing both ODE and PDE based models become easier to solve because the space discretization of the PDEs results in ODEs that can be solved together with the already existing ODEs. One disadvantage, though, is that the space discretization is independent of the error controlled step adjustment that is done in the ODE solution process. Thus, even though the ODE solver solves the given ODEs with a desired accuracy, error introduced during the space discretization can be much larger if space discretization is performed without caution.

25 Chapter 2 Background

Also, the relation between the step sizes in the space and time domain must fulfill certain criteria [16] in order to get a numerically stable solution. However, this is not checked by a pure ODE solver.

26 Chapter 3 A Modelica Library for PDE-based Modeling

“You can’t argue with a machine, Jim!” Dr. McCoy

This chapter describes a set of packages and models in Modelica to describe and solve PDE-based models.

3.1 Introduction

An object-oriented approach has been taken in the design of the PDE library. As described earlier, all PDE models have certain common components. These are found in this library on an abstract level, without any information about specific models or solution methods. Models and classes that contain specific informa- tion for different solution methods are separated into sub-packages. Here, we first present the continuous parts of the library and show an example of how these can be used to define a PDE-based model. Then, we describe the discrete parts, specif- ically the finite element package which is the main solver package used in the library. Due to restrictions in the Modelica language, the implementation of the PDE library requires a specific design. Therefore, the design is presented in two steps. First, we describe the general design using classes as they are known in object- oriented design terminology. Then, we describe the packages and models in the library in more detail. Mapping from the general design to a Modelica-specific

27 Chapter 3 A Modelica Library for PDE-based Modeling design using packages, called The Package Design, is described separately in order to clarify the concept.

3.1.1 Separation into Continuous and Discrete Parts The PDE library and the existing models are divided into a continuous and a dis- crete part, in order to separate the mathematical model itself from discretization details. However, only the discrete part of the models contain actual model equa- tions, because of the current lack of Modelica language constructs for expressing space-distributed equations, such as field variables, partial derivatives etc. Such language constructs are described in Chapter 4. Thus, the continuous part contains a number of PDE-based models that can be reused with different parameters (coef- ficients), with the actual equations given in the corresponding discrete models. This approach is similar to the coefficient-based approach, described in Section 7.2, ex- cept that here the discrete models can be fully described in the Modelica language itself instead of in external libraries, allowing Modelica library developers to define PDE-model libraries using the framework.

3.2 Continuous Part Design

The class design of the continuous part of the PDE library is described using object- oriented terminology and UML diagrams. Currently, only two-dimensional do- mains are supported. For discussion of generalization to one and three dimensional models, see Section 3.10. Some UML components used in the following descrip- tion is listed in Appendix A. The general classes in the PDE library are Field, Domain,andBoundary. Some help classes are also included, namely BoundaryCondition, Point and BPoint. These classes are independent of the solution methods and specific PDE models. The UML diagram in Figure 3.1 shows an overview of these classes and their relationship. A field represents a variable that is distributed over a spatial domain. The Field class is parameterized on the field value type. Thus, the field values can be of any type, including vector-valued types. A field has an operation called value which returns the field value at a given point in the domain. Hence, a field can be seen as a mapping from a spatial domain to field values. Each field has exactly one Domain component. The Domain class stores spatial domain information associated with each field. A domain is defined as the interior of a spatial region delimited by its boundary. Hence, a spatial domain is implicitly defined by its boundary component. Each boundary object can be a parametric curve or a number of concatenated boundary parts each of which are parametric curves. The Boundary class repre-

28 3.2 Continuous Part Design

FieldType: Field Domain +value(Point): FieldType

Boundary BoundaryCondition

+shape(in u): BPoint

ConstField Point BPoint +x: Integer +x: Integer +value(Point): FieldType +y: Integer +y: Integer +bcIndex: Integer

ConstConstField +constval: FieldType +value(Point): FieldType

Figure 3.1: Basic classes of the PDE library. See Section 3.4 for description of these packages including their definition in Modelica syntax.

29 Chapter 3 A Modelica Library for PDE-based Modeling sents the boundary of a domain using parametric curves or surfaces. A boundary has an operation called shape which defines the shape by mapping parameters to spatial coordinates. In the two dimensional case, the boundary is a curve depend- ing on one parameter, e.g. the shape function is a mapping from R to R2.In order to define a finite domain, a boundary must be closed, e.g. in the two di- mensional case the parameter range [0, 1[ must define a closed boundary, where shape(0) == shape(1). Other classes are BoundaryCondition, Point and BPoint. BoundaryCon- dition represents one of the included boundary condition types and also con- tains parameters needed by that type of boundary condition. The Point class sim- ply represents a coordinate. The BPoint class represents a point with additional boundary condition information, used for the discretized boundary points.

3.2.1 Standard Boundaries There are a number of boundary classes defined in the PDE library, in the package Boundaries. These are shown in Figure 3.2.

parts Boundary 1..n +shape(in u): BPoint

Rectangle Arc Bezier +p: Point +c: Point +p: array [2..n] of Point +w: Real +r: Real +shape(in u): BPoint +h: Real +a_start: Real +shape(in u): BPoint +a_end: Real +shape(in u): BPoint bottom, right, top, left Line 4 +p1: Point « a_start=0, a_end=2*PI » +p2: Point +shape(in u): BPoint Circle

+shape(in u): BPoint Composite

+shape(in u): BPoint

Figure 3.2: Standard boundary classes in the Boundaries package.

Line: Represents a straight line between two points.

30 3.3 The Package Design

Rectangle: Represents a rectangle. Contains four lines representing the sides.

Arc: Represents part of a circle, with the center c and radius r. Starting angle is given in a_start and the ending angle in a_end, using radians. The arc is drawn in the counter-clockwise direction, starting at the x axes.

Circle: Represents a full circle. Implemented by extending Arc with the values 0 and 2π for start and end angles.

Bezier: Represents a Bezier curve [17]. The control points are given as an array of Point elements.

Composite: Represents a composite boundary, consisting of a number of Bound- ary objects. The parameter range [0, 1[ is divided equally among the parts. The end points of the parts must be connected, e.g. for each pair of consecutive parts i and i +1must hold that shapei(1) == shapei+1(0), and also for the first and the last parts that shapelast(1) == shapefirst(0).

3.3 The Package Design

Due to restrictions in the Modelica language version 2.2, the design described in the previous section is not directly implementable. One restriction is that objects cannot have methods, i.e., object data is not im- plicitly passed to a function even if the function resides in a class. Thus, we need to pass the object data as an argument when calling methods. It is also not possible to call a function inside a class from outside that class, unless the class is a package. Hence, if we want to have different shape functions for different types of boundaries, we must either use different function names, or different packages containing the shape functions for each type of boundary. Our solution is to create a package for each of the boundary types discussed previously, and implement the function shape in each package. The object data is stored in a record called Data, which exists in all packages used as types. One of the arguments to the shape function is a record of type Data. Since we now have packages representing boundary types, we need to declare a replaceable package when we want a reference to a boundary object. For exam- ple, the Domain needs a reference to a general boundary object. This reference is declared as follows:

package Domain replaceable package boundaryP = Boundary extends Boundary ; // base class restriction

end Domain ;

31 Chapter 3 A Modelica Library for PDE-based Modeling

Here, we use a convention where we add the suffix P to the reference name, to dis- tinguish the package name boundaryP from the data structure name boundary. Also, while the convention is to have an initial capital letter in package names, we here use lowercase letters to emphasize that this package is only used for declaring an object reference. Note also that the use of the extends keyword here does not specify inheritance. Rather, this syntax is used to declare a constraint on possible types that can be used as replacement for boundaryP. The use of the keyword ex- tends is unfortunate, since a keyword subtypeof or constrainedby would be more accurate. A comment is added in the code snippets to clarify this difference. The data structure can be declared as follows: package Domain replaceable package boundaryP = Boundary extends Boundary ; // base class restriction

record Data boundaryP . Data boundary ; end Data ; end Domain ; Here, we also declare the data record for the Domain type. Each domain instance will now contain a record called boundary of type boundaryP.Data. When the boundary package is replaced, the correct Data record from that boundary package will be used accordingly. Domain objects can now be declared analogously. When declaring a domain object, the boundaryP package is replaced with the specific boundary to use. For example: model TestModel package domainP = Domain( redeclare boundaryP = Rectangle );

Rectangle . Data rectbnd (p=Point (0 ,0) , w=20, h=10); domainP . Data domain(boundary=rectbnd ); end Domain ; Here, domainP is the type “instance” of Domain, where the boundary type is Rectangle. Thus, domainP.Data.boundary will have the type Rectangle.Da- ta, i.e., domainP.boundaryP.Data. The modification boundary=rectbnd will then be correct. This approach solves the problem of methods with a straightforward naming convention. It also solves the problem of polymorphic types, i.e., the problem of declaring references to base class types which actually refer to objects of sub- classes, for example Boundary and Rectangle. Figure 3.3 shows the mapping from the classes in the design diagrams to the approach described here. The resulting packages are somewhat more complex than the classes in the design described earlier, but contain the same abstractions and give the same result.

32 3.3 The Package Design

Rectangle +p: Point +w: Real +h: Real +shape(in u:Real): BPoint

<< PartType=Line, n=4 >>

1 PartType: HComposite +parts: array [1..n] of PartType +shape(in u:Real): BPoint

<> <> Rectangle HComposite

<> <> Bnd = HComposite(PartType=Line, n=4) PartType = Boundary

<> <> Data Data

+p: Point +parts: array [1..n] of PartType.Data +w: Real +h: Real +bnddata: Bnd.Data <> shape

<> (in u:Real,in d:Data): BPoint shape

(in u:Real,in d:Data): BPoint

Figure 3.3: Mapping of classes to packages in Modelica. The HComposite type contains a number of boundary parts with identical types, called Part- Type. It is used internally by Rectangle to represent the lines of the rectangle.

33 Chapter 3 A Modelica Library for PDE-based Modeling

3.4 Continuous Part

This section describes the continuous parts of the PDE library, i.e., the parts that are independent of any spatial discretization. The geometry of the PDE model, known and unknown field variables, boundary conditions and parts of the equation models are declared in continuous form using the classes from this part.

3.4.1 Boundary Definition A boundary contains a shape function representing the parametric curve defined for parameters in the range [0, 1]. The shape function can be seen as a mapping from a real value, the formal parameter, to the coordinate vector x. In two dimensions, one parameter suffices, in three dimensions, two parameters are needed. Moreover, there is a formal parameter data (see below). The specific return value of the shape function has the type BPoint, which is a point with additional information about the boundary conditions that are in effect at that point. The base package for all boundary types is the package called Boundary: package Boundary replaceable function shape input Real u; input Data data ; output BPoint x; end shape ;

replaceable record Data parameter BoundaryCondition . Data bc ; end Data ; end Boundary ; The formal parameter data to the shape function contains the actual data of the specific boundary object. The record BPoint, representing a point with boundary condition information, has the following definition in the two-dimensional case: type BPoint = Real [3] "x , y and boundary part index " ; Here, index 1 and 2 of the BPoint type represent the x and y coordinates in two- dimensions, while index 3 is a boundary part index, needed by the discretization and solution steps to find the associated boundary condition for the boundary edges.

3.4.2 Domain Definition A base domain type called Domain is declared with a boundary instance defining the actual geometry of the domain: package Domain replaceable package boundaryP = Boundary extends Boundary ; // base class restriction

34 3.4 Continuous Part

replaceable record Data parameter boundaryP . Data boundary ; end Data ;

function discretizeBoundary input Integer n; input boundaryP . Data d; output BPoint p[n]; algorithm for i in 1:n loop p[ i , :] := boundaryP . shape (( i − 1)/n, d); end for ; end discretizeBoundary; end Domain ; The restriction specifies that if the package boundaryP is replaced, the replacing package must be a subtype of Boundary. The function discretizeBoundary must reside in the Domain package in or- der that the correct shape function is called, depending on the replaceable package boundaryP. The discretization simply calculates a given number of points uni- formly distributed on the boundary. The data record of the domain contains the boundary record, which is the actual data record of the selected boundary type.

3.4.3 Fields A field represents a mapping from a domain to scalar or vector values. The do- main is declared as a replaceable package, which can be replaced by a user-defined domain package or an existing standard domain from e.g. a library. All domain packages should extend the Domain package described in Section 3.4.2. The re- placeable type FieldType determines the value type of the field. The data record contains the actual parameters of the domain: package Field replaceable type FieldType = Real ; replaceable package domainP = Domain extends Domain ; // base class restriction

replaceable record Data parameter domainP . Data domain ; end Data ;

replaceable function value input Point x; input Data d; output FieldType y; algorithm y:=0; end value ;

35 Chapter 3 A Modelica Library for PDE-based Modeling

end Field ;

The function called value represents the mapping, which can be defined when specifying fields with known values. Fields with unknown values that must be solved for during simulation may use value functions that interpolate the values for given coordinates. The declaration of the package domainP contains a base class restriction, i.e. this package may only be replaced by a package that is a subtype of Domain. The default base package is also Domain. The field class can be used with points of any dimension by changing the definition of the type Point.

3.4.3.1 A Field Example

An example containing a field that is time-invariant follows:

model FieldExample function myFieldFunc input Point x; input myFieldP . Data d; output myFieldP . FieldType y; algorithm y:=cos(2* PI*x[1]/6) + sin(2* PI*x[2]/6); end myFieldFunc ;

package omegaP = Domain ( redeclare package boundaryP=Circle ); package myFieldP = Field ( redeclare package domainP=omegaP , redeclare function value=myFieldFunc );

parameter Circle .Data bnd( radius =2); parameter omegaP. Data omega(boundary=bnd ); parameter myFieldP . Data myfield ( domain=omega ); end FieldExample ;

The field function myFieldFunc defines the mapping from the space coordinates to the field values of type Real.

3.4.4 Included Boundaries

Some predefined boundaries can be found in the package Boundaries. All these packages extend the basic package Boundary. Therefore, the data records in each boundary contain the parameter bc of type BoundaryCondition.Data, defining the boundary conditions. Boundary conditions are described in Section 3.4.6. An overview of the included boundaries was previously presented in Figure 3.2. These are also briefly described in the following sections.

36 3.4 Continuous Part

3.4.4.1 Line Line is a straight line defined by two points, the start and the end points of the line. The data record of Line follows: package Line extends Boundary ;

redeclare record Data extends Boundary . Data ; parameter Point p1; parameter Point p2; end Data ; ... end Line ; The shape function simply interpolates the points linearly between the end points: package Line extends Boundary ; ... redeclare function shape input Real u; input Data d; output BPoint x; algorithm x[1:2] := d.p1 + u*(d.p2 − d.p1); x[3] := d. bc . index ; end shape ;

end Line ; The boundary part index is passed through to the points on the boundary, which is later used to find associated boundary conditions during solution.

3.4.4.2 Arc An arc is part of a circular boundary with given start and end angles around a center and with a given radius: package Arc extends Boundary ;

redeclare record Data extends Boundary . Data ; parameter Point c={0,0}; parameter Real r =1; parameter Real a_start =0; parameter Real a_end=pi /4; end Data ; ... end Arc ;

37 Chapter 3 A Modelica Library for PDE-based Modeling

The default values for the parameters give a full circle. The shape function calcu- lates the position using sin and cos functions: package Arc extends Boundary ; ... redeclare function shape input Real u; input Data d; output BPoint x; protected Real a=(d. a_end − d. a_start ); algorithm x[1:2] := d.c + d. r*{cos(d. a_start + a*u), sin(d. a_start + a*u)}; x[3] := d. bc. index ; end shape ;

end Arc ;

3.4.4.3 Circle A circle is simply defined by extending Arc and giving the angles for a full circle: package Circle extends Arc( Data ( a_start =0, a_end=2* pi )); end Circle ;

3.4.4.4 Rectangle A rectangle declares four lines as components, with the names bottom, right, top and left, as follows: package Rectangle extends Boundary ; package Bnd = HComposite ( redeclare package PartType = Line );

redeclare record Data extends Boundary . Data ; parameter Point p; parameter Real w; parameter Real h;

parameter Bnd. Data bnddata(n=4, parts={bottom , right , top , left }); parameter Line . Data bottom ( p1=p , p2=p + {w,0} , bc(index=1, name="bottom" )); parameter Line . Data right ( p1=p + {w,0} ,

38 3.4 Continuous Part

p2=p + {w, h} , bc( index=2, name="right")); parameter Line . Data top ( p1=p + {w, h} , p2=p + {0 ,h} , bc( index=3, name="top")); parameter Line . Data left ( p1=p + {0 ,h} , p2=p , bc( index=4, name="left")); end Data ;

redeclare function shape input Real u; input Data d; output BPoint x; algorithm x := Bnd. shape (u, d. bnddata ); end shape ;

end Rectangle ;

The parameters of the rectangle are p, w and h, representing the bottom left corner, the width, and the height, respectively. Internally, the rectangle class uses the HComposite package, which is a con- tainer for several boundary parts of the same type, as described in Section 3.4.4.7. Hence, bnddata is a data record inside the rectangle record, with the parts initial- ized to the vector containing the four declared lines, and as the PartType declared as Line, accordingly.

3.4.4.5 Bezier

The Bezier boundary package uses a number of control points given as parameters to calculate the coordinates of the points on a bézier curve, using De Casteljau’s Algorithm [17]. The data record for Bezier package follows:

package Bezier extends Boundary ;

redeclare record Data extends Boundary . Data ; parameter Integer n=1; parameter Point p[n]; end Data ; ... end Bezier ;

The shape function implements the algorithm for calculating the coordinates of a point on the curve, given the parameter u:

39 Chapter 3 A Modelica Library for PDE-based Modeling

package Bezier extends Boundary ; ... redeclare function shape input Real u; input Data d; output BPoint x; protected Point q[:]=d.p; algorithm for k in 1:(d.n − 1) loop for i in 1:(d.n − k) loop q[i , :] := (1 − u)* q[i , :] + u*q[i + 1, :]; end for ; end for ; x[1:2] := q[1, :]; x[3] := d. bc. index ; end shape ;

end Bezier ;

3.4.4.6 Generic

The boundary package Generic is needed in order to define composite bound- aries containing boundary parts of different types. Since there are no pointers or union types in Modelica, it is not possible to declare a container for boundary parts where each part can be a (different) subclass of Boundary, not known at the time of library development. Hence, the Generic package contains an enum parameter deciding the type of the boundary part, and data records for each of the existing types that can be selected. This leads to a lot of overhead, since only one of the records are actually used, but unused parameters are optimized away during the compilation so they do not affect the resulting simulation code. In future imple- mentations, union types or other solutions for polymorphism might allow more efficient implementation of generic boundary types. The enumeration type and the data record for the Generic boundary type fol- lows: package Generic extends Boundary ;

type PartTypeEnum = enumeration ( line , arc , bezier );

redeclare replaceable record Data extends Data ; parameter PartTypeEnum partType ;

40 3.4 Continuous Part

parameter Line . Data line ; parameter Arc . Data arc ; parameter Bezier . Data bezier ; end Data ; ... end Generic ; Because of lack of polymorphism, e.g. virtual functions, the shape function must check the enumeration variable and call the correct shape function: package Generic extends Boundary ; ... redeclare function shape input Real u; input Data d; output BPoint x; algorithm if d . partType==PartTypeEnum . line then x:=Line.shape(u,d.line); el seif d . partType==PartTypeEnum . arc then x := Arc . shape (u , d. arc ); el seif d . partType==PartTypeEnum . bezier then x := Bezier . shape (u, d. bezier ); end i f ; end shape ;

end Generic ;

3.4.4.7 Composite The Composite boundary simply uses a given number of Generic boundaries to build a complete boundary using parts of different types: package Composite extends Boundary ;

package PartType = Boundaries . Generic ;

redeclare replaceable record extends Data parameter Integer n=1; parameter PartType . Data parts [n]; end Data ; ... end Composite ; The shape function calls the shape function in the Generic boundary package, using the index calculated by dividing the formal parameter u uniformly among the existing parts: package Composite extends Boundary ;

41 Chapter 3 A Modelica Library for PDE-based Modeling

... redeclare function shape input Real u; input Data d; output BPoint x; protected Real s=d.n*u; Integer is=integer (s); algorithm x := PartType . shape (s − is , d. parts [1 + is ]); end shape ;

end Composite ; Here, is contains the part index corresponding to the value of the formal parameter u,ands-is is the new parameter value scaled to map to the parameter range of that particular boundary part. For example, if the shape function is called for a boundary containing four parts with u =0.8,thevalueofis will be integer(4 ∗ 0.8) = 3 and the value of s − is will be 4 ∗ 0.8 − 3=0.2, mapping to the u value on the fourth boundary part. HComposite is a simplified version of the Composite boundary, containing only parts of the same (replaceable) type.

3.4.5 Equation Models The Equation models contain all the different components of the PDE model, including the spatial discretization and the declaration of the discrete model equa- tions. The continuous components of the model, i.e., the domain, its boundary, the boundary conditions and the field, are declared here. Their discrete counterparts are declared and initialized automatically from the continuous components, using given discretization parameters. See Section 3.8.3 and Section 3.8.4 for the discrete parts of the equation models. For example, an equation model declares a domain and a field as follows: package Poisson2D ... model Equation "Poisson equation 2D" replaceable package domainP = Domain; parameter domainP . Data domain ;

package fieldP = Field ( redeclare package domainP = domainP ); parameter fieldP . Data u( domain=domain );

end Equation ;

end Poisson2D ; This approach allows the equation model to be reused with any domain without changing any part of the model. The package fieldP redeclares the replaceable

42 3.4 Continuous Part domain package in the Field package. This way, the package hierarchy is cor- rectly set up. The actual data records are declared separately, in order to build the object hierarchy of the model. The record u has the type fieldP.Data and will contain the correct domain data type from the given package domainP. The actual instance data for the domain is passed to the field object with the modification of the domain parameter when declaring the record u. When the domain is to be discretized, the shape function of its boundary package is called. Since the bound- ary package of the domain package is replaced when the domain is declared, the correct shape function will be called. This is handled automatically through the package DiscreteDomain, explained in Section 3.6.1, which is declared in the discrete parts of the equation models.

3.4.5.1 The Poisson Equation The Poisson equation is a stationary (time-independent) PDE model. In differential form, the equation is −∇ · (c∇u)=g in Ω (3.1) where u is the unknown field, c is a possibly space-dependent coefficient, g is the source term and Ω is the domain. The continuous part of the equation definition follows: package Poisson2D ...

model Equation "Poisson equation 2D" // User defined parameters replaceable package domainP = Domain; parameter domainP . Data domain ;

parameter Real c = 1; parameter Real g0=1 " Constant value for right hand side " ;

// Internal parameters package fieldP = Field ( redeclare package domainP = domainP ); parameter fieldP . Data u( domain=domain );

end Equation ;

end Poisson2D ; The current model only supports spatially constant values for the right hand side parameter g,givening0. A future extension is adding a field variable gField instead of the constant g. The boundary conditions defaults to Dirichlet type with value 0. This model is instantiated by defining the domain, right hand side value, number of different boundary conditions that exists in the domain boundary defi- nition, and a list of the boundary conditions of type BCType. See Section 3.9 for

43 Chapter 3 A Modelica Library for PDE-based Modeling an example defining a domain and boundary conditions. The discrete part of the equation model is presented in Section 3.5.2.3.

3.4.5.2 The Diffusion Equation The diffusion equation for a field u is: ∂u −∇·(c∇u)=g in Ω (3.2) ∂t where c is a possibly space-dependent coefficient, g is the source term and Ω is the domain. The continuous part of the diffusion equation model is identical to that of the Possion equation model shown in the previous section and is omitted here. For the discrete part of the model, see Section 3.5.2.4.

3.4.6 Boundary Conditions The boundary conditions can be one of three predefined types: Dirichlet, Neumann or mixed. The Dirichlet boundary condition is used where the value of the unknown field is known on the boundary:

u = h1 on ∂Ω (3.3) The Neumann boundary condition is used when the value of the normal deriva- tive of the field is known on the boundary: ∂u = h2 on ∂Ω (3.4) ∂n The mixed boundary condition, also called the Robin boundary condition, con- tains both the value of the field and the normal derivative: ∂u a + bu = h3 on ∂Ω (3.5) ∂n These boundary conditions are represented in the PDE library by the package BoundaryCondition, defined as follows: package BoundaryCondition type TypeEnum = enumeration ( d i r i c h l e t , neumann , robin ) ;

record Data TypeEnum bcType= d i r i c h l e t ; Real val =0; Integer index=1; String name="name" ; end Data ; end BoundaryCondition ;

44 3.5 Discrete Part Design

Here, the Data record contains the object data of the actual boundary condition ob- ject. The attribute bcType selects one of the predefined boundary condition types, which is recognized by the solver. A value parameter can be given for each type of condition, representing the right hand side value g in Equation (3.3), Equation (3.4) and Equation (3.5). The parameters a and b in Equation (3.5) are not yet added to the implementation, but are trivial to add.

3.4.6.1 Time-dependent Dirichlet Conditions

In order to handle coupling between time-dependent models, like a feedback con- troller, and PDE models, a special type of Dirichlet condition is introduced in the PDE library. This is needed because boundary conditions are handled as parame- ters in the library, but e.g. the temperature on a boundary dynamically controlled by a controller must be time-dependent. This is handled using an additional type of boundary condition, which, when assigned to a boundary, causes a time-dependent variable to be used as the boundary value in the equations in the discrete PDE models. Details about time-dependent conditions are described in Section 5.3.

3.5 Discrete Part Design

So far only the continuous parts of the packages have been discussed. These are independent of the solution method. The packages that contain discretized mod- els differs depending on the solution method because different solution methods require different information. For example, the finite element discretization of the spatial derivatives requires subdivision of the spatial domain into elements, most commonly triangles in two-dimensions. In this case, the field is represented by discrete values at the nodes of the triangulation, since linear basis functions are used. Also, the partial differential equation is only expressed in its discrete form because of missing language constructs in Modelica. In the finite element case, the discrete equation contains the stiffness matrix, the discrete field values and their time derivatives. Hence, the design of the discrete classes is highly dependent on the discretization method, consequently also on the solution method. For this reason, the discrete classes are located in sub-packages, for example FEM and FEMForms for the finite element case. The main solution method used in this work is the finite element method, im- plemented in the FEM package. The FEMForms package is a modified version of the FEM package to simplify the use of an external solver called Rheolef [18]. These packages use the same class design with slightly different attributes due to different representations in the solvers. Here, we first describe domain and model

45 Chapter 3 A Modelica Library for PDE-based Modeling discretization using the method of lines approach with finite elements. Then, we describe the design and contents of the packages FEM and FEMForms. The complete discretization and solution process is depicted in Figure 3.4. The external stiffness matrix calculation can be exchanged with internal code, i.e., func- tions implemented in Modelica. A prototype implementation of a finite element solver in Modelica exists for discretization of the Poisson equation with homoge- neous Dirichlet boundary conditions.

Continuous Modelica definition Boundary Discretization

Discrete Modelica definition (boundary) External Grid Generation

External Stiffness Matrix Discrete Calculation Modelica Definition Simulation of Modelica Model

Results

Figure 3.4: Solution diagram. The boxes on the left show the data flow. The rounded boxes show tools implemented in Modelica, and ellipses show external tools.

If linear polynomials are used as basis functions, the coefficients themselves correspond to the values of the solution field on the triangle nodes.

3.5.1 Domain Discretization The main approach for solving PDEs with the PDE library is to use the method of lines with finite elements. Spatial dependency is removed by discretizing the domain and replacing continuous fields with arrays of discrete values. The domain is divided into triangular regions the field is represented by the field values on the triangle nodes, which is sufficient because first-order polynomials are used as basis functions. Figure 3.5 depicts a triangulation example. The triangulation is generated by an external tool, a mesh generator. The interface functions for the mesh generator calls are defined in the MeshGeneration sub-package. The mesh generator used here, bamg [19], expects a polygon representing the boundary of the domain. The refinement of the discretization, e.g. the size and consequently the number of triangles and nodes, is controlled by a parameter to the mesh generation tool. A real number is given for each of the vertices. The smaller

46 3.5 Discrete Part Design

4

3.5

3

2.5

2

1.5

1 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

Figure 3.5: Example of a triangulation of a spatial domain, used in the finite element method.

this number is, the finer the triangulation will be in the vicinity of this vertex. Bamg can only handle two-dimensional domains and only polygons as boundaries. Other tools exist that handle three-dimensional domains as well as more complex geometry primitives to construct the boundary, see Section 3.10. A discrete domain is represented in the library by the DiscreteDomain pack- age, see Figure 3.7. A DiscreteDomain object contains an array of points rep- resenting the discretized boundary. Using these points as the boundary polygon, a mesh is generated to create a Mesh object. The Mesh object contains the informa- tion retrieved from the external mesh generator, i.e. the coordinates of the nodes, the edges of the boundary, and the triangles building up the interior of the domain. It also contains boundary condition indices, in order to keep track of boundary con- ditions when boundary edges are subdivided during mesh generation. The mesh representation contains the following components: vertices: An array of Integer arrays of size 3, e.g. a tuple (x, y, bc),where each element contains the coordinates of the vertex, (x, y), and the boundary condition index bc. Interior nodes have no boundary condition assigned, e.g. bc=0. edges: An array of Integer arrays of size 3 where each element (s, e, bc) contains indices to the start and end vertices, and the boundary condition index bc. triangles: An array of Integer arrays of size 4 where each element (v1, v2, v3, m) contains indices to the vertices that are at the corners of the triangle, and a material index m in order to keep track of different material parameters in case the model contains different sub-domains with different material properties.

47 Chapter 3 A Modelica Library for PDE-based Modeling

3.5.1.1 PDE Library Interface The package MeshGeneration contains functions to generate mesh and access different parts of the mesh data. Currently one and two dimensional domains are supported. Since external software is used to generate the mesh, the mesh gener- ation functions are given a filename where generated mesh is stored, and access functions takes a filename as an argument to read mesh data from. The size of each part of a mesh must be known before that part can be retrieved by a function call in Modelica, because the size of output variables of functions must be known in advance or possible to derive from input arguments. The mesh generation package contains the following functions for two dimen- sional meshes: generate2D: Generates a mesh stored in a file with the given filename. The mesh is generated using the given boundary polygon, boundary conditions and refinement parameter. sizes2D: Reads the sizes of vertices, edges and triangles from a given mesh file, previously generated by generate2D. vertices2D: Reads the vertex data from a given mesh file. The given size must match the size of vertex array in the file. edges2D: Reads the edge data from a given mesh file. The given size must match the size of edge array in the file. triangles2D: Reads the triangle data from a given mesh file. The given size must match the size of triangle array in the file. Corresponding one-dimensional mesh functions can also be found in the Mesh- Generation package.

3.5.1.2 Composite boundary The lack of polymorphic types in Modelica is also an issue when implementing composite boundaries. A composite boundary consists of a number of boundary parts, each of which can have a different type. Since the number and type of the parts is not known in advance, we cannot declare them as different components but as an array. Also, arrays cannot contain objects of different types. Our solution to this is to create a boundary type called Generic, which can represent any boundary type by declaring objects of each available boundary type and an identifier that identifies each type. The Generic and Composite types can be seen in Figure 3.6. Also, a simpler type HComposite is created, which contains a number of boundary parts of the same type. For example the Rectangle boundary internally uses HComposite to store four lines, as seen in Figure 3.3.

48 3.5 Discrete Part Design

Composite Generic +line: Line +shape(in u:Real): BPoint parts +arc: Arc 1..n +bezier: Bezier +boundaryType: enumeration +shape(in u:Real): BPoint

Figure 3.6: The Generic boundary type used to represent different boundary types.

3.5.2 Model Discretization The spatial discretization of the model using the finite element method results in a number of unknown coefficients. The unknown field is approximated by basis functions weighted with these coefficients. If linear polynomials are used as basis functions, the coefficients themselves correspond to the values of the solution field on the triangle nodes. Section 2.3.2 gives the details of the finite element method. For more details of the finite element methods and handling of different boundary conditions, see for example the textbook Computational Differential Equations by K.Erikssonetal[20]. The model discretization consists of calculating the equation matrices, e.g., A in Equation (3.13), and the right hand side of the model equation, based on the model equation, the triangulation and the boundary conditions. The size of the equation system is given by the refinement level of the domain discretization, since the number of unknown coefficients correspond to the number of triangles in the mesh. The type of the boundary conditions also affects the number of unknowns in the equation system.

3.5.2.1 Variational Formulation Before a PDE can be discretized using the finite element method with linear ele- ments, a variational formulation of the problem is needed, because linear elements are not two times differentiable. For example, consider the one-dimensional equation −u = g in Ω (3.6) u =0 on ∂Ω. In order to solve with Galerkin’s method, it is stated in the form (−u − g)vdx=0 for all functions v (3.7) Ω using the orthogonality of the residual to all functions. The approximation of u using linear elements is not possible to insert into Equation (3.6), because linear

49 Chapter 3 A Modelica Library for PDE-based Modeling functions do not have non-zero second derivatives. In order to solve this issue, integration by parts can be used to rewrite Equation (3.6) and use the following variational formulation: find the function u with u =0 on ∂Ω such that uv dx = gv dx. (3.8) Ω Ω for all functions v with v =0 on ∂Ω. Equation (3.8) is called a weak form of Equation (3.6). Here, the requirement has changed to existence of first-order derivatives. The discrete version of the variational formulation can now be stated: Find u ∈ V such that h h = ∈ uhvh dx ghvh dx for all vh Vh (3.9) Ω Ω where Vh is the space of piecewise linear functions fulfilling the boundary condi- tion. Using the hat functions, defined in Equation (2.5), as a basis for Vh, uh and gh can be defined as N uh(x)= ukϕk(x) (3.10) k=1 N gh(x)= gkϕk(x). (3.11) k=1

The fields uh and gh are now represented by their coefficients (uk) and (gk) using this basis for Vh. Checking for orthogonality against all functions vh in the test space can be accomplished by checking for a basis of the test space Vh, because all other functions are linear combinations of these. The test space have the same basis, e.g., the hat functions, which give the following equation system: N N = =1 uk ϕkϕi gk ϕkϕi i ..N (3.12) Ω Ω k=1 k=1 This equation system is equivalent to the linear system Au = Mg (3.13) where u =(uk) are the unknown coefficients of the basis functions, g =(gk) the known coefficients corresponding to the right hand side, and A and M are N × N matrices with the elements defined as = =1 aik ϕkϕi dx, i, k ..N (3.14) Ω

mik = ϕkϕi dx i, k =1..N. (3.15) Ω

50 3.5 Discrete Part Design

The matrix A is called the stiffness matrix,andthematrixM is called the mass matrix. The vector Mg = b =(bi) is called the load vector.

3.5.2.2 Two-dimensional Variational Formulation In order to derive the variational formulation in the two-dimensional case, the fol- lowing relationship between a plane region and a line integral on the regions bound- ary, called Green’s Theorem: ∂u v ∇·(∇u) dx = − ∇v∇udx + v ds (3.16) Ω Ω ∂Ω ∂n In case of homogeneous Dirichlet boundary conditions, assuming v ≡ 0 on ∂Ω: v ∇·(∇u) dx = − ∇v∇udx (3.17) Ω Ω Consider the time-dependent, two-dimensional diffusion equation, with homo- geneous Dirichlet boundary conditions: ∂u −∇·(∇u)=g in Ω ∂t (3.18) u =0 on ∂Ω The variational formulation is: Findu ∈ Vsuchthat ∂u −∇·(∇u) vdx = gvdx for all v ∈ V (3.19) Ω ∂t Ω Here,

1 2 2 V = H0 (Ω) = {u ∈ L (Ω), ∇u ∈ L (Ω),u≡ 0 on ∂Ω} (3.20) and L2(Ω) = {f :Ω→ R : |f|2 dx < ∞} (3.21) Ω which means that for a function f, Ω ff dx exists and is finite. Applying (3.17) to (3.19), the following is obtained: ∂ uvdx + ∇u ∇vdx = gvdx for all v ∈ V (3.22) ∂t Ω Ω Ω The discrete version of the two-dimensional variational formulation is: Finduh ∈ Vh such that ∂ uh vh dx + ∇uh ∇vh dx = gh vh dx for all vh ∈ Vh (3.23) ∂t Ω Ω Ω

51 Chapter 3 A Modelica Library for PDE-based Modeling

Here, Vh is the N-dimensional space of continuous piecewise linear functions, with N interior nodes in the triangulation and the two-dimensional hat functions ϕk as basis functions. Using this basis, uh and gh can be expressed as follows:

N uh(x)= uk ϕk(x) (3.24) k=1 N gh(x)= gk ϕk(x) (3.25) k=1 Inserting these expressions in (3.23) gives the following: ∂ N uk ϕkϕi dx + ∂t Ω k=1 N N uk ∇ϕk∇ϕi dx = gk ϕkϕi dx i =1..N (3.26) Ω Ω k=1 k=1 Here, the following equation system can be identified:

∂ M u + Au = Mg (3.27) ∂t

Here, u =(uk) are the unknown coefficients for the basis functions and g =(gk) are the values of g(x) on the nodes. The N × N matrices M and A are called the mass matrix and the stiffness matrix, respectively. The elements of these matrices are defined as follows:

mik = ϕkϕi dx i, k =1..N (3.28) Ω

aik = ∇ϕk∇ϕi dx i, k =1..N. (3.29) Ω

3.5.2.3 The Poisson Equation The Poisson equation is a simple example of a stationary (time-independent) mod- el. In differential form, the equation is

−∇ · (c∇u)=g in Ω (3.30) where u is the unknown field, c is a space-dependent coefficient, g is the source term and Ω is the domain. The discrete version of the equation, simplified with c =1,is

52 3.6 The FEM package

equation A * u.val = M * g.val; Here, u.val is a vector of size N containing the unknown coefficients, where N is the number of nodes that the domain was discretized to. The values of u.val also correspond to values of the field at the nodes since linear basis functions are used. The vector g.val is the discrete values of the right hand side on the nodes, also of size N. The matrix A is the N × N stiffness matrix and M is the N × N mass matrix, generated by the finite element assembly.

3.5.2.4 The Diffusion Equation The diffusion equation for a field u is:

∂u −∇·(c∇u)=g in Ω (3.31) ∂t where c is a space-dependent coefficient, g is the source term and Ω is the domain. The discrete version of the equation is, with c =1, equation M * der (u. val) + A * u.val = M * g.val; Here, der(u.val) represents the time derivatives of the discretized unknown vari- able, distributed over the domain, and originates from the first term of the diffusion equation. The other terms are the same as for the Poisson equation. Additional terms are introduced depending on the boundary conditions.

3.6 The FEM package

In order to represent the discrete version of the domain, boundary and the field of the PDE model, a package called FEM has been created. The domain and model representation is basically the same as what is described in Section 3.5.1 and Sec- tion 3.5.2. The difference between the FEM package and the FEMForms package described in Section 3.8 lies in the representation of the matrices resulting from the model discretization. In the FEM package, a straightforward representation is used. The FEMForms package uses a representation specially adapted to the Rhe- olef solver. Other solution methods such as finite difference and finite volume methods are briefly discussed in Section 3.10. The FEM package uses a common interface package called FEMSolver to the discretization routines. Sub-packages extend this interface package to implement different solvers. Currently the solver packages InternalSolver, Internal- DiffusionSolver and RheolefSolver exist in the PDE library. The internal solvers implement the finite element assembly directly as Modelica functions. The

53 Chapter 3 A Modelica Library for PDE-based Modeling external solver called RheolefSolver contains external function calls to calcu- late the matrices of the equations using the Rheolef FEM solver package [18]. The external calls in the RheolefSolver package automatically convert from the Rheolef matrix representation to the internal Modelica representation.

FieldType: DiscreteField Field +val: array of FieldType +value(Point): FieldType

DiscreteConstField Interpolation +constval: FieldType +value(Point): FieldType +interpolate(): array of FieldType

DiscreteDomain Domain +boundary: array of BPoint

Mesh +vertices: array of Integer[3] +edges: array of Integer[3] +triangles: array of Integer[4] +polygon: array of Point +bc: array of Integer +refine: Real

Figure 3.7: Finite element specific classes. These are defined in the FEM package.

3.6.1 DiscreteDomain DiscreteDomain is the discrete version of Domain. It contains a replaceable package domainP, representing the continuous version of the domain. The dis- cretization is done automatically, once DiscreteDomain is declared with a given Domain package. DiscreteDomain is defined as follows: package DiscreteDomain replaceable package domainP = Domain

54 3.6 The FEM package

extends Domain ; // base class restriction

replaceable record Data parameter Integer nbp ; parameter domainP . Data domain ; // A parameter to the mesh generator // specifying detail level , lesser means // more triangles parameter Real refine =0.7;

// Array of discrete points on the boundary parameter BPoint boundary[nbp]= domainP. discretizeBoundary(nbp, domain . boundary ); parameter Mesh . Data mesh ( n=size (boundary , 1) , polygon=boundary [: , 1:2] , bc=integer ( boundary [: , 3]) , refine=refine ); parameter Integer boundarySize= size ( boundary , 1); end Data ; end DiscreteDomain ; The actual mesh generation is done when the mesh component is instantiated by the compiler, i.e., the Mesh package contains the actual calls to the external mesh generator.

3.6.2 DiscreteField The package DiscreteField encapsulates the conversion of a continuous field to a discrete field, using a given discrete domain. A discrete field contains two separate arrays of discrete points in the domain, one array containing the unknown values and one containing the known values, i.e., from given boundary conditions. This representation corresponds to the representation used in Rheolef [18], in order to simplify the solver interface. Both arrays are indirect, i.e., they contain indices of the actual points in the mesh representation. The DiscreteField package is defined as follows: package DiscreteField replaceable package fieldP = Field ; replaceable package ddomainP = DiscreteDomain ;

replaceable record Data parameter ddomainP . Data ddomain ; parameter fieldP .Data fld ; fieldP . FieldType val [ddomain . mesh . nv ]( sta rt =zeros ( ddomain . mesh . nv )); parameter Integer fieldSize=size (val , 1); end Data ;

55 Chapter 3 A Modelica Library for PDE-based Modeling

end DiscreteField ; Here, the default start values for the unknowns are set to zero. This value is over- ridden in the discrete parts of the equation models, for appropriate initial value setting.

3.6.3 The Poisson Equation The Poisson equation is declared in the FEM package as follows: protected parameter Real laplace [nv, nv]= Solver . getMatrix_Laplace (); parameter Real g[nv]=Solver . getMatrix_g (); equation − laplace * u. val = g. val ; Here, u.val is a vector of size nv containing the unknown coefficients, where nv is the number of nodes that the domain was discretized to. The values of u.val also correspond to values of the field at the nodes if linear basis functions are used. The vector g.val is the right hand side values, also of size nv. The matrix Laplace is the stiffness matrix of size [nv,nv] generated by the finite element assembly in the Solver package. The Solver package is replaceable and can be either InternalSolver, InternalDiffusionSolver or RheolefSolver, see Section 3.6.5.

3.6.4 The Diffusion Equation The Diffusion equation is declared in the FEM package as follows: protected parameter Real Laplace[nv, nv]= Solver . getMatrix_Laplace (); parameter Real Mass[nv , nv]= Solver . getMatrix_Mass (); parameter Real g[nv]=Solver . getMatrix_g (); equation Mass * der(u.val) − Laplace * u. val = g. val ; Here, der(u.val) represents the time derivatives of the discretized unknown vari- able, distributed over the domain, and originates from the first term of the diffusion equation. The rest of the equation is same as for the Poisson equation.

3.6.5 PDE Library Interface The following interface functions exist in the FEMSolver interface: getMatrix_Laplace: Returns the matrix corresponding to the term ∇·(∇u). getMatrix_Mass: Returns the matrix corresponding to the term ∂u/∂t.

56 3.7 Rheolef Finite Element Solver getMatrix_g: Returns the corresponding right hand side vector (load vector) for a given equation. The boundary conditions are also incorporated here. writeMatrix: Writes a matrix to file. Used for debugging. writeVector: Writes a vector to file. Used for debugging. Three packages exist that implement this interface. InternalSolver is imple- mented as Modelica functions to solve the Poisson equation. The function get- Matrix_Mass is not implemented here and a zero-filled matrix is returned. If the time-derivative term is present and the mass matrix is required, the package In- ternalDiffusionSolver should be used instead, also implemented internally. The package RheolefSolver implements all methods by using the external solver Rheolef and converting to the internal matrix representation, in order to be com- patible to the internal solver interface. The following function can be found in the Interpolation interface: interpolate: Returns a given number of discrete field values for a given continuous field.

3.7 Rheolef Finite Element Solver

Rheolef is a software package written in C++ for solving PDEs. Some abstractions are used to formulate a PDE problem using existing C++ classes from the Rheolef library, which is automatically solved.

3.7.1 Forms As described in 3.5.2, the space discretization requires a variational formulation of the PDE problem. Some integrals occur frequently when solving different PDE problems, and these are represented as abstractions called forms in mathematical literature and also in Rheolef [21]. For example, Equation (3.6) is written as

1 a(u, v)=m(g,v) for all v ∈ H0 (Ω) (3.32)

1 with H0 (Ω) being the test space as defined in Equation (3.20) in Section 3.5.2.2, and the definitions a(u, v)= ∇u∇vdx Ω m(g,v)= gv dx Ω

57 Chapter 3 A Modelica Library for PDE-based Modeling

The discrete version of the problem is formulated using the finite dimensional space Vh of continuous piecewise polynomial functions as follows:

a(uh,vh)=m(gh,vh) for all vh ∈ Vh (3.33)

The forms declarations in Rheolef corresponding to a(uh,vh) and m(gh,vh) automatically assembles the corresponding matrices, based on the given discrete space Vh. The assembly of the matrices is done as described in Section 3.5.2.2, with the stiffness matrix A corresponding to the form a(uh,vh),andthemass matrix M corresponding to the form m(gh,vh). The fields and forms in Rheolef are divided into two and four parts, respec- tively, containing unknown and blocked values of the variables. Blocked values of the field are the values on the boundary with the Dirichlet boundary condition where the field value is known. Here, for simplicity, we remove the unused parts of the test vector and the matrices. The bilinear forms a(uh,vh) and m(gh,vh) are then represented by the matrices A = A.uu A.ub (3.34) M = M.uu M.ub (3.35) and the fields u and g are represented by h h uh.u uh = (3.36) uh.b gh.u gh = (3.37) gh.b Using these matrices, the problem reduces to finding uh such that A.uu ∗ uh.u = M.uu ∗ gh.u + M.ub ∗ gh.b − A.ub ∗ uh.b (3.38) The advantage of using forms is that different equations can be modeled using the same external interface, as long as the equations can be formulated using the existing forms. If new forms are needed, the external interface must be extended so that these can be retrieved from the external Rheolef code.

3.7.2 Boundary Conditions The variational formulation and the discrete formulation of the problem change depending on the boundary conditions. In order to handle these in a general way, the discrete formulation is done externally and the size of the form matrices are calculated. This is necessary because the number of discrete points on the boundary where Dirichlet boundary conditions are used will decide the number of blocked values in the field and consequently the sizes of the form matrices as described in the previous section. Also, Neumann and Robin boundary conditions generate new terms in the variational formulation of the equation.

58 3.8 The FEMForms package

3.8 The FEMForms package

The FEMForms package uses a representation compatible with the external solver Rheolef [18], which has support for a variety of problems and boundary conditions. Figure 3.8 shows the classes in the FEMForms package. The main difference lies in the representation of the fields and the matrices as described in Section 3.7. The parts of the package that differ from the FEM package is presented in the following sections.

FieldType: DiscreteField Field +val_u: array of FieldType +value(Point): FieldType +val_b: array of FieldType +u_indices: array of Integer +b_indices: array of Integer +formsize: FormSize

Interpolation

+interpolate(): array of FieldType +interpolate_indirect(): array of FieldType DiscreteConstField +constval: FieldType +value(Point): FieldType

DiscreteDomain Domain +boundary: array of BPoint

FormSize +nu: Integer +nb: Integer

Form Mesh +uu: array[nu,nu] of Real +vertices: array of Integer[3] +ub: array[nu,nb] of Real +edges: array of Integer[3] +bu: array[nb,nu] of Real +triangles: array of Integer[4] +bb: array[nb,nb] of Real +polygon: array of Point +nu: Integer +bc: array of Integer +nb: Integer +refine: Real

Figure 3.8: Finite element specific classes adapted to the external solver Rheolef. These are defined in the FEMForms package.

3.8.1 DiscreteField The DiscreteField package represents a discretized field: package DiscreteField replaceable package fieldP = Field ; replaceable package ddomainP = DiscreteDomain ;

replaceable record Data parameter ddomainP . Data ddomain ;

59 Chapter 3 A Modelica Library for PDE-based Modeling

parameter fieldP .Data fld ; parameter FEMSolver . FormSize formsize ; parameter Integer u_indices [formsize .nu]; parameter Integer b_indices [ formsize .nb]; fieldP . FieldType val_u[ formsize .nu]( start=zeros ( formsize .nu)); fieldP . FieldType val_b[ formsize .nb];

parameter Integer fieldSize_u=size(val_u , 1); parameter Integer fieldSize_b=size(val_b , 1); end Data ; end DiscreteField ;

Here, the field values are stored in two indirect arrays, one for the unknown values and one for the known values given as boundary conditions. FormSize contains the sizes of the two arrays of discrete values, and is calculated and returned from the external solver since the sizes depend on the discretization refinement and bound- ary conditions actually used in the model. The arrays u_indices and b_indices contain the corresponding indices of the actual nodes in the mesh data structure.

3.8.2 Form

The Form data structure contains a form matrix corresponding to the matrix repre- sentation in Rheolef:

package FEMSolver record Form parameter Integer nu; parameter Integer nb; parameter Real uu [nu , nu ] ; parameter Real ub [nu , nb ] ; parameter Real bu [nb , nu ] ; parameter Real bb [nb , nb ] ; end Form ;

record FormSize parameter Integer nu; parameter Integer nb; end FormSize ; ... end FEMSolver ;

The FormSize record is provided for convenience. These structures are used con- ceptually in the PDE library, but due to software issues several matrices with native types are directly used instead of a record, as in the following models.

60 3.8 The FEMForms package

3.8.3 The Poisson Equation

The Poisson equation is defined using the forms representation as follows:

protected parameter Real A_uu[ formsize .nu, formsize .nu] = getForm_gradgrad_uu ( . . . ) ; parameter Real A_ub[ formsize .nu, formsize .nb] = getForm_gradgrad_ub ( . . . ) ; parameter Real M_uu[ formsize .nu, formsize .nu] = getForm_mass_uu ( . . . ) ; parameter Real M_ub[ formsize .nu, formsize .nb] = getForm_mass_ub ( . . . ) ; parameter Real bvals [ formsize .nb] = getBlockedValues ( . . . ) ;

equation A_uu * u . v a l _ u = M_uu * g.val_u + M_ub * g.val_b − A_ub * u.val_b; u. val_b = bvals ;

Here, the unknown and blocked parts of the A and M matrices are retrieved from the Rheolef environment using external function calls in the PDE library. The arguments to these calls also contain mesh filename, mesh size, form size, and boundary conditions, but these are left out in the code listing above in order to im- prove readability. The derivation of this equation is similar to the time-dependent version, presented in Section 3.5.2.2.

3.8.4 The Diffusion Equation

The diffusion equation is defined using the forms representation as follows:

equation M_uu * der(u.val_u) = − A_uu * u.val_u − A_ub * u.val_b + M_uu * g.val_u + M_ub * g.val_b; u. val_b = bvals ;

Here, the unknown and blocked parts of the A and M matrices are retrieved from the Rheolef environment using external function calls in the PDE library, as in the previous section. For derivation of the discrete equation, see Section 3.5.2.2.

3.8.5 PDE Library Interface

The following functions are provided in the FEMForms package to access the finite element discretization using Rheolef:

61 Chapter 3 A Modelica Library for PDE-based Modeling getFormSize: Returns the number of unknown and blocked values for a given mesh and boundary conditions. This function needs to be called in order to declare correct sizes for the matrices. ∇ ∇ getForm_gradgrad: Returns the form corresponding to Ω uh vh dx for a given mesh and boundary conditions. getForm_mass: Returns the form corresponding to Ω uhvh dx for a given mesh and boundary conditions. getMassBdr_u: Returns the form corresponding to ∂Ω hhvh dx for a given mesh and boundary conditions, where h is the right hand side of the Neumann and Robin boundary conditions. getUnknownIndices: Get the indices of the unknown values in the field. getBlockedIndices: Get the indices of the blocked values in the field. getForm: Returns a form with a given name for a given mesh and boundary conditions. The name must correspond to one of the forms supported by Rheolef, for example "grad_grad", "mass", "mass_bdr" etc. See the Rheolef User’s Manual [21] for the available forms. The following additional function can be found in the Interpolation package: interpolate_indirect: Used for generating the discrete field values for a continu- ous field using the indirect field representation.

3.9 Example

The result of the discretization of the equation, i.e., the assembly step, is a coeffi- cient matrix for the unknown field values at the discrete points of the domain. The discrete part can be completely handled by the equation model, hiding the details from the user. An example using the PDE library to solve a two-dimensional Poisson equation on the domain shown in Figure 3.9 follows here: model MyBoundaryPoissonExample import PDELib. Boundaries .* ; import PDELib . * ;

parameter Integer n=64; parameter Real refine =0.5; parameter Point p={1,1}; parameter Real w=5; parameter Real h=3; parameter Real r =2;

62 3.9 Example

4

3.5

3

2.5

2

1.5

1

1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

Figure 3.9: Discretization of MyBoundary from the example in Section 3.9, with pa- rameters from the MyBoundaryPoissonExample model.

parameter Real cw=5;

package myBoundaryP = MyBoundary ;

parameter myBoundaryP . Data mybnd ( p=p , w=w , h=h , r=r , bottom (bc=dirzero ) , right (bc=dirzero ), roundedCorner (bc=dirfive ) , top(bc=dirzero ) , left(bc=dirzero ));

package omegaP = Domain( redeclare package boundaryP=myBoundaryP ); parameter omegaP. Data omega(boundary=mybnd ) ;

parameter BoundaryCondition . Data dirzero ( bcType=BoundaryCondition . dirichlet , g=0, index=1, name="dirzero");

parameter BoundaryCondition . Data dirfive ( bcType=BoundaryCondition . dirichlet , g=5, index=2, name="dirfive");

parameter BoundaryCondition . Data bclist [:] = { dirzero , dirfive };

package PDE = PDELib.FEMForms. Equations . Poisson2D ( redeclare package domainP = omegaP );

63 Chapter 3 A Modelica Library for PDE-based Modeling

PDE.Equation pde( domain=omega , nbp=n , refine=refine , nbc=size( bclist , 1), bc=bclist ); end MyBoundaryPoissonExample ; Here, two different boundary conditions are assigned to different parts of the bound- ary. Note that since both these conditions are Dirichlet conditions with different values, the boundary values contain two jumps and thus are not continuous. Thus, the problem is unrealistic but is included for demonstration purposes. The boundary used here is defined as follows: package MyBoundary extends Boundary ;

redeclare record Data extends Boundary . Data ; parameter Point p; parameter Real w; parameter Real h; parameter Real r ; parameter Line . Data bottom ( p1=p , p2=p + {w,0} , bc( index =1)); parameter Line . Data right ( p1=p + {w,0} , p2=p + {w, h − r}, bc( index =2)); parameter Line . Data top ( p1=p + {w − r,h}, p2=p + {0 ,h} , bc( index =3)); parameter Line . Data left ( p1=p + {0 ,h} , p2=p , bc( index =4)); parameter Arc . Data roundedCorner ( c=p + {w − r,h − r}, r=r , a_start=0, a_end=Arc . pi /2 , bc( index =5)); end Data ;

parameter Composite . Data boundary( parts1 ( line=bottom , partType=PartTypeEnumC . line ) ,

64 3.9 Example

parts2 ( line=right , partType=PartTypeEnumC . line ) , parts3 ( arc=rounderCorner , partType=PartTypeEnumC . arc ) , parts4 ( line=top , partType=PartTypeEnumC . line ) , parts5 ( line=left , partType=PartTypeEnumC . line ) ) ; end Data ;

redeclare function shape input Real u; input Data d; output BPoint x; algorithm x := Composite . shape (u, d. boundary ); end shape ;

end MyBoundary ; The boundary definition contains default values for the boundary indices that are overwritten with the actual indices when the boundary is used in the particular model. The contents of the Poisson2D equation model used above is defined as follows. First, the components to be modified by the user are declared: package Poisson2D "Poisson problem 2D"

replaceable package domainP = Domain;

model Equation parameter domainP . Data domain ; parameter Real g0=1 "Constant value of rhs field "; parameter Integer nbp=20; parameter Real refine =0.7; Here, the number of discrete boundary points to generate defaults to 20, refinement parameter controlling the size and number of generated triangles to 0.7 and one boundary condition of type Dirichlet and right-hand-side value 0 is used for the entire boundary. These parameters are modified for the current model, as shown in the example above. The following code declares internal variables used by the model in their con- tinuous form, i.e. before discretization: package rhsFieldP = ConstConstField ( redeclare package domainP = domainP ); parameter rhsFieldP . Data rhsField ( domain=domain , constval=g0);

package uFieldP = Field ( redeclare package domainP = domainP );

65 Chapter 3 A Modelica Library for PDE-based Modeling

parameter uFieldP . Data uField ( domain=domain );

The right hand side field is a constant field with the value g0. Then, the discrete data structures are declared, using the continuous variables and the discretization parameters to automatically generate discrete values and variables:

package ddomainP = DiscreteDomain ( redeclare package domainP = domainP ); parameter ddomainP . Data ddomain ( domain=domain , nbp=nbp , refine=refine );

parameter FormSize formsize=getFormSize ( . . . ) ;

parameter Integer u_indices [ formsize . nu]=getUnknownIndices ( ...); parameter Integer b_indices[formsize.nb]=getBlockedIndices (...);

package rhsDFieldP = DiscreteConstField ( redeclare package fieldP = rhsFieldP , redeclare package ddomainP = ddomainP );

package interpP = Interpolation ( redeclare package dfieldP = rhsDFieldP );

parameter rhsDFieldP . Data g_rhs( ddomain=ddomain , fld=rhsField , formsize=formsize , u_indices=u_indices , b_indices=b_indices , val_u=interpP . interpolate_indirect ( rhsField , u_indices , ...) , val_b=interpP . interpolate_indirect ( rhsField , b_indices , . . . ) ) ;

package uDFieldP = DiscreteField ( redeclare package ddomainP = ddomainP , redeclare package fieldP = uFieldP );

uDFieldP . Data ud( ddomain=ddomain , fld=uField , formsize=formsize , u_indices=u_indices , b_indices=b_indices , val_u ( start ={1 for i in 1: formsize .nu}));

Several arguments to the functions calls are omitted for readability. Here, the un- known discrete field is declared with the name ud, with the unknown values val_u and their initial values given as a constant array. A future improvement is to sup- port user-defined initial values given as a constant field which is interpolated and inserted as the start values here. With all the variables declared, the matrices can be generated and the actual

66 3.10 Discussion model equation can be formulated: parameter Real A_uu[formsize .nu, formsize .nu]= getForm_gradgrad_uu ( . . . ) ; parameter Real A_ub[formsize .nu, formsize .nb]= getForm_gradgrad_ub ( . . . ) ; parameter Real M_uu[formsize .nu, formsize .nu]= getForm_mass_uu ( . . . ) ; parameter Real M_ub[formsize .nu, formsize .nb]= getForm_mass_ub ( . . . ) ; parameter Real bvals [ formsize .nb]=getBlockedValues ( . . . ) ; parameter Real bdr_u_vals [ formsize .nu]=getMassBdr_u ( ...);

equation A_uu * ud . val_u = bdr_u_vals + M_uu* g_rhs . val_u + M_ub* g_rhs . val_b − A_ub*ud . val_b ; ud. val_b = bvals ; // known boundary values end Equation ; end Poisson2D ; Again, arguments to functions are omitted for readability. These contain mesh file- name, mesh size, form size and boundary conditions. The variable bdr_u_vals contains the boundary integral contribution to the right hand side from the Neu- ( )= mann and Robin boundary conditions, i.e., from the form mb h, v ∂Ω hhvh dx. Since external functions cannot have stored state information, these must be passed with each function. Future versions may optimize this interface using e.g. external objects, when external data access support in Modelica is improved. The simula- tion results of this example can be seen in Section 6.1.

3.10 Discussion

The PDE library presented here contains a set of packages for easily defining gen- eral domains over which the predefined PDE models from the library can be solved. New boundaries are easy to define using and combining existing boundaries as components, as shown in Section 3.9. Additional standard boundaries can also be added to the Boundaries package for future use. A similar sub-package contain- ing standard domains can be created as well, since declaration of domains using specific boundary packages can be done independently of actual user-defined do- main information. The problem of expressing a partial differential equation in Modelica is solved without language extensions, although restricted to discrete formulation. A number of predefined PDE equation models are provided, with corresponding equations in discrete form. These can be used with user-defined domains, parameters and discretization detail and user-selected boundary conditions. This approach leaves

67 Chapter 3 A Modelica Library for PDE-based Modeling the responsibility of the discretization of the model to the library developer. The advantage is that the model developer has knowledge about the appropriate dis- cretization and the solver needed for solving that specific model. The disadvantage is that some flexibility is lost because only predefined models can be used.

68 Chapter 4 Language Elements for Space-distributed Models

“If the facts don’t fit the theory, change the facts.” Albert Einstein

This chapter describes new language constructs for the Modelica language by introducing the design concepts shown in Chapter 3 at the language level, thereby allowing the specification of general continuous PDE problems in Modelica, inde- pendent of discretization.

4.1 Introduction

In Chapter 3, a design for a PDE library in Modelica was presented. The library is designed as two-levels, a continuous part and a discrete part, in order to sepa- rate discretization details from the actual models. This chapter describes language constructs to also enable this approach at the language level. Language support for continuous description of PDE models simplifies both reading and writing of mod- els, improves reusability, and decreases the dependency between the model and the solution method. The basic concepts from the PDE library that are introduced here are field vari- ables, domains,andboundaries. Additionally, language elements for derivative operators and examples of functions for differential operators using vector nota- tion are presented.

69 Chapter 4 Language Elements for Space-distributed Models

4.2 Fields

Quantities with spatial distribution are usually represented using arrays in program- ming languages as well as in modeling and simulation languages such as Modelica. In such cases, the variable is discretized during formulation of the model. In order to declare the model before doing any discretization, a new kind of type is needed in Modelica, called a field type. A field is a mapping from points in a domain (i.e., a geometrical region) to values. In mathematical software the domain is usu- ally discretized and the field is an array of values for each of the discrete points. In order to separate discretization of a model from the model declaration, fields in Modelica should be defined over continuous domains.

4.2.1 Field Variables Type specification in variable declarations in Modelica can contain attributes such as parameter, flow, etc., as seen in the example in the introduction. The type attributes are used to declare different kinds of variables with respect to variability, signal direction, etc. Using the keyword field to specify fields allows declaration of fields with any existing type. The syntax is as follows:

"field" Type fieldvar ";"

Here, Type can be any of the built-in types or user-defined types derived from the built-in types. For example: field Temperature T; Temperature can be defined as follows: type Temperature = Real ( unit="K" ); When declaring a field variable, the definition domain must be specified as well. In Modelica, built-in types have attributes such as unit, start, etc., which can be modified in declarations or new type definitions. A new built-in attribute domain in the Real type can be used to give the definition domain of a field variable using modifications. Modifications in Modelica are hierarchical parenthesized lists of name=value equations in declarations. For instance, a modification is used in the definition of the Temperature type above, for changing the unit attribute of the built-in type Real to the unit value that holds for temperature. The declaration of T above with a domain modification looks like this: RectangularDomain omega ( . . . ) ; field Temperature T( domain=omega ); Here, a domain of type RectangularDomain is used. An approach for domain definitions in Modelica is further described in Section 4.3.1.1.

70 4.2 Fields

4.2.2 Field Constructor In order to initialize field variables or define constant fields, literal field values must be possible to express in the language. A field constructor is an expression which generates a field value over a given domain using a given expression. The syntax for the field constructor is:

"field""(" expr1 "for" iter "in" expr2 ")"

Here, iter is a single iterator variable or a list of iterator variables enclosed in parenthesis. The iterator variables represent the coordinates in the coordinate space where the domain is defined. For example, for a two-dimensional domain, two iterator variables are needed, e.g.:

TestDomain omega(...); field Real f = field(2* x+y for (x,y) in omega ) ; The iterator variables are defined only in the local scope, e.g. they are only avail- able in the field constructor expression. Variables in the outer scope with the same names as the iterator variables are shadowed. The first expression expr1 is the expression for calculating the field values. Given a point in the domain, the value of the field at that point is the value of expr1.The iterator variables can be used in expr1 to define fields with spatial dependency. The second expression expr2 should evaluate to a domain object. Currently, this can only be a reference to a previously declared domain object. In future implementations, domain constructor expressions may be considered as well. This approach is similar to the existing array constructor syntax in the current Modelica language, where the keyword array is used instead of field. Array constructors in Modelica also have a shorter syntactic form:

"{" expr1 "for" iter "in" expr2 "}"

A corresponding short form for field constructors was considered, but using curly braces in both cases makes the semantics ambiguous and requires type checking of expr2 to determine whether the expression is an array or a field constructor. Other characters than curly braces might be considered for the short form of the field constructor.

4.2.3 Field Type in Expressions When field variables appear in expressions, the type of the expressions must be de- rived appropriately. Mixing of field variables and scalar variables must be handled, as well as field variables with different definition domains.

71 Chapter 4 Language Elements for Space-distributed Models

4.2.3.1 Binary Operators For mixing of scalars and fields, some of the binary operators can be overloaded in a similar way as for vectors and matrices in Modelica. Table 4.1 shows the binary operators in Modelica which are overloaded to handle operations between scalars and arrays. Similar overloading can be done for operations between scalars and fields.

Table 4.1: Array operations in Modelica Operand 1 Operand 2 Result =, := Array[m,n] Array[m,n] Array[m,n] +, - Array[m,n] Array[m,n] Array[m,n] * Scalar Array[m,n] Array[m,n] Array[m,n] Scalar Array[m,n] Array[m,n] Array[n,p] Array[m,p] / Scalar Array[m,n] Array[m,n] Array[m,n] Scalar Array[m,n]

The element-wise array operations require the sizes and dimensions of the op- erand arrays to be equal. Correspondingly, element-wise field operations should require the domains of the operands to be equal. Table 4.2 summarizes some bi- nary operators and their result types when used with fields or scalars and fields.

Table 4.2: Overloading of binary operators for fields Operand 1 Operand 2 Result = Scalar Field (on Ω) Field (on Ω) Field (on Ω) Scalar Field (on Ω) Field (on Ω) Field (on Ω) Field (on Ω) := Field (on Ω) Scalar Field (on Ω) Field (on Ω) Field (on Ω) Field (on Ω) +, - Scalar Field (on Ω) Field (on Ω) Field (on Ω) Scalar Field (on Ω) Field (on Ω) Field (on Ω) Field (on Ω) *, / Scalar Field (on Ω) Field (on Ω) Field (on Ω) Scalar Field (on Ω) Field (on Ω) Field (on Ω) Field (on Ω)

Although addition and subtraction of scalars and arrays is currently not directly supported by overloaded operations in Modelica, this can easily be arranged for fields and scalars. Addition or subtraction of a scalar with a field can be seen as changing the value of the field with a constant offset.

72 4.2 Fields

4.2.3.2 Special Operators

The built-in special operators in Modelica should be overloaded to handle fields as well. For example, the der() operator applied to v, i.e., der(v), represents the derivative of the variable v.Ifv is a field, the result of the operation should be a field with the same domain as v and where the resulting field is the derivative of the field v. The same applies to the overloaded derivative operator for partial deriva- tives, der(u ,...) , which has a field as its first argument, and spatial coordinates as the following arguments with respect to which the derivation is defined, in the given order. This operator should check for the first argument for type information, and keep the domain of the given field variable. For example, the time-derivative operator der(v) can be defined for a field argu- ment on a one dimensional domain using a field constructor:

der (v) = field( der (v(x)) for x in v . domain );

Here, v(x) is a field access operation with a time-dependent scalar variable as its type, as described in the following section, and der(v(x)) is the time derivative of the scalar variable according to standard Modelica.

4.2.4 Accessing Field Values

Values of the field on singular points in the domain can be accessed using the function-call like syntax:

fieldvar "(" expr [,expr ...] ")"

Here, fieldvar is a reference to a field variable, and the list of expressions is the coordinates in the domain of the field variable. The number of expressions given here should be equal to the domain dimension. For example:

model TempField field Temperature T( domain=omega ); Temperature t_interior ; equation t_interior = T(1.4 , 1.7); end TempField ;

Here omega is a two dimensional domain, and the equation states that the scalar variable t_interior is equal to the value of the field T at the coordinates (1.4, 1.7) in the domain.

73 Chapter 4 Language Elements for Space-distributed Models

4.3 Future Language Extensions

In this section, preliminary design for future language extensions is presented. These extensions have not yet been implemented and tested in the prototypes. Sev- eral design alternatives are sketched for some of the extensions. Prototype im- plementation and further evaluation of these alternatives are necessary to find a adequate final design.

4.3.1 Domain Geometry Definition The approach taken for domain geometry definition in the PDE library can be used for defining domains on a language primitive level as well. The approach in the PDE library is to define a domain implicitly by describing its boundary as a para- metric curve with a direction. For this, a shape function with an input parameter for the position on the curve is used, with coordinates of the point on the curve as output from the function. Here, as well as in the library, we need to define complex boundaries consisting of a number of simple boundaries, which can be referred to by names when as- signing boundary conditions. Thus, besides the built-in type for domains, a built-in type for boundaries are needed.

4.3.1.1 Domain Type The Domain type is an extension needed in the Modelica language needed for representation of definition domains. A separately declared domain object must be specified when declaring a field variable, in order to define its definition domain. The domain type needs to be built-in because it requires special handling. Do- mains must be handled as a built-in type so that type checking can be done when different fields are used together. During discretization, the compiler and the sim- ulation environment need to find domain definitions and coordinate mappings etc. This can be achieved by defining a built-in type with predefined components rep- resenting necessary information. A domain built-in type can be defined in the language specification similar to other built-in types, such as the Real type. For example: type Domain parameter Integer ndims =1; parameter Real cartesian[ndims]; parameter Real coord [ndims]= cartesian ; parameter Boundary boundary [:]; end Domain ; This built-in type can be used directly to declare domains, or it can be used as a base class to declare other standard domain types. Cartesian coordinates are used

74 4.3 Future Language Extensions by default, i.e., the elements of the coord array represent coordinates of an n- dimensional cartesian coordinate system. Here, the coord array is a placeholder for arbitrary curvilinear coordinates [22], while the cartesian array always repre- sents cartesian coordinates. This representation is useful for specifying mappings to other coordinate systems, as shown in Section 4.3.1.3. Using an array for the coordinates simplifies handling of an arbitrary number of dimensions. For convenience and readability, aliases can be defined for the coordinate vari- ables. For example, a two-dimensional cartesian coordinate system can be declared as follows, using the aliases x and y:

type Cartesian2D extends Domain( ndims =2); parameter Real x=coord [1]; // alias for first coordinate parameter Real y=coord [2]; // alias for second coordinate end Cartesian2D ;

Since no mapping for the coordinates is specified, the default mapping to carte- sian coordinates will be used. The aliases can be used when expressing partial derivatives, as discussed in Section 4.3.2.1. Using these domain types as base, a domain can be declared as follows:

type RectangularDomain extends Cartesian2D ( boundary={left , bottom , right , top }); parameter Point p; parameter Real w; parameter Real h;

parameter Point p2 = Point(p.x+w, p.y); parameter Point p3 = Point(p.x+w, p.y+h); parameter Point p4 = Point(p, p.y+h);

parameter Line bottom=Line(p,p2 ); parameter Line right=Line(p2 ,p3 ); parameter Line top=Line(p3 ,p4 ); parameter Line left=Line(p4 ,p); end RectangularDomain ;

Here, the parameters p, w and h can be modified to set the position and size of the domain. The boundaries used here can be defined as shown in Section 4.3.1.2. Note that the boundary arraydefinedintheDomain type has the type Boundary,but is assigned components of subtypes of Boundary. Modelica requires the types to be equivalent when modifying parameters. Thus, the built-in boundary compo- nent needs special handling unless the type is made replaceable which complicates the use and does not solve the problem of heterogeneous arrays anyway. A possible future solution is introducing union types in Modelica and allowing subtyping of array elements.

75 Chapter 4 Language Elements for Space-distributed Models

4.3.1.2 Boundary Type The built-in Boundary type is similar to the Domain type, except that here, the mapping for different coordinate systems is not needed. A boundary will use the mapping of the domain that it will be part of. In other words, boundaries can be seen as functions with parameters as input arguments and coordinates as output arguments, independent of the coordinate system. The built-in Boundary type can be defined as follows: type Boundary parameter Integer ndims =1; parameter Real coord [ndims ];

replaceable function shape input Real u[ndims −1]; // u[i] in [0,1) output Real coord [ndims ]; end shape ; end Boundary ; This built-in type can be extended to declare standard boundary components. For example a Line boundary type used in the example shown previously can be declared as: class Line extends Boundary ( ndims =2);

parameter Point p1; parameter Point p2;

redeclare function shape input Real u[1]; output Real coord [2]; algorithm coord := p1 + u*(p2−p1 ) ; end shape ; end Line ; Note that parameters declared in the Line class are used in the shape function, i.e. the shape function is a member function 1 in the class. This is currently not supported in Modelica, but it is the author’s belief that support for member functions is required for an object-oriented design. The necessary changes in the language to support this design is discussed in Section 4.3.5. A similar approach with less changes to the language syntax is to explicitly pass the class instance: class Line ... redeclare function shape

1Functions in Modelica are pure, i.e., they cannot have side effects. Hence, the concept of member functions here means functions with read-only access to the object, i.e., always with a constant self reference.

76 4.3 Future Language Extensions

input Line this ; input Real u [1]; output Real coord [2]; algorithm coord := this . p1 + u*(this.p2−this .p1); end shape ; end Line ; Line here can be a general class or restricted to be only a record.Themain idea is to have the function inside the data structure which also is the first argument to that function. Records are currently allowed as function arguments. A general class can be allowed as an argument to a function because of the read-only seman- tics, e.g. input arguments cannot be modified in the function. Thus, the function cannot have side-effects. If the class is restricted to be a record functions must be allowed as members in records. In either way, this approach does not need any language modifications concerning lookup. The only language modification is to remove the restriction that only functions inside packages can be called from outside that package.

4.3.1.3 Coordinate Systems Using the domain definition approach above, domains in coordinate systems other than cartesian can be declared easily. For example, a two-dimensional polar coor- dinate system can be declared as follows: class Polar2D extends Domain( ndims =2); Real r =coord [1]; // alias for first coordinate Real phi=coord [2]; // alias for second coordinate equation cartesian [1] = r* cos( phi ); cartesian [2] = r* sin ( phi ); end Polar2D ; Alternatively, using modifiers for the alias equalities, and the inverse mapping for the coordinates2: class Polar2D extends Domain(ndims=2,coord={r, phi }); Real r ; Real phi ; equation r =sqrt(cartesian [1]^2 + cartesian [2]^2); phi = atan( cartesian [2]/ cartesian [1]); end Polar2D ; Here, the relationship between the polar and the cartesian coordinates is declared as equations. This mapping is needed for generation of the discrete domain. The map-

2One of the mappings can be chosen depending on which one is more convenient to implement.

77 Chapter 4 Language Elements for Space-distributed Models ping is also needed for the differential operators, but finding corresponding deriva- tives from the mappings require some symbolic processing. See Section 4.3.2 for further discussion regarding differential operators.

4.3.2 Differential Operators In this section, built-in operators are presented, which are needed in the Modelica language for representation of differential operators. Also, example implementa- tions of differential operators using vector notation are shown.

4.3.2.1 Partial derivatives The current version of the Modelica Specification [1] allows declaration of partial derivatives using a short class definition:

IDENT "=" der "(" name "," IDENT ["," IDENT ...] ")" comment

Here, the IDENT arguments in the der operator are required to be Real inputs to the function with name name, and only functions are allowed to be declared this way. The syntax can be reused for the partial derivative operator for general field variables and expressions:

der "(" expr "," IDENT ["," IDENT ...] ")"

The requirement should be that expr is of a field type and the IDENT arguments are Real parameters declared in the domain of that field type. The parameters can be aliases or the actual coord components. For completeness, the coord com- ponents themselves should be allowed as parameters. The advantage of allowing these is also that coordinate system independent functions like divergence and gradient can be written without using coordinate aliases and without knowledge about the dimension of the coordinate system, as seen in Section 4.3.2.3.

4.3.2.2 Normal derivative The normal derivative is a directional derivative that occurs as boundary conditions in PDEs. It is the derivative of a field in the outward normal direction on the boundary of the domain of the field. In order to avoid new operators, and for consistency with the der operator for regular partial derivatives, the der operator can be reused with the special built-in identifier n, added to the built-in domain type: type Domain ... parameter Real [ndims] n;

78 4.3 Future Language Extensions

... end Domain ; Here, n represents a outward normal vector on the boundary. The contents of the variables will not be meaningful during translation, because the declaration is merely a implementation detail to handle the der operator with the regular lookup rules. Hence, the implementation of the translator and the solver will handle the combination of the der operator and the n variable specially, and automatically in- terpret it as the outward normal vector. The normal derivative can now be expressed as follows: model Test ... TestDomain omega; field Real u( domain=omega ); ... equation der(u, n) = 0 in omega. boundary ; end Domain ; Again, the compiler and simulation environment must handle the n parameter in the built-in type Domain especially. The lookup and syntax is consistent with the rest of the language specification though.

4.3.2.3 Vector notation In order to simplify implementation, general differential operators for curvilinear coordinates [22] can be defined using vector notation and scale factors [23]. This approach is similar to the design used in the Ctadel Tool [24,25]. The advantage of vector notation is that the equations can be written independently of the coordinate system. The scale factors can be included in the domain type: type Domain ... RealType scale [ ndims]=ones ( ndims ); ... end Domain ; Note that the scale factors can contain references to the space variables. Hence, they are functions of the spatial variables rather than constaints. The default scale factors are 1 for each coordinate, corresponding to cartesian coordinates. The ex- ample with the polar coordinate system can be extended with scale factor defini- tions: class Polar2D extends Domain( ndims=2, coord={r , phi } , scale {1 , r }); Real r ; Real phi ; equation

79 Chapter 4 Language Elements for Space-distributed Models

r = sqrt( cartesian [1]^2 + cartesian [2]^2); phi = if (cartesian[2] ==0 and cartesian [1] == 0) then 0 else atan2 ( cartesian [2] , cartesian [1]); end Polar2D ;

The differential operators can be defined in a general way [26] using scale fac- tors. Scale factors can be interpreted as the scaling of the derivative operators when changing to another coordinate system.

Gradient The gradient operator operates on scalar fields and results in a vector field with the same number of elements as the dimension of the coordinate system. In two dimensions and for general curvilinear coordinates, the gradient is defined as: 1 ∂(u) 1 ∂(u) ∇u = grad u(x1,x2)= h1 ∂x1 h2 ∂x2

The three dimensional gradient is similar: 1 ∂(u) 1 ∂(u) 1 ∂(u) ∇u = grad u(x1,x2,x3)= h1 ∂x1 h2 ∂x2 h3 ∂x3

A PDEModelica gradient function is straightforward to write using field variables and the derivative operator defined in Section 4.3.2.1:

function gradient input field Real u; output field Real du[u . domain . ndims ]; algorithm for i in 1:u . domain . ndims loop du [ i ] := der (u, coord [ i ]) / scale [ i ]; end for ; end gradient ;

Divergence

The divergence operator operates on a vector field and results in a scalar field. The two and three dimensional mathematical expressions for the divergence operator in arbitrary orthogonal curvilinear coordinates follows: 1 ∂(h2u1) ∂(h1u2) ∇·u = div u(x1,x2)= + h1h2 ∂x1 ∂x2

80 4.3 Future Language Extensions

∇· = ( ) u div u x1,x2,x3 1 ( ) ( ) ( ) = ∂ h2h3u1 + ∂ h1h3u2 + ∂ h1h2u3 h1h2h3 ∂x1 ∂x2 ∂x3

A corresponding PDEModelica function handling a general number of dimen- sions can be defined as follows: function divergence input field Real u [:]; output field Real du[u . domain . ndims ]; protected Real s ; algorithm assert ( size (u ,1) == u . domain . ndims ); for i in 1:u . domain . ndims loop s:=1; for j in 1:u . domain . ndims loop if (i != j) then s:=s* u . domain . scale [ j ]; end i f ; end for ; du := du + der (s*u , coord [ i ]); end for ; s:=1; for j in 1:u . domain . ndims loop s:=s* u . domain . scale [ j ]; end for ; du := du / s ; end divergence ; Note that the calculations in the algorithm section might need symbolic processing, depending on the implementation of the discretization module.

4.3.3 Domain Specifier in Equations The equation and assignment operators can have an optional domain specifier using the in keyword, which is needed when defining boundary conditions. The syntax for equation and assignment with an explicit domain is:

expr1 "=" expr2 "in" expr3; cref ":=" expr2 "in" expr3;

Here, expr3 is a domain object, which can currently only be a reference to a previ- ously declared domain. An equation with a domain specifier can look like this: model Test TestDomain omega(...);

81 Chapter 4 Language Elements for Space-distributed Models

field Real f ( domain=omega ); parameter Real q; equation f=qin omega. boundary ; end Test ; The fields appearing in the expression should still have compatible definition do- mains. The explicit domain attribute should then be a subset of the domain of the fields appearing in the expression. Possibly, this requirement can be relaxed, to only requiring that the explicit domain must be a subset of all appearing fields, which may have different domains with at least the same subset as the explicit domain. An optional extension is to also allow the keyword on for use with domain ob- jects that represent boundaries, as it is used in mathematical literature when refer- ring to boundaries e.g. in boundary conditions.

4.3.4 Field Reduction Integrals appear in equations in many modeling situations. In order to express in- tegrals of fields over spatial variables, an integral operator is needed. This can be seen as a field reduction operator. Reduction expressions for arrays are already supported for some operations in Modelica. Hence, the syntax for the integral op- erator should be similar to the existing syntax:

"integral""(" expr1 "for" iter "in" expr2 ")"

Here, iter is a list of local variables representing coordinates in the domain given in expr2. The result of the integral operation is a scalar. Optionally, single integration can be supported, i.e., integrating over fewer spatial variables than the dimension of the domain, resulting in a field with a smaller dimension. For example, an equation between a scalar variable and the boundary of a two- dimensional region can be written as follows: model ReductionExample RectangularDomain omega; field Real T(domain = omega ); Real T_heater ; ... equation T_heater = integral (T(x,y) for (x,y) in omega . l e f t ) / omega. left . length ; ... end ReductionExample; Note that the length component of the boundary is an additional future extension, needed to calculate the mean temperature. This can be manually set or automati- cally calculated, or explicitly expressed using a new operator, e.g., length().

82 4.3 Future Language Extensions

Alternatively, if explicit naming of coordinates is to be avoided, the following syntax can be used:

"integral""(" expr1, expr2 ")"

Here, the order of the parameters could be changed to reflect mathematical nota- tion, with the domain given first and the expression given second. The equation in the above example becomes: equation T_heater = integral (omega.left , T) / omega.left.length;

4.3.5 Discussion There are three major language extensions proposed in this chapter. The field type prefix to represent continuous fields, the Domain built-in type to represent definition domains of fields and the Boundary built-in type to declare boundaries needed to define domains. The field type is an essential language concept. Field variables are natural ele- ments in PDE-based models, as well as Real variables are in ODE-based models. Support for fields at the language level is a natural language extension to Modelica to support PDE-models. The need for the Domain and Boundary built-in types are not as obvious. Do- mains of fields must be declared somehow. The approach with packages used in the PDE library described in Chapter 3 illuminates the problem with lack of member functions in the Modelica language. The solution proposed here should be seen as a first step towards a more general language design where member functions are supported. A problem with member functions, or class methods as an object-oriented lan- guage concept is that the Modelica language is declarative and functions in Mod- elica are pure, i.e., side-effect free. Methods usually operate on and modify the object they are called on, which create many problems in a declarative language like Modelica, regarding semantics and symbolic manipulation of equations. How- ever, side-effects are not essential for PDE modeling as described in this work. Rather, the following features are needed for a convenient design:

• Polymorphism, i.e. to be able to call a particular function on a set of objects of different subtypes without knowing their particular type. For example, the shape function on a list of Boundary objects.

• Lookup in instance hierarchy, i.e. automatic access to data in a particular class instance for a function. For pure, side-effect free functions, access can be restricted to read-only.

83 Chapter 4 Language Elements for Space-distributed Models

These features would simplify object-oriented design in all Modelica models. Here, they are needed for a user-friendly design support in the language. One other problem is the lack of polymorphic references in Modelica, i.e. it is not possible to declare an array of Boundary object references where each reference not necessarily have the same subtype. This restriction also calls for a special handling of the boundary component in the Domain built-in type.

84 Chapter 5 Implementation

“You’re suffering from a Vulcan Mind Meld, Doctor.” Captain Kirk

This chapter contains implementation details about the two prototypes that were developed for testing the design described earlier. The language extensions de- scribed in Chapter 4 have been implemented as an extension to an earlier version of the OpenModelica Compiler (omc) [27]. In Section 5.1, a short overview of the OpenModelica Compiler is given, with PDEModelica extensions in separate sections in each part of the compiler. The PDE library that implements mainly same ideas but without any language extensions that was described in Chapter 3, is handled in Section 5.2. Finally, the solver environment, mainly used with the PDE library, is described in Section 5.3.

5.1 Modelica Compiler

The Modelica compiler consists of several parts. The first step is the lexer and the parser that reads textual Modelica code and generates an abstract syntax tree (AST). Next, a generated compiler (generated from semantics specification) traverses the AST and translates the models into a flat set of differential and algebraic equations and possibly a set of functions and algorithm sections. A numerical solver is then used to simulate the model by solving the total system of equations at different time steps. The different steps of the translation process and the tools used can be seen in Figure 5.1. The parser and the translator are described in more detail in the following sec- tions. The implementation of the language extensions presented in Chapter 4 is

85 Chapter 5 Implementation

Module Tool

Scanner and parser ANTLR Lexer and Parser

Abstract syntax tree in ANTLR

Absyn tree builder ANTLR Tree Walker

Abstract syntax tree in RML

Translator RML

DAE-list in-RML

Figure 5.1: The different steps of the translation process, the tools used and the intermediate results. described at the end of each section. In the current prototype implementation, the only extensions are the field type and related operators as described in Sec- tion 4.2. Different modules of this prototype including field extensions is shown in Figure 5.2.

User input PDEomc

PDEModelica Parser

Translator

Flattened Field functions PDEModelica

Figure 5.2: Overview of the PDEModelica Compiler prototype.

5.1.1 Modelica Parser The Modelica lexer and parser are implemented using ANTLR [28], a transla- tor generator with special meta-languages for grammar specifications. The lexer grammar specification consists of definition of the tokens, special characters and comments. The reserved keywords of the language are listed in a tokens sec- tion: tokens { ...

86 5.1 Modelica Compiler

CLASS = "class" ; CONNECT = "connect " ; CONNECTOR = "connector " ; ... } Operators, special characters, comments and literals are defined using rules. Each rule consists of a name, a definition, and optionally actions to be performed when the rule is matched. The syntax for a rule is: rule_name : alternative_1 | alternative_2 ... | alternative_n ; Each alternative contains a rule that is checked for a match. Table 5.1 lists some of the symbols used in ANTLR rules.

Table 5.1: Some symbols in ANTLR used in rules, consisting of regular expres- sions. Symbol Description (...) Subrule (...)* Closure subrule (repeat zero or more times) (...)+ Positive closure subrule (repeat one or more times) (...)? Optional {...} Semantic action | Alternative operator .. Range operator . Wildcard

Rules are also used in the parser, but instead of characters a stream of tokens is the input that is being parsed, and a parse tree is automatically generated. ANTLR also supports the implementation of tree walkers using a meta-language similar to the lexer and parser definition meta-languages. Tree walkers can be used to traverse a syntax tree built by the parser and perform some actions or transfor- mations on the tree. A tree walker is used in the OpenModelica compiler to go through the parse tree and build the corresponding abstract syntax tree used by the translator.

5.1.1.1 PDEModelica Extensions Currently, the only language extension in the PDEModelica prototype is the field type prefix. A keyword is added to the Modelica lexer and a new token FIELD is

87 Chapter 5 Implementation added to the Modelica parser. The tree node type FIELD_FUNCTION_CALL is added for the representation in the abstract syntax tree. In order to support the field type prefix, FIELD is added as an optional token in the type_prefix rule in the grammar:

type_prefix : (FLOW)? ( DISCRETE | PARAMETER | CONSTANT ) ? ( INPUT | OUTPUT )? ( FIELD )? ;

For initialization of field variables or definition of constant fields to use in ex- pressions, the field constructor was defined in Section 4.2. The support for array constructors is already implemented in the parser, where for-iterators are used in the array()-operator. Parsing of the field constructor is similar, except that the iterator variables can be a parenthesized list instead of single variables. This is implemented by the following addition to the grammar:

for_indices_field : ( IDENT | LPAR^ IDENT (COMMA! IDENT)* RPAR ! ) ( IN^ expression )? ; ...

for_or_expression_list : ( { LA( 1 ) = = IDENT && LA ( 2 ) == EQUALS | | LA ( 1 ) == RPAR } ? |( e: expression ( COMMA! explist : for_or_expression_list2 | FOR^ forind : for_indices | FOR^ forindf : for_indices_field )? ) ) ;

5.1.2 Modelica Translator

A tree walker written in ANTLR traverses the parse tree generated by the parser and creates the abstract syntax tree (AST) as declared in the Absyn RML module. The tree is subsequently processed further by the Modelica translator described in the following sections, starting with an introduction to RML used as the specification language for the translator.

88 5.1 Modelica Compiler

5.1.2.1 RML RML (Relational Meta Language) [29, 30] is a meta language for formal specifi- cation of language semantics using Natural Semantics [31]. A translator for the language described in RML is automatically generated using the rml2c compiler, which generates efficient C code that is compiled into an executable. Specifications in Natural Semantics are expressed using inference rules similar to natural deduction used in logics. Inference rules with the same input and output formal parameters can be grouped into signatures. Each rule is defined by a set of propositions called premises and a proposition called conclusion. A proposition is proved by applying a rule with a conclusion that can be instantiated to that propo- sition, and the premises of that rule are proven similarly. An inference rule with the premises p1..pn and the conclusion p is written

p1 ∧ p2 ∧···∧pn p

In RML, signatures are defined using relations. Each relation consist of a set of rules. Rules contain propositions consisting of relation invocation with arguments andresultsseparatedbythe=> symbol. The premises and the conclusion are separated by a line with two or more consecutive dashes, see Figure 5.3. The syntax is otherwise similar to that of Standard ML [32]. An example relation can be seen in Figure 5.3. The first part of an RML specification file contains the data type declarations and relation declarations that are visible to other modules. The module exprmod in Figure 5.3 contains one data type, Exp, that can be either an integer constant or an addition operation with two subexpressions. Integer numbers are represented by the primitive type int. The only relation in this module is called eval,which evaluates the value of an expression with the integer value as the result. Rules without premises are called axioms, as in the first rule of the eval rela- tion, which returns the value of an integer constant. The second rule handles the addition operations by first evaluating the subexpressions and adding their values using the built-in RML operator int_add. The result of the rule is then the result of that addition.

5.1.2.2 Modelica Translator Specified in RML A partial semantic specification of an early version of Modelica was initially devel- oped by David Kågedal [33,34] in RML, and has later been substantially expanded and improved. This specification describes the static semantics of the Modelica language, i.e., the interpretation of the object-oriented structure, typing, and dec- larations defined in the models. The dynamic semantics involving the run-time simulation of the models is not included. Hence, this specification describes the

89 Chapter 5 Implementation

module exprmod : datatype Exp = INTCONST of int | OP_ADD of Exp * Exp relation eval : Exp => int end

relation eval : Exp => int =

axiom eval INTCONST(v) => v

rule eval (e1) => v1 & eval (e2) => v2 & int_add (v1, v2) => v3 −−−−−−−−−−−−−−−−−−−−− eval (OP_ADD (e1 , e2)) => v3 ... end

Figure 5.3: Example of an RML specification. The first part contains the data type definitions and the module interface definition. The second part con- tains the relations. int is the built-in integer type, and int_add is the built-in integer addition operator. translation of Modelica models with structural and compositional information into a flat list of equations. The translator specification is divided into several modules. The Absyn module contains the representation of the abstract syntax tree, with data types that represent classes, variable declarations, equations, algorithms, expressions, and statements. The Absyn representation is close to the source representation of the Modelica code, i.e., the source can be recreated from the abstract syntax. From the abstract syntax tree the SCode intermediate tree is generated. This tree is defined in the SCode module. The SCode tree is a canonical representation of the Modelica code for more convenient translation. For example, the Modelica code and consequently the abstract syntax tree can contain multiple equation sec- tions, depending on how the code was entered. In the SCode representation the equation sections are merged into one list of equations that is semantically equiva- lent and makes further processing simpler. From the SCode representation, the appropriate Modelica class is symbolically instantiated by the Inst module. The result of the symbolic instantiation is the DAE representation defined in the DAE module, which contains the resulting func- tions and a flat set of equations and algorithms resulting from the translation. Sym- bolic instantiation of a Modelica class means: • Retrieving the class definition of the extended classes if there are any ex-

90 5.1 Modelica Compiler

tends clauses and inserting their contents into the current model.

• Retrieving the class definition of the declared class of each component in the model.

• Symbolically instantiating their contents with the current component name prefix to avoid name clashes.

• Applying the modifications and inserting their contents into the current mod- el. • Building connections sets and generating equations from these.

• Merging the equations from the symbolically instantiated subcomponents updated with the new component names.

During the symbolic instantiation, some type checking and constant expression evaluation is also performed. Type checking also includes checking whether the subtype relationship holds between Modelica classes. Figure 5.4 shows the RML relation that checks subtyping and type equivalence as defined in Section 2.1.3.

5.1.2.3 PDEModelica Extensions The extensions to the translator for PDEModelica support are those related to fields. A new element attribute is introduced in the AST to represent whether a component is a field or not:

datatype ElementAttributes = ATTR of bool (* flow *) * Variability (* parameter *) * Direction (* input / output *) * ArrayDim * Field (* pdeomc *)

datatype F i e l d = FIELD | NON_FIELD The walker used to generate the AST is modified correspondingly to create field nodes. A similar representation is added in the SCode module. Internally, the otherkeyfield prefix together with the component type is used to construct a field type. The field type is represented in the Types module as follows:

datatype Type = T_INTEGER of Var list |T_REALof Var list |T_STRINGof Var list | T_BOOL of Var list | T_ENUM | T_ENUMERATION of string list * Var list | T_ARRAY of ArrayDim * Type | T_COMPLEX of ClassInf . State * Var list

91 Chapter 5 Implementation

relation subtype : (Type , Type) => bool =

axiom s ubtype (T_INTEGER , T_INTEGER) => true axiom subtype (T_REAL,T_REAL) => true axiom subtype (T_STRING,T_STRING) => true axiom subtype (T_BOOL,T_BOOL) => true

...

rule subtype_varlist (el1 , el2) => true −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− s u b t y p e (T_COMPLEX( s t 1 , e l 1 ) , T_COMPLEX( s t 2 , e l 2 ) ) => true

axiom subtype (t1 , t2 ) => false

end

relation equivtypes : (Type , Type) => bool =

rule subtype (t1 , t2 ) => true & subtype (t2 , t1 ) => true −−−−−−−−−−−−−−−−−−−−−−− equivtypes (t1 , t2 ) => true

axiom equivtypes (t1 , t2 ) => false

end

Figure 5.4: The RML relations that check subtyping and type equivalence between to Modelica classes. Subtyping rules regarding arrays and tuples are not shown. The relation subtype_varlist calls the subtype relation for the declared types of each pair of variables in the given variable lists.

92 5.1 Modelica Compiler

| T_FUNCTION of FuncArg list * Type |T_TUPLEof Type list | T_FIELD of Type * Domain (* pdemodeq *) | T_NOTYPE

datatype D o m ain = DOMAIN of Exp . Exp | NO_DOMAIN

The domain type is used to represent domain information for a field variable. NO_DOMAIN is used before any domain is assigned to a variable. The DOMAIN type contains an expression which can be a component reference to a declared do- main component. A general expression is used in order to allow future extensions where a domain constructor can be used directly. During instantiation, the component declaration is checked for the existence of the field prefix, and if it is, the field type is constructed using the domain modifi- cation from the component declaration:

relation fix_field_type : ( Types .Mod, SCode . Attributes , Types . Type) => Types . Type =

rule is_field attr => true & Mod.lookup_comp_modification (mod,"domain" )=>mod& Mod. mod_equation(mod) => e −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− fix_field_type (mod, attr , ty) => ( ( T y p e s . T_FIELD ( t y , T y p e s . DOMAIN ( e ) ) , NONE ) )

... end

The specification code shown above is somewhat simplified. Once the field type is constructed, it follows the component during instantiation and type checking can be done and expression types can be derived for expressions where the compo- nent is referenced. For example, during instantiation of the der()-operator, the type of the first argument must be used to derive the type of the der()-operator expression. The instantiation results in a constructed DAE. Fields are represented in the DAE as well:

datatype Type = REAL |INT | BOOL |STRING | ENUM | ENUMERATION of string list | FIELD of Type * Domain

datatype D o m ain = DOMAIN of Exp . Exp | NO_DOMAIN

93 Chapter 5 Implementation

Hence, the field variables can be handled and included in the flattened model, with accompanying domain information. The flattened model can further be discretized to generate a flattened Modelica model with discrete fields, or other external sup- port for implementing fields can be utilized. Constant fields are expressed in the language using the field construction opera- tor, for example: TestDomain omega(...); field Real f = field(2* x+y for (x,y) in omega ) ; During flattening, an implicit function is automatically created, with the field con- structor iterator variables as input arguments and the field expression for calcu- lation of the output variable. This function can be called for calculation of field values over the domain during discretization. The field constructor is modified to contain a call to the generated function instead of the field expression, in order to simplify further conversion during the discretization step. The above example is converted to the following code: function f_tmp1 input Real x; input Real y; output Real out ; algorithm out = 2* x+y ; end f_tmp1 ; ... TestDomain omega(...); field Real f = field(f_tmp1(x,y) for (x,y) in omega ) ; With this method, the existing function code generation implementation in the compiler can be utilized. Code will be automatically generated for the field func- tion (f_tmp1) and it can be called during discretization.

5.2 The PDE Library

As discussed in Chapter 3, the PDE library has been designed to be layered in two levels, with a set of classes to be used for modeling using continuous fields and domains, and a set of classes representing the discretized fields and domains. The main continuous classes are Field, Domain,andBoundary. A domain is defined by giving a boundary component, which in turn is defined by a shape-function describing the boundary as a parametric curve. The continuous parts are designed to be independent of discretization and solu- tion method. Hence, they are not discussed further in this chapter. The discrete part and the solver environment are currently based on the finite element method. However, implementations for other methods can easily co-exist in the library due to the two-level design.

94 5.2 The PDE Library

Figure 5.5 depicts an overview of the PDE library implementation. Here, the library contains packages and models in Modelica used to specify a PDE model, which is automatically discretized with respect to spatial variables in order to re- move spatial dependency. With only ordinary differential equations left, the dis- crete model can be simulated as regular Modelica models. The user input is mainly based on the continuous parts, with some configuration needed for the discretiza- tion. Selection of the solution method is done by instantiating the discrete model from the specific package.

PDEModelica Library

User input Continuous PDE Model description Level 1 Discretization Level 2 configuration

Boundary Mesh generator boundary discretizer

discrete domain Finite element Discrete spatial discretizer stiffness matrix model

External software Figure 5.5: Overview of the PDE library and the implementation using the finite element method.

5.2.1 The Finite Element Package The discrete level is highly dependent on solution method. For this reason, the discrete parts of the library are located in solution method specific sub-packages, e.g the classes based on the finite element solver are collected in the FEMForms package. The FEMForms package contains the main prototype implementation developed in this work. The classes in this package and their relationship are de- picted in Figure 5.6.

5.2.1.1 DiscreteField The DiscreteField class in the FEMForms package closely resembles the field data type found in Rheolef. An indirect representation is used so that the unknowns and known (blocked) values of the field can be grouped into two separate vectors in the field: package DiscreteField

95 Chapter 5 Implementation

FieldType: DiscreteField Field +val_u: array of FieldType +value(Point): FieldType +val_b: array of FieldType +u_indices: array of Integer +b_indices: array of Integer +formsize: FormSize

Interpolation

+interpolate(): array of FieldType +interpolate_indirect(): array of FieldType DiscreteConstField +constval: FieldType +value(Point): FieldType

DiscreteDomain Domain +boundary: array of BPoint

FormSize +nu: Integer +nb: Integer

Form Mesh +uu: array[nu,nu] of Real +vertices: array of Integer[3] +ub: array[nu,nb] of Real +edges: array of Integer[3] +bu: array[nb,nu] of Real +triangles: array of Integer[4] +bb: array[nb,nb] of Real +polygon: array of Point +nu: Integer +bc: array of Integer +nb: Integer +refine: Real

Figure 5.6: Finite element method specific classes adapted to the external solver Rheolef. These are defined in the FEMForms package.

96 5.2 The PDE Library

replaceable package fieldP = Field ; replaceable package ddomainP = DiscreteDomain ;

replaceable record Data parameter ddomainP . Data ddomain ; parameter fieldP .Data field ; parameter FEMSolver . FormSize formsize ; parameter Integer u_indices [formsize .nu]; parameter Integer b_indices [formsize .nb]; fieldP . FieldType val_u[ formsize .nu]( start=zeros ( formsize .nu )); fieldP . FieldType val_b[ formsize .nb]( start=zeros ( formsize .nb )); end Data ;

end DiscreteField ;

The arrays u_indices and b_indices contain the actual indices of the field val- ues corresponding to the coordinates of the nodes in the mesh. The sizes of the unknown and blocked value arrays are not known before the mesh is generated and the final model is instantiated with given boundary conditions. This is because the type of the boundary conditions affect the number of unknowns in the field. For example, Dirichlet conditions result in known values on the boundary, while for Neumann boundary conditions the boundary nodes have unknown values. A discrete field has an associated continuous field and a discrete domain.

5.2.1.2 DiscreteDomain

A discrete domain in the FEMForms package represents a triangular mesh. The mesh data structure is defined separately and instantiated here. The mesh is gener- ated from a discrete boundary representation, which is an array of points sampled on the parametric curve defined as the boundary of the continuous domain. The number of sample points is a parameter to the Data record, where also the refine parameter is stored. The refine parameter controls the size of the generated trian- gles in the mesh. The actual mesh generation occurs during the instantiation of the Data.mesh data structure. The boundary condition indices are passed to the mesh data structure as well, in order to be passed to the mesh generator.

5.2.1.3 Mesh and MeshGeneration

The Mesh package represents a triangular mesh generated externally and read in and stored as parameters in Modelica records accessible to models. The mesh generation module is called and the result is read using external functions defined in the MeshGeneration package. The parameters for a mesh are the number of boundary points, an array con- taining coordinates of the boundary points describing the domain boundary as a

97 Chapter 5 Implementation polygon, an array of boundary condition indices, and a refine parameter control- ling the mesh detail. The data structures are initialized using calls to the external functions defined in the mesh generation interface. Although Modelica does not enforce a sequential order of declaration processing, the generation and reading of the mesh must be done sequentially. The call order is enforced by dependency between parameters and parameter initialization expressions: package Mesh "2D spatial domain" ... parameter Integer status = generate ( polygon , bcind , filename , refine );

parameter Integer s[3] = get_s(filename , status );

parameter Integer nv=s[1] "Number of vertices"; parameter Integer ne=s[2] "Number of edges on boundary " ; parameter Integer nt=s[3] "Number of triangles"; parameter Coordinate x[nv, 3]=get_v (filename , nv) "Coordinates of nodes (1:2) and index for boundary condition (3)"; parameter Integer edge [ne , 3]= get_e ( filename , ne) "Edges by node indices (1:2) and index for boundary condition (3)"; parameter Integer triangle [nt , 4]=get_t (filename , nt) "Triangles by node indices (1:3) and sub−domain index (4) " ; ... end Mesh ;

The status parameter is a dummy to enforce dependency between the generate call and the calls to retrieve the mesh. The generated mesh is stored in a file. First the sizes are retrieved and then the vertices, edges and triangles are read. The declaration of the external functions are straightforward. For example, the function MeshGeneration.generate2D is declared as follows:

function generate2D "Generates 2D triangular mesh" annotation ( Include="# include " , Library="bamg" ); input Real xPolygon [: , 2]; input Integer bc [ size ( xPolygon , 1)]; input String outputfile ; input Real refine =0.5; output Integer status ; external "C" bamg_generate_mesh ("bamgrun . bat " , outputfile , status , xPolygon , size ( xPolygon , 1) , size ( xPolygon , 2) , bc , size ( bc , 1) , ref ine ) ; end generate2D ;

The annotations Include and Library are used for including the declaration of the external C functions and the library name for linking. These are tool specific extensions and not yet included in the Modelica specification, but supported by several tools, e.g. Dymola and OpenModelica.

98 5.3 PDEModelica Solver Environment

5.2.1.4 Interpolation The Interpolation package contains functions to interpolate a continuous field over a discrete domain in order to generate a discrete field defined over that discrete domain. The purpose of the interpolation is to be able to use constant fields defined in Modelica together with a discretized model. Two functions, inter- polate and interpolate_indirect are defined, the latter supporting indirect meshes. The interpolation is simply sampling of the continuous field values at the coordinates of the nodes in the mesh. The function interpolate_indirect is defined as follows: function interpolate_indirect input dfieldP . ddomainP . Data ddomain ; input dfieldP . fieldP .Data fld ; input Integer vecSize ; input Integer indices [vecSize ]; output dfieldP . fieldP . FieldType val [ vecSize ]; protected Point x; algorithm for i in 1: size (val , 1) loop x := ddomain . mesh . x[ indices [ i ] , 1:2]; val[ i ] := dfieldP . fieldP . value (x, fld ); end for ; end interpolate_indirect ;

Here, fieldP is the package pointing to the continuous field definition, and value is the fields continuous value function as defined in the field package. Thus, the fields values are sampled and stored as a discrete field in the array val.

5.3 PDEModelica Solver Environment

In both the PDE library and the prototype with the compiler extensions external tools can be utilized for discretization of the PDEs with respect to spatial coordi- nates. This is especially necessary in case the finite element method is used, since triangular mesh generation and integration over the triangular elements are needed to generate the space-discrete differential equations. A variety of tools exist for mesh generation and the finite element method. Two such tools were used in this work, bamg for mesh generation and Rheolef for the finite element method.

5.3.1 Spatial Discretization of Equations The current approach to solve PDE based models is to remove spatial dependency by discretizing the differential equations with respect to space variables. Thus, partial derivatives and field variables are replaced with arrays of scalar variables

99 Chapter 5 Implementation and a system of equations depending on the solution method. The work presented in this thesis uses manual methods for the discretization, i.e., the developer of the PDE library also defines the discrete model using the solver framework. There is an ongoing effort to automate the discretization using both explicit finite differ- ence schemes [16] and implicit finite difference schemes [35], using Mathematica with the MathModelica environment [36]. This effort also includes FEM based discretization [37]. A prototype exists, but no paper has yet been published.

5.3.1.1 Finite Difference Discretization Finite difference discretization is the simplest method for automatic discretization of equations. It is straightforward to replace partial derivatives with difference equations, leaving only ordinary derivatives without spatial dependency. However, finite difference methods are not as general as finite element methods regarding complex domains, because a rectangular grid is needed in order to represent the derivatives with differences.

5.3.1.2 Finite Element Discretization The finite element method is more suitable in cases where the domain of a PDE is not known in advance and a large variety of domains need to be supported, because triangulation of general domains is well developed. However, the discretization of the equations is more involved, because symbolic processing and integration is needed to convert an equation in differential form into the variational form as de- scribed in Section 3.5.2. For this reason, a solver framework was designed and implemented for discretizing the equations using FEM and the method of lines. The first version of the framework is implemented fully in Modelica, using Mod- elica functions to calculate mass and stiffness matrices. Later, in order to reuse the existing, open-source PDE solvers, a version of the framework with an interface to external code was implemented, using forms (see Section 3.7.1).

5.3.1.3 External Finite Element Discretization

The external solver, Rheolef, is written in C++ and allows the PDE problem to be specified using C++ objects. A PDE problem corresponding to the existing models in the PDE library has been implemented in C++ using Rheolef. The problem speci- fication has been done on a general level to support different domains and different combination of boundary conditions. However, the implementation currently only supports the Poisson equation and the diffusion equation (time-dependent). For other types of equations, additional implementation is needed. Since all discrete information is declared as parameters in the Modelica model, all external calls for the discretization are done during the parameter initialization

100 5.3 PDEModelica Solver Environment before the simulation starts. In order to minimize the dependency between the Modelica simulation environ- ment and the external solver, the external solver is compiled as a separate exe- cutable binary. The external functions are stored in a library which is statically linked to the specific Modelica simulation executable generated by the Modelica tool for a model. These functions are wrapper functions that execute the external solver binary and read the result. The communication between the processes is done through text files, for sim- plicity. Also, the external binary does not have persistent state between the calls. Hence, each call instantiates the complete problem even though only partial infor- mation is requested. A future improvement is to implement the solver as a server that replies to requests without unloading all information between the calls. An- other improvement is to change the communication method to sockets or CORBA, see Section 9.3.3.1.

5.3.1.4 Discrete Models The PDE models representing different PDEs are stored in the solver specific pack- ages. A package is created for each specific PDE, containing a replaceable package representing the domain, domainP, and a model called Equation containing the model details and the spatially discrete equation. Currently, Poisson2D and Diffusion2D are implemented, which can be found in the FEMForms package. The actual equations are written in space-discrete form, using matrices retrieved from the external solver. For example, the diffusion equation contains the following matrices: parameter Real mass_uu[ formsize .nu, formsize .nu] = getForm_mass_uu ( . . . ) ; parameter Real mass_ub[ formsize .nu, formsize .nb] = getForm_mass_ub ( . . . ) ; parameter Real bvals [ formsize .nb] = getBlockedValues ( . . . ) ; parameter Real massb_u[ formsize . nu] = getMassBdr_u ( . . . ) ; parameter Real laplace_uu [formsize .nu, formsize .nu] = getForm_gradgrad_uu ( . . . ) ; parameter Real laplace_ub [formsize .nu, formsize .nb] = getForm_gradgrad_ub ( . . . ) ; used in the following equation: equation mass_uu* der (fd.val_u) = − laplace_uu* fd . val_u − laplace_ub* fd . val_b + mass_uu* g_rhs . val_u + mass_ub* g_rhs . val_b + massb_u ; The blocked values of the discrete field, fd.val_b, are determined by the bound- ary conditions. Special handling is needed for boundary conditions with a fixed but time-dependent value, which cannot be declared as a parameter:

101 Chapter 5 Implementation

for i in 1: formsize .nb loop if (bc[ integer ( fixed_x[ b_indices [ i ] , 3]) , BCTYPE] == BoundaryCondition . timedepdirichlet ) then fd . val_b [ i ] = timeDepBndValue ; else fd.val_b[i] = bc[integer(fixed_x[b_indices[i], 3]), BCGVAL]; end i f ; end for ; The variable timeDepBndValue can for example represent the temperature of a heater, dynamically controlled by a feedback controller connected to a sensor, as described in the example in Section 6.2.1. For regular Dirichlet boundary condi- tions, the constant values are retrieved from the list of boundary conditions. The arguments to the getForm-functions, left out above for clarity, contain all information needed for the discretization, i.e., the mesh and the boundary condi- tions. The matrices are divided into four blocks, as described in 3.7. Separate calls are needed to retrieve each block due to the parameter initialization syntax in Modelica. The getForm-functions are declared as external functions in the FEM- Forms.FEMSolver package. For example, the following common function is used to retrieve the mass matrix: within FEMForms.FEMSolver; function getForm_mass_internal annotation ( Include="#include " , Library="poisson_rheolef"); input String meshfilename ; input Integer meshnv ; // number of vertices input Integer nu; / / number of unknowns input Integer nb; / / number of knowns input Integer nbc ; // number of boundary conditions input BCType bc [ nbc ]; // boundary conditions output Real auu[nu , nu ]; // uu block output Real aub[nu , nb ]; // ub−block output Real abu[nb , nu ]; // bu−block output Real abb[nb , nb ]; // bb−block external "C" get_rheolef_form_mass (meshfilename , meshnv , nu , nb , auu , aub , abu , abb , size(bc,1),size(bc,2),bc); end getForm_mass_internal; The other functions in the FEMSolver package are the following: package FEMSolver function getFormSize . . . function getForm_gradgrad . . . function getUnknownIndices . . . function getForm_gradgrad_internal ... function getForm_gradgrad_uu . . . function getFormSize_internal ... function getBlockedIndices ... function getForm_mass_internal ...

102 5.3 PDEModelica Solver Environment

function getForm_mass . . . function getForm_mass_uu . . . function getForm_mass_ub . . . function getForm_gradgrad_ub . . . function getBlockedValues . . . function getForm . . . function getForm_internal ... function getMassBdr_u . . . end FEMSolver ;

package Diffusion2D ... model Equation ... package uFieldP = Field ( redeclare package domainP = domainP ); parameter uFieldP . Data uField (domain=domain );

// discrete part package ddomainP = DiscreteDomain ( redeclare package domainP = domainP ); parameter ddomainP . Data ddomain ( domain=domain , nbp=nbp , refine=refine );

parameter Real fixed_x [ddomain . mesh . nv , 3] = fixBlockedEdgeEnds (ddomain . mesh . x , ...);

equation // c* laplace => assume c is constant (not space dependent) da* mass_uu* der (fd.val_u) = − c * laplace_uu * fd . val_u − c * laplace_ub * fd . val_b + mass_uu* g_rhs . val_u + mass_ub* g_rhs . val_b + massb_u;

// fd . val_b = bvals ; for i in 1: formsize .nb loop // if bctype == timedepdirichlet if (bc[ integer ( fixedmeshx [ b_indices [ i ] , 3]) , BCTYPE] == BoundaryCondition . timedepdirichlet ) then fd . val_b [ i ] = timeDepBndValue ; else fd . val_b[ i ] = bc[ integer (fixedmeshx [ b_indices [ i ] , 3]) , BCGVAL ] ; end i f ; end for ; end Equation ; end Diffusion2D;

103 Chapter 5 Implementation

5.3.1.5 Solver Executable The solver executable uses command line arguments for different requests. The PDE problem is represented using a C++ struct. Each of the different functions han- dling the requests instantiates the problem and returns some specific information to the caller. The main function in the executable calls these functions and writes the result in a text file, to be read by the external function wrappers in the Modelica library. Text files are used in order to simplify debugging and verification. These files can be read in and viewed in tools like Mathematica or Matlab. Common func- tions to read and write arrays and matrices to text files are collected into a separate library, used by both binaries.

104 Chapter 6 Examples

“In this house, we obey the laws of thermodynamics!” Homer Simpson

This chapter shows some PDE application examples that can be modeled and simulated using the Modelica PDE library. For comparison, corresponding exam- ples are also simulated in FEMLAB and the plot results are included. See Sec- tion 8.2.4 for description of FEMLAB.

6.1 Stationary Heat Transfer

The equation for stationary heat transfer through conduction has the same structure as the Poisson equation: −∇ · (k∇T )=Q where k is the thermal conductivity of the material, T is the temperature and Q is the source term, i.e. generated heat inside the material, if any. This corresponds to Equation 3.1 with c = k and g = Q. The example shown in Section 3.9 was simulated on a rectangular domain with one rounded corner. The resulting plots from the simulation is depicted in Fig- ure 6.1 (see Appendix B for MATLAB scripts for plotting). Recall that Dirichlet boundary conditions were used for the entire boundary, with the value 0 every- where except on the rounded corner where the value 5 was used. For comparison, the same model is exported to and solved in FEMLAB. Fig- ure 6.2 shows the result generated by FEMLAB. The triangulation of the domain in both cases can be seen in Figure 6.3.

105 Chapter 6 Examples

The boundary conditions used here are not realistic because of the discrete jump the temperature does at the connection between the two Dirichlet conditions with different values, but the example is included for demonstration purposes. The dis- continuity in the temperature on the boundary is the reason for the spikes at the end points of the curved boundary section in Figure 6.2.

Figure 6.1: Results from solving the Poisson equation (steady-state) using the PDE Modelica library.

Figure 6.2: Results from solving the Poisson equation (steady-state) in FEMLAB.

106 6.1 Stationary Heat Transfer

4 4

3.5

3.5

3

3

2.5

2.5

2

2

1.5

1.5

1

1 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

Figure 6.3: The meshes automatically generated from domain description in Mod- elica. Bamg mesh on the left, FEMLAB solution mesh on the right.

6.1.1 Neumann and Robin Boundary Conditions Neumann boundary conditions are used to model insulated boundaries. The equa- tion is ∂ T = gon∂Ω ∂n Perfect insulation is specified with g =0. Other values for g sets a constant value for the outward normal derivative for T on the boundary. For non-perfect insulation, Robin (mixed) boundary conditions can be used:

∂ T + qT = gon∂Ω ∂n The corresponding boundary condition for heat transfer problems can be formu- lated using Newton’s law of cooling:

∂ T = g + h(T − T ) on ∂Ω ∂n h inf where h is an experimental coefficient depending on boundary material and geom- etry, and Tinf is the external temperature. These coefficients can be mapped to the general coefficients above as follows:

g = gh + hTinf q = h

For the example shown in Section 1.1, the left boundary condition can be mod- eled using this boundary condition. For the glass layer, the following heat transfer coefficient can be used [38]: h = kg/lg

107 Chapter 6 Examples

where kg is the thermal conductivity and lg is the thickness of the glass layer. This model was simulated with the following parameters:

kg =54 J/m · min · K −3 lg =3· 10 m k =4.92 · 10 3 J/m · min · K gh =0 ◦ Tinf =5 C Note that the parameters for thermal conductivity are adjusted to give results per minute. The simulation results for this example is depicted in Figure 6.4. Corre- sponding results from FEMLAB is shown in Figure 6.5. Note that the steady state model show the simulation result after the transient phase is finished, i.e., the solu- tion has stabilized. The plots show that with constant temperature on one boundary and a poorly insulated glass layer, the temperature near the glass layer will be al- most equal to the outside temperature. Slightly higher values can be seen near the corner of the glass layer that is close to the heater.

Figure 6.4: Results from simulation of example in Section 1.1 using the Modelica PDE library.

6.2 Time-dependent Heat Transfer

In order to study transient processes and controlled heating, the time-dependent heat transfer equation can be studied. The equation is ∂u ρC −∇·(k∇u)=Q ∂t

108 6.2 Time-dependent Heat Transfer

Figure 6.5: Results from simulation of example in Section 1.1 using FEMLAB.

Here, ρ denotes the density of the material where heat transfer occurs, C denotes the heat capacity of the material and k is the thermal conductivity as in the steady state model.

6.2.1 Heat Transfer with Controller The coupled example shown in Section 1.1.1 was simulated using the time depen- dent heat transfer model. The same material parameters as in the previous example were used, with the following additions for the time dependency: ρ =7.821 · 103 kg/m3 C = 449 J/kg · K A proportional, integrating controller (PI-controller) was used to control the tem- perature. The controller contains an ordinary differential equation: T = T − T error sensor goal

Theater(t)=KpTerror + Ki Terror dt

Here, Kp is the proportional constant of the controller, and Ki is the integral con- stant. The Modelica Standard Library contains a PI-controller with slightly differ- ent parameters:

Kp = k k K = i T

109 Chapter 6 Examples which gives k T (t)=kT + T dt heater error T error After some experiments, the values k =1and T = 200 were found to work well for the PI-regulator. Plots of the simulation results at different time points are showninFigure6.6.

6.3 Discussion

The examples show that object-oriented, component based models containing PDEs and combined ODE and PDE models is possible to specify and simulate using our approach. However, more work is needed to implement connections between ODE-based models and PDE-based models. For example, the integral operator should be possible to use to connect a boundary to a scalar variable. In our current implementation, only existing discrete points in the domain is possible to use as connection points to other scalar variables, e.g., a solution point in the domain is used as the sensor value and connected to the temperature controller, which is a limitation.

110 6.3 Discussion

(a) t=0.05 (b) t=1

(c) t=2 (d) t=5

80

70

60 heatervalue sensorvalue 50 goalvalue

40 temperature

30

20

10

0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 time

(e) Time plots of heater and sensor values

Figure 6.6: Results from simulation of example in Section 1.1.1 using the Modelica PDE library. 111 Chapter 6 Examples

112 Chapter 7 Previous Approaches With Examples

“Science may be described as the art of systematic oversimplification.” Karl Popper

This chapter describes the early iterations of this research work on designing, implementing, and evaluating object-oriented modeling language extensions and methods for general, PDE-based modeling. This description is included as a refer- ence for future work and as a background for the current design hypothesis which is the result of previous design iterations.

7.1 Mathematica-based Translator

The idea with this approach is to utilize the Mathematica environment to specify partial differential equations and do symbolic preprocessing for solving PDEs.

7.1.1 Space Variables

In early approaches, a type prefix similar to parameter, constants etc. called space was used to declare spatial coordinates. This is similar to the new prefix field, but these variables are just used for declaring spatial coordinate names. This is a rather unnecessary extension, because the same result can be obtained by using the parameter prefix, which also specifies that a variable is not time dependent.

113 Chapter 7 Previous Approaches With Examples

7.1.2 Domain Classes A mathematical approach to define domains and boundaries is to use constraints. A domain is a set of tuples of real numbers. By restricting the ranges of the coor- dinates using constraints, one can specify closed domains rather than open, infinite domains. Also, using equations, boundaries can be defined, because an equation restricting the value of a coordinate decreases the degrees of freedom, hence the dimension, of a domain. Using mathematical expressions for constraining domains is a general and ex- pressive way of specifying domains. However, the usability of this approach may be somewhat limited. Modern tools usually contain graphical user interfaces for defining domains, which can be difficult to use to define constraints mathemati- cally. Another drawback is that symbolic processing and is needed. This is reasonable to implement in a symbolic environment like Mathematica, but this creates a dependency to a third-party commercial tool. The prototype solver that was used for this approach is described in Section 7.1.3.

7.1.2.1 Example A circular domain and its boundary could be defined using constraints as follows: domain Cartesian2D space Real x ,y; end Cartesian2D ;

domain CircleBase extends Cartesian2D parameter Real r =1; parameter Real xc=0, yc=0; end CircleBase ;

domain Circle extends CircleBase constraint x==xc−sqrt (r^2−(y−yc )^2) or x==xc+ sqrt ( r^2−(y−yc )^2); end Circle ;

domain Circular extends CircleBase Circle boundary(xc=xc , yc=yc , r=r ); constraint xc−sqrt(r^2−(y−yc )^2) <= x <= xc+ s q r t ( r ^2−(y−yc )^2) and yc−r<=y<=yc+r; end Circular ; Here, the Circle domain is actually a boundary, as constrained by the two equa- tions in the constraint section. These equations are used together with the

114 7.1 Mathematica-based Translator boundary conditions during the solver generation. The Circular domain is the actual domain, i.e., the interior of the boundary. A drawback that can be seen here is that the boundary constraints needed to be repeated with inequalities instead of equalities. Domains for equations were defined in a syntax similar to the current design: f(x,y)=sin(x)+cos(y) where (x,y) in omg ;

The need for space variables and their local declaration as shown here is avoided by the introduction of field variables. Otherwise, the in construct and the domain reference are also present in the current design. A similar syntax was used in field constructors. The equation and the boundary conditions were defined in the model as follows:

model MyPDEModel space Real x,y; Circular circdomain ; Real U(x ,y, t ); boundary U(x , y , t )=0 where (x,y) in circdomain .boundary ; equation pder (U(x , y , t ) , t ,2) = pder (U(x , y , t ) ,x ,2) + pder (U(x , y , t ) ,y ,2) where (x,y) in circdomain ;

end MyPDEModel ;

Here, the partial derivative operator pder() was used, instead of the current over- loaded operator der().

7.1.3 Solver Generator in Mathematica

The Mathematica-based solver generator supports general Mathematica differential equation formulation of a PDE. Hence, no manual conversion to variational form is necessary, and the solver can be used for PDEs with different structure. Mathemat- ica is used for symbolic processing of the equations and generating a finite element solver for the specific domain. The resulting equation system can be solved by Mathematica’s built-in linear solver or an external solver such as SuperLU. Both finite difference method [16, 39] implementations and a finite element method implementation exist, as well as a method of lines implementation using finite differences. However, the approach with constraints for defining domains and boundaries is only supported with the finite difference solver generator. The finite difference solver and the method of lines solver are used with a translator implemented in MathModelica [40, 41].

115 Chapter 7 Previous Approaches With Examples

7.2 Coefficient-Based Translator

The coefficient-based translator uses new restricted classes and some special oper- ators for declaration of domains and boundaries. The basic idea is that the solver environment has knowledge about the PDE models defined using the Modelica lan- guage. Thus, it is sufficient to extract the parameters of the PDE model while the equations and their structure is assumed. A specific solver written for a specific equation is called with the given parameters of the current model and the cur- rent domain. The new keywords that were introduced in this design are domain, boundary, line, curve, composite and space. The drawback of this approach is the low degree of language support. Despite the powerful concepts the Modelica language is based on, the language itself is only used for defining parameters for predefined PDEs. The domain and boundary design is somewhat more integrated. However, the current approach requires fewer modifications to the language and at the same time is more general.

7.2.1 Domains As in the Mathematica-based translator, a new restricted class called domain is introduced. The design is based on the current approach with parametric curves but with a different syntax. One syntax that was considered is to declare space variables and define the expressions for the mapping in an algorithm section: domain Cartesian2D "Base class for two dimensional domains" space Real x ,y; end Cartesian2D ;

domain Circle2D " Circular domain with r=1" extends Cartesian2D ; algorithm (x,y) := ( cos(2* PI*u), sin(2* PI*u) ) where u in (0 ,1); end Circle2D ; A special composite() operator was needed to set up composite boundaries consisting of several simple boundary components: domain Line2D "A line segment" extends Cartesian2D ; parameter Real x0=0 , y0=0 , x1=1 , y1 =1; algorithm (x,y) := ( x0+r*(x1−x0 ) , y0+r *(y1−y0 ) ) where r in (0 ,1); end Line2D ;

domain Rectangle2D "A 6 by 4 rectangle" extends Cartesian2D ; parameter Real cx=0, cy=0, w=3, h=2; Line2D right (x0=cx+w, y0=cy−h , x1=cx+w ,y1=cy+h ) ; Line2D top ( x0=cx+w, y0=cy+h , x1=cx−w, y1=cy+h );

116 7.2 Coefficient-Based Translator

Line2D l e f t ( x0=cx−w, y0=cy+h , x1=cx−w, y1=cy−h); Line2D bottom (x0=cx−w, y0=cy−h , x1=cx+w, y1=cy−h); algorithm (x,y) := composite( right , top , left , bottom ); end Rectangle2D ; However, this approach differed too much from the current Modelica language, i.e., required several unnecessary additions to the language. Another drawback is that the semantics of this design was not cleared out completely and is sometimes a bit ad-hoc. Even though the simple version is straightforward, the composite() operator is somewhat complicated. Another approach is to define all curve declarations using special operators. This way, the extensions were consistent with each other. The introduced operator to define curves was called curve(), and could be used as follows: domain Cartesian2D "For all 2D−domains" space Real x,y; end Cartesian2D ;

domain Circle2D "Circular with r=1" extends Cartesian2D ; boundary curve(cos(2* PI*u), sin(2* PI*u)) where u in (0 ,1); end Circle2D ; Because lines are used very commonly when defining domains, a special operator called lines() was introduced as well, to declare a list of connected lines´: domain Line2D "A line segment" extends Cartesian2D ; parameter Real x0=0 , y0=0 , x1=1 , y1=1; boundary lines({{x0,y0},{x1,y1}}); end Line2D ;

7.2.2 Equations and Boundary Conditions In the coefficient-based approach, where the partial differential equation is prede- fined, only the parameters of the model are extracted from the Modelica model. Thus, some built-in models have been predefined in a parameterized way. These models can be used with new parameter values that are extracted by the translator and passed to the solver specifically implemented for that built-in model. The com- mon types of boundary conditions were defined similarly and assigned to particular boundaries using special built-in components in the domain restricted class: model PDEModel Neumann h_iso ; Dirichlet h_heated (g=50);

117 Chapter 7 Previous Approaches With Examples

HeatRobin h_glass (hh=30000); HeatTransfer ht ; Rectangle2D dom(eq=ht , left (bc = h_glass ) , right (bc = h_heated ) , top (bc = h_iso ) , bottom (bc = h_iso )); end PDEModel ; Here, also the eq built-in component is used to assign a PDE to the interior of the boundary. This approach is simple to understand and use, and PDE models with different equations on different parts of the domain is easy to declare. However, this approach needs to make too many assumptions about the used models and is poorly integrated with the language.

7.2.3 Implementation Details This section describes the implementation of the coefficient-based translator for future reference. Parts of the implementation is general and can be used in future prototypes, for example the C++ classes to describe domains in the back end.

7.2.3.1 Extensions in Parser Some additions have been done to the Standard Modelica parser to handle the PDE extensions. New keywords and operators are summarized in Table 7.1. The new restricted class domain is used to describe domain geometry, with a new section called boundary.Theboundary section is described by the rules shown in Figure 7.1.

Table 7.1: New keywords and operators in the coefficient-based approach.

Keyword Description space Space variables for coordinates domain New restricted class domain boundary New section in classes for domain geometry definition curve(), line(), composite() Boundary geometry description operators eq, bc Predefined variables in domain classes

All three pseudo functions use a syntax with parentheses similar to the connect operator, represented by LPAR and RPAR. The symbols ’^’ and ’!’ are used to control the automatic parse tree generation, ’^’ defines a node to be the root node

118 7.2 Coefficient-Based Translator

boundary :( | line_clause | curve_clause | composite_clause ) comment ! ;

line_clause : LINE^ LPAR! e: expression RPAR! ;

curve_clause : CURVE^ LPAR! e: expression_list RPAR! ;

composite_clause : COMPOSITE^ LPAR! el : component_reference_list RPAR! ;

Figure 7.1: Parser rules in ANTLR for the boundary section. of a current subtree, and ’!’ suppresses the node from the subtree. Figure 7.3 shows the abstract syntax tree resulting from the domain example in Figure 7.2.

domain TestDomain space Real x,y; parameter Real PI = 3.141593; parameter Real u; boundary curve (cos(2* PI*u), sin(2* PI*u), u); end TestDomain ;

Figure 7.2: A domain example in the coefficient-based approach.

7.2.3.2 Extensions in Translator

In this section the additions to the Modelica translator to handle domain restricted classes and PDE parameters are described. These are additional data types in the RML representation of the abstract syntax tree, and rules for instantiation of do- mains and code generation for domains and PDE parameter initialization.

119 Chapter 7 Previous Approaches With Examples

ROOT

DOMAIN TestDomain

PUBLIC BOUNDARY

CURVE ELEMENT ELEMENT ELEMENT cos(2*PI*u) sin(2*PI*u)

COMPONENTS COMPONENTS COMPONENTS

COMPONENT COMPONENT COMPONENT COMPONENT space Real parameter Real parameter Real x y PI u

MODIFICATION = 3.141593

Figure 7.3: The abstract syntax tree for the domain class example in Figure 7.2. The expression subtrees are compressed into single strings for read- ability.

Representation

Several extensions have been in different parts of the Modelica semantics spec- ification to represent and translate PDEs and domains. In the Absyn module, the Restriction data type is extended with the R_DOMAIN and R_PREDE- FINED_DOMAIN.TheClassPart data type is modified to support a boundary node with a list of boundary elements, where each element can be one of the three boundary types, see Figure 7.4. In the current prototype, the representation is kept simple, using the Exp data type for the LINES node, which corresponds to the list of points written as a single expression using the array syntax. Similarly, the CURVE node contains a list of expressions, one for each of the coordinates. The representation of boundaries in the SCode module are the same as in the Absyn module, but the ClassDef data type has been modified to also represent domain information (see Figure 7.5). The DAE representation is also extended with nodes needed to represent the ex- tra information related to PDEs, see Figure 7.6. Data types for expressions stored in the DAE representation are defined in the Exp module, and contain the statically analyzed expressions, as opposed to the Absyn.Exp data type which contains the expressions before the analysis. The DAElist stored in the CURVE node is needed during code generation to determine which component references in the

120 7.2 Coefficient-Based Translator

datatype ClassPart = PUBLIC of Element list | PROTECTED of Element list | EQUATIONS of Equation list | ALGORITHMS of Algorithm list | BOUNDARY of Boundary list

datatype Boundary = LINES of Exp | CURVE of Exp list | COMPOSITE of ComponentRef list

Figure 7.4: Data type extensions for domain representation in the Absyn module.

datatype ClassDef = PARTS of Element list * Equation list * Algorithm list | DERIVED of Path * Absyn . ArrayDim option * Mod | DOMAINPARTS of Element list * Boundary list

Figure 7.5: Data type extensions for domain representation in the SCode module.

121 Chapter 7 Previous Approaches With Examples curve expressions that are parameters, in order to prefix them with the correct pre- fix. See Section 7.2.3.3 for a description of the code generation phase.

datatype DAElist = DAE of Element list

datatype Element = VAR of Exp . ComponentRef * VarKind * VarDirection * Type * Exp . Exp option |DEFINEof Exp . ComponentRef * Exp . Exp | EQUATION of Exp . Exp * Exp . Exp | ALGORITHM of Algorithm . Algorithm |COMPof Ident * DAElist |FUNCTIONof Absyn . Path * DAElist * Types . Type | DOMAIN of Exp . ComponentRef * Boundary list

datatype Boundary = LINES of Exp . Exp * Static . Properties | CURVE of Exp . Exp list * DAElist | COMPOSITE of Exp . Exp list

Figure 7.6: Additions in the DAE module for storing domain information. The only addition in the Element data type is the DOMAIN node.

Translation The SCode module contains the relations that convert the Absyn representation to the SCode representation, beginning with the elaborate relation. Some re- lations in this module are modified to handle the domain extensions. The elab- _class relation redirects the translation to elab_domaindef instead of elab- _classdef if the current class has the restriction type R_DOMAIN, i.e., if the class being translated is a domain class. Conversion of the declaration part in elab_domaindef is identical to the conversion of other classes, but the con- version of equation and algorithm sections are replaced with a relation that con- verts the boundary section. The result of the boundary section conversion is the SCode.DOMAINPARTS structure. The first part of this structure are the elements from the declaration part, and the second part is the boundary description consist- ing of SCode.Boundary elements generated by the relation elab_bound- ary_parts, see Figure 7.7. The translation is done in the Inst module in different ways depending on the type of the SCode.ClassDef node, one of PARTS, DERIVED or DOMAIN- PARTS. In the latter case, the rule for translating the domains is activated. The declaration part is handled as for other classes. The boundary part is instantiated using the relation inst_boundary, see Figure 7.8. In this relation the three different kinds of boundary descriptions POINTS, CURVE and COMPOSITE are

122 7.2 Coefficient-Based Translator

relation elabbndparts : Absyn.Boundary list => Boundary list =

axiom elabbndparts ([]) => []

rule elabbndparts ( rest ) => bnds & let bnds ’ = POINTS(e ) : : bnds −−−−−−−−−−−−−−−−−−−−−−−− elabbndparts (Absyn.POINTS(e ):: rest ) => bnds ’

rule elabbndparts ( rest ) => bnds & let bnds ’ = CURVE( e l i s t ) : : bnds −−−−−−−−−−−−−−−−−−−−−−−− elabbndparts (Absyn.CURVE( elist ):: rest ) => bnds ’

rule elabbndparts ( rest ) => bnds & let bnds ’ = COMPOSITE( e l i st ) : : bnds −−−−−−−−−−−−−−−−−−−−−−−− elabbndparts (Absyn.COMPOSITE( elist ):: rest ) => bnds ’ end

Figure 7.7: The relation elab_boundary_parts (abbreviated to elabbndparts) in the SCode module that handles the boundary description parts from the Absyn module. recognized and corresponding DAE nodes are generated. The common steps for each kind is: • static analysis: constant expression evaluation, type analysis and type anno- tation of expressions, variable references, etc. In the COMPOSITE case, only variable references are checked, because that is the only kind of expression allowed as argument to the composite() operator. • prefixing expressions: adding the correct prefix to variable references in the current instantiation environment. A reference to a variable v in a variable comp in the class being instantiated is prefixed by comp. to build comp.v. • state transition in class inference: modifying the state in the class inference module ClassInf which keeps track of the class state in order to check if the class contents is consistent with the restricted class type. In this case the transition to FOUND_BOUNDARY has been added.

7.2.3.3 Code Generation The result of the Modelica translation phase is the DAE representation that contains the list of variables, parameters, functions, equations, algorithms, and domains. In

123 Chapter 7 Previous Approaches With Examples

relation inst_bnd :(Env, Mod, Prefix , Connect . Sets , ClassInf . State , SCode . Boundary , DAE. DAElist ) => (DAE. Boundary list , Env, Connect . Sets , ClassInf . State ) =

rule Static . elab_exp (env , e) => (e ’ , prop) & PrefixCode . prefix_exp (env , e’ , pre) => e’’ & C l a s s I n f . t r a n s ( s t , C l a s s I n f . FOUND_BOUNDARY) => s t ’ −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− inst_bnd (env , _, pre , csets , st , SCode.POINTS(e) , dae) => ( [DAE. POINTS( e ’ ’ , prop ) ] , env , cs ets , st ’ )

rule Static . elab_exp_list (env, elist ) => (el ’ , _) & PrefixCode. prefix_exp_list (env, el ’, pre) => el ’’ & C l a s s I n f . t r a n s ( s t , C l a s s I n f . FOUND_BOUNDARY) => s t ’ −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− inst_bnd (env , _, pre , csets , st , SCode.CURVE( elist ) , dae) => ( [ DAE . CURVE( e l ’ ’ , d a e ) ] , en v , c s e t s , s t ’ )

rule Static . elab_cref_list (env, crlst ) => (el ’,_,_) & canon_cref_list (env, el ’) => el ’’ & PrefixCode . prefix_exp_list (env , el ’ ’ , pre) => el ’ ’ ’ & C l a s s I n f . t r a n s ( s t , C l a s s I n f . FOUND_BOUNDARY) => s t ’ −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− inst_bnd (env , _, pre , csets , st , SCode.COMPOSITE( crlst ) , dae) => ( [ DAE . COMPOSITE ( e l ’ ’ ’ ) ] , env , c s e t s , s t ’ ) end

Figure 7.8: The inst_boundary relation that instantiates the three different kinds of boundary elements, POINTS, CURVE and COMPOSITE and builds the corresponding DAE structures.

124 7.2 Coefficient-Based Translator this prototype, there is also a code generation module for setting up the PDE prob- lem in C++ code so that it can be compiled and linked with a PDE solver. The code generation phase produces code for declaration and initialization of param- eters, function definitions, creating functions for parameterized boundary descrip- tion and associating boundary conditions and boundary sections. The generated code is incomplete, and is combined with prewritten C++ code.

Model Parameters

The model parameters declared in functions are collected and generated as record fields in separate C++ structs, one for each function instance. The model parameters of the instantiated, complete model are generated as record fields in a struct that contains all the parameters of all subcomponents as a flat list of C++ variables. Ini- tialization of all model parameters of all functions is performed in an initialization routine, and another routine initializes the values of the model parameters. The pointer to the model parameter struct is passed to functions so that model parame- ters can be accessed from within instantiated functions.

Functions

The first step of function code generation is to generate a unique C++ struct for each function, containing the Modelica parameters of that function. A global struct variable is declared at the same time, with a name corresponding to the full name of the function with dots replaced by underscores. Later, initialization code is generated for assigning the parameter values for all function parameters. Next, the function head is generated. The input variables are generated as argu- ments of the function with their type and value, and output variables are generated as the return values. For simple variable types simple C++ variables are generated, like int, real, etc. For complex types a C++ struct is generated and the name of the struct is used as the type. If there is only one output variable, the type of that variable is used as the return type of the function. If there are more output vari- ables, a return type struct is created and used as the return value containing all the output variables. The return variable is declared at the beginning of the function body and if a struct is used, the output variables are appropriately prefixed with the name of the struct. The function body is generated from the algorithm section of the corresponding Modelica function which has a close correspondence to C++ code. Finally, the return statement is constructed.

125 Chapter 7 Previous Approaches With Examples

Function Instances

Code instances of parameterized functions are implemented using the replaceable function feature of Modelica. PDE and boundary condition models contain re- placeable functions that represent coefficients that can depend on space variables. These Modelica functions are instantiated for each instance of a PDE or a boundary condition class, and a unique C++ function is generated in each case. The generated code for each function instance is identical to that for the Modelica function class that the function is an instance of, except that the parameter references are replaced with references to a separate parameter struct.

Domains

AsetofC++ classes has been developed in order to simplify code generation for domain classes. The class hierarchy can be seen in Figure 7.9. The three kinds of boundary descriptions use different approaches to code generation, but has the same interface so that the discretization is done automatically. The Object2D() class is the base class containing the interface method getPoints(),whichre- turns a required maximum number of discrete points describing the boundary. The Object2D() class also contains the isComposite() and the getCurves() methods needed for hierarchically composed curves.

Object -name: string

Object2D +getPoints(): point_vector +getCurves(): curvep_vector +isComposite(): bool

Curve2D DiscreteCurve2D Composite2D -points: point_vector -curves: curvep_vector +func(u:Real): Point2D +add(point:Point2D) +add(in curve:Object2D)

Figure 7.9: The class hierarchy for the C++ classes written to generate domain descriptions. Line2D objects are represented by the Discrete- Curve2D class.

The curve approach to boundary description uses a parametric expression that defines the boundary curve. The description is symbolic, but is discretized before the triangulation can be made. This is handled by generating a function which

126 7.2 Coefficient-Based Translator calculates the coordinates of a point on the curve for a given parameter value. For example, the boundary description:

curve(cos(2* PI*u), sin(2* PI*u), u); is translated into a C++ function with the structure shown in Figure 7.10.

Point2D func ( Real u) { Point2D res ; res .x = cos(2* PI*u); res .y = sin(2* PI*u); return res ; }

Figure 7.10: Function generated for the boundary described as curve(cos(2*PI*u), sin(2*PI*u), u);

The class Curve2D is used to represent parametric curve based descriptions. A new, specialized class is generated for each such domain description, which in- herits Curve2D and overloads the func() method to calculate the correct curve. The Curve2D class can be seen in Figure 7.11. The getPoints() method au- tomatically calls the func() method to generate the required number of discrete points on the curve.

class Curve2D : public Object2D { public : Curve2D(string name=string ("Curve2DObject " )) : Object2D (name) { }

virtual Point2D func ( Real u)=0; virtual point_vector* getPoints ( int n); };

Figure 7.11: The Curve2D class that represents parametric curves. Each specific boundary description inherits this class and overloads the func() method.

When the lines method is used for boundary description, the class Dis- creteCurve2D is instantiated and the set of points from the lines description is added to that instance. See Figure 7.12 for the contents of the Discrete- Curve2D class. The list of points added to an instance is directly returned from the getPoints() method, ignoring the desired maximum number of points, for simplicity. Hence, it is assumed that the number of points given in the lines

127 Chapter 7 Previous Approaches With Examples operator is always less than the required number of discretization points on the boundary. If this does not hold, the result will be a finer discretization than what is desired.

class DiscreteCurve2D : public Object2D { point_vector points ; public : DiscreteCurve2D ( string name=string ("DiscreteCurve2D " )) : Object2D (name) { } void add ( const Point2D& p ); void add ( const Point2D* p, int n); virtual point_vector* getPoints(int n); };

Figure 7.12: The DiscreteCurve2D class that represents a set of connected lines. Each specific boundary description instantiates this class and adds the present set of points to that instance using the add() method.

The composite method is slightly more complex to handle. Figure 7.13 shows the declaration of the Composite2D class that represents composite boundaries. A composite curve is discretized by retrieving its constituent curve segments and discretizing them, compensating for the overlaps at the joints. The getCurves() method is used to access the curve segments. It traverses the composition hierarchy and collects all non-composite curves into a single list. Hence, if a curve segment itself is composite, the getCurves() method is called recursively on that curve object and the resulting list of curves is inserted into the top level list. Thus, the list of curves returned only contains Curve2D or DiscreteCurve2D objects.

Boundary Conditions

Boundary conditions are represented by the BoundaryCondition C++ class, see Figure 7.14. The same class can be used for the three different kinds of boundary conditions: Dirichlet, Robin, and Neumann conditions. The names of the boundary condition objects are mapped from their names in the Modelica domain description. The mesh generator and the PDE solver supports named boundary segments. The code generation consists of instantiating the boundary condition objects and putting them in a list to be passed to the solver.

128 7.2 Coefficient-Based Translator

class Composite2D : public Object2D { curvep_vector curves ; public : Composite2D( string name=string ( "Composite2D " )) : Object2D (name) { } virtual point_vector* getPoints ( int n); curvep_vector* getCurves (); void add (Object2D* c); void add (Object2D** c, int n); virtual bool isComposite () { return true ; } };

Figure 7.13: The Composite2D class that represents a boundary that is com- posed of one or more other boundary objects, composite or plain (curve or discrete curve). The getCurves() method recursively goes through any constituent composite curves, returning only a flat list of non-composite curve segments.

class BoundaryCondition {

public : space_function * g; Float q; bool is_dirichlet ; string name;

public : typedef Float space_function (const point& p);

BoundaryCondition (); };

Figure 7.14: The BoundaryCondition class that is used to represent the three kinds of boundary conditions. The type space_function is used for functions that depend on the space variables. The type point represents the space coordinates in two or three dimensions.

129 Chapter 7 Previous Approaches With Examples

User input PDE-Modeq

PDE-Modelica Parser

domain Discretizer Translator

discrete domain boundary

Mesh generator

mesh

Solver boundary condition parameters equation parameters External software Figure 7.15: Solution method using an external PDE solver or a pre-generated solver. This method is used with Rheolef and FEMLAB.

130 7.2 Coefficient-Based Translator

User input PDE-Modeq

PDE-Modelica Parser

domain Discretizer Translator

discrete domain boundary equations boundary conditions parameters

Mesh generator mesh Solver generator

External software Mathematica

Solver New parameter values Parameter values Figure 7.16: Solution method with dynamic solver generation. This method is used with the MathFEM solver.

131 Chapter 7 Previous Approaches With Examples

7.2.4 Numerical Solver

The solution of a PDE problem involves discretization of the domain, mesh gen- eration for the finite element solver, and solution of the discretized problem using a solver. The mesh generation and the solution is handled by ex- ternal software, with some adaptation to support the approach taken in this thesis. The class diagram for the different parts of the solution process can be seen in Figure 7.17.

MeshGenerator DiscreteDomain2D

+generate(domain:Object2D) +discretize(curve:Object2D) +optimize() +getPoints() +getSegments() +getSubnames()

BamgMeshGenerator GeoMeshGenerator EasymeshMeshGenerator

Solver

+solve(domain,bclist,reglist)

RheolefSolver MathFEMSolver FEMLABSolver

Figure 7.17: The class diagram for the mesh generator and the solver classes.

7.2.4.1 Domain Discretization

Domain discretization is performed by the DiscreteDomain2D class. In the case with a parametric curve description, this involves sampling a given number of points on the boundary and creating a polygon with these points as the corners of the polygon, in practice approximating the curve with linear segments. The dis- cretization is performed by calling the getPoints() method of the Object2D interface. The discretizer also keeps track of the boundary section names in order to pass the information to the PDE solver for the boundary conditions to be applied appropriately. This discretization is done because most mesh generators support the boundary representation based on corner points and linear segments. In the future, splines and other higher-order representations may be supported.

132 7.2 Coefficient-Based Translator

7.2.4.2 Mesh Generator The mesh generator interface consists of a function generate() which takes an Object2D object. The mesh generator classes use the DiscreteDomain2D class to generate the polygonal approximation of the boundary from the Object2D object. The DiscreteDomain2D class traverses the boundary description ob- jects that can be a hierarchy of composite boundary objects and connected lines and curve objects, and generates a flat boundary description of connected lines, i.e., a polygon. From the discrete domain description, each mesh generator class generates the output in the corresponding format. Two mesh generators are supported, Bamg [19], and Easymesh [42]. The classes BamgMeshGenerator and EasymeshMesh- Generator. The mesh generator class GeoMeshGenerator is used to convert aBamgmeshintotheGeo format that one of the solvers, Rheolef, uses.

7.2.4.3 Finite Element Solver The solver interface contains one function, solve() which takes three arguments: An Object2D object describing the boundary, a list of BoundaryCondition objects and a list of DomainRegion objects. BoundaryCondition objects are named and contain the parameters of the boundary conditions for the boundary sections with matching names. The DomainRegion objects represent different regions in the domain that have different PDE coefficients. Only some of the co- efficients can be different in different regions though, depending on which solver that is used. Three different PDE solvers can be used with this prototype. The different mod- ules involved when using each solver can be seen in Figure 7.15 and Figure 7.16.

Coefficient Based Solver With the coefficient-based solver, a solver for a predefined, general PDE is used, with the proper parameters from the present PDE problem. Different solvers for different predefined PDEs can be used. In this work Rheolef and FEMLAB are used to solve equations of the form −∇ · (c∇u)=f. Rheolef [18, 21] is a publicly available package for solving PDEs using finite element methods. Besides some supporting Unix commands, it contains a set of C++ classes to handle domains, domain boundaries, fields and other PDE related objects. The problem is formulated in variational form by writing a C++ routine that is used together with the Rheolef package. The PDE problem mentioned above was converted to variational form manu- ally, together with the different possible boundary conditions. The coefficients of the problem are passed to the solver after the translation process. This formula- tion is independent of the domain geometry, and the occurrence and number of the

133 Chapter 7 Previous Approaches With Examples boundary conditions, as long as the supported kinds of boundary conditions are used. Currently, it handles the three kinds of boundary conditions that are used in the prototype: Dirichlet, Neumann, and Robin conditions. The list of boundary condition objects are passed to the solver which generates the correct problem for- mulation and further calls the Rheolef equation solver. Rheolef supports meshes generated using Bamg, with a converter that converts the mesh into a Geo mesh, that can be processed by the solver. Boundaries can be referred to by names which is utilized by the PDE Modelica translator. The FEMLAB solver interface is simpler since FEMLAB also uses the coeffi- cient-based problem formulation. The FEMLAB programming interface is used and coefficient assignments are generated into a Matlab script file. Mesh gener- ation is handled internally by FEMLAB, but the discrete domain description is transfered through the same interface and a FEMLAB polygon object is generated. A special routine was written though, in order to rearrange the boundary condi- tion indices on the edges because FEMLAB’s polygon creation routine sorts the boundary vertices which invalidates the boundary condition indices on the edges. The rearrange routine finds the vertices according to their coordinates and deter- mines the new edge indices so that the boundary conditions are applied correctly. Finally, mesh generation and solution commands are generated and put into the Matlab script file. The script can then be executed and FEMLAB’s post-processing tools can be used to analyze the solution.

7.2.4.4 Solver Generator in Mathematica The Mathematica solver for the coefficient-based implementation, called Math- FEM, uses the finite element method, but complete equation generation is not yet supported. Instead, a coefficient based PDE is generated together with the coeffi- cient value settings. The problem description generation is similar to that of FEM- LAB described previously, but here a Mathematica script file is generated which is compiled to C++ using MathCode. There is also ongoing work on a solver in Mathematica based on the method of lines using finite elements. Here, space discretization is performed by the solver which only generates time dependent ordinary differential equations. Standard Modelica code can be generated from this solver that can be solved further us- ing existing Modelica environments, for example the modeling and simulation tool Dymola [3], the OpenModelica environment [27,43,44], or the MathModelica en- vironment [40].

7.2.5 Issues with the Coefficient-Based Translator The coefficient based translator uses special operators like line(), curve() and composite() to define domains. Although this is convenient from the user

134 7.2 Coefficient-Based Translator perspective for certain domain geometries, it is not well integrated in the language and not general enough. Too many assumptions need to be made about the format in which the boundaries are specified, compared to the current design. Another issue with the coefficient based solver is that the composite() oper- ator has the following inconsistent properties: • Defining a boundary segment consisting of other boundary segments.

• Increasing the dimension of the domain, i.e., the domain containing the composite() operator automatically becomes a two-dimensional domain. To assure a correct domain, open composite boundaries are automatically closed, using a line segment between the end points. Thus, complex boundary segments that are not treated as one-dimensional bound- ary domains, and which can be used as boundaries in other domains, are not sup- ported. The correct semantics of composite(), not yet implemented, is to define a possibly non-closed boundary segment consisting of several parts.

135 Chapter 7 Previous Approaches With Examples

136 Chapter 8 Related Work

“I never learned from a man who agreed with me.” Robert A. Heinlein

This chapter contains an overview of work done on tools for modeling and sim- ulation of partial differential equation based models, categorized by the user in- teraction level. The first category of tools requires the user to write the problem formulation and the solution algorithm in an ordinary programming language such as Fortran, C or C++, with library support from the tool. The second category pro- vides a high-level interface, a problem description language, or a graphical user interface, where the problem can be specified.

8.1 Libraries and Programming Language-Based Packages

There exist several libraries of PDE solver algorithms with solver routines suitable for different PDE problems. When using these libraries the PDE problem is for- mulated by defining the appropriate functions and data structures and solved by calling the appropriate solver routine. Programming experience and knowledge of programming languages is required to use such libraries. Mathematical and numer- ical knowledge is also needed to use appropriate solution methods. Repositories of solution algorithms exist, for example Netlib [45], with many stand-alone sub- routines that are freely available for download. There are also commercial library packages, such as Diffpack [46], specialized for solving PDE problems with sup- port for both finite difference and finite element methods.

137 Chapter 8 Related Work

Some PDE solver packages are written as frameworks, usually in object-oriented languages, with a level of abstraction that is higher than just using solver libraries directly. A specific PDE problem is solved by a program written in a programming language, usually C++ for object-oriented packages. Classes and objects from the framework are used directly in the program, or new extension classes are added to the framework and subsequently used.

8.1.1 Diffpack

Diffpack [46] is a C++ library package with data structures and numerical methods that can be used to solve PDE problems. The package is divided into a kernel and application-specific toolboxes for use in different engineering areas. Diffpack in- cludes support for solving sparse linear systems using iterative methods and solving non-linear systems, using finite element and finite difference methods with a col- lection of finite elements and finite difference schemes, adaptive meshes, domain decomposition methods and multi-grid methods. The package also includes sup- port for administrative tasks, such as report generation, simulation result handling and data entry using a graphical user interface.

8.1.2 Overture

Overture [47] is a framework for writing PDE solvers in C++ using finite differ- ence or finite volume methods. Built-in classes are used to represent domains, dis- cretized domains, differentiation operators, solution vectors, and other data needed in a PDE solver system. The framework also includes grid generators, solvers, and graphical interface classes for plotting the results. Overture uses overlapping grids to support composition of domain geometries. A grid generator is used to generate overlapping grids which are used for domains composed of several domain components. In a composite domain, common grid points are generated for the overlapping parts of the domain components that com- prise the final domain. This method is also useful for moving overlapping grids where the domain components move over time, in which case the grid is regener- ated each time a domain component is moved.

8.1.3 Compose Compose [48] is an object-oriented framework built on top of Overture. The Com- pose framework has been developed using object-oriented analysis, design and im- plementation, with the objective of separating the classes used for problem formu- lation from the classes concerned with the numerical solution process. Hence, the equation classes, domain classes, and other classes that represent the mathemati- cal model are separated from classes that handle discretization and solution of the

138 8.2 High-Level Packages and Problem Solving Environments

PDEs. Thus, compared to Overture, where the formulation of the mathematical model and the numerical solution method are more tightly coupled, Compose has a higher level of abstraction. However, there is no automatic solver selection support in Compose in contrast to many problem solving environments. Equations and equation discretizers must be associated for an equation to be discretized appropriately. The framework is extensible, so that new types of equations and corresponding equation discretizers can be added to the system.

8.2 High-Level Packages and Problem Solving Environments

One of the first attempts to define a language for PDE problem formulation is PDEL [49]. In such high-level language based or graphical user interface based PDE solving systems, the PDE and boundary conditions are specified directly, ei- ther in text form in a special purpose language or interactively in a specialized editor. The system automatically solves the PDE problem using a general solver or by selecting an appropriate solver from a set of existing solvers. The details about the solution process can be hidden from the user, although it is still possible to manually direct a solver or to select a solver to use.

8.2.1 gPROMS gPROMS is a general modeling language and system for modeling and simulation of dynamic chemical processes, with support for combined lumped and distributed models [50]. gPROMS uses a high-level language for modeling and simulation of mixed systems of integral, partial, and ordinary differential, and algebraic equa- tions (IPDAEs) over rectangular domains.

MODEL TubularReactor

PARAMETER NbrComp AS INTEGER ... ReactorLength , ReactorRadius AS REAL

DISTRIBUTION_DOMAIN Axial AS ( 0 : ReactorLength ) Radial AS ( 0 : ReactorRadius )

Figure 8.1: Example of a model definition in gPROMS.

139 Chapter 8 Related Work

A model definition in the gPROMS language is depicted in Figure 8.1. Axial and Radial in the model are the independent variables. A dependent variable that is to be solved over this domain is declared as fol- lows: VARIABLE Temp AS DISTRIBUTION (Axial, Radial) OF Temperature Here, Temp is of type Temperature that is defined elsewhere, and its geometric domain is the three-dimensional area defined by the independent variables Axial and Radial and their limits as defined in Figure 8.1. This declaration is similar to declaration of arrays in the gPROMS language, which is done using the array keyword: F AS ARRAY (NbrComp) OF Flowrate For partial differentiation the partial operator is used. partial(expr, var) is the partial derivative of the expression expr with respect to the variable var (e.g., ∂rTemp(z,R) with expr=Temp(z,R) and var=r), i.e., the partial operator supports differentiation of entire expressions, not only single variables. For loops are used for restricting the applicability of an expression or equation to a part of the domain. An example can be seen in Figure 8.2, where a boundary condition is defined for the wall of the tubular reactor, which has an axial distribu- tion but not radial. The boundary condition applies for values of z between 0 and ReactorLength.

FOR z:= 0 TO ReactorLength DO − Kr * PARTIAL( Temp(z , ReactorRadius ) , Radial ) = Uh * ( Temp(z , ReactorRadius ) − TWall(z ) ); END

Figure 8.2: For loops for restricting an equation to part of a domain as specified in gPROMS.

8.2.2 PELLPACK PELLPACK [51] is a problem solving environment for specification, solution and post-processing of PDE problems. A PDE language is used to specify the PDE, the domain geometry, the boundary conditions, the discretization method, the solution method, and additional method-specific parameters that are needed as input for solving the problem. There are also tools providing graphical user interfaces for specifying different parts of the problem, from which the specification in the same PDE language is generated.

140 8.2 High-Level Packages and Problem Solving Environments

The PDE language used in PELLPACK is an extension of the ELLPACK lan- guage. The ELLPACK language divides a PDE problem specification into sec- tions where the PDE problem is specified and the solution method is selected. The equation section contains the PDE written in mathematical form. The bound- ary section defines the geometry by defining the domain boundary. The boundary conditions are also written in the boundary section together with the domain boundary descriptions. Other sections are grid, discretization, solu- tion and output which specify the modules to use in different stages of the solution process. The ELLPACK language also supports embedded Fortran code in fortran sections. The PELLPACK language additionally has the mesh section to support the finite-element method, and sections for domain decomposition to support paral- lel solutions. The language is also extended to contain information produced from the graphical user interface that needs to be preserved. In the ELLPACK language, there are predefined names for the solution variable and its derivatives, such as U, UX (∂xU), UYY (∂yyU) and the spatial variables X, Y and Z. These variables are used to specify the PDE. For example:

EQUATION . UXX + UYY + 3 . 0 *UX − 4.0*U=EXP(X+Y)* SIN ( PI*X) The boundary conditions can be specified in different ways, using lines and para- metric curves. A circular domain is defined as in Figure 8.3, where the boundary section specifies the condition that the function is zero on a circle with radius 1 and center (1, 1).Theboundary statement also defines the geometry of the problem. The equation and boundary parts of an ELLPACK program are declarative, whereas the rest, i.e., grid, discretization, fortran etc., are executed in sequential order.

BOUNDARY .U=0.0ON X= 1.− COS( P I *THETA) , & Y= 1.− SIN ( PI*THETA) & FOR THETA = 0 . TO 2.

Figure 8.3: Domain definition and boundary condition assignment in ELLPACK.

The PDE and the boundary conditions written in the PDE language are symbol- ically processed using the Macsyma [52] symbolic system. Procedural (Fortran) code is generated and linked with the selected libraries and executed. The PELL- PACK system contains libraries of modules for the different steps of the solution process, such as domain discretization modules and PDE solver libraries. There are several integrated libraries that are ready to use in the system. It is also possible to integrate new libraries by writing the appropriate interfaces on different levels of the software architecture.

141 Chapter 8 Related Work

8.2.3 PDESpec S. Weerawarana [53] presents a high-level language PDESpec where the PDE prob- lem is specified using objects. Different types of objects are equation, domain, boundary_condition, initial_condition, mesh, decomposition, algorithm, solve and solution. Figure 8.4 shows an example of an equation object describing the steady- state heat flow, where Tx represents ∂xT and Dx(A) is an alias for diff(A, x) which represents ∂x(A). Aliases, the dimension of the problem, and names of the independent variables are defined as defaults for equation objects. The domain “dome” is defined as a separate object, as well as the boundary conditions and their equations. The definition of the domain object can be seen in Figure 8.5.

equation ( name = "steady−state heat flow" , domain = "dome" , expressions =[Dx(k(x,y)* Tx ) + Dy( k (x , y )* Ty ) = 0 ] , properties =[[self−adjoint ] , [steady−state] ] );

Figure 8.4: An equation object in PDESpec describing the steady-state heat flow.

domain ( name = "dome" , type = piecewise_parametric , boundary =[ orientation = clockwise , parametric (x=3, y=.7− t, t, 0, .7), ... ] );

Figure 8.5: Definition of a domain object in PDESpec.

Besides PDESpec, a problem solving environment with an extensible architec- ture for different solvers and an intelligent PDE solver selection based on expert system methodology are presented.

8.2.4 FEMLAB FEMLAB [54], first a Matlab package but currently also a stand-alone application, is a tool for solving PDE problems. Both steady-state and time-dependent problems

142 8.3 Discussion can be solved, as well as scalar PDEs and systems of PDEs. An environment with a graphical user interface as well as the Matlab command line interface is used for problem specification, solution, and visualization. FEMLAB provides different modes, each with several built-in models. In the PDE Mode, the coefficients of a predefined PDE are specified in coefficient form. In general mode, general expressions are given, suited for non-linear problems. In the Physics Application Mode, the model can be described by its physical param- eters rather than through its PDE coefficients. There are several built-in models to choose from in a number of application areas like electromagnetics, heat transfer, structural mechanics etc. There is also support for multiphysics problems, where, for instance both electric and thermal effects can be studied simultaneously. Once a model has been selected, the domain geometry is defined using a built-in two- or three-dimensional geometry editor with predefined geometric objects that can be combined to build complex geometries. Then the PDE and boundary con- ditions are assigned to each part of the domain and its boundary. Next, a finite element mesh is automatically generated, which can be viewed and refined interac- tively. Finally, the problem is solved and the result can be visualized and analyzed.

8.3 Discussion

In the beginning of this chapter we classified available systems for solving PDEs into two groups:

• programming language based packages,

• high-level packages, and/or mathematical modeling languages.

The first category of tools is directed towards users with numerical knowledge and some programming language skills. Also, a varying degree of manual work on the solution must be done before the actual implementation. On the other hand, an efficient solver can be obtained for a specific problem. The second category contains tools that do not require numerical knowledge to the same extent, and the details of the solution process are hidden. This is true especially for the problem solving environments, and in particular FEMLAB. In FEMLAB, existing models can be used directly, with some modification of the parameters and new models can be defined using the graphical user interface. Al- though, there is not really any language support, merely a MATLAB interface for manipulating model parameters and domain objects using a number of helper func- tions. PELLPACK has a more advanced, but still limited, specification language. The tool with the most advanced language is gPROMS, which defines a formal modeling language and supports hierarchical modeling, domain description, etc., but only rectangular domains are supported.

143 Chapter 8 Related Work

PDEModelica belongs to the second category, being a high-level language, and aims to hide numerical solution details from the high level model specified by the user. The closest tool to PDEModelica is gPROMS which only supports rectangu- lar domains, whereas PDEModelica supports general domains. PDEModelica has also a more clear concept of fields, separated from arrays. Separate, component- based description of the domain geometry and possibility to reuse domains with different models is also an addition compared to gPROMS. Furthermore, PDEMod- elica has a more readable, mathematical syntax for explicit domain specification in equations. Possibility to define coordinate systems in PDEModelica allows model- ing with vector notation-based differential operators , e.g., gradient and divergence, which supports expressions and equations that are independent of coordinate sys- tems and number of dimensions. Compared to the other packages PDEModelica has additional object-orientation support, like inheritance, as well as support for a general connection concept and modern and more intuitive syntax.

144 Chapter 9 Conclusion

“Live long and prosper!” Mr. Spock

This chapter contains a summary of the thesis and its contributions, and direc- tions for future work.

9.1 Summary

The aim of this work has been to define a high-level language for general, ana- lytical (continuous), component-based modeling of systems with combined differ- ential and algebraic equations (DAEs) and partial differential equations (PDEs). The goal is to represent mathematical DAE and PDE models in a way that al- lows easy reuse as components in other models. The Modelica language, which already supports ODE models and has object-oriented constructs for hierarchical and component-based modeling, has been used as the basis for such a language, and possible language extensions have been considered to add support for PDE models in Modelica. The necessary additions for supporting PDEs that have been designed and partially implemented are: • Domains. The definition domain of the independent variables. With the spa- tial coordinates as the independent variables, the definition domain is the geometrical region where the dependent variable is defined. Continuous rep- resentation is used and general one, two and three dimensional domains are possible to define using the shown design. • Fields. Continuous representation of a dependent variable over a continuous definition domain. Arrays of fields are possible to declare using the same

145 Chapter 9 Conclusion

syntax as arrays of scalar variables. Field constructors can be used as literal to define constant fields which can be used directly in expressions. Fields are integrated into the language to allow type-checking and automatic dis- cretization. • Equations: – Language additions for differential operators are designed to express partial derivatives. Implementation of differential operators using vec- tor notation (divergence, gradient etc.) using the basic language addi- tions is shown. – Domain specification in equations is designed to allow equations to be defined on sub-domains and on boundaries, i.e., to define boundary conditions. – The integral operator is defined for field reduction, i.e., to convert a field to a scalar or a field with lesser dimension. Since the numerical methods for solving PDEs are not as well developed and automatic as ODE/DAE solvers, it is not possible to hide all discretization details from users. Although, our approach with two layers where only the continuous part needs to be defined by an end user allows fairly high abstraction. PDE-based models can be defined at the discrete level and inserted in a library by a library developer with knowledge about the numerical solution, which an end-user can use directly with an arbitrary domain. Discretization parameters may be required however, but this is also needed during simulation of regular Modelica models. Default values can of course be given by the library model developer. The Modelica PDE Library is usable as it is, but more work is needed. In the current prototype, only most basic PDE models have been implemented, in order to test the design. Many standard PDE models are missing, which can be added to the library for easy reuse. Also, in order to allow modeling using the graphical user interfaces of Modelica tools, i.e., using graphical components and connections, icons and connectors are needed for the components of the library. The major drawback of the Modelica PDE Library is the complicated syntax with declaration of both packages and data structures, which originates from lim- itations in the Modelica language. Another drawback is that the discretization is done using external function calls and the discrete domain is represented using pa- rameters, which is inefficient because the purpose of parameters is not to represent large amounts of data. Thus, granularity of domain discretization is limited when using the library. A separate discretization module integrated into the Modelica compiler could interact with the external solver and handle the discrete domain much more effi- ciently. Hence, the language approach is the natural choice to further develop li- braries of reusable PDE models. The language extensions need to be completed

146 9.2 Contributions and integrated into for example OpenModelica and evaluated further. With an existing discretization and simulation environment environment implementing the new language constructs, the Modelica PDE library can be rewritten using the new language constructs. Future work is discussed further in Section 9.3.

9.2 Contributions

As discussed in Section 8.3, related work that our approach with a high-level mod- eling comes closest to is gPROMS [50]. Here, we give a summary of our contribu- tions compared to the gPROMS language and other related work.

• Object-oriented, component-based modeling with PDEs. Support for hierar- chical modeling exist in the gPROMS language, but is more developed in the Modelica language and the design of PDEModelica extensions are consistent with Modelica language design. • General, complex geometry description. The gPROMS language only sup- ports rectangular domains. Other systems have support for complex geome- try definitions, but lack high level language and component based modeling support. • Component-based geometry definition, i.e., separation of geometry defini- tion from model definition. In the gPROMS language, the domain is declared within the specific low-level models. With our approach, geometries can be defined separately and collected into libraries and reused in new models. • Separation of analytical, continuous model description from discretization and numerical solution. • Field concept for general declaration of spatially distributed variables inte- grated in the language. Compared to the gPROMS language, the field con- cept in this work affords a clearer abstraction and defines a new type of variable. Arrays of such variables can be defined in the same way as arrays of regular, scalar variables. • Clear, mathematical syntax for equations containing fields and explicit do- main specification. The gPROMS language uses for-loops for explicit do- main specification in equation. This is only suitable for rectangular domains. Also, with our approach, the components of the boundary are declared with names, which can be referred to by name in equations for specifying bound- ary conditions. • Hierarchical modeling and decomposition with a general connection con- cept. Using integrals in connectors, connections between ODE/DAE and

147 Chapter 9 Conclusion

PDE based models should be possible, although future work is needed for further evaluation.

9.3 Future Work 9.3.1 Modelica PDE Library Further work is needed on the finite difference and the finite volume packages and to adapt them to the new continuous PDE problem definition design presented in this thesis. Also, the finite difference solver package can be improved to support non-rectangular domains. The Mathematica-based prototypes already implement finite difference solvers which support non-rectangular domains to some extent, which can be adapted to the library. A simple extension of the library is to include domains that use the existing standard boundaries. For example, a CircularDomain can be defined as follows: package CircularDomain extends Domain( redeclare package boundaryP = Circle ); end CircularDomain ; Such a domain can be used directly when defining new problems, instead of declar- ing a general domain each time and replacing the boundary manually.

9.3.1.1 PDE Models Future work is needed for automatic discretization of general user-defined partial differential equations. An intermediate step towards the most general expression is to use predefined PDEs with a connection mechanism so that sub-domains with different PDEs can be connected together to solve more complex problems. A simple case of this support was tested in a previous prototype, see Section 7.2, where the same equation was used with different constants and different source terms in different parts of the domain. It is possible to add new PDE models to the Modelica PDE library. Models that can be formulated using forms as described in the Rheolef User Manual [21] are easily added to the library, by using the external function interface and imple- menting necessary extensions. Other models using different discretization models require more work in terms of external interface functions or internal discretization functions.

9.3.1.2 Domain Definition The prototype Modelica PDE library was implemented and tested with two-di- mensional examples only. A minor extension is necessary for supporting one- dimensional domains. One problem is that the Boundary package and the shape

148 9.3 Future Work functions is a special case in one dimensions, i.e., two separate points are needed as the boundary, instead of a continuous shape function. One possible solution is to define a shape function which only accepts the parameter values 0 and 1 and maps these values to the end points. For three-dimensional models, the same boundary and shape approach is appli- cable, but care must be taken when defining complex boundaries because sub-parts of the boundaries must have matching edges. Boundary shapes other than linear ones, e.g. polygons, can be difficult to use together. The definition of a boundary is also highly dependent on the external domain discretization support. The bidimensional mesh generator bamg wasusedinthis prototype [19]. Other mesh generators exist that have higher level primitives like splines, for example GRUMMP [55], which also have support for three dimensional mesh generation. Support for such higher-level primitives and three-dimensional mesh representation and external access are other future extensions needed in the li- brary. When using higher level boundary primitives with corresponding lower-level components supported by the mesh generator, the internal boundary discretization must be omitted, which indicates that some redesign of parts of the library might be needed.

9.3.1.3 Solution Method The discrete sections of the Modelica PDE library are highly dependent on dis- cretization based on the method of lines. Spatial dependency is removed by dis- cretization of space-distributed variables and elimination of space derivatives, leav- ing only time-dependent variables and time-derivatives. The main discretization method uses the finite element method, which is highly flexible with respect to general, complex domains. An early version of the library also implements the finite difference method, though only for rectangular domains. Future work in- volves investigating whether the finite difference discretization module can be gen- eralized to accept arbitrary domains, possibly using a similar approach as in the Mathematica-based prototypes [16, 35]. Development of a module for finite vol- ume discretization is possible future work to consider.

9.3.2 Connectors Connectors in Modelica represent interfaces between components, from which equations for the complete model are automatically generated. Currently, con- nectors consist of scalar, time dependent variables or arrays of such variables. The extension of connectors to support field variables and models with partial differ- ential equations is not straightforward. The concept of connectors in Modelica is based on flow and non-flow variables, e.g. potential and current as in the electri- cal domain. Corresponding variables in PDEs determine the boundary conditions.

149 Chapter 9 Conclusion

For example, assigning Dirichlet boundary conditions to the boundary of a domain can be seen as connecting a component to that boundary which determines the po- tential. Similarly, Neumann boundary conditions correspond to assigning the flow variable on a boundary. Thus, a natural extension of the connection concept in Modelica involves distributed connectors over given boundaries. This can be done either when declaring connectors where field variables are used, or when writing connect equations. A domain and whole or part of its boundary can be given to specify where the connection should occur. Connections can be between two PDE models or a PDE model and a scalar, time-dependent variable, in which case field reduction as described in Section 4.3.4 can be used. Using connectors would also make the specification of boundary conditions implicit, making it unnecessary to explicitly specify boundary conditions. For example, a connection defining the temperature on a boundary would give Dirichlet conditions, while a connection where the heat flux is known would give Neumann conditions. Further research is needed in this area in order to work out mathematical details and language design and implementation.

9.3.3 Language Implementation This section presents possible future work in the PDEModelica prototype language implementation.

9.3.3.1 Language Implementation of Fields As described in Section 5.1.2.3, the current language implementation of fields in PDEModelica supports continuous represantation, discretization being handled by lower modules. Field variables are represented in the DAE module in the RML-based OpenMod- elica translator with a special type node FIELD consisting of the field value type and a domain. A future discretization module needs to convert variables of these types into arrays. The space discrete format depends on the solution method. For example, if triangular meshes are used, for the finite element method, same for- mat as in the FEMForms library can be used, see Section 5.2.1.3. Recall the field translation example shown above: function f_tmp1 input Real x; input Real y; output Real out ; algorithm out = 2* x+y ; end f_tmp1 ; ... TestDomain omega(...); field Real f = field(f_tmp1(x,y) for (x,y) in omega ) ;

150 9.3 Future Work

Using the FEMForms.Mesh data structure, the discrete version of this code could be as follows, without any changes to the generated field constructor function f_tmp1: Mesh omega(...); Real f [ omega . nv ] = { f_tmp1 ( omega . x[ i ,1] , omega . x[ i , 2 ] ) for i in 1: omega . nv }; // boundary condition indices in omega.x[i ,3] One option could be to generate code that utilizes the PDE library, with the advantage that the same solver and mesh generation implementation can be reused. A design proposal for extensions of the OpenModelica simulation environment is depicted in Figure 9.1, using Corba for communication between the translator and the external PDE discretizer.

Parse Client: Graphical Model Editor

Server: Main Client: OMShell Program (Compiler Corba Interpreter, etc.) Interactive Session Handler

Client: Eclipse Server: PDE Plugin Discretizer

PDE extensions

Figure 9.1: The OpenModelica Compiler architecture with additions for PDE ex- tensions.

151 Chapter 9 Conclusion

152 References

[1] Modelica Association. Modelica – A Unified Object-Oriented Language for Physical Systems Modeling - Language Specification Version 2.2, Feb 2005. http://www.modelica.org/.

[2] Peter Fritzson. Principles of Object-Oriented Modeling and Simulation with Modelica 2.1. Wiley-IEEE Press, 2003. http://www.mathcore.com/ drmodelica/.

[3] Dymola. http://www.dymola.com/, http://www.dynasim. se/.

[4] Peter Fritzson, Peter Aronsson, Håkan Lundvall, Kaj Nyström, Adrian Pop, Levon Saldamli, and David Broman. The OpenModelica Modeling, Simula- tion and Development Environment. In Proc. of the 46th Conference on Sim- ulation and Modelling of the Scandinavian Simulation Society (SIMS2005), Trondheim, Norway, Oct. 13–14 2005.

[5] Andreas Borg, Jens Gustavsson, Levon Saldamli, and John Wilander. Metodologi inom datavetenskap. Rapport från en studiecirkel vid Linköpings universitet, August 2003.

[6] L. Saldamli and P. Fritzson. Object-Oriented Modeling with Partial Differen- tial Equations. In Proc. of Modelica Workshop 2000, Lund, Sweden, October 2000. http://www.modelica.org/.

[7] L. Saldamli and P. Fritzson. A Modelica-based Language for Object-Oriented Modeling with Partial Differential Equations. In A. Heemink, L. Dekker, H. de Swaan Arons, I. Smith, and T. van Stijn, editors, Proc. of the 4th Inter- national EUROSIM Congress, Delft, The Netherlands, June 2001.

[8] L. Saldamli and P. Fritzson. Domains and Partial Differential Equations in Modelica. In Tor Anders Hauge, Bernt Lie, Rolf Ergon, Marta Due nas Díes, Glenn-Ole Kaasa, Anita Dale, Bjorn¯ Glemmestad, and Are Mjaavatten, edi- tors, Proc. of the 42nd SIMS Conference, Porsgrunn, Norway, October 2001.

153 References

[9] L. Saldamli, P. Fritzson, and B. Bachmann. Extending Modelica for Partial Differential Equations. In Martin Otter, editor, Proc. of the 2nd International Modelica Conference, Oberpfaffenhofen, Germany, March 2002. [10] L. Saldamli and P. Fritzson. Field Type and Field Constructor in Modelica. In Proc. of SIMS 2004, the 45th Conference on Simulation and Modelling, Copenhagen, Denmark, September 2004.

[11] L. Saldamli, B. Bachmann, H Wiesmann, and P. Fritzson. A Framework for Describing and Solving PDE Models in Modelica. In Proceedings of the 4th International Modelica Conference, Hamburg, Germany, March 7–8 2005. [12] Modelica Association. Modelica – A Unified Object-Oriented Language for Physical Systems Modeling - Language Specification Version 2.1, Jan 2004. http://www.modelica.org/. [13] Modelica Association. Modelica Standard Library. http://www. modelica.org/libraries.shtml. [14] Hubertus Tummescheit. Design and Implementation of Object-Oriented Model Libraries using Modelica. PhD thesis, Lund Institute of Technology, 2002. [15] G. D. Smith. Numerical Solution of Partial Differential Equations: Finite Difference Methods, chapter one, pages 6–9. Oxford University Press, third edition, 1985. [16] K. Sheshadri and P. Fritzson. A General Symbolic PDE-Solver Generator – Explicit Schemes. Scientific Programming, 11:1, 2003. [17] Gerald Farin. Curves and Surfaces for CAGD. Academic Press, fifth edition, 2002. [18] Pierre Saramito, Nicolas Roquet, and Jocelyn Etienne. Rheolef home page. http://www-lmc.imag.fr/lmc-edp/Pierre.Saramito/ rheolef/, 2002. [19] BAMG home page. http://www-rocq.inria.fr/gamma/cdrom/ www/bamg/eng.htm. [20] K. Eriksson, D. Estep, P. Hansbo, and C. Johnson. Computational Differential Equations. Studentlitteratur, 1996. [21] Pierre Saramito, Nicolas Roquet, and Jocelyn Etienne. Rheolef users man- ual. LMC-IMAG, 2002. http://www-lmc.imag.fr/lmc-edp/ Pierre.Saramito/rheolef/usrman.ps.gz.

154 References

[22] Eric W. Weisstein. Curvilinear coordinates. From MathWorld– A Wolfram Web Resource. http://mathworld.wolfram.com/ CurvilinearCoordinates.html. [23] Eric W. Weisstein. Scale factor. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/ScaleFactor.html. [24] Robert van Engelen and Lex Wolters. A High-Level Language and Interpreter for the Use of Mathematical Vector Notation in PDE-Problem Specifications. Technical Report 97-05, Department of Computer Science, Leiden Univer- sity, October 1997. [25] Robert van Engelen. Ctadel: A Generator of Efficient Codes. PhD thesis, LIACS, Leiden University, October 1998. [26] Eric W. Weisstein. Divergence. From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/Divergence.html. [27] OpenModelica. http://www.ida.liu.se/labs/pelab/ modelica/OpenModelica.html. [28] ANTLR home page. http://www.antlr.org/. [29] Mikael Pettersson. Compiling Natural Semantics., volume 1549 of Lecture Notes in Computer Science. Springer, 1999. [30] P. Fritzson. Efficient Language Implementation by Natural Semantics. Per- sonal communication. Book draft 1996. [31] G. Kahn. Natural semantics. In Proceedings of the Symposium on Theoretical Aspects of Computer Science, STACS’87, volume 247 of LNCS, pages 22–39. Springer-Verlag, 1987. [32] R. Milner, M. Tofte, R. Harper, and D. MacQueen. The Definition of Standard ML (Revised). MIT Press, 1997. [33] D. Kågedal. A Natural Semantics Specification for the Equation-based Mod- eling Language Modelica. Master’s thesis, PELAB, Dept. of Computer and Information Science, Linköpings universitet, October 1998. LiTH-IDA-Ex- 98/48. [34] D. Kågedal and P. Fritzson. Generating a Modelica Compiler from Natu- ral Semantics Specifications. In Proceedings of the 1998 Summer Computer Simulation Conference (SCSC’98), Reno, Nevada, July 1998. [35] K. Sheshadri and P. Fritzson. A General Symbolic PDE-Solver Generator – Beyond Explicit Schemes. Scientific Programming, 11:2, 2003.

155 References

[36] K. Sheshadri and P. Fritzson. MathModelica – An Object Oriented Math- ematical Modeling and Simulation Environment. Accepted to Mathematica Journal, Oct 2004. [37] K. Sheshadri and P. Fritzson. Personal communication. [38] COMSOL AB. FEMLAB Model Library, v2.3 edition. [39] K. Sheshadri and P. Fritzson. A Mathematica-based PDE-solver generator. In Proc. of the Scandinavian Simulation Society (SIMS) Conference, Linköping University, Linköping, Sweden, September 1999. [40] P. Fritzson, J. Gunnarsson, and M. Jirstrand. MathModelica - An Exten- sible Modeling and Simulation Environment with Integrated Graphics and Literate Programming. In Proc. of the 2nd International Modelica Confer- ence, Munich, March 2002. http://www.modelica.org/. See also http://www.mathcore.com/. [41] MathCore AB. http://www.mathcore.com/. [42] EasyMesh home page. http://www-dinma.univ.trieste.it/ ~nirftc/research/easymesh/easymesh.htm%l. [43] P. Fritzson, P. Aronsson, P. Bunus, V. Engelson, L. Saldamli, H. Johansson, and A. Karström. The Open Source Modelica Project. In Martin Otter, ed- itor, Proc. of the 2nd International Modelica Conference, Oberpfaffenhofen, Germany, March 2002. http://www.modelica.org/. [44] P. Aronsson, P. Fritzson, L. Saldamli, and P. Bunus. Incremental Declaration Handling in Open Source Modelica. In Martin Otter, editor, Proc. of the SIMS - 43rd Conference on Simulation and Modeling, Oulu, Finland, September 2002. [45] NETLIB home page. http://www.netlib.org/. [46] Diffpack home page. http://www.diffpack.com/. [47] Overture home page. http://www.llnl.gov/CASC/Overture/. [48] K. Åhlander. An Object-Oriented Framework for PDE Solvers. PhD thesis, Uppsala University, 1999. [49] A. F. Cardenas and W. J. Karplus. PDEL — a Language for Partial Differen- tial Equations. Communications of the ACM, 13(3):184–191, March 1970. [50] M. Oh. Modelling and Simulation of Combined Lumped and Distributed Processes. PhD thesis, University of London, 1995.

156 References

[51] E. N. Houstis, J. R. Rice, S. Weerawarana, A. C. Catlin, P. Papachiou, K.-Y. Wang, and M. Gaitatzes. PELLPACK: A Problem-Solving Environment for PDE-Based Applications on Multicomputer Platforms. ACM Transactions on Mathematical Software, 24(1):30–73, March 1998. [52] Macsyma home page. http://www.scientek.com/macsyma/ main.htm.

[53] S. Weerawarana. Problem Solving Environments for Partial Differential Equation based Applications. PhD thesis, Department of Computer Sciences, Purdue University, August 1994. [54] FEMLAB home page. http://www.femlab.com/. [55] GRUMMP home page. http://tetra.mech.ubc.ca/GRUMMP/ index.html.

157 References

158 159 Appendix A UML Notation

Appendix A UML Notation

ClassName Class +attribute: Type +method(paramType): returnType

ParameterName: Parameterized ParameterizedClass Class

BaseClass

Inheritance

SubClass

Association ClassA ClassB

n Composition Owner Member

n Aggregate Referer Reference 160 Appendix B Plotting Simulation Results

The MATLAB functions shown here can be used to plot simulation results stored in a MATLAB .mat file. The MATLAB script package from Dymola (dymget etc.) is required in order to access variables.

B.1 Visualization of Domain Boundary

function showboundary( matfile ,name) % Show the boundary of a domain defined using the Modelica PDE Library % matfile : .mat−file containing simulation result % name: name of the discrete domain containing the domain boundary % Example: showboundary( ’ test .mat ’ , ’pde . ddomain ’) res=dymload ( matfile ); nodes=cell2mat (dymget( res ,[ name ’ . polygon ’ ])); x=nodes (2:2: size( nodes ,1) ,1); y=nodes (2:2: size( nodes ,1) ,2); fill (x,y, ’b’ ); B.2 Visualization of Meshes

function showmesh ( matfile , name) % Show a triangular mesh generated by Modelica PDE Library % matfile : .mat−file containing simulation result . % name: name of the discrete domain containing the mesh. % Example : showmesh ( ’ t e st . mat ’ , ’pde . ddomain ’)

res=dymload ( matfile ); nodes=cell2mat (dymget( res ,[ name ’.mesh.x’])); tris=cell2mat(dymget(res ,[name ’.mesh. triangle ’ ])); t=tris (2:2:size(tris ,1),1:3); x=nodes (2:2: size( nodes ,1) ,1); y=nodes (2:2: size( nodes ,1) ,2); trimesh (t ,x,y, ’Color ’ , ’black’); B.3 Visualization of Steady-state Fields

161 Appendix B Plotting Simulation Results function showfield_ind ( matfile , name) % Show an i n d i r e c t f i e l d from a steady−state simulation % Indirect fields are used in the FEMForms package in the % Modelica PDE Library , with Rheolef as the external solver . % matfile : .mat−file containing simulation result . % name: Name of the field variable . % Example: showfield_ind (’ test .mat’ , ’pde. fd ’) res=dymload ( matfile ); nodes=cell2mat (dymget( res ,[ name ’ . ddomain . mesh . x ’ ])); t r i s =cell2mat ( dymget( res , [ name ’ . ddomain . mesh . triangle ’ ])); valsu=cell2mat (dymget(res ,[name ’.val_u’])) ’; valsb=cell2mat (dymget(res ,[name ’.val_b’])) ’; uindices=cell2mat (dymget(res ,[name ’. u_indices ’ ])) ’; bindices=cell2mat (dymget(res ,[name ’. b_indices ’ ])) ’; t=tris (2:2: size (tris ,1) ,1:3); x=nodes (2:2: size ( nodes ,1) ,1); y=nodes (2:2: size ( nodes ,1) ,2); ui=uindices (: ,1); bi=bindices (: ,1); z(ui)=valsu (: ,1); z(bi)=valsb (: ,1); trisurf(t ,x,y,z, ’FaceColor ’ , ’interp’, ’EdgeColor ’ , ’interp’); B.4 Visualization of Time-dependent Fields function showfieldt_ind(matfile , name, timestep ) % Show an i n d i r e c t f i e l d from a time−dependent simulation % Indirect fields are used in FEMForms, with the Rheolef solver . % matfile : matfile containing simulation result . % name: Name of the field variable . % timestep : The time step to show, % an integer index 1−number of simulation steps % Example: showfieldt_ind ( ’ test . mat ’ , ’pde . fd ’ , 3000) res=dymload ( matfile ); nodes=cell2mat (dymget( res ,[ name ’ . ddomain . mesh . x ’ ])); t r i s =cell2mat ( dymget( res , [ name ’ . ddomain . mesh . triangle ’ ])); valsu=cell2mat (dymget(res ,[name ’.val_u’])) ’; valsb=cell2mat (dymget(res ,[name ’.val_b’])) ’; uindices=cell2mat (dymget(res ,[name ’. u_indices ’ ])) ’; bindices=cell2mat (dymget(res ,[name ’. b_indices ’ ])) ’; t=tris (2:2: size (tris ,1) ,1:3); x=nodes (2:2: size ( nodes ,1) ,1); y=nodes (2:2: size ( nodes ,1) ,2); ui=uindices (: ,1); bi=bindices (: ,1); z(ui)=valsu (: , timestep ); z(bi)=valsb (: , timestep ); trisurf(t ,x,y,z, ’FaceColor ’ , ’interp’, ’EdgeColor ’ , ’interp’);

162 Index

backward difference, 20 normal derivative, 18 boundary conditions, 17 ODE, see ordinary differential equa- central difference, 20 tions ordinary differential equations, 16 definition domain, 16, 17 dependent variables, 16 package design, 25 derivative partial derivative, 17 directional, 17 partial differential equations, 17 normal, see normal derivative PDE, see partial differential equations partial, see partial derivative PDE library, 25 difference stationary problem, 17 backward, 20 central, 20 time-dependent problem, 17 forward, 20 differential equations ordinary, 16 partial, 17 directional derivative, 17 domain, 17 definition, 16

FEM, see finite element method field, 16 finite element method, 22 finite difference methods, 20 forward difference, 20 independent variables, 16 initial conditions, 18 method of lines, 23

163

Department of Computer and Information Science Linköpings universitet Dissertations Linköping Studies in Science and Technology

No 14 Anders Haraldsson: A Program Manipulation Non-Monotonic Reasoning, 1987, ISBN 91-7870- System Based on Partial Evaluation, 1977, ISBN 183-X. 91-7372-144-1. No 170 Zebo Peng: A Formal Methodology for Automated No 17 Bengt Magnhagen: Probability Based Verification Synthesis of VLSI Systems, 1987, ISBN 91-7870- of Time Margins in Digital Designs, 1977, ISBN 225-9. 91-7372-157-3. No 174 Johan Fagerström: A Paradigm and System for No 18 Mats Cedwall: Semantisk analys av process- Design of Distributed Systems, 1988, ISBN 91- beskrivningar i naturligt språk, 1977, ISBN 91- 7870-301-8. 7372-168-9. No 192 Dimiter Driankov: Towards a Many Valued Logic No 22 Jaak Urmi: A Machine Independent LISP Compil- of Quantified Belief, 1988, ISBN 91-7870-374-3. er and its Implications for Ideal Hardware, 1978, No 213 Lin Padgham: Non-Monotonic Inheritance for an ISBN 91-7372-188-3. Object Oriented Knowledge Base, 1989, ISBN 91- No 33 Tore Risch: Compilation of Multiple File Queries 7870-485-5. in a Meta-Database System 1978, ISBN 91-7372- No 214 Tony Larsson: A Formal Hardware Description and 232-4. Verification Method, 1989, ISBN 91-7870-517-7. No 51 Erland Jungert: Synthesizing Database Structures No 221 Michael Reinfrank: Fundamentals and Logical from a User Oriented Data Model, 1980, ISBN 91- Foundations of Truth Maintenance, 1989, ISBN 91- 7372-387-8. 7870-546-0. No 54 Sture Hägglund: Contributions to the Develop- No 239 Jonas Löwgren: Knowledge-Based Design Support ment of Methods and Tools for Interactive Design and Discourse Management in User Interface Man- of Applications Software, 1980, ISBN 91-7372- agement Systems, 1991, ISBN 91-7870-720-X. 404-1. No 244 Henrik Eriksson: Meta-Tool Support for Knowl- No 55 Pär Emanuelson: Performance Enhancement in a edge Acquisition, 1991, ISBN 91-7870-746-3. Well-Structured Pattern Matcher through Partial Evaluation, 1980, ISBN 91-7372-403-3. No 252 Peter Eklund: An Epistemic Approach to Interac- tive Design in Multiple Inheritance Hierar- No 58 Bengt Johnsson, Bertil Andersson: The Human- chies,1991, ISBN 91-7870-784-6. Computer Interface in Commercial Systems, 1981, ISBN 91-7372-414-9. No 258 Patrick Doherty: NML3 - A Non-Monotonic For- malism with Explicit Defaults, 1991, ISBN 91- No 69 H. Jan Komorowski: A Specification of an Ab- 7870-816-8. stract Prolog Machine and its Application to Partial Evaluation, 1981, ISBN 91-7372-479-3. No 260 Nahid Shahmehri: Generalized Algorithmic De- bugging, 1991, ISBN 91-7870-828-1. No 71 René Reboh: Knowledge Engineering Techniques and Tools for Expert Systems, 1981, ISBN 91- No 264 Nils Dahlbäck: Representation of Discourse-Cog- 7372-489-0. nitive and Computational Aspects, 1992, ISBN 91- 7870-850-8. No 77 Östen Oskarsson: Mechanisms of Modifiability in large Software Systems, 1982, ISBN 91-7372-527- No 265 Ulf Nilsson: Abstract Interpretations and Abstract 7. Machines: Contributions to a Methodology for the Implementation of Logic Programs, 1992, ISBN 91- No 94 Hans Lunell: Code Generator Writing Systems, 7870-858-3. 1983, ISBN 91-7372-652-4. No 270 Ralph Rönnquist: Theory and Practice of Tense- No 97 Andrzej Lingas: Advances in Minimum Weight bound Object References, 1992, ISBN 91-7870- Triangulation, 1983, ISBN 91-7372-660-5. 873-7. No 109 Peter Fritzson: Towards a Distributed Program- No 273 Björn Fjellborg: Pipeline Extraction for VLSI Data ming Environment based on Incremental Compila- Path Synthesis, 1992, ISBN 91-7870-880-X. tion,1984, ISBN 91-7372-801-2. No 276 Staffan Bonnier: A Formal Basis for Horn Clause No 111 Erik Tengvald: The Design of Expert Planning Logic with External Polymorphic Functions, 1992, Systems. An Experimental Operations Planning ISBN 91-7870-896-6. System for Turning, 1984, ISBN 91-7372-805-5. No 277 Kristian Sandahl: Developing Knowledge Man- No 155 Christos Levcopoulos: Heuristics for Minimum agement Systems with an Active Expert Methodolo- Decompositions of Polygons, 1987, ISBN 91-7870- gy, 1992, ISBN 91-7870-897-4. 133-3. No 281 Christer Bäckström: Computational Complexity No 165 James W. Goodwin: A Theory and System for of Reasoning about Plans, 1992, ISBN 91-7870- No 461 Lena Strömbäck: User-Defined Constructions in 979-2. Unification-Based Formalisms,1997, ISBN 91- No 292 Mats Wirén: Studies in Incremental Natural Lan- 7871-857-0. guage Analysis, 1992, ISBN 91-7871-027-8. No 462 Lars Degerstedt: Tabulation-based Logic Program- No 297 Mariam Kamkar: Interprocedural Dynamic Slic- ming: A Multi-Level View of Query Answering, ing with Applications to Debugging and Testing, 1996, ISBN 91-7871-858-9. 1993, ISBN 91-7871-065-0. No 475 Fredrik Nilsson: Strategi och ekonomisk styrning - No 302 Tingting Zhang: A Study in Diagnosis Using Clas- En studie av hur ekonomiska styrsystem utformas sification and Defaults, 1993, ISBN 91-7871-078-2. och används efter företagsförvärv, 1997, ISBN 91- 7871-914-3. No 312 Arne Jönsson: Dialogue Management for Natural Language Interfaces - An Empirical Approach, No 480 Mikael Lindvall: An Empirical Study of Require- 1993, ISBN 91-7871-110-X. ments-Driven Impact Analysis in Object-Oriented Software Evolution, 1997, ISBN 91-7871-927-5. No 338 Simin Nadjm-Tehrani: Reactive Systems in Phys- ical Environments: Compositional Modelling and No 485 Göran Forslund: Opinion-Based Systems: The Co- Framework for Verification, 1994, ISBN 91-7871- operative Perspective on Knowledge-Based Deci- 237-8. sion Support, 1997, ISBN 91-7871-938-0. No 371 Bengt Savén: Business Models for Decision Sup- No 494 Martin Sköld: Active Database Management Sys- port and Learning. A Study of Discrete-Event Man- tems for Monitoring and Control, 1997, ISBN 91- ufacturing Simulation at Asea/ABB 1968-1993, 7219-002-7. 1995, ISBN 91-7871-494-X. No 495 Hans Olsén: Automatic Verification of Petri Nets in No 375 Ulf Söderman: Conceptual Modelling of Mode a CLP framework, 1997, ISBN 91-7219-011-6. Switching Physical Systems, 1995, ISBN 91-7871- No 498 Thomas Drakengren: Algorithms and Complexity 516-4. for Temporal and Spatial Formalisms, 1997, ISBN No 383 Andreas Kågedal: Exploiting Groundness in Log- 91-7219-019-1. ic Programs, 1995, ISBN 91-7871-538-5. No 502 Jakob Axelsson: Analysis and Synthesis of Hetero- No 396 George Fodor: Ontological Control, Description, geneous Real-Time Systems, 1997, ISBN 91-7219- Identification and Recovery from Problematic Con- 035-3. trol Situations, 1995, ISBN 91-7871-603-9. No 503 Johan Ringström: Compiler Generation for Data- No 413 Mikael Pettersson: Compiling Natural Semantics, Parallel Programming Langugaes from Two-Level 1995, ISBN 91-7871-641-1. Semantics Specifications, 1997, ISBN 91-7219- 045-0. No 414 Xinli Gu: RT Level Testability Improvement by Testability Analysis and Transformations, 1996, No 512 Anna Moberg: Närhet och distans - Studier av ISBN 91-7871-654-3. kommunikationsmmönster i satellitkontor och flexi- bla kontor, 1997, ISBN 91-7219-119-8. No 416 Hua Shu: Distributed Default Reasoning, 1996, ISBN 91-7871-665-9. No 520 Mikael Ronström: Design and Modelling of a Par- allel Data Server for Telecom Applications, 1998, No 429 Jaime Villegas: Simulation Supported Industrial ISBN 91-7219-169-4. Training from an Organisational Learning Perspec- tive - Development and Evaluation of the SSIT No 522 Niclas Ohlsson: Towards Effective Fault Method, 1996, ISBN 91-7871-700-0. Prevention - An Empirical Study in Software Engi- neering, 1998, ISBN 91-7219-176-7. No 431 Peter Jonsson: Studies in Action Planning: Algo- rithms and Complexity, 1996, ISBN 91-7871-704- No 526 Joachim Karlsson: A Systematic Approach for Pri- 3. oritizing Software Requirements, 1998, ISBN 91- 7219-184-8. No 437 Johan Boye: Directional Types in Logic Program- ming, 1996, ISBN 91-7871-725-6. No 530 Henrik Nilsson: Declarative Debugging for Lazy Functional Languages, 1998, ISBN 91-7219-197-x. No 439 Cecilia Sjöberg: Activities, Voices and Arenas: Participatory Design in Practice, 1996, ISBN 91- 7871-728-0. No 555 Jonas Hallberg: Timing Issues in High-Level Syn- No 448 Patrick Lambrix: Part-Whole Reasoning in De- thesis,1998, ISBN 91-7219-369-7. scription Logics, 1996, ISBN 91-7871-820-1. No 561 Ling Lin: Management of 1-D Sequence Data - From Discrete to Continuous, 1999, ISBN 91-7219- 402-2. No 452 Kjell Orsborn: On Extensible and Object-Rela- tional Database Technology for Finite Element No 563 Eva L Ragnemalm: Student Modelling based on Analysis Applications, 1996, ISBN 91-7871-827-9. Collaborative Dialogue with a Learning Compan- ion, 1999, ISBN 91-7219-412-X. No 459 Olof Johansson: Development Environments for Complex Product Models, 1996, ISBN 91-7871- No 567 Jörgen Lindström: Does Distance matter? On geo- 855-4. graphical dispersion in organisations, 1999, ISBN 91-7219-439-1. No 689 Joakim Gustafsson: Extending Temporal Action No 582 Vanja Josifovski: Design, Implementation and Logic, 2001, ISBN 91-7373-017-3. Evaluation of a Distributed Mediator System for No 720 Carl-Johan Petri: Organizational Information Pro- Data Integration, 1999, ISBN 91-7219-482-0. vision - Managing Mandatory and Discretionary Use No 589 Rita Kovordányi: Modeling and Simulating Inhib- of Information Technology, 2001, ISBN-91-7373- itory Mechanisms in Mental Image Reinterpretation 126-9. - Towards Cooperative Human-Computer Creativi- No 724 Paul Scerri: Designing Agents for Systems with Ad- ty, 1999, ISBN 91-7219-506-1. justable Autonomy, 2001, ISBN 91 7373 207 9. No 592 Mikael Ericsson: Supporting the Use of Design No 725 Tim Heyer: Semantic Inspection of Software Arti- Knowledge - An Assessment of Commenting facts: From Theory to Practice, 2001, ISBN 91 7373 Agents, 1999, ISBN 91-7219-532-0. 208 7. No 593 Lars Karlsson: Actions, Interactions and Narra- No 726 Pär Carlshamre: A Usability Perspective on Re- tives, 1999, ISBN 91-7219-534-7. quirements Engineering - From Methodology to Prod- No 594 C. G. Mikael Johansson: Social and Organization- uct Development, 2001, ISBN 91 7373 212 5. al Aspects of Requirements Engineering Methods - No 732 Juha Takkinen: From Information Management to A practice-oriented approach, 1999, ISBN 91- Task Management in Electronic Mail, 2002, ISBN 7219-541-X. 91 7373 258 3. No 595 Jörgen Hansson: Value-Driven Multi-Class Over- No 745 Johan Åberg: Live Help Systems: An Approach to load Management in Real-Time Database Systems, Intelligent Help for Web Information Systems, 1999, ISBN 91-7219-542-8. 2002, ISBN 91-7373-311-3. No 596 Niklas Hallberg: Incorporating User Values in the No 746 Rego Granlund: Monitoring Distributed Team- Design of Information Systems and Services in the work Training, 2002, ISBN 91-7373-312-1. Public Sector: A Methods Approach, 1999, ISBN No 757 Henrik André-Jönsson: Indexing Strategies for 91-7219-543-6. Time Series Data, 2002, ISBN 917373-346-6. No 597 Vivian Vimarlund: An Economic Perspective on No 747 Anneli Hagdahl: Development of IT-suppor-ted In- the Analysis of Impacts of Information Technology: ter-organisational Collaboration - A Case Study in From Case Studies in Health-Care towards General the Swedish Public Sector, 2002, ISBN 91-7373- Models and Theories, 1999, ISBN 91-7219-544-4. 314-8. No 749 Sofie Pilemalm: Information Technology for Non- No 598 Johan Jenvald: Methods and Tools in Computer- Profit Organisations - Extended Participatory De- Supported Taskforce Training, 1999, ISBN 91- sign of an Information System for Trade Union Shop 7219-547-9. Stewards, 2002, ISBN 91-7373- No 607 Magnus Merkel: Understanding and enhancing 318-0. translation by parallel text processing, 1999, ISBN No 765 Stefan Holmlid: Adapting users: Towards a theory 91-7219-614-9. of use quality, 2002, ISBN 91-7373-397-0. No 611 Silvia Coradeschi: Anchoring symbols to sensory No 771 Magnus Morin: Multimedia Representations of data, 1999, ISBN 91-7219-623-8. Distributed Tactical Operations, 2002, ISBN 91- No 613 Man Lin: Analysis and Synthesis of Reactive 7373-421-7. Systems: A Generic Layered Architecture No 772 Pawel Pietrzak: A Type-Based Framework for Lo- Perspective, 1999, ISBN 91-7219-630-0. cating Errors in Constraint Logic Programs, 2002, ISBN 91-7373-422-5. No 618 Jimmy Tjäder: Systemimplementering i praktiken No 758 Erik Berglund: Library Communication Among - En studie av logiker i fyra projekt, 1999, ISBN 91- Programmers Worldwide, 2002, 7219-657-2. ISBN 91-7373-349-0. No 627 Vadim Engelson: Tools for Design, Interactive Simulation, and Visualization of Object-Oriented Models in Scientific Computing, 2000, ISBN 91- No 774 Choong-ho Yi: Modelling Object-Oriented 7219-709-9. Dynamic Systems Using a Logic-Based Framework, No 637 Esa Falkenroth: Database Technology for Control 2002, ISBN 91-7373-424-1. and Simulation, 2000, ISBN 91-7219-766-8. No 779 Mathias Broxvall: A Study in the No 639 Per-Arne Persson: Bringing Power and Computational Complexity of Temporal Knowledge Together: Information Systems Design Reasoning, 2002, ISBN 91-7373-440-3. for Autonomy and Control in Command Work, No 793 Asmus Pandikow: A Generic Principle for 2000, ISBN 91-7219-796-X. Enabling Interoperability of Structured and No 660 Erik Larsson: An Integrated System-Level Design Object-Oriented Analysis and Design Tools, 2002, for Testability Methodology, 2000, ISBN 91-7219- ISBN 91-7373-479-9. 890-7. No 785 Lars Hult: Publika Informationstjänster. En studie av den Internetbaserade encyklopedins bruksegen- No 688 Marcus Bjäreland: Model-based Execution skaper, 2003, ISBN 91-7373-461-6. Monitoring, 2001, ISBN 91-7373-016-5. No 800 Lars Taxén: A Framework for the Coordination of 85295-82-5. Complex Systems´ Development, 2003, ISBN 91- No 918 Jonas Lundberg: Shaping Electronic News: Gen- 7373-604-X re Perspectives on Interaction Design, 2004, ISBN No 808 Klas Gäre: Tre perspektiv på förväntningar och 91-85297-14-3. förändringar i samband med införande av informa- No 900 Mattias Arvola: Shades of use: The dynamics of tionsystem, 2003, ISBN 91-7373-618-X. interaction design for sociable use, 2004, ISBN No 821 Mikael Kindborg: Concurrent Comics - program- 91-85295-42-6. ming of social agents by children, 2003, No 920 Luis Alejandro Cortés: Verification and Sched- ISBN 91-7373-651-1. uling Techniques for Real-Time Embedded Sys- No 823 Christina Ölvingson: On Development of Infor- tems, 2004, ISBN 91-85297-21-6. mation Systems with GIS Functionality in Public No 929 Diana Szentivanyi: Performance Studies of Health Informatics: A Requirements Engineering Fault-Tolerant Middleware, 2005, ISBN 91- Approach, 2003, ISBN 91-7373-656-2. 85297-58-5. No 828 Tobias Ritzau: Memory Efficient Hard Real-Time No 933 Mikael Cäker: Management Accounting as Con- Garbage Collection, 2003, ISBN 91-7373-666-X. structing and Opposing Customer Focus: Three No 833 Paul Pop: Analysis and Synthesis of Case Studies on Management Accounting and Communication-Intensive Heterogeneous Real- Customer Relations, 2005, ISBN 91-85297-64-X. Time Systems, 2003, ISBN 91-7373-683-X. No 937 Jonas Kvarnström: TALplanner and Other Ex- No 852 Johan Moe: Observing the Dynamic tensions to Temporal Action Logic, 2005, ISBN Behaviour of Large Distributed Systems to Improve 91-85297-75-5. Development and Testing - An Emperical Study in No 938 Bourhane Kadmiry: Fuzzy Gain-Scheduled Vis- Software Engineering, 2003, ISBN 91-7373-779-8. ual Servoing for Unmanned Helicopter, 2005, No 867 Erik Herzog: An Approach to Systems Engineer- ISBN 91-85297-76-3. ing Tool Data Representation and Exchange, 2004, No 945 Gert Jervan: Hybrid Built-In Self-Test and Test ISBN 91-7373-929-4. Generation Techniques for Digital Systems, 2005, No 872 Aseel Berglund: Augmenting the Remote Control: ISBN: 91-85297-97-6. Studies in Complex Information Navigation for No 946 Anders Arpteg: Intelligent Semi-Structured In- Digital TV, 2004, ISBN 91-7373-940-5. formation Extraction, 2005, ISBN 91-85297-98-4. No 869 Jo Skåmedal: Telecommuting’s Implications on No 947 Ola Angelsmark: Constructing Algorithms for Travel and Travel Patterns, 2004, ISBN 91-7373- Constraint Satisfaction and Related Problems - 935-9. Methods and Applications, 2005, ISBN 91- No 870 Linda Askenäs: The Roles of IT - Studies of Or- 85297-99-2. ganising when Implementing and Using Enterprise No 963 Calin Curescu: Utility-based Optimisation of Re- Systems, 2004, ISBN 91-7373-936-7. source Allocation for Wireless Networks, 2005. No 874 Annika Flycht-Eriksson: Design and Use of On- ISBN 91-85457-07-8. tologies in Information-Providing Dialogue Sys- Björn Johansson: tems, 2004, ISBN 91-7373-947-2. No 972 Joint Control in Dynamic Situ- No 873 Peter Bunus: Debugging Techniques for Equation- ations, 2005, ISBN 91-85457-31-0. Based Languages, 2004, ISBN 91-7373-941-3. No 974 Dan Lawesson: An Approach to Diagnosability No 876 Jonas Mellin: Resource-Predictable and Effi- Analysis for Interacting Finite State Systems, cient Monitoring of Events, 2004, ISBN 91-7373- 2005, ISBN 91-85457-39-6. 956-1. No 979 Claudiu Duma: Security and Trust Mechanisms for Groups in Distributed Services, 2005, ISBN No 883 Magnus Bång: Computing at the Speed of Paper: 91-85457-54-X. Ubiquitous Computing Environments for Health- No 983 Sorin Manolache: Analysis and Optimisation of care Professionals, 2004, ISBN 91-7373-971-5 Real-Time Systems with Stochastic Behaviour, No 882 Robert Eklund: Disfluency in Swedish 2005, ISBN 91-85457-60-4. human-human and human-machine travel booking No 986 Yuxiao Zhao: Standards-Based Application Inte- dialogues, 2004. ISBN 91-7373-966-9. gration for Business-to-Business Communica- No 887 Anders Lindström: English and other Foreign Lin- tions, 2005, ISBN 91-85457-66-3. quistic Elements in Spoken Swedish. Studies of No 1004 Patrik Haslum: Admissible Heuristics for Auto- Productive Processes and their Modelling using Fi- mated Planning, 2006, ISBN 91-85497-28-2. nite-State Tools, 2004, ISBN 91-7373-981-2. No 1005 Aleksandra Tesanovic: Developing Re- No 889 Zhiping Wang: Capacity-Constrained Production- usable and Reconfigurable Real-Time Software inventory systems - Modellling and Analysis in using Aspects and Components, 2006, ISBN 91- both a traditional and an e-business context, 2004, 85497-29-0. ISBN 91-85295-08-6. No 1008 David Dinka: Role, Identity and Work: Extending No 893 Pernilla Qvarfordt: Eyes on Multimodal Interac- the design and development agenda, 2006, ISBN tion, 2004, ISBN 91-85295-30-2. 91-85497-42-8. No 910 Magnus Kald: In the Borderland between Strate- No 1009 Iakov Nakhimovski: Contributions to the Mode- gy and Management Control - Theoretical Frame- ling and Simulation of Mechanical Systems with work and Empirical Evidence, 2004, ISBN 91- Detailed Contact Analysis, 2006, ISBN 91- 85497-43-X. No 1013 Wilhelm Dahllöf: Exact Algorithms for Exact Satisfiability Problems, 2006, ISBN 91- 85523-97-6. No 1016 Levon Saldamli: PDEModelica - A High- Level Language for Modeling with Partial Differ- ential Equations, 2006, ISBN 91-85523-84-4.

Linköping Studies in Information Science No 1 Karin Axelsson: Metodisk systemstrukturering- att skapa samstämmighet mellan informa-tionssyste- markitektur och verksamhet, 1998. ISBN-9172-19- 296-8. No 2 Stefan Cronholm: Metodverktyg och användbar- het - en studie av datorstödd metodbaserad syste- mutveckling, 1998. ISBN-9172-19-299-2. No 3 Anders Avdic: Användare och utvecklare - om an- veckling med kalkylprogram, 1999. ISBN-91- 7219-606-8. No 4 Owen Eriksson: Kommunikationskvalitet hos in- formationssystem och affärsprocesser, 2000. ISBN 91-7219-811-7. No 5 Mikael Lind: Från system till process - kriterier för processbestämning vid verksamhetsanalys, 2001, ISBN 91-7373-067-X No 6 Ulf Melin: Koordination och informationssystem i företag och nätverk, 2002, ISBN 91-7373-278-8. No 7 Pär J. Ågerfalk: Information Systems Actability - Understanding Information Technology as a Tool for Business Action and Communication, 2003, ISBN 91-7373-628-7. No 8 Ulf Seigerroth: Att förstå och förändra systemutvecklingsverksamheter - en taxonomi för metautveckling, 2003, ISBN91-7373-736-4. No 9 Karin Hedström: Spår av datoriseringens värden - Effekter av IT i äldreomsorg, 2004, ISBN 91- 7373-963-4. No 10 Ewa Braf: Knowledge Demanded for Action - Studies on Knowledge Mediation in Organisations, 2004, ISBN 91-85295-47-7. No 11 Fredrik Karlsson: Method Configuration - method and computerized tool support, 2005, ISBN 91-85297-48-8. No 12 Malin Nordström: Styrbar systemförvaltning - Att organisera systemförvaltningsverksamhet med hjälp av effektiva förvaltningsobjekt, 2005, ISBN 91-85297-60-7. No 13 Stefan Holgersson: Yrke: POLIS - Yrkeskunskap, motivation, IT-system och andra förutsättningar för polisarbete, 2005, ISBN 91-85299-43-X.