185
Linköping Studies in Science and Technology Dissertation No. 1016 PDEModelica A High-Level Language for Modeling with Partial Differential Equations by Levon Saldamli Department of Computer and Information Science Linköpings universitet SE-581 83 Linköping, Sweden Linköping 2006

levon-titelsid - DiVA portal

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: levon-titelsid - DiVA portal

Linköping Studies in Science and Technology

Dissertation No. 1016

PDEModelica A High-Level Language for Modeling with

Partial Differential Equations

by

Levon Saldamli

Department of Computer and Information Science Linköpings universitet

SE-581 83 Linköping, Sweden

Linköping 2006

Page 2: levon-titelsid - DiVA portal
Page 3: levon-titelsid - DiVA portal

“. . . to boldly go whereno man has gone before.”

James T. Kirk

Page 4: levon-titelsid - DiVA portal
Page 5: levon-titelsid - DiVA portal

Abstract

This thesis describes work on a new high-level mathematical modeling languageand framework called PDEModelica for modeling with partial differential equa-tions. It is an extension to the current Modelica modeling language for object-oriented, equation-based modeling based on differential and algebraic equations.The language extensions and the framework presented in this thesis are consistentwith the concepts of Modelica while adding support for partial differential equa-tions and space-distributed variables called fields.

The specification of a partial differential equation problem consists of threeparts: 1) the description of the definition domain, i.e., the geometric region wherethe equations are defined, 2) the initial and boundary conditions, and 3) the ac-tual equations. The known and unknown distributed variables in the equation arerepresented by field variables in PDEModelica. Domains are defined by a geo-metric description of their boundaries. Equations may use the Modelica derivativeoperator extended with support for partial derivatives, or vector differential opera-tors such as divergence and gradient, which can be defined for general curvilinearcoordinates based on coordinate system definitions.

The PDEModelica system also allows the partial differential equation models tobe defined using a coefficient-based approach, where PDE models from a libraryare instantiated with different parameter values. Such a library contains both con-tinuous and discrete representations of the PDE model. The user can instantiatethe continuous parts and define the parameters, and the discrete parts containingthe equations are automatically instantiated and used to solve the PDE problemnumerically.

Compared to most earlier work in the area of mathematical modeling languagessupporting PDEs, this work provides a modern object-oriented component-basedapproach to modeling with PDEs, including general support for hierarchical mod-eling, and for general, complex geometries. It is possible to separate the geometrydefinition from the model definition, which allows geometries to be defined sep-arately, collected into libraries, and reused in new models. It is also possible toseparate the analytical continuous model description from the chosen discretizationand 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

Page 6: levon-titelsid - DiVA portal

variables. Compared to most other approaches, the field concept described in thiswork affords a clearer abstraction and defines a new type of variable. Arrays ofsuch field variables can be defined in the same way as arrays of regular, scalarvariables. The PDEModelica language supports a clear, mathematical syntax thatcan be used both for equations referring to fields and explicit domain specifica-tions, used for example to specify boundary conditions. Hierarchical modelingand decomposition is integrated with a general connection concept, which allowsconnections 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. ThePDEModelica library contains internal and external solver implementations, anduses external software for mesh generation, requisite for numerical solution of thePDEs. Finally, some examples modeled with PDEModelica and solved using theseimplementations are presented.

vi

Page 7: levon-titelsid - DiVA portal

Acknowledgments

First of all, I would like to thank my supervisor Peter Fritzson, for the inspirationand the motivation I needed to finish this thesis, and for commenting both my workand 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 valuablecomments on the contents of this thesis. Thanks also to Hansjürg Wiesmann forhelp with the implementation and for interesting discussions.

Other colleagues at PELAB I would like to thank, who have contributed to theOpenModelica platform, where I could experiment with language extensions, arePeter Aronsson, Kaj Nyström, Adrian Pop, Peter Bunus, Håkan Lundvall, andDavid Broman. Thanks to the rest of the PELAB members for interesting dis-cussions about both work and other more or less relevant subjects, especially toJens Gustavsson, Andreas Borg, and John Wilander for our very interesting worktogether on research methodology and computer science. Special thanks to An-drzej Bednarski for being both a colleague and a friend. Many thanks to BodilMattsson-Kihlström for her support in many ways, and to Lillemor Wallgren forher administrative help.

Finally, I would like to thank my parents for enhancing my motivation, and myfriends, for their company and support that helped me finish this work.

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

vii

Page 8: levon-titelsid - DiVA portal

viii

Page 9: levon-titelsid - DiVA portal

Contents

1 Introduction 11.1 PDE-based Model Example . . . . . . . . . . . . . . . . . . . . . 2

1.1.1 Connection to ODE/DAE models . . . . . . . . . . . . . 41.2 Research Method . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.4 Overview of the Thesis . . . . . . . . . . . . . . . . . . . . . . . 9

2 Background 112.1 Modelica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.1.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.1.2 Variable Declarations . . . . . . . . . . . . . . . . . . . . 122.1.3 Subtyping and Inheritance . . . . . . . . . . . . . . . . . 132.1.4 Modifications . . . . . . . . . . . . . . . . . . . . . . . . 152.1.5 Equations and Algorithms . . . . . . . . . . . . . . . . . 162.1.6 Replaceable Elements . . . . . . . . . . . . . . . . . . . 16

2.2 Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . 182.2.1 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.2.2 Ordinary Differential Equations and Differential and Alge-

braic Equations . . . . . . . . . . . . . . . . . . . . . . . 182.2.3 Partial Differential Equations . . . . . . . . . . . . . . . . 192.2.4 Boundary Conditions . . . . . . . . . . . . . . . . . . . . 202.2.5 Initial Conditions . . . . . . . . . . . . . . . . . . . . . . 212.2.6 Classification . . . . . . . . . . . . . . . . . . . . . . . . 21

2.3 Numerical Solution Methods . . . . . . . . . . . . . . . . . . . . 222.3.1 Finite Difference Methods . . . . . . . . . . . . . . . . . 222.3.2 Finite Element Methods . . . . . . . . . . . . . . . . . . 232.3.3 Method of Lines . . . . . . . . . . . . . . . . . . . . . . 25

3 A Modelica Library for PDE-based Modeling 273.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

3.1.1 Separation into Continuous and Discrete Parts . . . . . . . 283.2 Continuous Part Design . . . . . . . . . . . . . . . . . . . . . . . 28

ix

Page 10: levon-titelsid - DiVA portal

Contents

3.2.1 Standard Boundaries . . . . . . . . . . . . . . . . . . . . 303.3 The Package Design . . . . . . . . . . . . . . . . . . . . . . . . 313.4 Continuous Part . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.4.1 Boundary Definition . . . . . . . . . . . . . . . . . . . . 343.4.2 Domain Definition . . . . . . . . . . . . . . . . . . . . . 343.4.3 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.4.4 Included Boundaries . . . . . . . . . . . . . . . . . . . . 363.4.5 Equation Models . . . . . . . . . . . . . . . . . . . . . . 423.4.6 Boundary Conditions . . . . . . . . . . . . . . . . . . . . 44

3.5 Discrete Part Design . . . . . . . . . . . . . . . . . . . . . . . . 453.5.1 Domain Discretization . . . . . . . . . . . . . . . . . . . 463.5.2 Model Discretization . . . . . . . . . . . . . . . . . . . . 49

3.6 The FEM package . . . . . . . . . . . . . . . . . . . . . . . . . . 533.6.1 DiscreteDomain . . . . . . . . . . . . . . . . . . . . . . 543.6.2 DiscreteField . . . . . . . . . . . . . . . . . . . . . . . . 553.6.3 The Poisson Equation . . . . . . . . . . . . . . . . . . . 563.6.4 The Diffusion Equation . . . . . . . . . . . . . . . . . . . 563.6.5 PDE Library Interface . . . . . . . . . . . . . . . . . . . 56

3.7 Rheolef Finite Element Solver . . . . . . . . . . . . . . . . . . . 573.7.1 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573.7.2 Boundary Conditions . . . . . . . . . . . . . . . . . . . . 58

3.8 The FEMForms package . . . . . . . . . . . . . . . . . . . . . . 593.8.1 DiscreteField . . . . . . . . . . . . . . . . . . . . . . . . 593.8.2 Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603.8.3 The Poisson Equation . . . . . . . . . . . . . . . . . . . 613.8.4 The Diffusion Equation . . . . . . . . . . . . . . . . . . . 613.8.5 PDE Library Interface . . . . . . . . . . . . . . . . . . . 61

3.9 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623.10 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4 Language Elements for Space-distributed Models 694.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694.2 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

4.2.1 Field Variables . . . . . . . . . . . . . . . . . . . . . . . 704.2.2 Field Constructor . . . . . . . . . . . . . . . . . . . . . . 714.2.3 Field Type in Expressions . . . . . . . . . . . . . . . . . 714.2.4 Accessing Field Values . . . . . . . . . . . . . . . . . . . 73

4.3 Future Language Extensions . . . . . . . . . . . . . . . . . . . . 744.3.1 Domain Geometry Definition . . . . . . . . . . . . . . . 744.3.2 Differential Operators . . . . . . . . . . . . . . . . . . . 784.3.3 Domain Specifier in Equations . . . . . . . . . . . . . . . 814.3.4 Field Reduction . . . . . . . . . . . . . . . . . . . . . . . 82

x

Page 11: levon-titelsid - DiVA portal

Contents

4.3.5 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . 83

5 Implementation 855.1 Modelica Compiler . . . . . . . . . . . . . . . . . . . . . . . . . 85

5.1.1 Modelica Parser . . . . . . . . . . . . . . . . . . . . . . 865.1.2 Modelica Translator . . . . . . . . . . . . . . . . . . . . 88

5.2 The PDE Library . . . . . . . . . . . . . . . . . . . . . . . . . . 945.2.1 The Finite Element Package . . . . . . . . . . . . . . . . 95

5.3 PDEModelica Solver Environment . . . . . . . . . . . . . . . . . 995.3.1 Spatial Discretization of Equations . . . . . . . . . . . . . 99

6 Examples 1056.1 Stationary Heat Transfer . . . . . . . . . . . . . . . . . . . . . . 105

6.1.1 Neumann and Robin Boundary Conditions . . . . . . . . 1076.2 Time-dependent Heat Transfer . . . . . . . . . . . . . . . . . . . 108

6.2.1 Heat Transfer with Controller . . . . . . . . . . . . . . . 1096.3 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

7 Previous Approaches With Examples 1137.1 Mathematica-based Translator . . . . . . . . . . . . . . . . . . . 113

7.1.1 Space Variables . . . . . . . . . . . . . . . . . . . . . . . 1137.1.2 Domain Classes . . . . . . . . . . . . . . . . . . . . . . . 1147.1.3 Solver Generator in Mathematica . . . . . . . . . . . . . 115

7.2 Coefficient-Based Translator . . . . . . . . . . . . . . . . . . . . 1167.2.1 Domains . . . . . . . . . . . . . . . . . . . . . . . . . . 1167.2.2 Equations and Boundary Conditions . . . . . . . . . . . . 1177.2.3 Implementation Details . . . . . . . . . . . . . . . . . . . 1187.2.4 Numerical Solver . . . . . . . . . . . . . . . . . . . . . . 1327.2.5 Issues with the Coefficient-Based Translator . . . . . . . . 134

8 Related Work 1378.1 Libraries and Programming Language-Based Packages . . . . . . 137

8.1.1 Diffpack . . . . . . . . . . . . . . . . . . . . . . . . . . 1388.1.2 Overture . . . . . . . . . . . . . . . . . . . . . . . . . . 1388.1.3 Compose . . . . . . . . . . . . . . . . . . . . . . . . . . 138

8.2 High-Level Packages and Problem Solving Environments . . . . . 1398.2.1 gPROMS . . . . . . . . . . . . . . . . . . . . . . . . . . 1398.2.2 PELLPACK . . . . . . . . . . . . . . . . . . . . . . . . . 1408.2.3 PDESpec . . . . . . . . . . . . . . . . . . . . . . . . . . 1428.2.4 FEMLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 142

8.3 Discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

xi

Page 12: levon-titelsid - DiVA portal

Contents

9 Conclusion 1459.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1459.2 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1479.3 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

9.3.1 Modelica PDE Library . . . . . . . . . . . . . . . . . . . 1489.3.2 Connectors . . . . . . . . . . . . . . . . . . . . . . . . . 1499.3.3 Language Implementation . . . . . . . . . . . . . . . . . 150

References 153

A UML Notation 159

B Plotting Simulation Results 161B.1 Visualization of Domain Boundary . . . . . . . . . . . . . . . . . 161B.2 Visualization of Meshes . . . . . . . . . . . . . . . . . . . . . . . 161B.3 Visualization of Steady-state Fields . . . . . . . . . . . . . . . . . 161B.4 Visualization of Time-dependent Fields . . . . . . . . . . . . . . 162

xii

Page 13: levon-titelsid - DiVA portal

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 thecontents it may have, for example occurence of equations.

extends Term used for subclassing of Modelica classes, for defining inheritancehierarchies of classes.

modification In Modelica, a mechanism to change values of parameters, typesof 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 generateequations.

domain The definition domain of the independent variables. For time-dependentfunctions, the domain is the time interval where the variable is defined. Fortwo or three-dimensional space-dependent functions, the domain is the twoand 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, twodimensional 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 ofthe independent variables, e.g., one of the space coordinates.

PDE Partial differential equation, i.e., an equation containing partial derivativesof functions.

ODE Ordinary differential equation. containing functions of one independentvariable and derivatives of functions and expressions with respect to thatindependent variable.

xiii

Page 14: levon-titelsid - DiVA portal

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. ThePDE is usually valid only in the interior of the domain, while the boundaryconditions give the values of the unknown or its derivatives on the boundaryof the domain.

initial condition In time-dependent equations, the starting values of the unknownvariables, 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 ofthe unknown variable on the boundary.

Robin A type of boundary condition, consisting of an equation containing boththe 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 wave equation.

stationary (steady-state) The time-independent equation, corresponding to thetime-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 distancebetween the grid points.

central difference A finite difference method using discrete values from bothprevious and next discrete point.

forward difference A finite difference method using discrete values from thenext discrete point.

xiv

Page 15: levon-titelsid - DiVA portal

Contents

backward difference A finite difference method using discrete values from theprevious 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 termsof known basis functions and solving the resulting equation systems.

method of lines A method to solve time-dependent PDE problems by replacingthe time- or space-dependent parts of the equations with discrete formula-tions, resulting in a only time- or only space-dependent problem. In thiswork, spatial discretization is used, generating DAEs from time-dependentPDEs.

xv

Page 16: levon-titelsid - DiVA portal

Contents

xvi

Page 17: levon-titelsid - DiVA portal

Chapter 1

Introduction

“Its five year mission: To explorestrange new worlds, to seek out newlife and new civilizations, to boldlygo 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 algebraicequations, i.e. algebraic equations containing derivatives.

For large scale models, some properties of the physical system that is modeledare often approximated; for example when controlling the temperature of a fluid ina container, the temperature can be assumed to be the same everywhere inside thecontainer. This way, the space dependency is eliminated, resulting in models con-taining only ordinary differential equations (ODEs), or differential and algebraicequations (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 isneeded for the whole or some part of the system. Such space-dependent modelsare 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 coordinatesystem. 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 differentialequations as well as with partial differential equations. Most are however spe-cialized for certain application domains or special kinds of models.

1

Page 18: levon-titelsid - DiVA portal

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 asa result. Modelica® [1, 2] is a standard language designed for component-basedmodeling, where previously defined models can be reused as components in newmodels. Object oriented constructs, equation-based and declarative modeling sup-port, as well as a connection concept make this possible. Currently, Modelica onlysupports models with ordinary differential equations, algebraic equations, discreteequations, hybrid (mixed time-discrete and time-continuous) equations but not par-tial differential equations. Several Modelica implementations and simulation toolsexist [3, 4].

Thanks to the progress in computer performance, the use of detailed models con-taining partial differential equations is becoming increasingly common. The aimof this work is to define a language based on Modelica, in order to handle partialdifferential equations in models in addition to differential and algebraic equations.This language is called PDEModelica, and this thesis discusses the initial languageextensions 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-bution in the x and y directions is studied and the temperature in the z directionis assumed to be constant. A heater is installed on one of the walls and there is awindow on another wall. The domain of this problem, i.e., the region (includinggeometry) on which it is defined, can be seen in Figure 1.1. A heater is representedby assigning constant temperature boundary condition to the middle part of theupper 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., noheat flow occurs through these walls. The right wall is curved in order to illustratemodeling with complex geometries.

Heat transfer by conduction in two dimensions can be modeled using Poisson’sequation:

−(∂2T (x, y)

∂x2+

∂2T (x, y)∂y2

) = g(x, y) on Ω

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

Page 19: levon-titelsid - DiVA portal

1.1 PDE-based Model Example

Heater

Windowleft

bottom

top3 top1top2

right

x

y

h

w

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

• Neumann2 boundary condition for insulated walls:

∂T (x, y)∂n

= h2(x, y) on ∂Ω

• Robin3 (also called mixed) boundary condition for the window which is notperfectly insulated:

∂T (x, y)∂n

+ qT (x, y) = h3(x, y) on ∂Ω

If heat distribution over time is studied, a time derivative is added to the Laplaceequation which gives the heat diffusion equation:

ρC∂T (x, y, t)

∂t− k(

∂2T (x, y, t)∂x2

+∂2T (x, y, t)

∂y2) = g(x, y, t) on Ω

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 modeldescription 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 alsoSection 2.2.4.

3A linear combination of the unknown variable and its outward normal derivative is known on theboundary. See also Section 2.2.4.

3

Page 20: levon-titelsid - DiVA portal

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 definedas named components in the domain description. Hence, when defining the PDEmodel, boundary conditions can be assigned to each section using the name of eachboundary component. The definition of the boundary conditions and the PDE arenot shown in this example; they can be defined as described in Chapter 4. Thesolution 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-dependentmodel as shown in the previous section. A temperature sensor can be approximatedby 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 inFigure 1.3, and the PDEModelica code is listed in Figure 1.4.

The controller is a proportional, integrating controller (PI-controller), whichcontains an ordinary differential equation:

Terror = Tsensor − Tgoal

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 acomplete system with only ODEs. However, if a more realistic temperature modelis 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, resultingin 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 simplefield access to read the temperature value. The connection between the controllerand the PDE model is accomplished manually by writing down the equations. Inthe 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

Page 21: levon-titelsid - DiVA portal

1.1 PDE-based Model Example

c l a s s C u r v e d R e c t a n g u l a r " Geometry "extends C a r t e s i a n 2 D ( boundary = bottom , r i g h t , top1 , top2 , top3 , l e f t ) ;

parameter P o i n t p0 ;parameter Real w;parameter Real h ;parameter Real cw ;

parameter Real ch=h ;parameter P o i n t 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 r i g h t ( 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 C u r v e d R e c t a n g u l a r ;

model D i f f u s i o n " Heat d i f f u s i o n w i t h h e a t e r ". . .import Model ica . S I U n i t s . T em pera tu re ;parameter T em pera tu re h e a t e r V a l u e ;parameter Real h_3 ;parameter Real q ;C u r v e d R e c t a n g u l a r omega ;D i f f u s i o n 2 D pde ( domain=omega ) ;

equat ionder ( pde . u , n ) = 0 on omega . bot tom ;der ( pde . u , n ) = 0 on omega . r i g h t ;der ( pde . u , n ) = 0 on omega . top1 ;pde . u = h e a t e r V a l u e 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 D i f f u s i o n ;

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

5

Page 22: levon-titelsid - DiVA portal

Chapter 1 Introduction

Heater

Glass layer

PI-Controller

Sensor

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

1.2 Research Method

The research method used in this work can be called explorative design [5]. Theapproach starts with a design hypothesis which is believed to be a possible solutionto the problem. A prototype implementation of this design is developed. Duringimplementation, flaws in the design are discovered and new knowledge about theproblem is acquired. The implementation is modified to handle these issues. Thus,the system that is implemented differs from that in the original design. On theother hand, the implementation also differs from the one that would have beenimplemented from start using the new knowledge. For this reason, at some point,the prototype is discarded and a new design and prototype are developed. SeeFigure 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 actualimplemented prototype, and a proposed, improved design. In this thesis, we presentthe previous iterations of the design and implementation in Chapter 7. The finaldesign of PDEModelica in this thesis work is presented in Chapter 4 and the finalimplementation is described in Chapter 3 and Chapter 5.

6

Page 23: levon-titelsid - DiVA portal

1.2 Research Method

c l a s s C u r v e d R e c t a n g u l a r " Geometry "extends C a r t e s i a n 2 D ( boundary = bottom , r i g h t , top1 , top2 , top3 , l e f t ) ;

parameter P o i n t p0 ;parameter Real w;parameter Real h ;parameter Real cw ;

parameter Real ch=h ;parameter P o i n t 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 r i g h t ( 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 C u r v e d R e c t a n g u l a r ;

model C o n t r o l l e d D i f f u s i o n " Heat d i f f u s i o n w i t h c o n t r o l l e d h e a t e r ". . .import Model ica . S I U n i t s . T em pera tu re ;parameter T em pera tu re g o a l V a l u e ;parameter Real h_3 ;parameter Real q ;/ / Use PI r e g u l a t o r from Standard L i b r a r yModel ica . Blocks . Cont inuous . PI r e g u l a t o r ;C u r v e d R e c t a n g u l a r omega ;D i f f u s i o n 2 D pde ( domain=omega ) ;T em pera tu re h e a t e r V a l u e ;T em pera tu re s e n s o r V a l u e ;

equat ionder ( pde . u , n ) = 0 on omega . bot tom ;der ( pde . u , n ) = 0 on omega . r i g h t ;der ( pde . u , n ) = 0 on omega . top1 ;pde . u = h e a t e r V a l u e 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 ;h e a t e r V a l u e = r e g u l a t o r . y [ 1 ] ;r e g u l a t o r . i n P o r t . s i g n a l [ 1 ] = g o a l V a l u e − s e n s o r V a l u e ;s e n s o r V a l u e = pde . u ( 2 . 6 1 , 2 . 3 3 ) ;

end C o n t r o l l e d D i f f u s i o n ;

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 Diffusion2Dand detailed parameter declarations have been left out. The syntax isexplained in Chapter 4.

7

Page 24: levon-titelsid - DiVA portal

Chapter 1 Introduction

Prototypeimplementation

Design Hyptohesis

ModifiedDesign

Hyptohesis

ImprovedDesign

Hyptohesis

New knowledge

Iterations

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 specifyand simulate PDE-based models. Second, a design and a partial implementationof language extensions for the Modelica language is presented, which integratesthe concepts from the PDE library into the Modelica language. The proposed lan-guage design for an object-oriented modeling language, PDEModelica, supportsthe following:

• Object-oriented, component-based modeling with PDEs.

• General, complex geometry description with lines, polygons, parametric curvesand 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 discretizationand numerical solution.

• Field concept for general declaration of spatially distributed variables inte-grated in the language.

8

Page 25: levon-titelsid - DiVA portal

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 languageis rather new. See also the discussion and comparison to other related systems inSection 8.3.

A prototype translator and solver environment is set up as well, with a basic PDEsolver interface for adding new solvers and mesh generators.

Some of the work discussed in this thesis has been published previously in thefollowing 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 4thInternational EUROSIM Congress, Delft, The Netherlands, June 2001 [7].

3. L. Saldamli and P. Fritzson. Domains and Partial Differential Equations inModelica. In Proceedings of the 42nd SIMS Conference, Porsgrunn, Norway,October 2001 [8].

4. L. Saldamli, P. Fritzson and B. Bachmann. Extending Modelica for PartialDifferential Equations. In Proceedings of the 2nd International ModelicaConference, 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 andModelling, Copenhagen, Denmark, September 2004 [10].

6. L. Saldamli, B. Bachmann, H Wiesmann and P. Fritzson. A Framework forDescribing and Solving PDE Models in Modelica. In Proceedings of the 4thInternational 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

Page 26: levon-titelsid - DiVA portal

Chapter 1 Introduction

to partial differential equations and some existing numerical solution methods forpartial 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 PDEmodels on general domains using the finite element method and the method of linesdiscretization.

Chapter 4 presents proposed extensions to the Modelica language for definitionof space-distributed models, e.g. models containing fields and partial derivatives.

Chapter 5 contains the implementation details. The PDE library, prototypes forlanguage extensions and the interface to external solvers are described here.

Chapter 6 contains examples to demonstrate the use of the PDE library and thelanguage extensions.

Chapter 7 discusses the previous design iterations that were implemented andtested.

Chapter 8 presents an overview of related work. Different low- and high-leveltools with varying modeling language support are summarized here.

Finally, some conclusions and possible future work directions are discussed inChapter 9.

10

Page 27: levon-titelsid - DiVA portal

Chapter 2

Background

“Logic is the beginning ofwisdom; not the end.”

Mr. Spock

The basic concepts of Modelica are presented in the first part of this chapter. Inthe second part, the topic of partial differential equations (PDEs) and classifica-tion of PDEs are briefly presented, and finally an overview of different numericalsolution 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 allowshierarchical, component-based modeling which in turn makes reuse of existingmodels possible. The general modeling concepts in Modelica allow it to be usedin different application domains and in multi-domain modeling, for example whendefining a combined electrical and mechanical model. There is a free ModelicaStandard Library [13] and other free Modelica libraries with packages of existingmodels 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 notexplicitly declared as input or output. This causality information is rather derivedfrom the context where the model is used. In his PhD thesis [14], H. Tummescheitdiscusses design and implementation of modeling libraries using Modelica.

11

Page 28: levon-titelsid - DiVA portal

Chapter 2 Background

Models in Modelica are built hierarchically from sub-models that are definedseparately, 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 valuesfor each instance, and a set of connections between these components/instances.Additionally, each model can have variables of built-in types, and equations thatdefine 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 seenin Figure 2.1. Other keywords can be used to denote classes, restricted classes thatare special cases of classes with some restrictions. These are record, type,connector, model, block, package and function. Different restrictedclasses and restrictions that apply to them can be seen in Table 2.1.

model MyModel " S h o r t d e s c r i p t i o n o f t h i s model "Real x , y ;

equat ionx + y = 5 ;x + 2y = 1 1 ;

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 oneof the primitive types or another class name. The primitive types are Real, In-teger, String, Boolean and Enumeration. Each declaration can also havetype modifiers, such as the variability type prefix constant, discrete, or pa-rameter, or a causality prefix, input or output, used in function and blockclasses to declare the direction of a variable.

Variables with the constant or parameter prefix keep their value constantduring a simulation, i.e., they are constants. The difference between parametersand constants is that values of parameters can be changed before each simula-tion without needing to recompile the Modelica code. An exception is structuralparameters , which require recompilation of the model because they change themodel 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

Page 29: levon-titelsid - DiVA portal

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 theder() operator. Using the time derivatives, ordinary differential equations can beexpressed, and full systems of differential and algebraic equations (DAEs) can bespecified.

2.1.3 Subtyping and Inheritance

Modelica models can be defined using inheritance. The extends clause is usedtogether 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 extendsclause resides.

Type equivalence in Modelica is defined as follows: Two types T and U areequivalent 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

Page 30: levon-titelsid - DiVA portal

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. Subtypesand supertypes do not necessarily need to be in an inheritance hierarchy, but a classthat is inherited from, a base class, is a supertype of a class that inherits from it, aderived class. An example is shown in Figure 2.2.

p a r t i a l model OnePortP in p , n ;V o l t a g e v " V o l t a g e drop " ;

equat ionv = p . v − n . v ;p . i + n . i = 0 ;

end OnePort ;

model R e s i s t o r ;extends OnePort ;parameter Real R( u n i t ="Ohm" ) " R e s i s t a n c e " ;

equat ionv = p . i * R ;

end R e s i s t o r ;

model TempRes is to r " Tempera ture d e p e n d e n t r e s i s t o r "extends OnePort ;parameter Real R( u n i t ="Ohm" )

" R e s i s t a n c e a t r e f e r e n c e t e m p e r a t u r e " ;parameter Real RT( u n i t ="Ohm/ degC " ) = 0

" Tempera ture d e p e n d e n t r e s i s t a n c e " ;parameter Real T r e f ( u n i t =" degC " ) = 20 " R e f e r e n c e temp . " ;Rea l Temp = 20 " A c t u a l t e m p e r a t u r e " ;

equat ionv = p . i * (R + RT * ( Temp − T r e f ) ) ;

end TempRes is to r ;

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

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

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

14

Page 31: levon-titelsid - DiVA portal

2.1 Modelica

2.1.4 Modifications

A modification in Modelica is a short-hand Modelica syntax for expressing classspecialization. For example, the modification compa(pa=1) in ModelB in Figure 2.3expresses that the equation pa=0 in ModelA should be replaced by the equationpa=1 to create a temporary, specialized class derived from ModelA and used forcreation of the compa instance.

Since models are built up hierarchically, modifications can be overridden, inwhich case the topmost (outermost) modification is applied. A modification canalso be hierarchical, in order to modify a lower level parameter directly. Eachmodification consists of a component reference and an expression that is evaluatedin the context where the declaration resides. Example of modifications can be seenin Figure 2.3. Declarations preceded by the final keyword are final elements andcannot be modified using modifications. The final keyword can also precedemodifications, in which case it prevents further modifications of that variable inouter modifications.

model ModelAparameter Real pa = 0 ; / / d e f a u l t v a l u e

end ModelA ;

model ModelBModelA compa ( pa = 1 ) ; / / m o d i f i c a t i o nparameter Real pb = 0 ;

end ModelB ;

model MyModelparameter Real mypa =3 , mypb=4;/ / h i e r a r c h i c a l m o d i f i c a t i o nModelB compb ( pb=mypb , compa ( pa=mypa ) ) ;

end MyModel ;

Figure 2.3: Modifications in Modelica. The resulting value of the variablecompb-.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 MyNewModelextends MyModel ( mypb = 5 ) ;

When instantiating components of MyNewModel the default value of mypb willbe 5.

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

15

Page 32: levon-titelsid - DiVA portal

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 consistof two expressions and the equality operator denoted by =. The assignment oper-ator := is not allowed in equation sections, whereas the equality operator = isnot allowed in algorithm sections. Besides the common operators like arithmeticoperators and function calls, Modelica has if-expressions, which can be used insituations like:

equat ionx = i f ( z > 0) 2* z e l s e (−2*z ) ;

Connect equations consist of the connect() operator with two arguments thatare references to connectors. Connectors are instances of connector restrictedclasses 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. Connectequations are translated into standard equations during compilation, where for eachconnection the non-flow variables of the involved connectors are set equal, and thesum of all the flow variables is set to be equal to zero. Figure 2.4 illustrates the useof connectors and connections, and the resulting equations.

Conditional equations can be written using the if-elseif-else constructwith equations in the body. for equations are useful for repetitive equation struc-tures involving arrays, whereas when equations and when statements are used fordiscrete event simulation.

Algorithm section can contain assignments, conditional statements, for-loops,while-loops and when-statements. The difference from equation sections is thatalgorithm sections contain assignments instead of equations, and the contents ofthe algorithms are executed sequentially. An assignment consists of a variablereference as the left-hand side, the assignment operator := and an expression asthe right-hand side.

2.1.6 Replaceable Elements

Elements in classes in Modelica can be declared as replaceable, in which casethey can be replaced by another type of element that is type compatible when thecontaining class is extended or instantiated. Generic classes with type parametersis supported in Modelica through the replaceable mechanism.

The type restriction of a redeclaration is that the new declared type must be asubtype of the original declared type, a constraining type.

16

Page 33: levon-titelsid - DiVA portal

2.1 Modelica

BA

p

p p

C

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

connector Pin " E l e c t r i c a l p i n "f low C u r r e n t i ;V o l t a g e v ;

end Pin ;

model OnePinP in p ;

end OnePin ;

model T e s tOnePin a , b , c ;

equat ionc o n n e c t ( a . p , b . p ) ;c o n n e c t ( b . p , c . p ) ;

end T e s t ;

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

equat iona . 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

Page 34: levon-titelsid - DiVA portal

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 modelsrelate certain variables, called dependent variables, and their derivatives to othervariables, called independent variables. For example the time variable or spacecoordinates occur commonly as independent variables.

2.2.1 Fields

A field is a mapping from a domain to scalar or vector values. The geometricalregion, i.e., the domain where the field is defined, is called the fields definitiondomain. 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. Thescalar field is a mapping R

2 → R while the vector field is a mapping R2 → R

2,i.e. for each tuple (x, y), the fields give a value u and (u, v), respectively.

omega

x

y

u

omega

x

y

v

u

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 domaincan be seen on the right.

2.2.2 Ordinary Differential Equations and Differential andAlgebraic Equations

In some cases a variable that is distributed in space and/or time, e.g. a temperaturefield, can be approximated by a scalar variable. For example, when the temperatureof a fluid in a container is studied, the temperature could be assumed to be thesame throughout the entire container at each specific time instant, and one canstudy the temperature change as a function of time based on the incoming andoutgoing 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

Page 35: levon-titelsid - DiVA portal

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 isstudied, with different temperature values at different positions inside the container,the temperature is a function of the independent variables. representing the spacecoordinates 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 differentialequations (PDEs). If the equations contain the time variable or any time-dependentvariable, 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 modelsof many practical systems are second-order PDEs, containing second order deriva-tives. A partial derivative can be stated in different ways. The first-order partialderivative of a dependent variable u with respect to the independent variable x isrepresented using the following three variants of mathematical notation:

∂u

∂x= ∂xu = ux

A second order derivative can be written accordingly as

∂2u

∂x2= ∂xxu = uxx

The second differentiation can be done with respect to a different variable y thanthe first differentiation, e.g. ∂xyu = uxy, which is also a second order derivative, amixed partial derivative.

A general, second order PDE with an unknown dependent variable u and theindependent 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 bythe 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 completelyinside the region.

19

Page 36: levon-titelsid - DiVA portal

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 expressPDEs using vector notation. These operators are dimension and coordinate nameindependent. The gradient operator is defined as follows:

∇u = grad u(x1, . . . , xn) =(

∂(u)∂x1

. . .∂(u)∂xn

)

The divergence operator is defined as follows:

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

∂x1+ . . . +

∂un

∂xn

2.2.4 Boundary Conditions

Boundary conditions in a PDE problem specify the behaviour of the model on theboundary of the domain Ω, denoted ∂Ω, and usually contain derivatives of oneorder 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 partialderivative with respect to one variable. A common directional derivative is theoutward normal derivative, which is obtained by the scalar product of the outwardnormal on the domain boundary and a vector of the partial derivatives. The outwardnormal derivative is denoted ∂n and is commonly used in boundary conditions tospecify e.g. heat flux through the boundary.

20

Page 37: levon-titelsid - DiVA portal

2.2 Differential Equations

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

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 calledhomogeneous, otherwise non-homogeneous.

2.2.5 Initial Conditions

Initial conditions are needed in order to find a unique solution to a time-dependentdifferential equation. Due to the zero derivatives of constants, infinite number ofsolutions 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 constantcan be determined and a unique solution can be found.

2.2.6 Classification

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

L(αu + βv) = f

is linear ifL(αu + βv) = αL(u) + βL(v)

If a PDE with the dependent variable u and the independent variables x and y canbe 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 coefficientsare functions of the independent variables only, x and y in this example, the PDEis semi-linear, and if the coefficients also depend on u or its first-order derivativesthe PDE is quasi-linear. Equations that cannot be expressed linearly in the secondorder derivatives as in Equation (2.1) are nonlinear. In this text, semi-linear PDEswill be regarded as linear, while quasi-linear PDEs will be classified together withthe nonlinear.

3An example of a linear operator is the derivative operator.

21

Page 38: levon-titelsid - DiVA portal

Chapter 2 Background

Equation (2.3) is classified further into three categories depending on the valueof b2 − ac:

Elliptic : b2 − ac < 0

Parabolic : b2 − ac = 0

Hyperbolic : b2 − ac > 0

Elliptic equations typically occur in stationary heat conduction models, whereasparabolic equations arise in time-dependent models. The wave equation used formodeling propagation of waves such as sound waves in gas or electro-magneticwaves 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 fewerof these are solvable with practically useful boundary conditions. For this rea-son, much research has been done on numerical solution of PDEs and differentmethods have been developed. Unlike the case for solution of ordinary differentialequations, there is no unified method for solution of general PDE problems, how-ever, and an appropriate numerical solver must be selected for the specific kindPDE being solved.

The solution method depends on whether a stationary or a time-dependent PDEis solved. Only space discretization is needed for stationary problems, whereastime-dependent problems need both space and time discretization. The methodsdescribed below can be used for both these cases. Discretization of only time orspace variables can be done as well. For example, an equation can be discretizedwith respect to space coordinates, leaving a system of algebraic equations contain-ing only time derivatives (the method of lines). Time-dependency can be removedsimilarly, replacing time derivatives with a finite difference, leaving a stationaryPDE problem which can be solved iteratively at different time steps.

Space discretization is performed in different ways, depending on the numericalsolution method. The finite difference method requires a grid, which is usuallyregular, i.e., with equidistant discrete points. This also requires that the definitiondomain is rectangular. The finite element method can be used on more generaldomains, 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 whichthe problem is defined is discretized into a set of grid points and the values of the

22

Page 39: levon-titelsid - DiVA portal

2.3 Numerical Solution Methods

function at these points are calculated. When the domain is discretized, the partialderivatives 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 thepoints can be approximated by for instance:

∂u

∂x=

u(x + h) − u(x − h)2h

+ O(h2)

Here, O(h2) represents the approximation error. This equation is called a central-difference approximation. Other approximations can be derived, for example

∂u

∂x u(x + h) − u(x)

h

which is called a forward-difference formula, and

∂u

∂x u(x) − u(x − h)

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 thevalues of u at the grid points as unknowns. The boundary conditions are applied atthe grid points neighboring the boundary, depending on the kind of boundary con-ditions. With Dirichlet boundary conditions, the values on the boundary are knownand 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 pointsoutside the domain are generated, that can be used to express the unknown valueson the boundary.

When solving time-dependent problems, the time derivatives can be approxi-mated with finite differences as well. Note however that especially when usingfinite 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 dependentvariable u with a function u belonging to a finite dimensional space with knownbasis functions βk(x), also called trial functions. Using a vector space of dimen-sion N , the approximate function is defined as

u(x) =N∑

k=1

ckβk(x). (2.4)

23

Page 40: levon-titelsid - DiVA portal

Chapter 2 Background

Each set of coefficients c1...cN is the coordinates of a function in this space. Theproblem is then reduced to finding the coefficients for a function u that satisfythe equation as well as possible, i.e. minimizing the error u − u. Because u isunknown, the error cannot be measured directly. Instead, the partial differentialequation is used to measure the error introduced by using the approximation uinstead of u. Different measurements lead to different solution methods, such asthe least squares method or the weighted residual method. Since there are a finitenumber of basis functions and finite number of unknown coefficients, it is possibleto calculate the coefficients numerically, given the PDE and known values at somepoints, 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 Rof 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 afunction 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 accordingto this definition. The residual of the approximation is checked against a set of testfunctions from an appropriate test space. It is sufficient to check the basis vectorsof 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 thebasis 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 integralsgives 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

Page 41: levon-titelsid - DiVA portal

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, thedegree 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 domaininto M subdomains, called partitions or elements, and use basis functions with onlylocal contribution. Each basis function ϕk is zero in the entire domain except for asmall number of elements. The hat function is an example of a basis function withlocal support, defined as:

ϕi(x) =

0, x /∈ [xi−1, xi+1],x−xi−1xi−xi−1

, x ∈ [xi−1, xi],x−xi+1xi−xi+1

, x ∈ [xi, xi+1].(2.5)

With the finite element method, may smaller sized elements can be used for betterapproximation instead of polynomials of higher order. Element size and shape canbe 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 wherethe 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 ODEsinvolving only time-dependent functions and time-derivatives. The conversion isdone by discretizing the PDE in space, leaving a number of unknowns and theirtime derivatives. For the space discretization, any of the methods described earliercan 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 thedomain, 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, forinstance, solvers with automatic step adjustment to find a solution with requiredaccuracy. Another advantage is that coupled systems containing both ODE andPDE based models become easier to solve because the space discretization of thePDEs results in ODEs that can be solved together with the already existing ODEs.

One disadvantage, though, is that the space discretization is independent of theerror 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, errorintroduced during the space discretization can be much larger if space discretizationis performed without caution.

25

Page 42: levon-titelsid - DiVA portal

Chapter 2 Background

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

26

Page 43: levon-titelsid - DiVA portal

Chapter 3

A Modelica Library forPDE-based Modeling

“You can’t argue with amachine, Jim!”

Dr. McCoy

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

3.1 Introduction

An object-oriented approach has been taken in the design of the PDE library. Asdescribed earlier, all PDE models have certain common components. These arefound in this library on an abstract level, without any information about specificmodels or solution methods. Models and classes that contain specific informa-tion for different solution methods are separated into sub-packages. Here, we firstpresent the continuous parts of the library and show an example of how these canbe 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 thelibrary.

Due to restrictions in the Modelica language, the implementation of the PDElibrary 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 thelibrary in more detail. Mapping from the general design to a Modelica-specific

27

Page 44: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

design using packages, called The Package Design, is described separately in orderto 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 discretizationdetails. However, only the discrete part of the models contain actual model equa-tions, because of the current lack of Modelica language constructs for expressingspace-distributed equations, such as field variables, partial derivatives etc. Suchlanguage constructs are described in Chapter 4. Thus, the continuous part containsa number of PDE-based models that can be reused with different parameters (coef-ficients), with the actual equations given in the corresponding discrete models. Thisapproach 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 languageitself instead of in external libraries, allowing Modelica library developers to definePDE-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 dimensionalmodels, 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, and Boundary.Some help classes are also included, namely BoundaryCondition, Point andBPoint. These classes are independent of the solution methods and specific PDEmodels. The UML diagram in Figure 3.1 shows an overview of these classes andtheir relationship.

A field represents a variable that is distributed over a spatial domain. The Fieldclass is parameterized on the field value type. Thus, the field values can be of anytype, including vector-valued types. A field has an operation called value whichreturns the field value at a given point in the domain. Hence, a field can be seen as amapping from a spatial domain to field values. Each field has exactly one Domaincomponent.

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 concatenatedboundary parts each of which are parametric curves. The Boundary class repre-

28

Page 45: levon-titelsid - DiVA portal

3.2 Continuous Part Design

Boundary

+shape(in u): BPoint

Domain

BoundaryCondition

BPoint

+x: Integer

+y: Integer

+bcIndex: Integer

Field

+value(Point): FieldType

FieldType:

Point

+x: Integer

+y: Integer

ConstConstField

+constval: FieldType

+value(Point): FieldType

ConstField

+value(Point): FieldType

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

29

Page 46: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

sents the boundary of a domain using parametric curves or surfaces. A boundaryhas an operation called shape which defines the shape by mapping parameters tospatial 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. Inorder 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, whereshape(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 additionalboundary 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 packageBoundaries. These are shown in Figure 3.2.

Line

+p1: Point

+p2: Point

+shape(in u): BPoint

Arc

+c: Point

+r: Real

+a_start: Real

+a_end: Real

+shape(in u): BPoint

Circle

+shape(in u): BPoint

« a_start=0, a_end=2*PI »

Rectangle

+p: Point

+w: Real

+h: Real

+shape(in u): BPoint

Bezier

+p: array [2..n] of Point

+shape(in u): BPoint

Composite

+shape(in u): BPoint

parts

1..n Boundary

+shape(in u): BPoint

bottom, right, top, left

4

Figure 3.2: Standard boundary classes in the Boundaries package.

Line: Represents a straight line between two points.

30

Page 47: levon-titelsid - DiVA portal

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 isgiven in a_start and the ending angle in a_end, using radians. The arc is drawnin the counter-clockwise direction, starting at the x axes.

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

Bezier: Represents a Bezier curve [17]. The control points are given as an arrayof 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. Theend points of the parts must be connected, e.g. for each pair of consecutive parts iand i + 1 must hold that shapei(1) == shapei+1(0), and also for the first and thelast parts that shapelast(1) == shapefirst(0).

3.3 The Package Design

Due to restrictions in the Modelica language version 2.2, the design described inthe 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 needto 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 functionsfor different types of boundaries, we must either use different function names, ordifferent packages containing the shape functions for each type of boundary. Oursolution 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 storedin a record called Data, which exists in all packages used as types. One of thearguments to the shape function is a record of type Data.

Since we now have packages representing boundary types, we need to declarea 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 isdeclared as follows:

package Domainr e p l a c e a b l e package boundaryP = Boundary

extends Boundary ; / / base c l a s s r e s t r i c t i o n

end Domain ;

31

Page 48: levon-titelsid - DiVA portal

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, wehere use lowercase letters to emphasize that this package is only used for declaringan object reference. Note also that the use of the extends keyword here does notspecify inheritance. Rather, this syntax is used to declare a constraint on possibletypes that can be used as replacement for boundaryP. The use of the keyword ex-tends is unfortunate, since a keyword subtypeof or constrainedby would bemore accurate. A comment is added in the code snippets to clarify this difference.

The data structure can be declared as follows:

package Domainr e p l a c e a b l e package boundaryP = Boundary

extends Boundary ; / / base c l a s s r e s t r i c t i o n

record DataboundaryP . Data boundary ;

end Data ;end Domain ;

Here, we also declare the data record for the Domain type. Each domain instancewill now contain a record called boundary of type boundaryP.Data. When theboundary package is replaced, the correct Data record from that boundary packagewill be used accordingly.

Domain objects can now be declared analogously. When declaring a domainobject, the boundaryP package is replaced with the specific boundary to use. Forexample:

model TestModelpackage domainP = Domain ( r e d e c l a r e boundaryP = R e c t a n g l e ) ;

R e c t a n g l e . Data r e c t b n d ( p= P o i n t ( 0 , 0 ) , w=20 , h = 1 0 ) ;domainP . Data domain ( boundary= r e c t b n d ) ;

end Domain ;

Here, domainP is the type “instance” of Domain, where the boundary type isRectangle. Thus, domainP.Data.boundarywill 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 problemof 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 theapproach described here. The resulting packages are somewhat more complex thanthe classes in the design described earlier, but contain the same abstractions andgive the same result.

32

Page 49: levon-titelsid - DiVA portal

3.3 The Package Design

Rectangle

+p: Point

+w: Real

+h: Real

+shape(in u:Real): BPoint

HComposite

+parts: array [1..n] of PartType

+shape(in u:Real): BPoint

PartType:

<< PartType=Line, n=4 >>

1

<<package>>

Rectangle

Bnd = HComposite(PartType=Line, n=4)

<<package>>

<<record>>

Data

+p: Point

+w: Real

+h: Real

+bnddata: Bnd.Data

<<package>>

HComposite

<<record>>

Data

+parts: array [1..n] of PartType.Data

PartType = Boundary

<<replaceable package>>

<<function>>

shape

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

<<function>>

shape

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

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

33

Page 50: levon-titelsid - DiVA portal

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 thatare independent of any spatial discretization. The geometry of the PDE model,known and unknown field variables, boundary conditions and parts of the equationmodels 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 forparameters in the range [0, 1]. The shape function can be seen as a mapping froma 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 theshape function has the type BPoint, which is a point with additional informationabout the boundary conditions that are in effect at that point.

The base package for all boundary types is the package called Boundary:

package Boundaryr e p l a c e a b l e f u n c t i o n shape

input Real u ;input Data d a t a ;output BPoin t x ;

end shape ;

r e p l a c e a b l e record Dataparameter BoundaryCon di t io n . Data bc ;

end Data ;end Boundary ;

The formal parameter data to the shape function contains the actual data of thespecific boundary object. The record BPoint, representing a point with boundarycondition information, has the following definition in the two-dimensional case:

type BPoin t = Rea l [ 3 ] " x , y and boundary p a r t i n d e x " ;

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 discretizationand 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 definingthe actual geometry of the domain:

package Domainr e p l a c e a b l e package boundaryP = Boundary

extends Boundary ; / / base c l a s s r e s t r i c t i o n

34

Page 51: levon-titelsid - DiVA portal

3.4 Continuous Part

r e p l a c e a b l e record Dataparameter boundaryP . Data boundary ;

end Data ;

f u n c t i o n d i s c r e t i z e B o u n d a r yinput I n t e g e r n ;input boundaryP . Data d ;output BPoin t p [ n ] ;

a lgor i thmf o r i in 1 : n loop

p [ i , : ] := boundaryP . shape ( ( i − 1 ) / n , d ) ;end f o r ;

end d i s c r e t i z e B o u n d a r y ;end Domain ;

The restriction specifies that if the package boundaryP is replaced, the replacingpackage 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 packageboundaryP. The discretization simply calculates a given number of points uni-formly distributed on the boundary. The data record of the domain contains theboundary 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-defineddomain package or an existing standard domain from e.g. a library. All domainpackages 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 recordcontains the actual parameters of the domain:

package F i e l dr e p l a c e a b l e type F i e l d T y p e = Real ;r e p l a c e a b l e package domainP = Domain

extends Domain ; / / base c l a s s r e s t r i c t i o n

r e p l a c e a b l e record Dataparameter domainP . Data domain ;

end Data ;

r e p l a c e a b l e f u n c t i o n v a l u einput P o i n t x ;input Data d ;output F i e l d T y p e y ;

a lgor i thmy := 0 ;

end v a l u e ;

35

Page 52: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

end F i e l d ;

The function called value represents the mapping, which can be defined whenspecifying fields with known values. Fields with unknown values that must besolved for during simulation may use value functions that interpolate the values forgiven coordinates. The declaration of the package domainP contains a base classrestriction, i.e. this package may only be replaced by a package that is a subtypeof Domain. The default base package is also Domain. The field class can be usedwith 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 Fie ldE xam plef u n c t i o n myFieldFunc

input P o i n t x ;input myFieldP . Data d ;output myFieldP . F i e l d T y p e y ;

a lgor i thmy := cos (2* PI *x [ 1 ] / 6 ) + s i n (2* PI *x [ 2 ] / 6 ) ;

end myFieldFunc ;

package omegaP =Domain ( r e d e c l a r e package boundaryP = C i r c l e ) ;

package myFieldP =F i e l d ( r e d e c l a r e package domainP =omegaP ,

r e d e c l a r e f u n c t i o n v a l u e = myFieldFunc ) ;

parameter C i r c l e . Data bnd ( r a d i u s = 2 ) ;parameter omegaP . Data omega ( boundary=bnd ) ;parameter myFieldP . Data m y f i e l d ( domain=omega ) ;

end Fie ldE xam ple ;

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

3.4.4 Included Boundaries

Some predefined boundaries can be found in the package Boundaries. All thesepackages extend the basic package Boundary. Therefore, the data records in eachboundary contain the parameter bc of type BoundaryCondition.Data, definingthe boundary conditions. Boundary conditions are described in Section 3.4.6. Anoverview of the included boundaries was previously presented in Figure 3.2. Theseare also briefly described in the following sections.

36

Page 53: levon-titelsid - DiVA portal

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 L ineextends Boundary ;

r e d e c l a r e record Dataextends Boundary . Data ;parameter P o i n t p1 ;parameter P o i n t p2 ;

end Data ;. . .

end L ine ;

The shape function simply interpolates the points linearly between the end points:

package L ineextends Boundary ;. . .r e d e c l a r e f u n c t i o n shape

input Real u ;input Data d ;output BPoin t x ;

a lgor i thmx [ 1 : 2 ] := d . p1 + u *( d . p2 − d . p1 ) ;x [ 3 ] := d . bc . i n d e x ;

end shape ;

end L ine ;

The boundary part index is passed through to the points on the boundary, which islater 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 centerand with a given radius:

package Arcextends Boundary ;

r e d e c l a r e record Dataextends Boundary . Data ;parameter P o i n t c =0 , 0 ;parameter Real r =1 ;parameter Real a _ s t a r t =0 ;parameter Real a_end = p i / 4 ;

end Data ;. . .

end Arc ;

37

Page 54: levon-titelsid - DiVA portal

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 Arcextends Boundary ;. . .r e d e c l a r e f u n c t i o n shape

input Real u ;input Data d ;output BPoin t x ;

p r o t e c t e dReal a =( d . a_end − d . a _ s t a r t ) ;

a lgor i thmx [ 1 : 2 ] := d . c + d . r * cos ( d . a _ s t a r t + a *u ) ,

s i n ( d . a _ s t a r t + a *u ) ;x [ 3 ] := d . bc . i n d e x ;

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 C i r c l eextends Arc ( Data ( a _ s t a r t =0 , a_end =2* p i ) ) ;

end C i r c l e ;

3.4.4.4 Rectangle

A rectangle declares four lines as components, with the names bottom, right,top and left, as follows:

package R e c t a n g l eextends Boundary ;package Bnd = HComposite ( r e d e c l a r e package Par tT ype = L ine ) ;

r e d e c l a r e record Dataextends Boundary . Data ;parameter P o i n t p ;parameter Real w;parameter Real h ;

parameter Bnd . Data b n d d a t a ( n =4 , p a r t s = bottom , r i g h t , top , l e f t ) ;parameter L ine . Data bot tom (

p1=p ,p2=p + w, 0 ,bc ( i n d e x =1 , name=" bo t tom " ) ) ;

parameter L ine . Data r i g h t (p1=p + w, 0 ,

38

Page 55: levon-titelsid - DiVA portal

3.4 Continuous Part

p2=p + w, h ,bc ( i n d e x =2 , name=" r i g h t " ) ) ;

parameter L ine . Data t o p (p1=p + w, h ,p2=p + 0 , h ,bc ( i n d e x =3 , name=" t o p " ) ) ;

parameter L ine . Data l e f t (p1=p + 0 , h ,p2=p ,bc ( i n d e x =4 , name=" l e f t " ) ) ;

end Data ;

r e d e c l a r e f u n c t i o n shapeinput Real u ;input Data d ;output BPoin t x ;

a lgor i thmx := Bnd . shape ( u , d . b n d d a t a ) ;

end shape ;

end R e c t a n g l e ;

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 declaredas Line, accordingly.

3.4.4.5 Bezier

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

package B e z i e rextends Boundary ;

r e d e c l a r e record Dataextends Boundary . Data ;parameter I n t e g e r n =1 ;parameter P o i n t p [ n ] ;

end Data ;. . .

end B e z i e r ;

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

39

Page 56: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

package B e z i e rextends Boundary ;. . .

r e d e c l a r e f u n c t i o n shapeinput Real u ;input Data d ;output BPoin t x ;

p r o t e c t e dP o i n t q [ : ] = d . p ;

a lgor i thmf o r k in 1 : ( d . n − 1) loop

f o r i in 1 : ( d . n − k ) loopq [ i , : ] := (1 − u )* q [ i , : ] + u*q [ i + 1 , : ] ;

end f o r ;end f o r ;x [ 1 : 2 ] := q [ 1 , : ] ;x [ 3 ] := d . bc . i n d e x ;

end shape ;

end B e z i e r ;

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 orunion types in Modelica, it is not possible to declare a container for boundary partswhere each part can be a (different) subclass of Boundary, not known at the timeof library development. Hence, the Generic package contains an enum parameterdeciding the type of the boundary part, and data records for each of the existingtypes that can be selected. This leads to a lot of overhead, since only one of therecords are actually used, but unused parameters are optimized away during thecompilation so they do not affect the resulting simulation code. In future imple-mentations, union types or other solutions for polymorphism might allow moreefficient implementation of generic boundary types.

The enumeration type and the data record for the Generic boundary type fol-lows:

package G e n e r i cextends Boundary ;

type PartTypeEnum = e n u m e r a t i o n (l i n e ,a rc ,b e z i e r ) ;

r e d e c l a r e r e p l a c e a b l e record Dataextends Data ;parameter PartTypeEnum p a r t T y p e ;

40

Page 57: levon-titelsid - DiVA portal

3.4 Continuous Part

parameter L ine . Data l i n e ;parameter Arc . Data a r c ;parameter B e z i e r . Data b e z i e r ;

end Data ;. . .

end G e n e r i c ;

Because of lack of polymorphism, e.g. virtual functions, the shape function mustcheck the enumeration variable and call the correct shape function:

package G e n e r i cextends Boundary ;. . .r e d e c l a r e f u n c t i o n shape

input Real u ;input Data d ;output BPoin t x ;

a lgor i thmi f d . p a r t T y p e ==PartTypeEnum . l i n e then

x := L ine . shape ( u , d . l i n e ) ;e l s e i f d . p a r t T y p e ==PartTypeEnum . a r c then

x := Arc . shape ( u , d . a r c ) ;e l s e i f d . p a r t T y p e ==PartTypeEnum . b e z i e r then

x := B e z i e r . shape ( u , d . b e z i e r ) ;end i f ;

end shape ;

end G e n e r i c ;

3.4.4.7 Composite

The Composite boundary simply uses a given number of Generic boundaries tobuild a complete boundary using parts of different types:

package Composi teextends Boundary ;

package Par tT ype = B o u n d a r i e s . G e n e r i c ;

r e d e c l a r e r e p l a c e a b l e record extends Dataparameter I n t e g e r n =1 ;parameter Par tT ype . Data p a r t s [ n ] ;

end Data ;. . .

end Composi te ;

The shape function calls the shape function in the Generic boundary package,using the index calculated by dividing the formal parameter u uniformly amongthe existing parts:

package Composi teextends Boundary ;

41

Page 58: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

. . .r e d e c l a r e f u n c t i o n shape

input Real u ;input Data d ;output BPoin t x ;

p r o t e c t e dReal s=d . n*u ;I n t e g e r i s = i n t e g e r ( s ) ;

a lgor i thmx := Par tT ype . shape ( s − i s , d . p a r t s [1 + i s ] ) ;

end shape ;

end Composi te ;

Here, is contains the part index corresponding to the value of the formal parameteru, and s-is is the new parameter value scaled to map to the parameter range of thatparticular boundary part. For example, if the shape function is called for a boundarycontaining four parts with u = 0.8, the value of is will be integer(4 ∗ 0.8) = 3 andthe value of s − is will be 4 ∗ 0.8 − 3 = 0.2, mapping to the u value on the fourthboundary 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, theboundary conditions and the field, are declared here. Their discrete counterpartsare declared and initialized automatically from the continuous components, usinggiven discretization parameters. See Section 3.8.3 and Section 3.8.4 for the discreteparts of the equation models.

For example, an equation model declares a domain and a field as follows:

package Poisson2D. . .model E q u a t i o n " P o i s s o n e q u a t i o n 2D"

r e p l a c e a b l e package domainP = Domain ;parameter domainP . Data domain ;

package f i e l d P = F i e l d ( r e d e c l a r e package domainP = domainP ) ;parameter f i e l d P . Data u ( domain=domain ) ;

end E q u a t i o n ;

end Poisson2D ;

This approach allows the equation model to be reused with any domain withoutchanging any part of the model. The package fieldP redeclares the replaceable

42

Page 59: levon-titelsid - DiVA portal

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 theobject hierarchy of the model. The record u has the type fieldP.Data and willcontain the correct domain data type from the given package domainP. The actualinstance data for the domain is passed to the field object with the modification ofthe domain parameter when declaring the record u. When the domain is to bediscretized, 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, thecorrect shape function will be called. This is handled automatically through thepackage DiscreteDomain, explained in Section 3.6.1, which is declared in thediscrete parts of the equation models.

3.4.5.1 The Poisson Equation

The Poisson equation is a stationary (time-independent) PDE model. In differentialform, the equation is

−∇ · (c∇u) = g in Ω (3.1)

where u is the unknown field, c is a possibly space-dependent coefficient, g is thesource term and Ω is the domain. The continuous part of the equation definitionfollows:

package Poisson2D. . .

model E q u a t i o n " P o i s s o n e q u a t i o n 2D"/ / User d e f i n e d p a r a m e t e r sr e p l a c e a b l e package domainP = Domain ;parameter domainP . Data domain ;

parameter Real c = 1 ;parameter Real g0=1 " C o n s t a n t v a l u e f o r r i g h t hand s i d e " ;

/ / I n t e r n a l p a r a m e t e r spackage f i e l d P = F i e l d (

r e d e c l a r e package domainP = domainP ) ;parameter f i e l d P . Data u ( domain=domain ) ;

end E q u a t i o n ;

end Poisson2D ;

The current model only supports spatially constant values for the right hand sideparameter g, given in g0. A future extension is adding a field variable gField

instead of the constant g. The boundary conditions defaults to Dirichlet type withvalue 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

Page 60: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

an example defining a domain and boundary conditions. The discrete part of theequation 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

∂t−∇ · (c∇u) = g in Ω (3.2)

where c is a possibly space-dependent coefficient, g is the source term and Ω is thedomain.

The continuous part of the diffusion equation model is identical to that of thePossion equation model shown in the previous section and is omitted here. For thediscrete 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, Neumannor mixed. The Dirichlet boundary condition is used where the value of the unknownfield 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

∂n= h2 on ∂Ω (3.4)

The mixed boundary condition, also called the Robin boundary condition, con-tains both the value of the field and the normal derivative:

a∂u

∂n+ bu = h3 on ∂Ω (3.5)

These boundary conditions are represented in the PDE library by the packageBoundaryCondition, defined as follows:

package BoundaryCond i t io ntype TypeEnum = e n u m e r a t i o n ( d i r i c h l e t , neumann , r o b i n ) ;

record DataTypeEnum bcType= d i r i c h l e t ;Rea l v a l =0 ;I n t e g e r i n d e x =1;S t r i n g name=" name " ;

end Data ;end BoundaryCond i t i on ;

44

Page 61: levon-titelsid - DiVA portal

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 ofcondition, 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 tothe 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 thePDE library. This is needed because boundary conditions are handled as parame-ters in the library, but e.g. the temperature on a boundary dynamically controlledby a controller must be time-dependent. This is handled using an additional type ofboundary condition, which, when assigned to a boundary, causes a time-dependentvariable to be used as the boundary value in the equations in the discrete PDEmodels. 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 areindependent of the solution method. The packages that contain discretized mod-els differs depending on the solution method because different solution methodsrequire different information. For example, the finite element discretization of thespatial derivatives requires subdivision of the spatial domain into elements, mostcommonly triangles in two-dimensions. In this case, the field is represented bydiscrete values at the nodes of the triangulation, since linear basis functions areused. Also, the partial differential equation is only expressed in its discrete formbecause of missing language constructs in Modelica. In the finite element case, thediscrete equation contains the stiffness matrix, the discrete field values and theirtime derivatives.

Hence, the design of the discrete classes is highly dependent on the discretizationmethod, consequently also on the solution method. For this reason, the discreteclasses are located in sub-packages, for example FEM and FEMForms for the finiteelement 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 ofthe 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 todifferent representations in the solvers. Here, we first describe domain and model

45

Page 62: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

discretization using the method of lines approach with finite elements. Then, wedescribe the design and contents of the packages FEM and FEMForms.

The complete discretization and solution process is depicted in Figure 3.4. Theexternal stiffness matrix calculation can be exchanged with internal code, i.e., func-tions implemented in Modelica. A prototype implementation of a finite elementsolver in Modelica exists for discretization of the Poisson equation with homoge-neous Dirichlet boundary conditions.

DiscreteModelica definition

(boundary)

ContinuousModelica definition

DiscreteModelica Definition

ExternalGrid Generation

Results

ExternalStiffness Matrix

Calculation

BoundaryDiscretization

Simulation ofModelica Model

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

If linear polynomials are used as basis functions, the coefficients themselvescorrespond 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 methodof lines with finite elements. Spatial dependency is removed by discretizing thedomain and replacing continuous fields with arrays of discrete values. The domainis divided into triangular regions the field is represented by the field values onthe triangle nodes, which is sufficient because first-order polynomials are used asbasis functions. Figure 3.5 depicts a triangulation example. The triangulation isgenerated by an external tool, a mesh generator. The interface functions for themesh generator calls are defined in the MeshGeneration sub-package.

The mesh generator used here, bamg [19], expects a polygon representing theboundary of the domain. The refinement of the discretization, e.g. the size andconsequently the number of triangles and nodes, is controlled by a parameter to themesh generation tool. A real number is given for each of the vertices. The smaller

46

Page 63: levon-titelsid - DiVA portal

3.5 Discrete Part Design

1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 61

1.5

2

2.5

3

3.5

4

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

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 complexgeometry 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, amesh 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 meshrepresentation contains the following components:

vertices: An array of Integer arrays of size 3, e.g. a tuple (x, y, bc), whereeach element contains the coordinates of the vertex, (x, y), and the boundarycondition 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 amaterial index m in order to keep track of different material parameters in case themodel contains different sub-domains with different material properties.

47

Page 64: levon-titelsid - DiVA portal

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 accessdifferent parts of the mesh data. Currently one and two dimensional domains aresupported. Since external software is used to generate the mesh, the mesh gener-ation functions are given a filename where generated mesh is stored, and accessfunctions takes a filename as an argument to read mesh data from. The size of eachpart of a mesh must be known before that part can be retrieved by a function callin Modelica, because the size of output variables of functions must be known inadvance 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 isgenerated using the given boundary polygon, boundary conditions and refinementparameter.

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 mustmatch the size of vertex array in the file.

edges2D: Reads the edge data from a given mesh file. The given size must matchthe size of edge array in the file.

triangles2D: Reads the triangle data from a given mesh file. The given size mustmatch 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 implementingcomposite boundaries. A composite boundary consists of a number of boundaryparts, each of which can have a different type. Since the number and type of theparts is not known in advance, we cannot declare them as different components butas an array. Also, arrays cannot contain objects of different types. Our solution tothis is to create a boundary type called Generic, which can represent any boundarytype by declaring objects of each available boundary type and an identifier thatidentifies 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 boundaryparts of the same type. For example the Rectangle boundary internally usesHComposite to store four lines, as seen in Figure 3.3.

48

Page 65: levon-titelsid - DiVA portal

3.5 Discrete Part Design

Composite

+shape(in u:Real): BPoint

Generic

+line: Line

+arc: Arc

+bezier: Bezier

+boundaryType: enumeration

+shape(in u:Real): BPoint

parts

1..n

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

3.5.2 Model Discretization

The spatial discretization of the model using the finite element method results ina number of unknown coefficients. The unknown field is approximated by basisfunctions weighted with these coefficients. If linear polynomials are used as basisfunctions, the coefficients themselves correspond to the values of the solution fieldon 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 boundaryconditions, see for example the textbook Computational Differential Equations byK. Eriksson et al [20].

The model discretization consists of calculating the equation matrices, e.g., Ain Equation (3.13), and the right hand side of the model equation, based on themodel equation, the triangulation and the boundary conditions. The size of theequation system is given by the refinement level of the domain discretization, sincethe number of unknown coefficients correspond to the number of triangles in themesh. The type of the boundary conditions also affects the number of unknowns inthe 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 elementsare not two times differentiable.

For example, consider the one-dimensional equation −u′′ = g in Ωu = 0 on ∂Ω.

(3.6)

In order to solve with Galerkin’s method, it is stated in the form∫Ω

(−u′′ − g)v dx = 0 for all functions v (3.7)

using the orthogonality of the residual to all functions. The approximation of uusing linear elements is not possible to insert into Equation (3.6), because linear

49

Page 66: levon-titelsid - DiVA portal

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 followingvariational formulation: find the function u with u = 0 on ∂Ω such that∫

Ω

u′v′ dx =∫

Ω

gv dx. (3.8)

for all functions v with v = 0 on ∂Ω. Equation (3.8) is called a weak formof Equation (3.6). Here, the requirement has changed to existence of first-orderderivatives. The discrete version of the variational formulation can now be stated:Find uh ∈ Vh such that∫

Ω

u′hv′h 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 andgh can be defined as

uh(x) =N∑

k=1

ukϕk(x) (3.10)

gh(x) =N∑

k=1

gkϕk(x). (3.11)

The fields uh and gh are now represented by their coefficients (uk) and (gk) usingthis basis for Vh. Checking for orthogonality against all functions vh in the testspace can be accomplished by checking for a basis of the test space Vh, becauseall other functions are linear combinations of these. The test space have the samebasis, e.g., the hat functions, which give the following equation system:

N∑k=1

uk

∫Ω

ϕ′kϕ′

i =N∑

k=1

gk

∫Ω

ϕkϕi i = 1..N (3.12)

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) theknown coefficients corresponding to the right hand side, and A and M are N ×Nmatrices with the elements defined as

aik =∫

Ω

ϕ′kϕ′

i dx, i, k = 1..N (3.14)

mik =∫

Ω

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

50

Page 67: levon-titelsid - DiVA portal

3.5 Discrete Part Design

The matrix A is called the stiffness matrix, and the matrix M is called the massmatrix. 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:∫

Ω

v∇ · (∇u) dx = −∫

Ω

∇v∇u dx +∫

∂Ω

v∂u

∂nds (3.16)

In case of homogeneous Dirichlet boundary conditions, assuming v ≡ 0 on ∂Ω:∫Ω

v∇ · (∇u) dx = −∫

Ω

∇v∇u dx (3.17)

Consider the time-dependent, two-dimensional diffusion equation, with homo-geneous Dirichlet boundary conditions:

∂u∂t −∇ · (∇u) = g in Ω

u = 0 on ∂Ω(3.18)

The variational formulation is:Find u ∈ V such that∫

Ω

∂u

∂t−∇ · (∇u) v dx =

∫Ω

g v dx for all v ∈ V (3.19)

Here,

V = H10 (Ω) = u ∈ L2(Ω), ∇u ∈ L2(Ω), 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:

∂t

∫Ω

u v dx +∫

Ω

∇u∇v dx =∫

Ω

g v dx for all v ∈ V (3.22)

The discrete version of the two-dimensional variational formulation is:Find uh ∈ Vh such that

∂t

∫Ω

uh vh dx +∫

Ω

∇uh ∇vh dx =∫

Ω

gh vh dx for all vh ∈ Vh (3.23)

51

Page 68: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

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

uh(x) =N∑

k=1

uk ϕk(x) (3.24)

gh(x) =N∑

k=1

gk ϕk(x) (3.25)

Inserting these expressions in (3.23) gives the following:

∂t

(N∑

k=1

uk

∫Ω

ϕkϕi dx

)+

N∑k=1

uk

∫Ω

∇ϕk∇ϕi dx =N∑

k=1

gk

∫Ω

ϕkϕi dx i = 1..N (3.26)

Here, the following equation system can be identified:

M∂

∂tu + Au = Mg (3.27)

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 themass matrix and the stiffness matrix, respectively. The elements of these matricesare 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 sourceterm and Ω is the domain. The discrete version of the equation, simplified withc = 1, is

52

Page 69: levon-titelsid - DiVA portal

3.6 The FEM package

equat ionA * u . v a l = M * g . v a l ;

Here, u.val is a vector of size N containing the unknown coefficients, where Nis the number of nodes that the domain was discretized to. The values of u.valalso correspond to values of the field at the nodes since linear basis functions areused. 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 × Nmass matrix, generated by the finite element assembly.

3.5.2.4 The Diffusion Equation

The diffusion equation for a field u is:

∂u

∂t−∇ · (c∇u) = g in Ω (3.31)

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,

equat ionM * der ( u . v a l ) + A * u . v a l = M * g . v a l ;

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 diffusionequation. The other terms are the same as for the Poisson equation. Additionalterms 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 ofthe PDE model, a package called FEM has been created. The domain and modelrepresentation 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 packagedescribed in Section 3.8 lies in the representation of the matrices resulting fromthe model discretization. In the FEM package, a straightforward representation isused. The FEMForms package uses a representation specially adapted to the Rhe-olef solver. Other solution methods such as finite difference and finite volumemethods are briefly discussed in Section 3.10.

The FEM package uses a common interface package called FEMSolver to thediscretization routines. Sub-packages extend this interface package to implementdifferent solvers. Currently the solver packages InternalSolver, Internal-DiffusionSolver and RheolefSolver exist in the PDE library. The internalsolvers implement the finite element assembly directly as Modelica functions. The

53

Page 70: levon-titelsid - DiVA portal

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 theRheolef matrix representation to the internal Modelica representation.

DiscreteDomain

+boundary: array of BPoint

Domain

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

DiscreteField

+val: array of FieldType

Field

+value(Point): FieldType

FieldType:

DiscreteConstField

+constval: FieldType

+value(Point): FieldType

Interpolation

+interpolate(): array of FieldType

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 replaceablepackage domainP, representing the continuous version of the domain. The dis-cretization is done automatically, once DiscreteDomain is declared with a givenDomain package. DiscreteDomain is defined as follows:

package Discre teDomainr e p l a c e a b l e package domainP = Domain

54

Page 71: levon-titelsid - DiVA portal

3.6 The FEM package

extends Domain ; / / base c l a s s r e s t r i c t i o n

r e p l a c e a b l e record Dataparameter I n t e g e r nbp ;parameter domainP . Data domain ;/ / A parameter t o t h e mesh g e n e r a t o r/ / s p e c i f y i n g d e t a i l l e v e l , l e s s e r means/ / more t r i a n g l e sparameter Real r e f i n e = 0 . 7 ;

/ / Array o f d i s c r e t e p o i n t s on t h e boundaryparameter BPoin t boundary [ nbp ]=

domainP . d i s c r e t i z e B o u n d a r y ( nbp ,domain . boundary ) ;

parameter Mesh . Data mesh (n= s i z e ( boundary , 1 ) ,po lygon = boundary [ : , 1 : 2 ] ,bc= i n t e g e r ( boundary [ : , 3 ] ) ,r e f i n e = r e f i n e ) ;

parameter I n t e g e r b o u n d a r y S i z e =s i z e ( boundary , 1 ) ;

end Data ;end Discre teDomain ;

The actual mesh generation is done when the mesh component is instantiated bythe compiler, i.e., the Mesh package contains the actual calls to the external meshgenerator.

3.6.2 DiscreteField

The package DiscreteField encapsulates the conversion of a continuous fieldto a discrete field, using a given discrete domain. A discrete field contains twoseparate arrays of discrete points in the domain, one array containing the unknownvalues and one containing the known values, i.e., from given boundary conditions.This representation corresponds to the representation used in Rheolef [18], in orderto simplify the solver interface. Both arrays are indirect, i.e., they contain indicesof the actual points in the mesh representation. The DiscreteField package isdefined as follows:

package D i s c r e t e F i e l dr e p l a c e a b l e package f i e l d P = F i e l d ;r e p l a c e a b l e package ddomainP = Discre teDom ain ;

r e p l a c e a b l e record Dataparameter ddomainP . Data ddomain ;parameter f i e l d P . Data f l d ;f i e l d P . F i e l d T y p e v a l [ ddomain . mesh . nv ] (

s t a r t = z e r o s ( ddomain . mesh . nv ) ) ;parameter I n t e g e r f i e l d S i z e = s i z e ( va l , 1 ) ;

end Data ;

55

Page 72: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

end D i s c r e t e F i e l d ;

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 valuesetting.

3.6.3 The Poisson Equation

The Poisson equation is declared in the FEM package as follows:

p r o t e c t e dparameter Real l a p l a c e [ nv , nv ]= S o l v e r . g e t M a t r i x _ L a p l a c e ( ) ;parameter Real g [ nv ]= S o l v e r . g e t M a t r i x _ g ( ) ;

equat ion− l a p l a c e * u . v a l = g . v a l ;

Here, u.val is a vector of size nv containing the unknown coefficients, wherenv is the number of nodes that the domain was discretized to. The values of u.valalso correspond to values of the field at the nodes if linear basis functions areused. The vector g.val is the right hand side values, also of size nv. The matrixLaplace is the stiffness matrix of size [nv,nv] generated by the finite elementassembly in the Solver package. The Solver package is replaceable and canbe 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:

p r o t e c t e dparameter Real L a p l a c e [ nv , nv ]= S o l v e r . g e t M a t r i x _ L a p l a c e ( ) ;parameter Real Mass [ nv , nv ]= S o l v e r . ge tMat r ix_Mass ( ) ;parameter Real g [ nv ]= S o l v e r . g e t M a t r i x _ g ( ) ;

equat ionMass * der ( u . v a l ) − L a p l a c e * u . v a l = g . v a l ;

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 diffusionequation. 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

Page 73: levon-titelsid - DiVA portal

3.7 Rheolef Finite Element Solver

getMatrix_g: Returns the corresponding right hand side vector (load vector) fora 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 thetime-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 solverRheolef 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 continuousfield.

3.7 Rheolef Finite Element Solver

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

3.7.1 Forms

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

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

with H10 (Ω) being the test space as defined in Equation (3.20) in Section 3.5.2.2,

and the definitions

a(u, v) =∫

Ω

∇u∇v dx

m(g, v) =∫

Ω

gv dx

57

Page 74: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

The discrete version of the problem is formulated using the finite dimensional spaceVh 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 discretespace 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), and the massmatrix 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 valuesof the field are the values on the boundary with the Dirichlet boundary conditionwhere the field value is known. Here, for simplicity, we remove the unused partsof the test vector and the matrices. The bilinear forms a(uh, vh) and m(gh, vh) arethen represented by the matrices

A =(

A.uu A.ub)

(3.34)

M =(

M.uu M.ub)

(3.35)

and the fields uh and gh are represented by

uh =(

uh.uuh.b

)(3.36)

gh =(

gh.ugh.b

)(3.37)

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 usingthe same external interface, as long as the equations can be formulated using theexisting forms. If new forms are needed, the external interface must be extendedso 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 changedepending 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 arecalculated. This is necessary because the number of discrete points on the boundarywhere Dirichlet boundary conditions are used will decide the number of blockedvalues in the field and consequently the sizes of the form matrices as described inthe previous section. Also, Neumann and Robin boundary conditions generate newterms in the variational formulation of the equation.

58

Page 75: levon-titelsid - DiVA portal

3.8 The FEMForms package

3.8 The FEMForms package

The FEMForms package uses a representation compatible with the external solverRheolef [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 liesin the representation of the fields and the matrices as described in Section 3.7. Theparts of the package that differ from the FEM package is presented in the followingsections.

DiscreteDomain

+boundary: array of BPoint

Domain

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

DiscreteField

+val_u: array of FieldType

+val_b: array of FieldType

+u_indices: array of Integer

+b_indices: array of Integer

+formsize: FormSize

Field

+value(Point): FieldType

FieldType:

DiscreteConstField

+constval: FieldType

+value(Point): FieldType

Interpolation

+interpolate(): array of FieldType

+interpolate_indirect(): array of FieldType

Form

+uu: array[nu,nu] of Real

+ub: array[nu,nb] of Real

+bu: array[nb,nu] of Real

+bb: array[nb,nb] of Real

+nu: Integer

+nb: Integer

FormSize

+nu: Integer

+nb: Integer

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 D i s c r e t e F i e l dr e p l a c e a b l e package f i e l d P = F i e l d ;r e p l a c e a b l e package ddomainP = Discre teDom ain ;

r e p l a c e a b l e record Dataparameter ddomainP . Data ddomain ;

59

Page 76: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

parameter f i e l d P . Data f l d ;parameter FEMSolver . FormSize f o r m s i z e ;

parameter I n t e g e r u _ i n d i c e s [ f o r m s i z e . nu ] ;parameter I n t e g e r b _ i n d i c e s [ f o r m s i z e . nb ] ;f i e l d P . F i e l d T y p e v a l _ u [ f o r m s i z e . nu ] (

s t a r t = z e r o s ( f o r m s i z e . nu ) ) ;f i e l d P . F i e l d T y p e v a l _ b [ f o r m s i z e . nb ] ;

parameter I n t e g e r f i e l d S i z e _ u = s i z e ( val_u , 1 ) ;parameter I n t e g e r f i e l d S i z e _ b = s i z e ( val_b , 1 ) ;

end Data ;end D i s c r e t e F i e l d ;

Here, the field values are stored in two indirect arrays, one for the unknown valuesand one for the known values given as boundary conditions. FormSize containsthe sizes of the two arrays of discrete values, and is calculated and returned from theexternal solver since the sizes depend on the discretization refinement and bound-ary conditions actually used in the model. The arrays u_indices and b_indicescontain 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 FEMSolverrecord Form

parameter I n t e g e r nu ;parameter I n t e g e r nb ;parameter Real uu [ nu , nu ] ;parameter Real ub [ nu , nb ] ;parameter Real bu [ nb , nu ] ;parameter Real bb [ nb , nb ] ;

end Form ;

record FormSizeparameter I n t e g e r nu ;parameter I n t e g e r 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 nativetypes are directly used instead of a record, as in the following models.

60

Page 77: levon-titelsid - DiVA portal

3.8 The FEMForms package

3.8.3 The Poisson Equation

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

p r o t e c t e dparameter Real A_uu [ f o r m s i z e . nu , f o r m s i z e . nu ] =

ge tForm _gradgrad_u u ( . . . ) ;parameter Real A_ub [ f o r m s i z e . nu , f o r m s i z e . nb ] =

ge tForm _gradgrad_u b ( . . . ) ;parameter Real M_uu [ f o r m s i z e . nu , f o r m s i z e . nu ] =

getForm_mass_uu ( . . . ) ;parameter Real M_ub [ f o r m s i z e . nu , f o r m s i z e . nb ] =

getForm_mass_ub ( . . . ) ;parameter Real b v a l s [ f o r m s i z e . nb ] = g e t B l o c k e d V a l u e s ( . . . ) ;

equat ionA_uu * u . v a l _ u = M_uu * g . v a l _ u

+ M_ub * g . v a l _ b− A_ub * u . v a l _ b ;

u . v a l _ b = b v a l s ;

Here, the unknown and blocked parts of the A and M matrices are retrieved fromthe Rheolef environment using external function calls in the PDE library. Thearguments to these calls also contain mesh filename, mesh size, form size, andboundary 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-dependentversion, presented in Section 3.5.2.2.

3.8.4 The Diffusion Equation

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

equat ionM_uu * der ( u . v a l _ u ) = − A_uu * u . v a l _ u

− A_ub * u . v a l _ b+ M_uu * g . v a l _ u+ M_ub * g . v a l _ b ;

u . v a l _ b = b v a l s ;

Here, the unknown and blocked parts of the A and M matrices are retrieved from theRheolef environment using external function calls in the PDE library, as in theprevious 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 finiteelement discretization using Rheolef:

61

Page 78: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

getFormSize: Returns the number of unknown and blocked values for a givenmesh and boundary conditions. This function needs to be called in order to declarecorrect 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 meshand boundary conditions, where h is the right hand side of the Neumann and Robinboundary 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 boundaryconditions. 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. Thediscrete part can be completely handled by the equation model, hiding the detailsfrom the user.

An example using the PDE library to solve a two-dimensional Poisson equationon the domain shown in Figure 3.9 follows here:

model MyBoundaryPoissonExampleimport PDELib . B o u n d a r i e s . * ;import PDELib . * ;

parameter I n t e g e r n =64;parameter Real r e f i n e = 0 . 5 ;parameter P o i n t p =1 , 1 ;parameter Real w=5;parameter Real h =3;parameter Real r =2 ;

62

Page 79: levon-titelsid - DiVA portal

3.9 Example

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

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 ,bot tom ( bc= d i r z e r o ) ,r i g h t ( bc= d i r z e r o ) ,roundedCorner ( bc= d i r f i v e ) ,t o p ( bc= d i r z e r o ) ,l e f t ( bc= d i r z e r o ) ) ;

package omegaP = Domain (r e d e c l a r e package boundaryP =myBoundaryP ) ;

parameter omegaP . Data omega ( boundary=mybnd ) ;

parameter BoundaryCond i t i o n . Data d i r z e r o (bcType= BoundaryCond i t i o n . d i r i c h l e t ,g =0 ,i n d e x =1 ,name=" d i r z e r o " ) ;

parameter BoundaryCond i t i o n . Data d i r f i v e (bcType= BoundaryCond i t i o n . d i r i c h l e t ,g =5 ,i n d e x =2 ,name=" d i r f i v e " ) ;

parameter BoundaryCond i t i o n . Data b c l i s t [ : ] = d i r z e r o ,

d i r f i v e ;

package PDE =PDELib . FEMForms . E q u a t i o n s . Poisson2D

( r e d e c l a r e package domainP = omegaP ) ;

63

Page 80: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

PDE . E q u a t i o n pde (domain=omega ,nbp=n ,r e f i n e = r e f i n e ,nbc= s i z e ( b c l i s t , 1 ) ,bc= b c l i s t ) ;

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 differentvalues, 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 MyBoundaryextends Boundary ;

r e d e c l a r e record Dataextends Boundary . Data ;parameter P o i n t p ;parameter Real w;parameter Real h ;parameter Real r ;parameter L ine . Data bot tom (

p1=p ,p2=p + w, 0 ,bc ( i n d e x = 1 ) ) ;

parameter L ine . Data r i g h t (p1=p + w, 0 ,p2=p + w, h − r ,bc ( i n d e x = 2 ) ) ;

parameter L ine . Data t o p (p1=p + w − r , h ,p2=p + 0 , h ,bc ( i n d e x = 3 ) ) ;

parameter L ine . Data l e f t (p1=p + 0 , h ,p2=p ,bc ( i n d e x = 4 ) ) ;

parameter Arc . Data roundedCorner (c=p + w − r , h − r ,r =r ,a _ s t a r t =0 ,a_end=Arc . p i / 2 ,bc ( i n d e x = 5 ) ) ;

end Data ;

parameter Composi te . Data boundary (p a r t s 1 ( l i n e =bottom ,

p a r t T y p e =PartTypeEnumC . l i n e ) ,

64

Page 81: levon-titelsid - DiVA portal

3.9 Example

p a r t s 2 ( l i n e = r i g h t ,p a r t T y p e =PartTypeEnumC . l i n e ) ,

p a r t s 3 ( a r c = rounderCo rn e r ,p a r t T y p e =PartTypeEnumC . a r c ) ,

p a r t s 4 ( l i n e = top ,p a r t T y p e =PartTypeEnumC . l i n e ) ,

p a r t s 5 ( l i n e = l e f t ,p a r t T y p e =PartTypeEnumC . l i n e ) ) ;

end Data ;

r e d e c l a r e f u n c t i o n shapeinput Real u ;input Data d ;output BPoin t x ;

a lgor i thmx := Composi te . shape ( u , d . boundary ) ;

end shape ;

end MyBoundary ;

The boundary definition contains default values for the boundary indices that areoverwritten with the actual indices when the boundary is used in the particularmodel.

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 " P o i s s o n problem 2D"

r e p l a c e a b l e package domainP = Domain ;

model E q u a t i o nparameter domainP . Data domain ;parameter Real g0=1 " C o n s t a n t v a l u e o f r h s f i e l d " ;parameter I n t e g e r nbp =20;parameter Real r e f i n e = 0 . 7 ;

Here, the number of discrete boundary points to generate defaults to 20, refinementparameter controlling the size and number of generated triangles to 0.7 and oneboundary condition of type Dirichlet and right-hand-side value 0 is used for theentire boundary. These parameters are modified for the current model, as shown inthe example above.

The following code declares internal variables used by the model in their con-tinuous form, i.e. before discretization:

package r h s F i e l d P = C o n s t C o n s t F i e l d (r e d e c l a r e package domainP = domainP ) ;

parameter r h s F i e l d P . Data r h s F i e l d ( domain=domain ,c o n s t v a l =g0 ) ;

package u F i e l d P = F i e l d (r e d e c l a r e package domainP = domainP ) ;

65

Page 82: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

parameter u F i e l d P . Data u F i e l d ( domain=domain ) ;

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

package ddomainP = Discre teDom ain (r e d e c l a r e package domainP = domainP ) ;

parameter ddomainP . Data ddomain ( domain=domain ,nbp=nbp ,r e f i n e = r e f i n e ) ;

parameter FormSize f o r m s i z e = ge tForm Size ( . . . ) ;

parameter I n t e g e r u _ i n d i c e s [ f o r m s i z e . nu ]= ge tUnknownInd ices ( . . . ) ;parameter I n t e g e r b _ i n d i c e s [ f o r m s i z e . nb ]= g e t B l o c k e d I n d i c e s ( . . . ) ;

package r h s D F i e l d P = D i s c r e t e C o n s t F i e l d (r e d e c l a r e package f i e l d P = r h s F i e l d P ,r e d e c l a r e package ddomainP = ddomainP ) ;

package i n t e r p P = I n t e r p o l a t i o n (r e d e c l a r e package d f i e l d P = r h s D F i e l d P ) ;

parameter r h s D F i e l d P . Data g _ r h s (ddomain=ddomain ,f l d = r h s F i e l d ,f o r m s i z e = f o r m s i z e ,u _ i n d i c e s = u _ i n d i c e s ,b _ i n d i c e s = b _ i n d i c e s ,v a l _ u = i n t e r p P . i n t e r p o l a t e _ i n d i r e c t ( r h s F i e l d , u _ i n d i c e s , . . . ) ,v a l _ b = i n t e r p P . i n t e r p o l a t e _ i n d i r e c t ( r h s F i e l d , b _ i n d i c e s , . . . ) ) ;

package uDFieldP = D i s c r e t e F i e l d (r e d e c l a r e package ddomainP = ddomainP ,r e d e c l a r e package f i e l d P = u F i e l d P ) ;

uDFieldP . Data ud (ddomain=ddomain ,f l d = u F i e l d ,f o r m s i z e = f o r m s i z e ,u _ i n d i c e s = u _ i n d i c e s ,b _ i n d i c e s = b _ i n d i c e s ,v a l _ u ( s t a r t =1 f o r i in 1 : f o r m s i z e . 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_uand 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 andinserted as the start values here.

With all the variables declared, the matrices can be generated and the actual

66

Page 83: levon-titelsid - DiVA portal

3.10 Discussion

model equation can be formulated:

parameter Real A_uu [ f o r m s i z e . nu , f o r m s i z e . nu ]=ge tForm _gradgrad_uu ( . . . ) ;

parameter Real A_ub [ f o r m s i z e . nu , f o r m s i z e . nb ]=ge tForm _gradgrad_ub ( . . . ) ;

parameter Real M_uu [ f o r m s i z e . nu , f o r m s i z e . nu ]=getForm_mass_uu ( . . . ) ;

parameter Real M_ub [ f o r m s i z e . nu , f o r m s i z e . nb ]=getForm_mass_ub ( . . . ) ;

parameter Real b v a l s [ f o r m s i z e . nb ]= g e t B l o c k e d V a l u e s ( . . . ) ;parameter Real b d r _ u _ v a l s [ f o r m s i z e . nu ]= getMassBdr_u ( . . . ) ;

equat ionA_uu * ud . v a l _ u

= b d r _ u _ v a l s+ M_uu* g _ r h s . v a l _ u + M_ub* g _ r h s . v a l _ b− A_ub*ud . v a l _ b ;

ud . v a l _ b = b v a l s ; / / known boundary v a l u e send E q u a t i o n ;

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 passedwith each function. Future versions may optimize this interface using e.g. externalobjects, 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 ascomponents, as shown in Section 3.9. Additional standard boundaries can also beadded to the Boundaries package for future use. A similar sub-package contain-ing standard domains can be created as well, since declaration of domains usingspecific boundary packages can be done independently of actual user-defined do-main information.

The problem of expressing a partial differential equation in Modelica is solvedwithout language extensions, although restricted to discrete formulation. A numberof predefined PDE equation models are provided, with corresponding equationsin discrete form. These can be used with user-defined domains, parameters anddiscretization detail and user-selected boundary conditions. This approach leaves

67

Page 84: levon-titelsid - DiVA portal

Chapter 3 A Modelica Library for PDE-based Modeling

the responsibility of the discretization of the model to the library developer. Theadvantage is that the model developer has knowledge about the appropriate dis-cretization and the solver needed for solving that specific model. The disadvantageis that some flexibility is lost because only predefined models can be used.

68

Page 85: levon-titelsid - DiVA portal

Chapter 4

Language Elements forSpace-distributed Models

“If the facts don’t fit thetheory, change the facts.”

Albert Einstein

This chapter describes new language constructs for the Modelica language byintroducing the design concepts shown in Chapter 3 at the language level, therebyallowing 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 libraryis 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 languageconstructs to also enable this approach at the language level. Language support forcontinuous description of PDE models simplifies both reading and writing of mod-els, improves reusability, and decreases the dependency between the model and thesolution method.

The basic concepts from the PDE library that are introduced here are field vari-ables, domains, and boundaries. Additionally, language elements for derivativeoperators and examples of functions for differential operators using vector nota-tion are presented.

69

Page 86: levon-titelsid - DiVA portal

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 orderto declare the model before doing any discretization, a new kind of type is neededin 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 inModelica should be defined over continuous domains.

4.2.1 Field Variables

Type specification in variable declarations in Modelica can contain attributes suchas parameter, flow, etc., as seen in the example in the introduction. The typeattributes are used to declare different kinds of variables with respect to variability,signal direction, etc. Using the keyword field to specify fields allows declarationof 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 thebuilt-in types. For example:

f i e l d T em pera tu re T ;

Temperature can be defined as follows:

type T em pera tu re = Rea l ( u n i t ="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 bemodified in declarations or new type definitions. A new built-in attribute domainin the Real type can be used to give the definition domain of a field variable usingmodifications. Modifications in Modelica are hierarchical parenthesized lists ofname=value equations in declarations. For instance, a modification is used in thedefinition of the Temperature type above, for changing the unit attribute of thebuilt-in type Real to the unit value that holds for temperature. The declaration ofT above with a domain modification looks like this:

Rec tangu la rDom ain omega ( . . . ) ;f i e l d T em pera tu re T ( domain=omega ) ;

Here, a domain of type RectangularDomain is used. An approach for domaindefinitions in Modelica is further described in Section 4.3.1.1.

70

Page 87: levon-titelsid - DiVA portal

4.2 Fields

4.2.2 Field Constructor

In order to initialize field variables or define constant fields, literal field values mustbe possible to express in the language. A field constructor is an expression whichgenerates a field value over a given domain using a given expression. The syntaxfor the field constructor is:

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

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

TestDomain omega ( . . . ) ;f i e l d Real f = f i e l d (2* x+y f o r ( 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 samenames as the iterator variables are shadowed.

The first expression expr1 is the expression for calculating the field values. Givena point in the domain, the value of the field at that point is the value of expr1. Theiterator 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 futureimplementations, domain constructor expressions may be considered as well.

This approach is similar to the existing array constructor syntax in the currentModelica language, where the keyword array is used instead of field. Arrayconstructors in Modelica also have a shorter syntactic form:

"" expr1 "for" iter "in" expr2 ""

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

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

Page 88: levon-titelsid - DiVA portal

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 ina similar way as for vectors and matrices in Modelica. Table 4.1 shows the binaryoperators in Modelica which are overloaded to handle operations between scalarsand arrays. Similar overloading can be done for operations between scalars andfields.

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 shouldrequire 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 directlysupported by overloaded operations in Modelica, this can easily be arranged forfields and scalars. Addition or subtraction of a scalar with a field can be seen aschanging the value of the field with a constant offset.

72

Page 89: levon-titelsid - DiVA portal

4.2 Fields

4.2.3.2 Special Operators

The built-in special operators in Modelica should be overloaded to handle fieldsas well. For example, the der() operator applied to v, i.e., der(v), represents thederivative of the variable v. If v is a field, the result of the operation should be afield with the same domain as v and where the resulting field is the derivative of thefield 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 coordinatesas the following arguments with respect to which the derivation is defined, in thegiven 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 ) = f i e l d ( der ( v ( x ) ) f o r x in v . domain ) ;

Here, v(x) is a field access operation with a time-dependent scalar variable as itstype, as described in the following section, and der(v(x)) is the time derivative ofthe 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 thefunction-call like syntax:

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

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

model TempFieldf i e l d T em pera tu re T ( domain=omega ) ;T em pera tu re t _ i n t e r i o r ;

equat iont _ i n t e r i o r = T ( 1 . 4 , 1 . 7 ) ;

end TempField ;

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

73

Page 90: levon-titelsid - DiVA portal

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 aadequate final design.

4.3.1 Domain Geometry Definition

The approach taken for domain geometry definition in the PDE library can be usedfor defining domains on a language primitive level as well. The approach in thePDE 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 parameterfor the position on the curve is used, with coordinates of the point on the curve asoutput from the function.

Here, as well as in the library, we need to define complex boundaries consistingof 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-intype for boundaries are needed.

4.3.1.1 Domain Type

The Domain type is an extension needed in the Modelica language needed forrepresentation of definition domains. A separately declared domain object must bespecified 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 whendifferent 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 toother built-in types, such as the Real type. For example:

type Domainparameter I n t e g e r ndims =1;parameter Real c a r t e s i a n [ ndims ] ;parameter Real coord [ ndims ]= c a r t e s i a n ;parameter Boundary boundary [ : ] ;

end Domain ;

This built-in type can be used directly to declare domains, or it can be used as abase class to declare other standard domain types. Cartesian coordinates are used

74

Page 91: levon-titelsid - DiVA portal

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 placeholderfor arbitrary curvilinear coordinates [22], while the cartesian array always repre-sents cartesian coordinates. This representation is useful for specifying mappingsto other coordinate systems, as shown in Section 4.3.1.3. Using an array for thecoordinates 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 declaredas follows, using the aliases x and y:

type C a r t e s i a n 2 Dextends Domain ( ndims = 2 ) ;parameter Real x= coord [ 1 ] ; / / a l i a s f o r f i r s t c o o r d i n a t eparameter Real y= coord [ 2 ] ; / / a l i a s f o r second c o o r d i n a t e

end C a r t e s i a n 2 D ;

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 partialderivatives, as discussed in Section 4.3.2.1.

Using these domain types as base, a domain can be declared as follows:

type Rectangu la rDom ainextends C a r t e s i a n 2 D ( boundary = l e f t , bottom , r i g h t , t o p ) ;parameter P o i n t p ;parameter Real w;parameter Real h ;

parameter P o i n t p2 = P o i n t ( p . x+w, p . y ) ;parameter P o i n t p3 = P o i n t ( p . x+w, p . y+h ) ;parameter P o i n t p4 = P o i n t ( p , p . y+h ) ;

parameter L ine bottom = L ine ( p , p2 ) ;parameter L ine r i g h t = L ine ( p2 , p3 ) ;parameter L ine t o p = L ine ( p3 , p4 ) ;parameter L ine l e f t = L ine ( p4 , p ) ;

end Rectangu la rDom ain ;

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

75

Page 92: levon-titelsid - DiVA portal

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, themapping for different coordinate systems is not needed. A boundary will use themapping of the domain that it will be part of. In other words, boundaries can beseen as functions with parameters as input arguments and coordinates as outputarguments, independent of the coordinate system. The built-in Boundary typecan be defined as follows:

type Boundaryparameter I n t e g e r ndims =1;parameter Real coord [ ndims ] ;

r e p l a c e a b l e f u n c t i o n shapeinput Real u [ ndims −1]; / / u [ i ] i n [ 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 bedeclared as:

c l a s s L ineextends Boundary ( ndims = 2 ) ;

parameter P o i n t p1 ;parameter P o i n t p2 ;

r e d e c l a r e f u n c t i o n shapeinput Real u [ 1 ] ;output Real coord [ 2 ] ;

a lgor i thmcoord := p1 + u *( p2−p1 ) ;

end shape ;end L ine ;

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 currentlynot supported in Modelica, but it is the author’s belief that support for memberfunctions is required for an object-oriented design. The necessary changes in thelanguage to support this design is discussed in Section 4.3.5. A similar approachwith less changes to the language syntax is to explicitly pass the class instance:

c l a s s L ine. . .r e d e c l a r e f u n c t i o n shape

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

76

Page 93: levon-titelsid - DiVA portal

4.3 Future Language Extensions

input L ine t h i s ;input Real u [ 1 ] ;output Real coord [ 2 ] ;

a lgor i thmcoord := t h i s . p1 + u *( t h i s . p2−t h i s . p1 ) ;

end shape ;end L ine ;

Line here can be a general class or restricted to be only a record. The mainidea is to have the function inside the data structure which also is the first argumentto that function. Records are currently allowed as function arguments. A generalclass 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 functioncannot have side-effects. If the class is restricted to be a record functions mustbe allowed as members in records. In either way, this approach does not needany language modifications concerning lookup. The only language modificationis to remove the restriction that only functions inside packages can be called fromoutside that package.

4.3.1.3 Coordinate Systems

Using the domain definition approach above, domains in coordinate systems otherthan cartesian can be declared easily. For example, a two-dimensional polar coor-dinate system can be declared as follows:

c l a s s Polar2Dextends Domain ( ndims = 2 ) ;Rea l r = coord [ 1 ] ; / / a l i a s f o r f i r s t c o o r d i n a t eReal p h i = coord [ 2 ] ; / / a l i a s f o r second c o o r d i n a t e

equat ionc a r t e s i a n [ 1 ] = r * cos ( p h i ) ;c a r t e s i a n [ 2 ] = r * s i n ( p h i ) ;

end Polar2D ;

Alternatively, using modifiers for the alias equalities, and the inverse mapping forthe coordinates2:

c l a s s Polar2Dextends Domain ( ndims =2 , coord = r , p h i ) ;Rea l r ;Rea l p h i ;

equat ionr = s q r t ( c a r t e s i a n [ 1 ] ^ 2 + c a r t e s i a n [ 2 ] ^ 2 ) ;p h i = a t a n ( c a r t e s i a n [ 2 ] / c a r t e s i a n [ 1 ] ) ;

end Polar2D ;

Here, the relationship between the polar and the cartesian coordinates is declared asequations. 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

Page 94: levon-titelsid - DiVA portal

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 forfurther discussion regarding differential operators.

4.3.2 Differential Operators

In this section, built-in operators are presented, which are needed in the Modelicalanguage 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 partialderivatives 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 tothe function with name name, and only functions are allowed to be declared thisway. The syntax can be reused for the partial derivative operator for general fieldvariables and expressions:

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

The requirement should be that expr is of a field type and the IDENT argumentsare Real parameters declared in the domain of that field type. The parameters canbe aliases or the actual coord components. For completeness, the coord com-ponents themselves should be allowed as parameters. The advantage of allowingthese is also that coordinate system independent functions like divergence andgradient can be written without using coordinate aliases and without knowledgeabout 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 conditionsin PDEs. It is the derivative of a field in the outward normal direction on theboundary of the domain of the field. In order to avoid new operators, and forconsistency with the der operator for regular partial derivatives, the der operatorcan be reused with the special built-in identifier n, added to the built-in domaintype:

type Domain. . .parameter Real [ ndims ] n ;

78

Page 95: levon-titelsid - DiVA portal

4.3 Future Language Extensions

. . .end Domain ;

Here, n represents a outward normal vector on the boundary. The contents ofthe variables will not be meaningful during translation, because the declaration ismerely a implementation detail to handle the der operator with the regular lookuprules. Hence, the implementation of the translator and the solver will handle thecombination 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 expressedas follows:

model T e s t. . .TestDomain omega ;f i e l d Real u ( domain=omega ) ;. . .

equat ionder ( u , n ) = 0 in omega . boundary ;

end Domain ;

Again, the compiler and simulation environment must handle the n parameter inthe built-in type Domain especially. The lookup and syntax is consistent with therest of the language specification though.

4.3.2.3 Vector notation

In order to simplify implementation, general differential operators for curvilinearcoordinates [22] can be defined using vector notation and scale factors [23]. Thisapproach is similar to the design used in the Ctadel Tool [24,25]. The advantage ofvector notation is that the equations can be written independently of the coordinatesystem. The scale factors can be included in the domain type:

type Domain. . .RealType s c a l e [ 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 scalefactors 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:

c l a s s Polar2Dextends Domain ( ndims =2 , coord = r , p h i , s c a l e 1 , r ) ;Rea l r ;Rea l p h i ;

equat ion

79

Page 96: levon-titelsid - DiVA portal

Chapter 4 Language Elements for Space-distributed Models

r = s q r t ( c a r t e s i a n [ 1 ] ^ 2 + c a r t e s i a n [ 2 ] ^ 2 ) ;p h i = i f ( c a r t e s i a n [ 2 ] == 0 and c a r t e s i a n [ 1 ] == 0) then

0e l s e

a t a n 2 ( c a r t e s i a n [ 2 ] , c a r t e s i a n [ 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 whenchanging to another coordinate system.

Gradient

The gradient operator operates on scalar fields and results in a vector field withthe same number of elements as the dimension of the coordinate system. In twodimensions and for general curvilinear coordinates, the gradient is defined as:

∇u = grad u(x1, x2) =(

1h1

∂(u)∂x1

1h2

∂(u)∂x2

)

The three dimensional gradient is similar:

∇u = grad u(x1, x2, x3) =(

1h1

∂(u)∂x1

1h2

∂(u)∂x2

1h3

∂(u)∂x3

)

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

f u n c t i o n g r a d i e n tinput f i e l d Real u ;output f i e l d Real du [ u . domain . ndims ] ;

a lgor i thmf o r i in 1 : u . domain . ndims loop

du [ i ] := der ( u , coord [ i ] ) / s c a l e [ i ] ;end f o r ;

end g r a d i e n t ;

Divergence

The divergence operator operates on a vector field and results in a scalar field. Thetwo and three dimensional mathematical expressions for the divergence operator inarbitrary orthogonal curvilinear coordinates follows:

∇ · u = div u(x1, x2) =(

1h1h2

)(∂(h2u1)

∂x1+

∂(h1u2)∂x2

)

80

Page 97: levon-titelsid - DiVA portal

4.3 Future Language Extensions

∇ · u = div u(x1, x2, x3)

=(

1h1h2h3

)(∂(h2h3u1)

∂x1+

∂(h1h3u2)∂x2

+∂(h1h2u3)

∂x3

)

A corresponding PDEModelica function handling a general number of dimen-sions can be defined as follows:

f u n c t i o n d i v e r g e n c einput f i e l d Real u [ : ] ;output f i e l d Real du [ u . domain . ndims ] ;

p r o t e c t e dReal s ;

a lgor i thma s s e r t ( s i z e ( u , 1 ) == u . domain . ndims ) ;f o r i in 1 : u . domain . ndims loop

s := 1 ;f o r j in 1 : u . domain . ndims loop

i f ( i != j ) thens := s * u . domain . s c a l e [ j ] ;

end i f ;end f o r ;du := du + der ( s *u , coord [ i ] ) ;

end f o r ;s := 1 ;f o r j in 1 : u . domain . ndims loop

s := s * u . domain . s c a l e [ j ] ;end f o r ;du := du / s ;

end d i v e r g e n c e ;

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 usingthe in keyword, which is needed when defining boundary conditions. The syntaxfor 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 T e s tTestDomain omega ( . . . ) ;

81

Page 98: levon-titelsid - DiVA portal

Chapter 4 Language Elements for Space-distributed Models

f i e l d Real f ( domain=omega ) ;parameter Real q ;

equat ionf = q in omega . boundary ;

end T e s t ;

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 thefields appearing in the expression. Possibly, this requirement can be relaxed, toonly 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 explicitdomain.

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 beseen as a field reduction operator. Reduction expressions for arrays are alreadysupported 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 inexpr2. The result of the integral operation is a scalar. Optionally, single integrationcan be supported, i.e., integrating over fewer spatial variables than the dimensionof 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 Reduc t ionE xam pleRec tangu la rDom ain omega ;f i e l d Real T ( domain = omega ) ;Rea l T _ h e a t e r ;. . .

equat ionT _ h e a t e r = i n t e g r a l (T ( x , y ) f o r ( x , y ) in omega . l e f t )

/ omega . l e f t . l e n g t h ;. . .

end Reduc t ionE xam ple ;

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

Page 99: levon-titelsid - DiVA portal

4.3 Future Language Extensions

Alternatively, if explicit naming of coordinates is to be avoided, the followingsyntax 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 inthe above example becomes:

equat ionT _ h e a t e r = i n t e g r a l ( omega . l e f t , T ) / omega . l e f t . l e n g t h ;

4.3.5 Discussion

There are three major language extensions proposed in this chapter. The fieldtype prefix to represent continuous fields, the Domain built-in type to representdefinition domains of fields and the Boundary built-in type to declare boundariesneeded 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 Modelicato 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 thePDE library described in Chapter 3 illuminates the problem with lack of memberfunctions in the Modelica language. The solution proposed here should be seen asa first step towards a more general language design where member functions aresupported.

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 theobject they are called on, which create many problems in a declarative languagelike 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 objectsof different subtypes without knowing their particular type. For example, theshape function on a list of Boundary objects.

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

83

Page 100: levon-titelsid - DiVA portal

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. itis not possible to declare an array of Boundary object references where eachreference not necessarily have the same subtype. This restriction also calls for aspecial handling of the boundary component in the Domain built-in type.

84

Page 101: levon-titelsid - DiVA portal

Chapter 5

Implementation

“You’re suffering from a VulcanMind Meld, Doctor.”

Captain Kirk

This chapter contains implementation details about the two prototypes that weredeveloped for testing the design described earlier. The language extensions de-scribed in Chapter 4 have been implemented as an extension to an earlier versionof the OpenModelica Compiler (omc) [27]. In Section 5.1, a short overview ofthe OpenModelica Compiler is given, with PDEModelica extensions in separatesections in each part of the compiler.

The PDE library that implements mainly same ideas but without any languageextensions that was described in Chapter 3, is handled in Section 5.2. Finally, thesolver 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 theparser that reads textual Modelica code and generates an abstract syntax tree (AST).Next, a generated compiler (generated from semantics specification) traverses theAST and translates the models into a flat set of differential and algebraic equationsand possibly a set of functions and algorithm sections. A numerical solver is thenused to simulate the model by solving the total system of equations at differenttime steps. The different steps of the translation process and the tools used can beseen 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

Page 102: levon-titelsid - DiVA portal

Chapter 5 Implementation

DAE-listin-RML

ANTLR Lexer and Parser

ANTLR Tree Walker

RML

Abstract syntax

Abstract syntax

Scanner and parser

Absyn tree builder

Translator

ToolModule

tree in ANTLR

tree in RML

Figure 5.1: The different steps of the translation process, the tools used and theintermediate 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 inFigure 5.2.

PDEomc

PDEModelica

Parser

Translator

Flattened

PDEModelica

Field functions

User input

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 lexergrammar specification consists of definition of the tokens, special characters andcomments. The reserved keywords of the language are listed in a tokens sec-tion:

tokens . . .

86

Page 103: levon-titelsid - DiVA portal

5.1 Modelica Compiler

CLASS = " c l a s s " ;CONNECT = " c o n n e c t " ;CONNECTOR = " c o n n e c t o r " ;. . .

Operators, special characters, comments and literals are defined using rules.Each rule consists of a name, a definition, and optionally actions to be performedwhen the rule is matched. The syntax for a rule is:

ru le_nam e :a l t e r n a t i v e _ 1

| a l t e r n a t i v e _ 2. . .| a l t e r n a t i v e _ n;

Each alternative contains a rule that is checked for a match. Table 5.1 lists some ofthe 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 isthe input that is being parsed, and a parse tree is automatically generated.

ANTLR also supports the implementation of tree walkers using a meta-languagesimilar to the lexer and parser definition meta-languages. Tree walkers can be usedto 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 gothrough the parse tree and build the corresponding abstract syntax tree used by thetranslator.

5.1.1.1 PDEModelica Extensions

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

87

Page 104: levon-titelsid - DiVA portal

Chapter 5 Implementation

added to the Modelica parser. The tree node type FIELD_FUNCTION_CALL isadded for the representation in the abstract syntax tree.

In order to support the field type prefix, FIELD is added as an optional token inthe type_prefix rule in the grammar:

t y p e _ p r e f i x :( 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 arrayconstructors is already implemented in the parser, where for-iterators are used inthe array()-operator. Parsing of the field constructor is similar, except that theiterator variables can be a parenthesized list instead of single variables. This isimplemented by the following addition to the grammar:

f o r _ i n d i c e s _ f i e l d :( IDENT | LPAR^ IDENT (COMMA! IDENT)* RPAR ! )( IN^ e x p r e s s i o n ) ?;

. . .

f o r _ o r _ e x p r e s s i o n _ l i s t :(

LA(1)==IDENT && LA( 2 ) == EQUALS | | LA( 1 ) == RPAR ?| (

e : e x p r e s s i o n( COMMA! e x p l i s t : f o r _ o r _ e x p r e s s i o n _ l i s t 2| FOR^ f o r i n d : f o r _ i n d i c e s| FOR^ f o r i n d f : f o r _ i n d i c e s _ f i e l d) ?

));

5.1.2 Modelica Translator

A tree walker written in ANTLR traverses the parse tree generated by the parser andcreates the abstract syntax tree (AST) as declared in the Absyn RML module. Thetree is subsequently processed further by the Modelica translator described in thefollowing sections, starting with an introduction to RML used as the specificationlanguage for the translator.

88

Page 105: levon-titelsid - DiVA portal

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 thelanguage 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 similarto natural deduction used in logics. Inference rules with the same input and outputformal parameters can be grouped into signatures. Each rule is defined by a set ofpropositions called premises and a proposition called conclusion. A proposition isproved 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 withthe 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 ofrules. Rules contain propositions consisting of relation invocation with argumentsand results separated by the => symbol. The premises and the conclusion areseparated by a line with two or more consecutive dashes, see Figure 5.3. Thesyntax is otherwise similar to that of Standard ML [32]. An example relation canbe seen in Figure 5.3.

The first part of an RML specification file contains the data type declarationsand relation declarations that are visible to other modules. The module exprmodin Figure 5.3 contains one data type, Exp, that can be either an integer constantor an addition operation with two subexpressions. Integer numbers are representedby the primitive type int. The only relation in this module is called eval, whichevaluates 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 theaddition operations by first evaluating the subexpressions and adding their valuesusing the built-in RML operator int_add. The result of the rule is then the resultof 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 expandedand improved. This specification describes the static semantics of the Modelicalanguage, i.e., the interpretation of the object-oriented structure, typing, and dec-larations defined in the models. The dynamic semantics involving the run-timesimulation of the models is not included. Hence, this specification describes the

89

Page 106: levon-titelsid - DiVA portal

Chapter 5 Implementation

module exprmod :datatype Exp = INTCONST of i n t

| OP_ADD of Exp * Expr e l a t i o n e v a l : Exp => i n t

end

r e l a t i o n e v a l : Exp => i n t =

axiom e v a l INTCONST( v ) => v

r u l e e v a l ( e1 ) => v1 &e v a l ( e2 ) => v2 &i n t _ a d d ( v1 , v2 ) => v3−−−−−−−−−−−−−−−−−−−−−e v a l (OP_ADD ( e1 , e2 ) ) => v3

. . .end

Figure 5.3: Example of an RML specification. The first part contains the data typedefinitions and the module interface definition. The second part con-tains the relations. int is the built-in integer type, and int_add isthe built-in integer addition operator.

translation of Modelica models with structural and compositional information intoa flat list of equations.

The translator specification is divided into several modules. The Absyn modulecontains the representation of the abstract syntax tree, with data types that representclasses, variable declarations, equations, algorithms, expressions, and statements.The Absyn representation is close to the source representation of the Modelicacode, i.e., the source can be recreated from the abstract syntax.

From the abstract syntax tree the SCode intermediate tree is generated. This treeis defined in the SCode module. The SCode tree is a canonical representation ofthe Modelica code for more convenient translation. For example, the Modelicacode and consequently the abstract syntax tree can contain multiple equation sec-tions, depending on how the code was entered. In the SCode representation theequation 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 symbolicallyinstantiated by the Inst module. The result of the symbolic instantiation is theDAE 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

Page 107: levon-titelsid - DiVA portal

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 themodel.

• Symbolically instantiating their contents with the current component nameprefix 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 subcomponentsupdated with the new component names.

During the symbolic instantiation, some type checking and constant expressionevaluation is also performed. Type checking also includes checking whether thesubtype relationship holds between Modelica classes. Figure 5.4 shows the RMLrelation 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 componentis a field or not:

datatype E l e m e n t A t t r i b u t e s = ATTR of boo l (* f l o w *)

* V a r i a b i l i t y (* parameter *)

* D i r e c t i o n (* i n p u t / o u t p u t * )

* ArrayDim

* F i e l d (* pdeomc *)

datatype F i e l d = FIELD | NON_FIELD

The walker used to generate the AST is modified correspondingly to create fieldnodes. A similar representation is added in the SCode module. Internally, theotherkeyfield prefix together with the component type is used to construct a fieldtype. The field type is represented in the Types module as follows:

datatype Type = T_INTEGER of Var l i s t| T_REAL of Var l i s t| T_STRING of Var l i s t| T_BOOL of Var l i s t| T_ENUM| T_ENUMERATION of s t r i n g l i s t * Var l i s t| T_ARRAY of ArrayDim * Type| T_COMPLEX of C l a s s I n f . S t a t e * Var l i s t

91

Page 108: levon-titelsid - DiVA portal

Chapter 5 Implementation

r e l a t i o n s u b t y p e : ( Type , Type ) => boo l =

axiom s u b t y p e ( T_INTEGER , T_INTEGER) => t rueaxiom s u b t y p e (T_REAL , T_REAL) => t rueaxiom s u b t y p e ( T_STRING , T_STRING) => t rueaxiom s u b t y p e (T_BOOL , T_BOOL) => t rue

. . .

r u l e s u b t y p e _ v a r l i s t ( e l1 , e l 2 ) => t rue−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−s u b t y p e (T_COMPLEX( s t1 , e l 1 ) , T_COMPLEX( s t2 , e l 2 ) ) => t rue

axiom s u b t y p e ( t1 , t 2 ) => f a l s e

end

r e l a t i o n e q u i v t y p e s : ( Type , Type ) => boo l =

r u l e s u b t y p e ( t1 , t 2 ) => t rue &s u b t y p e ( t2 , t 1 ) => t rue−−−−−−−−−−−−−−−−−−−−−−−e q u i v t y p e s ( t1 , t 2 ) => t rue

axiom e q u i v t y p e s ( t1 , t 2 ) => f a l s e

end

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

92

Page 109: levon-titelsid - DiVA portal

5.1 Modelica Compiler

| T_FUNCTION of FuncArg l i s t * Type| T_TUPLE of Type l i s t| T_FIELD of Type * Domain (* pdemodeq *)| T_NOTYPE

datatype Domain = 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 DOMAINtype 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 extensionswhere a domain constructor can be used directly.

During instantiation, the component declaration is checked for the existence ofthe field prefix, and if it is, the field type is constructed using the domain modifi-cation from the component declaration:

r e l a t i o n f i x _ f i e l d _ t y p e :( Types . Mod , SCode . A t t r i b u t e s , Types . Type ) => Types . Type =

r u l e i s _ f i e l d a t t r => t rue &Mod . l o o k u p _ c o m p _ m o d i f i c a t i o n ( mod , " domain " ) => mod &Mod . m od_equa t ion ( mod ) => e

−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−f i x _ f i e l d _ t y p e ( mod , a t t r , t y )=> ( ( Types . T_FIELD ( ty , Types .DOMAIN( e ) ) ,NONE) )

. . .end

The specification code shown above is somewhat simplified. Once the field type isconstructed, it follows the component during instantiation and type checking canbe done and expression types can be derived for expressions where the compo-nent is referenced. For example, during instantiation of the der()-operator, thetype of the first argument must be used to derive the type of the der()-operatorexpression.

The instantiation results in a constructed DAE. Fields are represented in the DAEas well:

datatype Type = REAL| INT| BOOL| STRING| ENUM| ENUMERATION of s t r i n g l i s t| FIELD of Type * Domain

datatype Domain = DOMAIN of Exp . Exp| NO_DOMAIN

93

Page 110: levon-titelsid - DiVA portal

Chapter 5 Implementation

Hence, the field variables can be handled and included in the flattened model, withaccompanying domain information. The flattened model can further be discretizedto 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 ( . . . ) ;f i e l d Real f = f i e l d (2* x+y f o r ( 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 fieldvalues over the domain during discretization. The field constructor is modified tocontain a call to the generated function instead of the field expression, in order tosimplify further conversion during the discretization step. The above example isconverted to the following code:

f u n c t i o n f_tmp1input Real x ;input Real y ;output Real o u t ;

a lgor i thmo u t = 2* x+y ;

end f_tmp1 ;. . .TestDomain omega ( . . . ) ;f i e l d Real f = f i e l d ( f_tmp1 ( x , y ) f o r ( x , y ) in omega ) ;

With this method, the existing function code generation implementation in thecompiler 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 twolevels, with a set of classes to be used for modeling using continuous fields anddomains, and a set of classes representing the discretized fields and domains. Themain continuous classes are Field, Domain, and Boundary. A domain is definedby giving a boundary component, which in turn is defined by a shape-functiondescribing 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 discretepart and the solver environment are currently based on the finite element method.However, implementations for other methods can easily co-exist in the library dueto the two-level design.

94

Page 111: levon-titelsid - DiVA portal

5.2 The PDE Library

Figure 5.5 depicts an overview of the PDE library implementation. Here, thelibrary 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 mainlybased on the continuous parts, with some configuration needed for the discretiza-tion. Selection of the solution method is done by instantiating the discrete modelfrom the specific package.

Continuousdescription

Discretemodel

discretizerBoundary

Finite elementspatial discretizer

Mesh generator

Discretizationconfiguration

boundary

Level 2

Level 1

PDEModelica Library

User input

PDE Model

discrete domain

stiffness matrix

External software

Figure 5.5: Overview of the PDE library and the implementation using the finiteelement method.

5.2.1 The Finite Element Package

The discrete level is highly dependent on solution method. For this reason, thediscrete 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 FEMFormspackage. The FEMForms package contains the main prototype implementationdeveloped 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 thefield data type found in Rheolef. An indirect representation is used so thatthe unknowns and known (blocked) values of the field can be grouped into twoseparate vectors in the field:

package D i s c r e t e F i e l d

95

Page 112: levon-titelsid - DiVA portal

Chapter 5 Implementation

DiscreteDomain

+boundary: array of BPoint

Domain

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

DiscreteField

+val_u: array of FieldType

+val_b: array of FieldType

+u_indices: array of Integer

+b_indices: array of Integer

+formsize: FormSize

Field

+value(Point): FieldType

FieldType:

DiscreteConstField

+constval: FieldType

+value(Point): FieldType

Interpolation

+interpolate(): array of FieldType

+interpolate_indirect(): array of FieldType

Form

+uu: array[nu,nu] of Real

+ub: array[nu,nb] of Real

+bu: array[nb,nu] of Real

+bb: array[nb,nb] of Real

+nu: Integer

+nb: Integer

FormSize

+nu: Integer

+nb: Integer

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

96

Page 113: levon-titelsid - DiVA portal

5.2 The PDE Library

r e p l a c e a b l e package f i e l d P = F i e l d ;r e p l a c e a b l e package ddomainP = Discre teDom ain ;

r e p l a c e a b l e record Dataparameter ddomainP . Data ddomain ;parameter f i e l d P . Data f i e l d ;parameter FEMSolver . FormSize f o r m s i z e ;parameter I n t e g e r u _ i n d i c e s [ f o r m s i z e . nu ] ;parameter I n t e g e r b _ i n d i c e s [ f o r m s i z e . nb ] ;f i e l d P . F i e l d T y p e v a l _ u [ f o r m s i z e . nu ] ( s t a r t = z e r o s ( f o r m s i z e . nu ) ) ;f i e l d P . F i e l d T y p e v a l _ b [ f o r m s i z e . nb ] ( s t a r t = z e r o s ( f o r m s i z e . nb ) ) ;

end Data ;

end D i s c r e t e F i e l d ;

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 theunknown and blocked value arrays are not known before the mesh is generatedand the final model is instantiated with given boundary conditions. This is becausethe type of the boundary conditions affect the number of unknowns in the field.For example, Dirichlet conditions result in known values on the boundary, whilefor Neumann boundary conditions the boundary nodes have unknown values. Adiscrete 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. Themesh data structure is defined separately and instantiated here. The mesh is gener-ated from a discrete boundary representation, which is an array of points sampledon the parametric curve defined as the boundary of the continuous domain. Thenumber of sample points is a parameter to the Data record, where also the refineparameter 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 theData.mesh data structure. The boundary condition indices are passed to the meshdata 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 inand stored as parameters in Modelica records accessible to models. The meshgeneration module is called and the result is read using external functions definedin 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

Page 114: levon-titelsid - DiVA portal

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 inthe mesh generation interface. Although Modelica does not enforce a sequentialorder of declaration processing, the generation and reading of the mesh must bedone sequentially. The call order is enforced by dependency between parametersand parameter initialization expressions:

package Mesh " 2D s p a t i a l domain ". . .parameter I n t e g e r s t a t u s =

g e n e r a t e ( polygon , bcind , f i l e n a m e , r e f i n e ) ;

parameter I n t e g e r s [ 3 ] = g e t _ s ( f i l e n a m e , s t a t u s ) ;

parameter I n t e g e r nv= s [ 1 ] " Number o f v e r t i c e s " ;parameter I n t e g e r ne= s [ 2 ] " Number o f edges on boundary " ;parameter I n t e g e r n t = s [ 3 ] " Number o f t r i a n g l e s " ;parameter C o o r d i n a t e x [ nv , 3]= g e t _ v ( f i l e n a m e , nv )" C o o r d i n a t e s o f nodes ( 1 : 2 ) and i n d e x f o r boundary c o n d i t i o n ( 3 ) " ;parameter I n t e g e r edge [ ne , 3]= g e t _ e ( f i l e n a m e , ne )" Edges by node i n d i c e s ( 1 : 2 ) and i n d e x f o r boundary c o n d i t i o n ( 3 ) " ;parameter I n t e g e r t r i a n g l e [ nt , 4]= g e t _ t ( f i l e n a m e , n t )" T r i a n g l e s by node i n d i c e s ( 1 : 3 ) and sub−domain i n d e x ( 4 ) " ;. . .

end Mesh ;

The status parameter is a dummy to enforce dependency between the generatecall and the calls to retrieve the mesh. The generated mesh is stored in a file. Firstthe sizes are retrieved and then the vertices, edges and triangles are read.

The declaration of the external functions are straightforward. For example, thefunction MeshGeneration.generate2D is declared as follows:

f u n c t i o n genera te2 D " G e n e r a t e s 2D t r i a n g u l a r mesh "annotat ion ( I n c l u d e =" # i n c l u d e <bamg . h>" , L i b r a r y ="bamg " ) ;input Real xPolygon [ : , 2 ] ;input I n t e g e r bc [ s i z e ( xPolygon , 1 ) ] ;input S t r i n g o u t p u t f i l e ;input Real r e f i n e = 0 . 5 ;output I n t e g e r s t a t u s ;

e x t e r n a l "C" bamg_generate_mesh ( " bamgrun . b a t " , o u t p u t f i l e , s t a t u s ,xPolygon , s i z e ( xPolygon , 1 ) , s i z e ( xPolygon , 2 ) ,bc , s i z e ( bc , 1 ) , r e f i n e ) ;

end genera te2D ;

The annotations Include and Library are used for including the declarationof the external C functions and the library name for linking. These are tool specificextensions and not yet included in the Modelica specification, but supported byseveral tools, e.g. Dymola and OpenModelica.

98

Page 115: levon-titelsid - DiVA portal

5.3 PDEModelica Solver Environment

5.2.1.4 Interpolation

The Interpolation package contains functions to interpolate a continuousfield over a discrete domain in order to generate a discrete field defined over thatdiscrete domain. The purpose of the interpolation is to be able to use constant fieldsdefined in Modelica together with a discretized model. Two functions, inter-polate and interpolate_indirect are defined, the latter supporting indirectmeshes. The interpolation is simply sampling of the continuous field values at thecoordinates of the nodes in the mesh. The function interpolate_indirect isdefined as follows:

f u n c t i o n i n t e r p o l a t e _ i n d i r e c tinput d f i e l d P . ddomainP . Data ddomain ;input d f i e l d P . f i e l d P . Data f l d ;input I n t e g e r v e c S i z e ;input I n t e g e r i n d i c e s [ v e c S i z e ] ;output d f i e l d P . f i e l d P . F i e l d T y p e v a l [ v e c S i z e ] ;

p r o t e c t e dP o i n t x ;

a lgor i thmf o r i in 1 : s i z e ( va l , 1 ) loop

x := ddomain . mesh . x [ i n d i c e s [ i ] , 1 : 2 ] ;v a l [ i ] := d f i e l d P . f i e l d P . v a l u e ( x , f l d ) ;

end f o r ;end i n t e r p o l a t e _ i n d i r e c t ;

Here, fieldP is the package pointing to the continuous field definition, and valueis the fields continuous value function as defined in the field package. Thus, thefields 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 externaltools 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, sincetriangular mesh generation and integration over the triangular elements are neededto generate the space-discrete differential equations. A variety of tools exist formesh generation and the finite element method. Two such tools were used in thiswork, 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 dependencyby discretizing the differential equations with respect to space variables. Thus,partial derivatives and field variables are replaced with arrays of scalar variables

99

Page 116: levon-titelsid - DiVA portal

Chapter 5 Implementation

and a system of equations depending on the solution method. The work presentedin this thesis uses manual methods for the discretization, i.e., the developer of thePDE library also defines the discrete model using the solver framework. There isan ongoing effort to automate the discretization using both explicit finite differ-ence schemes [16] and implicit finite difference schemes [35], using Mathematicawith the MathModelica environment [36]. This effort also includes FEM baseddiscretization [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 discretizationof equations. It is straightforward to replace partial derivatives with differenceequations, leaving only ordinary derivatives without spatial dependency. However,finite difference methods are not as general as finite element methods regardingcomplex domains, because a rectangular grid is needed in order to represent thederivatives with differences.

5.3.1.2 Finite Element Discretization

The finite element method is more suitable in cases where the domain of a PDE isnot known in advance and a large variety of domains need to be supported, becausetriangulation of general domains is well developed. However, the discretizationof the equations is more involved, because symbolic processing and integration isneeded 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 andimplemented 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 theexisting, open-source PDE solvers, a version of the framework with an interface toexternal 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 bespecified using C++ objects. A PDE problem corresponding to the existing modelsin 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 differentcombination of boundary conditions. However, the implementation currently onlysupports the Poisson equation and the diffusion equation (time-dependent). Forother 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

Page 117: levon-titelsid - DiVA portal

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 staticallylinked to the specific Modelica simulation executable generated by the Modelicatool for a model. These functions are wrapper functions that execute the externalsolver 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 serverthat 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 packagerepresenting the domain, domainP, and a model called Equation containingthe model details and the spatially discrete equation. Currently, Poisson2D andDiffusion2D are implemented, which can be found in the FEMForms package.

The actual equations are written in space-discrete form, using matrices retrievedfrom the external solver. For example, the diffusion equation contains the followingmatrices:

parameter Real mass_uu [ f o r m s i z e . nu , f o r m s i z e . nu ] =getForm_mass_uu ( . . . ) ;

parameter Real mass_ub [ f o r m s i z e . nu , f o r m s i z e . nb ] =getForm_mass_ub ( . . . ) ;

parameter Real b v a l s [ f o r m s i z e . nb ] = g e t B l o c k e d V a l u e s ( . . . ) ;parameter Real massb_u [ f o r m s i z e . nu ] = getMassBdr_u ( . . . ) ;parameter Real l a p l a c e _ u u [ f o r m s i z e . nu , f o r m s i z e . nu ] =

ge tForm _gradgrad_ uu ( . . . ) ;parameter Real l a p l a c e _ u b [ f o r m s i z e . nu , f o r m s i z e . nb ] =

ge tForm _gradgrad_ ub ( . . . ) ;

used in the following equation:

equat ionmass_uu * der ( fd . v a l _ u ) = − l a p l a c e _ u u * fd . v a l _ u − l a p l a c e _ u b * fd . v a l _ b

+ mass_uu * g _ r h s . v a l _ u + mass_ub * g _ r h s . v a l _ 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 buttime-dependent value, which cannot be declared as a parameter:

101

Page 118: levon-titelsid - DiVA portal

Chapter 5 Implementation

f o r i in 1 : f o r m s i z e . nb loopi f ( bc [ i n t e g e r ( f i x e d _ x [ b _ i n d i c e s [ i ] , 3 ] ) , BCTYPE] ==

BoundaryCondi t i on . t i m e d e p d i r i c h l e t ) thenfd . v a l _ b [ i ] = timeDepBndValue ;

e l s efd . v a l _ b [ i ] = bc [ i n t e g e r ( f i x e d _ x [ b _ i n d i c e s [ i ] , 3 ] ) , BCGVAL ] ;

end i f ;end f o r ;

The variable timeDepBndValue can for example represent the temperature of aheater, dynamically controlled by a feedback controller connected to a sensor, asdescribed 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 allinformation 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. Separatecalls are needed to retrieve each block due to the parameter initialization syntax inModelica. The getForm-functions are declared as external functions in the FEM-Forms.FEMSolver package. For example, the following common function isused to retrieve the mass matrix:

w i t h i n FEMForms . FEMSolver ;f u n c t i o n g e t F o r m _ m a s s _ i n t e r n a l

annotat ion ( I n c l u d e =" # i n c l u d e < p o i s s o n _ r h e o l e f . h>" ,L i b r a r y =" p o i s s o n _ r h e o l e f " ) ;

input S t r i n g meshf i l ename ;input I n t e g e r meshnv ; / / number o f v e r t i c e sinput I n t e g e r nu ; / / number o f unknownsinput I n t e g e r nb ; / / number o f knownsinput I n t e g e r nbc ; / / number o f boundary c o n d i t i o n sinput BCType bc [ nbc ] ; / / boundary c o n d i t i o n soutput Real auu [ nu , nu ] ; / / uu b l o c koutput Real aub [ nu , nb ] ; / / ub−b l o c koutput Real abu [ nb , nu ] ; / / bu−b l o c koutput Real abb [ nb , nb ] ; / / bb−b l o c ke x t e r n a l "C" g e t _ r h e o l e f _ f o r m _ m a s s ( m eshf i l enam e , meshnv ,

nu , nb , auu , aub , abu , abb ,s i z e ( bc , 1 ) , s i z e ( bc , 2 ) , bc ) ;

end g e t F o r m _ m a s s _ i n t e r n a l ;

The other functions in the FEMSolver package are the following:

package FEMSolverf u n c t i o n ge tForm Size . . .f u n c t i o n ge tForm _gra d gr a d . . .f u n c t i o n ge tUnknownInd ices . . .f u n c t i o n g e t F o r m _ g r a d g r a d _ i n t e r n a l . . .f u n c t i o n ge tForm _gradgrad_u u . . .f u n c t i o n g e t F o r m S i z e _ i n t e r n a l . . .f u n c t i o n g e t B l o c k e d I n d i c e s . . .f u n c t i o n g e t F o r m _ m a s s _ i n t e r n a l . . .

102

Page 119: levon-titelsid - DiVA portal

5.3 PDEModelica Solver Environment

f u n c t i o n getForm_mass . . .f u n c t i o n getForm_mass_uu . . .f u n c t i o n getForm_mass_ub . . .f u n c t i o n ge tForm _gradgrad_u b . . .f u n c t i o n g e t B l o c k e d V a l u e s . . .f u n c t i o n getForm . . .f u n c t i o n g e t F o r m _ i n t e r n a l . . .f u n c t i o n getMassBdr_u . . .

end FEMSolver ;

package D i f f u s i o n 2 D. . .model E q u a t i o n. . .

package u F i e l d P = F i e l d ( r e d e c l a r e package domainP = domainP ) ;parameter u F i e l d P . Data u F i e l d ( domain=domain ) ;

/ / d i s c r e t e p a r tpackage ddomainP = Discre teDom ain ( r e d e c l a r e

package domainP = domainP ) ;parameter ddomainP . Data ddomain ( domain=domain ,

nbp=nbp ,r e f i n e = r e f i n e ) ;

parameter Real f i x e d _ x [ ddomain . mesh . nv , 3 ] =f ixBlockedE dgeE nds ( ddomain . mesh . x , . . . ) ;

equat ion/ / c * l a p l a c e => assume c i s c o n s t a n t ( n o t space d e p e n d e n t )da * mass_uu * der ( fd . v a l _ u ) = − c * l a p l a c e _ u u * fd . v a l _ u

− c * l a p l a c e _ u b * fd . v a l _ b+ mass_uu* g _ r h s . v a l _ u+ mass_ub* g _ r h s . v a l _ b + massb_u ;

/ / f d . v a l _ b = b v a l s ;f o r i in 1 : f o r m s i z e . nb loop

/ / i f b c t y p e == t i m e d e p d i r i c h l e ti f ( bc [ i n t e g e r ( f ixedm eshx [ b _ i n d i c e s [ i ] , 3 ] ) , BCTYPE] ==

BoundaryCondi t i on . t i m e d e p d i r i c h l e t ) thenfd . v a l _ b [ i ] = timeDepBndValue ;

e l s efd . v a l _ b [ i ] = bc [ i n t e g e r ( f ixedm eshx [ b _ i n d i c e s [ i ] , 3 ] ) ,

BCGVAL ] ;end i f ;

end f o r ;end E q u a t i o n ;

end D i f f u s i o n 2 D ;

103

Page 120: levon-titelsid - DiVA portal

Chapter 5 Implementation

5.3.1.5 Solver Executable

The solver executable uses command line arguments for different requests. ThePDE problem is represented using a C++ struct. Each of the different functions han-dling the requests instantiates the problem and returns some specific informationto the caller. The main function in the executable calls these functions and writesthe result in a text file, to be read by the external function wrappers in the Modelicalibrary. Text files are used in order to simplify debugging and verification. Thesefiles 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 separatelibrary, used by both binaries.

104

Page 121: levon-titelsid - DiVA portal

Chapter 6

Examples

“In this house, we obey thelaws of thermodynamics!”

Homer Simpson

This chapter shows some PDE application examples that can be modeled andsimulated 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 structureas the Poisson equation:

−∇ · (k∇T ) = Q

where k is the thermal conductivity of the material, T is the temperature and Q isthe source term, i.e. generated heat inside the material, if any. This corresponds toEquation 3.1 with c = k and g = Q.

The example shown in Section 3.9 was simulated on a rectangular domain withone 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 Dirichletboundary 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 domainin both cases can be seen in Figure 6.3.

105

Page 122: levon-titelsid - DiVA portal

Chapter 6 Examples

The boundary conditions used here are not realistic because of the discrete jumpthe temperature does at the connection between the two Dirichlet conditions withdifferent 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 endpoints of the curved boundary section in Figure 6.2.

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

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

106

Page 123: levon-titelsid - DiVA portal

6.1 Stationary Heat Transfer

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

1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 61

1.5

2

2.5

3

3.5

4

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

∂nT = g on ∂Ω

Perfect insulation is specified with g = 0. Other values for g sets a constant valuefor the outward normal derivative for T on the boundary.

For non-perfect insulation, Robin (mixed) boundary conditions can be used:

∂nT + qT = g on ∂Ω

The corresponding boundary condition for heat transfer problems can be formu-lated using Newton’s law of cooling:

∂nT = gh + h(Tinf − T ) on ∂Ω

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 thegeneral 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 transfercoefficient can be used [38]:

h = kg/lg

107

Page 124: levon-titelsid - DiVA portal

Chapter 6 Examples

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

kg = 54 J/m · min · Klg = 3 · 10−3 mk = 4.92 · 10 3 J/m · min · Kgh = 0Tinf = 5 C

Note that the parameters for thermal conductivity are adjusted to give results perminute. 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 statemodel 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 boundaryand 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 thecorner of the glass layer that is close to the heater.

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

6.2 Time-dependent Heat Transfer

In order to study transient processes and controlled heating, the time-dependentheat transfer equation can be studied. The equation is

ρC∂u

∂t−∇ · (k∇u) = Q

108

Page 125: levon-titelsid - DiVA portal

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 denotesthe heat capacity of the material and k is the thermal conductivity as in the steadystate 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 examplewere used, with the following additions for the time dependency:

ρ = 7.821 · 103 kg/m3

C = 449 J/kg · KA proportional, integrating controller (PI-controller) was used to control the tem-

perature. The controller contains an ordinary differential equation:

Terror = Tsensor − Tgoal

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

Ki =k

T

109

Page 126: levon-titelsid - DiVA portal

Chapter 6 Examples

which gives

Theater(t) = kTerror +k

T

∫Terror dt

After some experiments, the values k = 1 and T = 200 were found to workwell for the PI-regulator. Plots of the simulation results at different time points areshown in Figure 6.6.

6.3 Discussion

The examples show that object-oriented, component based models containing PDEsand combined ODE and PDE models is possible to specify and simulate usingour approach. However, more work is needed to implement connections betweenODE-based models and PDE-based models. For example, the integral operatorshould be possible to use to connect a boundary to a scalar variable. In our currentimplementation, only existing discrete points in the domain is possible to use asconnection points to other scalar variables, e.g., a solution point in the domain isused as the sensor value and connected to the temperature controller, which is alimitation.

110

Page 127: levon-titelsid - DiVA portal

6.3 Discussion

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

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

0.5 1 1.5 2 2.5 3 3.5 4 4.5 50

10

20

30

40

50

60

70

80

time

tem

pera

ture

heatervaluesensorvaluegoalvalue

(e) Time plots of heater and sensor values

Figure 6.6: Results from simulation of example in Section 1.1.1 using the ModelicaPDE library.

111

Page 128: levon-titelsid - DiVA portal

Chapter 6 Examples

112

Page 129: levon-titelsid - DiVA portal

Chapter 7

Previous Approaches WithExamples

“Science may be described as the artof systematic oversimplification.”

Karl Popper

This chapter describes the early iterations of this research work on designing,implementing, and evaluating object-oriented modeling language extensions andmethods 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 whichis the result of previous design iterations.

7.1 Mathematica-based Translator

The idea with this approach is to utilize the Mathematica environment to specifypartial 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. calledspace was used to declare spatial coordinates. This is similar to the new prefixfield, but these variables are just used for declaring spatial coordinate names.This is a rather unnecessary extension, because the same result can be obtainedby using the parameter prefix, which also specifies that a variable is not timedependent.

113

Page 130: levon-titelsid - DiVA portal

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, infinitedomains. Also, using equations, boundaries can be defined, because an equationrestricting the value of a coordinate decreases the degrees of freedom, hence thedimension, 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 maybe somewhat limited. Modern tools usually contain graphical user interfaces fordefining domains, which can be difficult to use to define constraints mathemati-cally.

Another drawback is that symbolic processing and equation solving is needed.This is reasonable to implement in a symbolic environment like Mathematica, butthis creates a dependency to a third-party commercial tool. The prototype solverthat 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 C a r t e s i a n 2 D

space Real x , y ;end C a r t e s i a n 2 D ;

domain C i r c l e B a s eextends C a r t e s i a n 2 Dparameter Real r =1 ;parameter Real xc =0 , yc =0;

end C i r c l e B a s e ;

domain C i r c l eextends C i r c l e B a s ec o n s t r a i n t

x==xc−s q r t ( r ^2−(y−yc ) ^ 2 ) orx==xc+ s q r t ( r ^2−(y−yc ) ^ 2 ) ;

end C i r c l e ;

domain C i r c u l a r extends C i r c l e B a s eC i r c l e boundary ( xc=xc , yc=yc , r = r ) ;c o n s t r a i n t

xc−s q r t ( r ^2−(y−yc ) ^ 2 ) <= x<= xc+ s q r t ( r ^2−(y−yc ) ^ 2 ) and

yc−r <= y <= yc+ r ;end C i r c u l a r ;

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

Page 131: levon-titelsid - DiVA portal

7.1 Mathematica-based Translator

boundary conditions during the solver generation. The Circular domain is theactual domain, i.e., the interior of the boundary. A drawback that can be seen hereis that the boundary constraints needed to be repeated with inequalities instead ofequalities.

Domains for equations were defined in a syntax similar to the current design:

f ( x , y )= s i n ( x )+ cos ( y ) where ( x , y ) in omg ;

The need for space variables and their local declaration as shown here is avoidedby the introduction of field variables. Otherwise, the in construct and the domainreference are also present in the current design. A similar syntax was used in fieldconstructors.

The equation and the boundary conditions were defined in the model as follows:

model MyPDEModelspace Real x , y ;C i r c u l a r c i r c d o m a i n ;Rea l U( x , y , t ) ;boundary

U( x , y , t )=0 where ( x , y ) in c i r c d o m a i n . boundary ;equat ion

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 c i r c d o m a i n ;

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 differentialequation formulation of a PDE. Hence, no manual conversion to variational form isnecessary, 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 elementsolver for the specific domain. The resulting equation system can be solved byMathematica’s built-in linear solver or an external solver such as SuperLU.

Both finite difference method [16, 39] implementations and a finite elementmethod implementation exist, as well as a method of lines implementation usingfinite differences. However, the approach with constraints for defining domainsand boundaries is only supported with the finite difference solver generator. Thefinite difference solver and the method of lines solver are used with a translatorimplemented in MathModelica [40, 41].

115

Page 132: levon-titelsid - DiVA portal

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 solverenvironment 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 theequations and their structure is assumed. A specific solver written for a specificequation 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. Despitethe powerful concepts the Modelica language is based on, the language itself isonly used for defining parameters for predefined PDEs. The domain and boundarydesign is somewhat more integrated. However, the current approach requires fewermodifications 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 isintroduced. The design is based on the current approach with parametric curvesbut with a different syntax. One syntax that was considered is to declare spacevariables and define the expressions for the mapping in an algorithm section:

domain C a r t e s i a n 2 D " Base c l a s s f o r two d i m e n s i o n a l domains "space Real x , y ;

end C a r t e s i a n 2 D ;

domain Circ le2D " C i r c u l a r domain w i t h r=1"extends C a r t e s i a n 2 D ;

a lgor i thm( x , y ) := ( cos (2* PI *u ) , s i n (2* PI *u ) ) where u in ( 0 , 1 ) ;

end Circ le2D ;

A special composite() operator was needed to set up composite boundariesconsisting of several simple boundary components:

domain Line2D "A l i n e segment "extends C a r t e s i a n 2 D ;parameter Real x0 =0 , y0 =0 , x1 =1 , y1 =1;

a lgor i thm( x , y ) := ( x0+ r *( x1−x0 ) , y0+ r *( y1−y0 ) ) where r in ( 0 , 1 ) ;

end Line2D ;

domain Rectang le2D "A 6 by 4 r e c t a n g l e "extends C a r t e s i a n 2 D ;parameter Real cx =0 , cy =0 , w=3 , h =2 ;Line2D r i g h t ( x0=cx+w, y0=cy−h , x1=cx+w , y1=cy+h ) ;Line2D t o p ( x0=cx+w, y0=cy+h , x1=cx−w, y1=cy+h ) ;

116

Page 133: levon-titelsid - DiVA portal

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 ) ;

a lgor i thm( x , y ) := c o m p o s i t e ( r i g h t , top , l e f t , bot tom ) ;

end Rectang le2D ;

However, this approach differed too much from the current Modelica language,i.e., required several unnecessary additions to the language. Another drawback isthat the semantics of this design was not cleared out completely and is sometimes abit 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. Thisway, the extensions were consistent with each other. The introduced operator todefine curves was called curve(), and could be used as follows:

domain C a r t e s i a n 2 D " For a l l 2D−domains "space Real x , y ;

end C a r t e s i a n 2 D ;

domain Circ le2D " C i r c u l a r w i t h r=1"extends C a r t e s i a n 2 D ;

boundaryc u r v e ( cos (2* PI *u ) ,

s i n (2* PI *u ) ) where u in ( 0 , 1 ) ;end Circ le2D ;

Because lines are used very commonly when defining domains, a special operatorcalled lines() was introduced as well, to declare a list of connected lines´:

domain Line2D "A l i n e segment "extends C a r t e s i a n 2 D ;parameter Real x0 =0 , y0 =0 , x1 =1 , y1 =1;

boundaryl i n e s ( 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. Thesemodels can be used with new parameter values that are extracted by the translatorand passed to the solver specifically implemented for that built-in model. The com-mon types of boundary conditions were defined similarly and assigned to particularboundaries using special built-in components in the domain restricted class:

model PDEModelNeumann h _ i s o ;D i r i c h l e t h _ h e a t e d ( g = 5 0 ) ;

117

Page 134: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

HeatRobin h _ g l a s s ( hh =30000) ;H e a t T r a n s f e r h t ;Rec tang le2D dom ( eq= ht ,

l e f t ( bc = h _ g l a s s ) ,r i g h t ( bc = h _ h e a t e d ) ,t o p ( bc = h _ i s o ) ,bot tom ( bc = h _ i s o ) ) ;

end PDEModel ;

Here, also the eq built-in component is used to assign a PDE to the interior of theboundary. This approach is simple to understand and use, and PDE models withdifferent 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 ispoorly integrated with the language.

7.2.3 Implementation Details

This section describes the implementation of the coefficient-based translator forfuture reference. Parts of the implementation is general and can be used in futureprototypes, 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 PDEextensions. New keywords and operators are summarized in Table 7.1. The newrestricted class domain is used to describe domain geometry, with a new sectioncalled boundary. The boundary section is described by the rules shown inFigure 7.1.

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

Keyword Description

space Space variables for coordinatesdomain New restricted class domainboundary New section in classes for domain

geometry definitioncurve(), line(), composite() Boundary geometry description

operatorseq, bc Predefined variables in domain

classes

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

118

Page 135: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

boundary: (

| l i n e _ c l a u s e| c u r v e _ c l a u s e| c o m p o s i t e _ c l a u s e)comment !

;

l i n e _ c l a u s e :LINE^ LPAR! e : e x p r e s s i o n RPAR!

;

c u r v e _ c l a u s e :CURVE^ LPAR! e : e x p r e s s i o n _ l i s t RPAR!

;

c o m p o s i t e _ c l a u s e :COMPOSITE^ LPAR! e l : c o m p o n e n t _ r e f e r e n c e _ l i s t 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.3shows the abstract syntax tree resulting from the domain example in Figure 7.2.

domain TestDomainspace Real x , y ;parameter Real PI = 3 . 1 4 1 5 9 3 ;parameter Real u ;

boundaryc u r v e ( cos (2* PI *u ) , s i n (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 restrictedclasses and PDE parameters are described. These are additional data types in theRML representation of the abstract syntax tree, and rules for instantiation of do-mains and code generation for domains and PDE parameter initialization.

119

Page 136: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

ROOT

DOMAINTestDomain

PUBLIC BOUNDARY

ELEMENT ELEMENT ELEMENT

COMPONENTS

space RealCOMPONENT

xCOMPONENT

y

COMPONENTS

parameter RealCOMPONENT

PI

MODIFICATION = 3.141593

COMPONENTS

parameter RealCOMPONENT

u

CURVEcos(2*PI*u)sin(2*PI*u)

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. The ClassPart data type is modified to support a boundarynode with a list of boundary elements, where each element can be one of the threeboundary types, see Figure 7.4. In the current prototype, the representation is keptsimple, using the Exp data type for the LINES node, which corresponds to thelist of points written as a single expression using the array syntax. Similarly, theCURVE 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 theAbsyn module, but the ClassDef data type has been modified to also representdomain 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 storedin the DAE representation are defined in the Exp module, and contain the staticallyanalyzed expressions, as opposed to the Absyn.Exp data type which containsthe expressions before the analysis. The DAElist stored in the CURVE node isneeded during code generation to determine which component references in the

120

Page 137: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

datatype C l a s s P a r t = PUBLIC of Element l i s t| PROTECTED of Element l i s t| EQUATIONS of E q u a t i o n l i s t| ALGORITHMS of Algor i thm l i s t| BOUNDARY of Boundary l i s t

data type Boundary = LINES of Exp| CURVE of Exp l i s t| COMPOSITE of ComponentRef l i s t

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

datatype Clas sDef = PARTS of Element l i s t

* E q u a t i o n l i s t

* Algor i thm l i s t| DERIVED of Path

* Absyn . ArrayDim o p t i o n

* Mod| DOMAINPARTS of Element l i s t

* Boundary l i s t

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

121

Page 138: levon-titelsid - DiVA portal

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 DAE l is t = DAE of Element l i s t

data type Element = VAR of Exp . ComponentRef * VarKind *V a r D i r e c t i o n * Type * Exp . Exp o p t i o n

| DEFINE of Exp . ComponentRef * Exp . Exp| EQUATION of Exp . Exp * Exp . Exp| ALGORITHM of Algor i thm . Algor i thm| COMP of I d e n t * DAE l i s t| FUNCTION of Absyn . Pa th * DAE l i s t *

Types . Type| DOMAIN of Exp . ComponentRef * Boundary l i s t

data type Boundary = LINES of Exp . Exp * S t a t i c . P r o p e r t i e s| CURVE of Exp . Exp l i s t * DAE l is t| COMPOSITE of Exp . Exp l i s t

Figure 7.6: Additions in the DAEmodule for storing domain information. The onlyaddition in the Element data type is the DOMAIN node.

Translation

The SCode module contains the relations that convert the Absyn representationto 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 theclass being translated is a domain class. Conversion of the declaration part inelab_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 theSCode.DOMAINPARTS structure. The first part of this structure are the elementsfrom 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 thetype of the SCode.ClassDef node, one of PARTS, DERIVED or DOMAIN-PARTS. In the latter case, the rule for translating the domains is activated. Thedeclaration part is handled as for other classes. The boundary part is instantiatedusing the relation inst_boundary, see Figure 7.8. In this relation the threedifferent kinds of boundary descriptions POINTS, CURVE and COMPOSITE are

122

Page 139: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

r e l a t i o n e l a b b n d p a r t s : Absyn . Boundary l i s t => Boundary l i s t =

axiom e l a b b n d p a r t s ( [ ] ) => [ ]

r u l e e l a b b n d p a r t s ( r e s t ) => bnds &l e t bnds ’ = POINTS ( e ) : : bnds−−−−−−−−−−−−−−−−−−−−−−−−e l a b b n d p a r t s ( Absyn . POINTS ( e ) : : r e s t ) => bnds ’

r u l e e l a b b n d p a r t s ( r e s t ) => bnds &l e t bnds ’ = CURVE( e l i s t ) : : bnds−−−−−−−−−−−−−−−−−−−−−−−−e l a b b n d p a r t s ( Absyn .CURVE( e l i s t ) : : r e s t ) => bnds ’

r u l e e l a b b n d p a r t s ( r e s t ) => bnds &l e t bnds ’ = COMPOSITE ( e l i s t ) : : bnds−−−−−−−−−−−−−−−−−−−−−−−−e l a b b n d p a r t s ( Absyn . COMPOSITE ( e l i s t ) : : r e s t ) => bnds ’

end

Figure 7.7: The relation elab_boundary_parts (abbreviated to elabbndparts)in the SCode module that handles the boundary description parts fromthe Absyn module.

recognized and corresponding DAE nodes are generated. The common steps foreach kind is:

• static analysis: constant expression evaluation, type analysis and type anno-tation of expressions, variable references, etc. In the COMPOSITE case, onlyvariable references are checked, because that is the only kind of expressionallowed as argument to the composite() operator.

• prefixing expressions: adding the correct prefix to variable references in thecurrent instantiation environment. A reference to a variable v in a variablecomp in the class being instantiated is prefixed by comp. to build comp.v.

• state transition in class inference: modifying the state in the class inferencemodule ClassInf which keeps track of the class state in order to check ifthe class contents is consistent with the restricted class type. In this case thetransition to FOUND_BOUNDARY has been added.

7.2.3.3 Code Generation

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

123

Page 140: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

r e l a t i o n i n s t _ b n d : ( Env , Mod , P r e f i x , Connect . Se t s ,C l a s s I n f . S t a t e , SCode . Boundary , DAE. DAE l i s t )

=> (DAE. Boundary l i s t , Env , Connect . Se t s , C l a s s I n f . S t a t e ) =

r u l e S t a t i c . e l a b _ e x p ( env , e ) => ( e ’ , p rop ) &P r e f i x C o d e . p r e f i x _ e x p ( env , e ’ , p r e ) => 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 ’−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−i n s t _ b n d ( env , _ , pre , c s e t s , s t , SCode . POINTS ( e ) , dae )

=> ( [DAE. POINTS ( e ’ ’ , p rop ) ] , env , c s e t s , s t ’ )

r u l e S t a t i c . e l a b _ e x p _ l i s t ( env , e l i s t ) => ( e l ’ , _ ) &P r e f i x C o d e . p r e f i x _ e x p _ l i s t ( env , e l ’ , p r e ) => 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 ’−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−i n s t _ b n d ( env , _ , pre , c s e t s , s t , SCode .CURVE( e l i s t ) , dae )

=> ( [DAE.CURVE( e l ’ ’ , dae ) ] , env , c s e t s , s t ’ )

r u l e S t a t i c . e l a b _ c r e f _ l i s t ( env , c r l s t ) => ( e l ’ , _ , _ ) &c a n o n _ c r e f _ l i s t ( env , e l ’ ) => e l ’ ’ &P r e f i x C o d e . p r e f i x _ e x p _ l i s t ( env , e l ’ ’ , p r e ) => 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 ’−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−i n s t _ b n d ( env , _ , pre , c s e t s , s t , SCode . COMPOSITE ( c r l s t ) , 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 differentkinds of boundary elements, POINTS, CURVE and COMPOSITE andbuilds the corresponding DAE structures.

124

Page 141: levon-titelsid - DiVA portal

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. Thecode 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 generatedcode is incomplete, and is combined with prewritten C++ code.

Model Parameters

The model parameters declared in functions are collected and generated as recordfields in separate C++ structs, one for each function instance. The model parametersof the instantiated, complete model are generated as record fields in a struct thatcontains 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 initializationroutine, and another routine initializes the values of the model parameters. Thepointer 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 foreach function, containing the Modelica parameters of that function. A global structvariable is declared at the same time, with a name corresponding to the full nameof the function with dots replaced by underscores. Later, initialization code isgenerated 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 generatedas 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 ofthe struct is used as the type. If there is only one output variable, the type of thatvariable 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 theoutput variables. The return variable is declared at the beginning of the functionbody and if a struct is used, the output variables are appropriately prefixed with thename of the struct.

The function body is generated from the algorithm section of the correspondingModelica function which has a close correspondence to C++ code. Finally, the returnstatement is constructed.

125

Page 142: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

Function Instances

Code instances of parameterized functions are implemented using the replaceablefunction 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 boundarycondition class, and a unique C++ function is generated in each case. The generatedcode for each function instance is identical to that for the Modelica function classthat the function is an instance of, except that the parameter references are replacedwith references to a separate parameter struct.

Domains

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

DiscreteCurve2D-points: point_vector+add(point:Point2D)

Object-name: string

Object2D

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

Curve2D

+func(u:Real): Point2D

Composite2D-curves: curvep_vector+add(in curve:Object2D)

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

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

126

Page 143: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

calculates the coordinates of a point on the curve for a given parameter value. Forexample, the boundary description:

c u r v e ( cos (2* PI *u ) , s i n (2* PI *u ) , u ) ;

is translated into a C++ function with the structure shown in Figure 7.10.

Point2D func ( Rea l u ) Point2D r e s ;r e s . x = cos (2* PI *u ) ;r e s . y = s i n (2* PI *u ) ;return r e s ;

Figure 7.10: Function generated for the boundary described ascurve(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 discretepoints on the curve.

c l a s s Curve2D : p u b l i c Object2D p u b l i c :

Curve2D ( s t r i n g name= s t r i n g ( " Curve2DObject " ) ): Object2D ( name )

v i r t u a l Point2D func ( Rea l u ) = 0 ;v i r t u a l p o i n t _ v e c t o r * g e t P o i n t s ( i n t n ) ;

;

Figure 7.11: The Curve2D class that represents parametric curves. Each specificboundary 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 descriptionis 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 fromthe getPoints() method, ignoring the desired maximum number of points, forsimplicity. Hence, it is assumed that the number of points given in the lines

127

Page 144: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

operator is always less than the required number of discretization points on theboundary. If this does not hold, the result will be a finer discretization than what isdesired.

c l a s s Discre teCurv e2 D : p u b l i c Object2D p o i n t _ v e c t o r p o i n t s ;

p u b l i c :D isc re teCurv e 2D ( s t r i n g name= s t r i n g ( " Discre teCurve2D " ) )

: Object2D ( name ) void add ( c o n s t Point2D& p ) ;void add ( c o n s t Point2D * p , i n t n ) ;v i r t u a l p o i n t _ v e c t o r * g e t P o i n t s ( i n t n ) ;

;

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

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

Boundary Conditions

Boundary conditions are represented by the BoundaryConditionC++ class, seeFigure 7.14. The same class can be used for the three different kinds of boundaryconditions: Dirichlet, Robin, and Neumann conditions. The names of the boundarycondition objects are mapped from their names in the Modelica domain description.The mesh generator and the PDE solver supports named boundary segments. Thecode generation consists of instantiating the boundary condition objects and puttingthem in a list to be passed to the solver.

128

Page 145: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

c l a s s Composite2D : p u b l i c Object2D c u r v e p _ v e c t o r c u r v e s ;

p u b l i c :Composite2D ( s t r i n g name= s t r i n g ( " Composite2D " ) )

: Object2D ( name ) v i r t u a l p o i n t _ v e c t o r * g e t P o i n t s ( i n t n ) ;c u r v e p _ v e c t o r * g e t C u r v e s ( ) ;void add ( Object2D * c ) ;void add ( Object2D ** c , i n t n ) ;v i r t u a l boo l i s C o m p o s i t e ( )

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 goesthrough any constituent composite curves, returning only a flat list ofnon-composite curve segments.

c l a s s BoundaryCond i t i o n

p u b l i c :s p a c e _ f u n c t i o n * g ;F l o a t q ;bool i s _ d i r i c h l e t ;s t r i n g name ;

p u b l i c :t y p e d e f F l o a t s p a c e _ f u n c t i o n ( c o n s t p o i n t& p ) ;

BoundaryCondi t i on ( ) ; ;

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

129

Page 146: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

Parser

Discretizer Translator

Mesh generator

Solver

PDE-Modelica

boundary condition parametersequation parameters

mesh

domain

PDE-ModeqUser input

External software

discrete domain boundary

Figure 7.15: Solution method using an external PDE solver or a pre-generatedsolver. This method is used with Rheolef and FEMLAB.

130

Page 147: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

PDE-Modelica

Discretizer

Parser

Translator

parametersboundary conditionsequations

Solver generatorMesh generator

Solver

domain

User input PDE-Modeq

mesh

MathematicaExternal software

discrete domain boundary

Parameter valuesNew parameter values

Figure 7.16: Solution method with dynamic solver generation. This method is usedwith the MathFEM solver.

131

Page 148: levon-titelsid - DiVA portal

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 usinga linear equation 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 inFigure 7.17.

MeshGenerator

+generate(domain:Object2D)

BamgMeshGenerator GeoMeshGenerator EasymeshMeshGenerator

DiscreteDomain2D

+discretize(curve:Object2D)

+optimize()

+getPoints()

+getSegments()

+getSubnames()

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 thecase with a parametric curve description, this involves sampling a given numberof points on the boundary and creating a polygon with these points as the cornersof the polygon, in practice approximating the curve with linear segments. The dis-cretization is performed by calling the getPoints() method of the Object2Dinterface. The discretizer also keeps track of the boundary section names in orderto pass the information to the PDE solver for the boundary conditions to be appliedappropriately.

This discretization is done because most mesh generators support the boundaryrepresentation based on corner points and linear segments. In the future, splinesand other higher-order representations may be supported.

132

Page 149: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

7.2.4.2 Mesh Generator

The mesh generator interface consists of a function generate() which takesan Object2D object. The mesh generator classes use the DiscreteDomain2Dclass to generate the polygonal approximation of the boundary from the Object2Dobject. The DiscreteDomain2D class traverses the boundary description ob-jects that can be a hierarchy of composite boundary objects and connected linesand 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 theoutput 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 converta Bamg mesh into the Geo 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 BoundaryConditionobjects and a list of DomainRegion objects. BoundaryCondition objectsare named and contain the parameters of the boundary conditions for the boundarysections with matching names. The DomainRegion objects represent differentregions in the domain that have different PDE coefficients. Only some of the co-efficients can be different in different regions though, depending on which solverthat 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 fordifferent predefined PDEs can be used. In this work Rheolef and FEMLAB areused to solve equations of the form −∇ · (c∇u) = f .

Rheolef [18, 21] is a publicly available package for solving PDEs using finiteelement methods. Besides some supporting Unix commands, it contains a set ofC++ classes to handle domains, domain boundaries, fields and other PDE relatedobjects. The problem is formulated in variational form by writing a C++ routine thatis 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 ofthe 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

Page 150: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

boundary conditions, as long as the supported kinds of boundary conditions areused. Currently, it handles the three kinds of boundary conditions that are used inthe prototype: Dirichlet, Neumann, and Robin conditions. The list of boundarycondition objects are passed to the solver which generates the correct problem for-mulation and further calls the Rheolef equation solver. Rheolef supports meshesgenerated 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 whichis 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 usedand coefficient assignments are generated into a Matlab script file. Mesh gener-ation is handled internally by FEMLAB, but the discrete domain description istransfered 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 theboundary 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 theMatlab script file. The script can then be executed and FEMLAB’s post-processingtools 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 yetsupported. 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 iscompiled to C++ using MathCode.

There is also ongoing work on a solver in Mathematica based on the method oflines using finite elements. Here, space discretization is performed by the solverwhich only generates time dependent ordinary differential equations. StandardModelica code can be generated from this solver that can be solved further us-ing existing Modelica environments, for example the modeling and simulation toolDymola [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

Page 151: levon-titelsid - DiVA portal

7.2 Coefficient-Based Translator

perspective for certain domain geometries, it is not well integrated in the languageand not general enough. Too many assumptions need to be made about the formatin 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 thecomposite() operator automatically becomes a two-dimensional domain.To assure a correct domain, open composite boundaries are automaticallyclosed, 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 definea possibly non-closed boundary segment consisting of several parts.

135

Page 152: levon-titelsid - DiVA portal

Chapter 7 Previous Approaches With Examples

136

Page 153: levon-titelsid - DiVA portal

Chapter 8

Related Work

“I never learned from aman 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 problemformulation and the solution algorithm in an ordinary programming language suchas 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 userinterface, where the problem can be specified.

8.1 Libraries and ProgrammingLanguage-Based Packages

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

137

Page 154: levon-titelsid - DiVA portal

Chapter 8 Related Work

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

8.1.1 Diffpack

Diffpack [46] is a C++ library package with data structures and numerical methodsthat can be used to solve PDE problems. The package is divided into a kernel andapplication-specific toolboxes for use in different engineering areas. Diffpack in-cludes support for solving sparse linear systems using iterative methods and solvingnon-linear systems, using finite element and finite difference methods with a col-lection of finite elements and finite difference schemes, adaptive meshes, domaindecomposition methods and multi-grid methods. The package also includes sup-port for administrative tasks, such as report generation, simulation result handlingand 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 neededin a PDE solver system. The framework also includes grid generators, solvers, andgraphical 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 domainscomposed of several domain components. In a composite domain, common gridpoints are generated for the overlapping parts of the domain components that com-prise the final domain. This method is also useful for moving overlapping gridswhere 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, theequation classes, domain classes, and other classes that represent the mathemati-cal model are separated from classes that handle discretization and solution of the

138

Page 155: levon-titelsid - DiVA portal

8.2 High-Level Packages and Problem Solving Environments

PDEs. Thus, compared to Overture, where the formulation of the mathematicalmodel and the numerical solution method are more tightly coupled, Compose hasa higher level of abstraction.

However, there is no automatic solver selection support in Compose in contrastto many problem solving environments. Equations and equation discretizers mustbe associated for an equation to be discretized appropriately. The framework isextensible, so that new types of equations and corresponding equation discretizerscan be added to the system.

8.2 High-Level Packages and Problem SolvingEnvironments

One of the first attempts to define a language for PDE problem formulation isPDEL [49]. In such high-level language based or graphical user interface basedPDE solving systems, the PDE and boundary conditions are specified directly, ei-ther in text form in a special purpose language or interactively in a specializededitor. The system automatically solves the PDE problem using a general solveror by selecting an appropriate solver from a set of existing solvers. The detailsabout the solution process can be hidden from the user, although it is still possibleto 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 simulationof dynamic chemical processes, with support for combined lumped and distributedmodels [50]. gPROMS uses a high-level language for modeling and simulation ofmixed systems of integral, partial, and ordinary differential, and algebraic equa-tions (IPDAEs) over rectangular domains.

MODEL T u b u l a r R e a c t o r

PARAMETERNbrComp AS INTEGER. . .Reac to rL ength , R e a c t o r R a d i u s AS REAL

DISTRIBUTION_DOMAINA x i a l AS ( 0 : R e a c t o r L e n g t h )R a d i a l AS ( 0 : R e a c t o r R a d i u s )

Figure 8.1: Example of a model definition in gPROMS.

139

Page 156: levon-titelsid - DiVA portal

Chapter 8 Related Work

A model definition in the gPROMS language is depicted in Figure 8.1. Axial andRadial in the model are the independent variables.

A dependent variable that is to be solved over this domain is declared as fol-lows:

VARIABLETemp AS DISTRIBUTION ( Axial , R a d i a l ) OF T em pera tu re

Here, Temp is of type Temperature that is defined elsewhere, and its geometricdomain is the three-dimensional area defined by the independent variables Axialand Radial and their limits as defined in Figure 8.1. This declaration is similarto declaration of arrays in the gPROMS language, which is done using the arraykeyword:

F AS ARRAY ( NbrComp ) OF F l o w r a t e

For partial differentiation the partial operator is used. partial(expr,var) is the partial derivative of the expression expr with respect to the variablevar (e.g., ∂rTemp(z, R) with expr=Temp(z, R) and var=r), i.e., the partialoperator 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 boundarycondition 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 andReactorLength.

FOR z := 0 TO R e a c t o r L e n g t h DO− Kr * PARTIAL( Temp ( z , R e a c t o r R a d i u s ) , R a d i a l ) =Uh * ( Temp ( z , R e a c t o r R a d i u s ) − TWall ( z ) ) ;

END

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

8.2.2 PELLPACK

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

140

Page 157: levon-titelsid - DiVA portal

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. Theequation section contains the PDE written in mathematical form. The bound-ary section defines the geometry by defining the domain boundary. The boundaryconditions are also written in the boundary section together with the domainboundary descriptions. Other sections are grid, discretization, solu-tion and output which specify the modules to use in different stages of thesolution process.

The ELLPACK language also supports embedded Fortran code in fortransections. The PELLPACK language additionally has the mesh section to supportthe finite-element method, and sections for domain decomposition to support paral-lel solutions. The language is also extended to contain information produced fromthe graphical user interface that needs to be preserved.

In the ELLPACK language, there are predefined names for the solution variableand its derivatives, such as U, UX (∂xU ), UYY (∂yyU ) and the spatial variables X, Yand 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 boundarysection specifies the condition that the function is zero on a circle with radius 1 andcenter (1, 1). The boundary 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 insequential order.

BOUNDARY. U = 0 . 0 ON X = 1 . − COS( PI *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 solutionprocess, such as domain discretization modules and PDE solver libraries. Thereare several integrated libraries that are ready to use in the system. It is also possibleto integrate new libraries by writing the appropriate interfaces on different levelsof the software architecture.

141

Page 158: levon-titelsid - DiVA portal

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 andsolution. 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 ofthe 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 theirequations. The definition of the domain object can be seen in Figure 8.5.

equat ion (name = " s t e a d y−s t a t e h e a t f l o w " ,domain = "dome " ,e x p r e s s i o n s = [ Dx( k ( x , y )* Tx ) + Dy( k ( x , y )* Ty ) = 0 ] ,p r o p e r t i e s = [ [ s e l f −a d j o i n t ] , [ s t e a d y−s t a t e ] ]

) ;

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

domain (name = "dome " ,type = piecewise_para me tr i c ,boundary = [

o r i e n t a t i o n = c lockwise ,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 expertsystem 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

Page 159: levon-titelsid - DiVA portal

8.3 Discussion

can be solved, as well as scalar PDEs and systems of PDEs. An environment witha graphical user interface as well as the Matlab command line interface is used forproblem specification, solution, and visualization.

FEMLAB provides different modes, each with several built-in models. In thePDE Mode, the coefficients of a predefined PDE are specified in coefficient form.In general mode, general expressions are given, suited for non-linear problems. Inthe 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 tochoose 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-intwo- or three-dimensional geometry editor with predefined geometric objects thatcan 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 finiteelement 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 PDEsinto 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 knowledgeand some programming language skills. Also, a varying degree of manual work onthe solution must be done before the actual implementation. On the other hand, anefficient solver can be obtained for a specific problem.

The second category contains tools that do not require numerical knowledge tothe same extent, and the details of the solution process are hidden. This is trueespecially for the problem solving environments, and in particular FEMLAB. InFEMLAB, existing models can be used directly, with some modification of theparameters and new models can be defined using the graphical user interface. Al-though, there is not really any language support, merely a MATLAB interface formanipulating 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 formalmodeling language and supports hierarchical modeling, domain description, etc.,but only rectangular domains are supported.

143

Page 160: levon-titelsid - DiVA portal

Chapter 8 Related Work

PDEModelica belongs to the second category, being a high-level language, andaims to hide numerical solution details from the high level model specified by theuser. The closest tool to PDEModelica is gPROMS which only supports rectangu-lar domains, whereas PDEModelica supports general domains. PDEModelica hasalso a more clear concept of fields, separated from arrays. Separate, component-based description of the domain geometry and possibility to reuse domains withdifferent models is also an addition compared to gPROMS. Furthermore, PDEMod-elica has a more readable, mathematical syntax for explicit domain specification inequations. 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 PDEModelicahas additional object-orientation support, like inheritance, as well as support for ageneral connection concept and modern and more intuitive syntax.

144

Page 161: levon-titelsid - DiVA portal

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, whichalready supports ODE models and has object-oriented constructs for hierarchicaland component-based modeling, has been used as the basis for such a language,and possible language extensions have been considered to add support for PDEmodels in Modelica. The necessary additions for supporting PDEs that have beendesigned 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 thegeometrical region where the dependent variable is defined. Continuous rep-resentation is used and general one, two and three dimensional domains arepossible to define using the shown design.

• Fields. Continuous representation of a dependent variable over a continuousdefinition domain. Arrays of fields are possible to declare using the same

145

Page 162: levon-titelsid - DiVA portal

Chapter 9 Conclusion

syntax as arrays of scalar variables. Field constructors can be used as literalto define constant fields which can be used directly in expressions. Fieldsare integrated into the language to allow type-checking and automatic dis-cretization.

• Equations:

– Language additions for differential operators are designed to expresspartial 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 tobe defined on sub-domains and on boundaries, i.e., to define boundaryconditions.

– The integral operator is defined for field reduction, i.e., to convert afield to a scalar or a field with lesser dimension.

Since the numerical methods for solving PDEs are not as well developed andautomatic as ODE/DAE solvers, it is not possible to hide all discretization detailsfrom users. Although, our approach with two layers where only the continuouspart needs to be defined by an end user allows fairly high abstraction. PDE-basedmodels can be defined at the discrete level and inserted in a library by a librarydeveloper with knowledge about the numerical solution, which an end-user canuse directly with an arbitrary domain. Discretization parameters may be requiredhowever, 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 thecurrent prototype, only most basic PDE models have been implemented, in order totest the design. Many standard PDE models are missing, which can be added to thelibrary for easy reuse. Also, in order to allow modeling using the graphical userinterfaces 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 syntaxwith declaration of both packages and data structures, which originates from lim-itations in the Modelica language. Another drawback is that the discretization isdone using external function calls and the discrete domain is represented using pa-rameters, which is inefficient because the purpose of parameters is not to representlarge amounts of data. Thus, granularity of domain discretization is limited whenusing the library.

A separate discretization module integrated into the Modelica compiler couldinteract 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

Page 163: levon-titelsid - DiVA portal

9.2 Contributions

and integrated into for example OpenModelica and evaluated further. With anexisting discretization and simulation environment environment implementing thenew language constructs, the Modelica PDE library can be rewritten using the newlanguage 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 theModelica language and the design of PDEModelica extensions are consistentwith 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 modelingsupport.

• Component-based geometry definition, i.e., separation of geometry defini-tion from model definition. In the gPROMS language, the domain is declaredwithin the specific low-level models. With our approach, geometries can bedefined separately and collected into libraries and reused in new models.

• Separation of analytical, continuous model description from discretizationand 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 ofvariable. Arrays of such variables can be defined in the same way as arraysof 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 withnames, 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

Page 164: levon-titelsid - DiVA portal

Chapter 9 Conclusion

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

9.3 Future Work

9.3.1 Modelica PDE Library

Further work is needed on the finite difference and the finite volume packages andto adapt them to the new continuous PDE problem definition design presented inthis thesis. Also, the finite difference solver package can be improved to supportnon-rectangular domains. The Mathematica-based prototypes already implementfinite 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 existingstandard boundaries. For example, a CircularDomain can be defined as follows:

package Circu la rD om a i nextends Domain ( r e d e c l a r e package boundaryP = C i r c l e ) ;

end Circu la rDo m a i n ;

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 partialdifferential equations. An intermediate step towards the most general expressionis to use predefined PDEs with a connection mechanism so that sub-domains withdifferent PDEs can be connected together to solve more complex problems. Asimple 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 sourceterms in different parts of the domain.

It is possible to add new PDE models to the Modelica PDE library. Modelsthat 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 modelsrequire more work in terms of external interface functions or internal discretizationfunctions.

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

Page 165: levon-titelsid - DiVA portal

9.3 Future Work

functions is a special case in one dimensions, i.e., two separate points are neededas the boundary, instead of a continuous shape function. One possible solution is todefine a shape function which only accepts the parameter values 0 and 1 and mapsthese 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-partsof the boundaries must have matching edges. Boundary shapes other than linearones, e.g. polygons, can be difficult to use together.

The definition of a boundary is also highly dependent on the external domaindiscretization support. The bidimensional mesh generator bamg was used in thisprototype [19]. Other mesh generators exist that have higher level primitives likesplines, for example GRUMMP [55], which also have support for three dimensionalmesh generation. Support for such higher-level primitives and three-dimensionalmesh representation and external access are other future extensions needed in the li-brary. When using higher level boundary primitives with corresponding lower-levelcomponents supported by the mesh generator, the internal boundary discretizationmust be omitted, which indicates that some redesign of parts of the library mightbe 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 discretizationmethod uses the finite element method, which is highly flexible with respect togeneral, complex domains. An early version of the library also implements thefinite 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 theMathematica-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 whichequations for the complete model are automatically generated. Currently, con-nectors consist of scalar, time dependent variables or arrays of such variables. Theextension of connectors to support field variables and models with partial differ-ential equations is not straightforward. The concept of connectors in Modelica isbased 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

Page 166: levon-titelsid - DiVA portal

Chapter 9 Conclusion

For example, assigning Dirichlet boundary conditions to the boundary of a domaincan be seen as connecting a component to that boundary which determines the po-tential. Similarly, Neumann boundary conditions correspond to assigning the flowvariable on a boundary. Thus, a natural extension of the connection concept inModelica involves distributed connectors over given boundaries. This can be doneeither when declaring connectors where field variables are used, or when writingconnect equations. A domain and whole or part of its boundary can be givento specify where the connection should occur. Connections can be between twoPDE models or a PDE model and a scalar, time-dependent variable, in which casefield reduction as described in Section 4.3.4 can be used. Using connectors wouldalso make the specification of boundary conditions implicit, making it unnecessaryto explicitly specify boundary conditions. For example, a connection defining thetemperature on a boundary would give Dirichlet conditions, while a connectionwhere the heat flux is known would give Neumann conditions. Further research isneeded in this area in order to work out mathematical details and language designand implementation.

9.3.3 Language Implementation

This section presents possible future work in the PDEModelica prototype languageimplementation.

9.3.3.1 Language Implementation of Fields

As described in Section 5.1.2.3, the current language implementation of fields inPDEModelica supports continuous represantation, discretization being handled bylower 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 typeand a domain. A future discretization module needs to convert variables of thesetypes into arrays. The space discrete format depends on the solution method. Forexample, 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 fieldtranslation example shown above:

f u n c t i o n f_tmp1input Real x ;input Real y ;output Real o u t ;

a lgor i thmo u t = 2* x+y ;

end f_tmp1 ;. . .TestDomain omega ( . . . ) ;f i e l d Real f = f i e l d ( f_tmp1 ( x , y ) f o r ( x , y ) in omega ) ;

150

Page 167: levon-titelsid - DiVA portal

9.3 Future Work

Using the FEMForms.Mesh data structure, the discrete version of this code couldbe as follows, without any changes to the generated field constructor functionf_tmp1:

Mesh omega ( . . . ) ;Rea l f [ omega . nv ] = f_tmp1 ( omega . x [ i , 1 ] , omega . x [ i , 2 ] )

f o r i in 1 : omega . nv ;/ / boundary c o n d i t i o n i n d i c e s i n omega . x [ i , 3 ]

One option could be to generate code that utilizes the PDE library, with theadvantage that the same solver and mesh generation implementation can be reused.

A design proposal for extensions of the OpenModelica simulation environmentis depicted in Figure 9.1, using Corba for communication between the translatorand the external PDE discretizer.

Server: MainProgram (Compiler

Interpreter, etc.)

Client: GraphicalModel Editor

Client: OMShellInteractive

Session Handler

Client: EclipsePluginServer: PDE

Discretizer

Parse

Corba

PDE extensions

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

151

Page 168: levon-titelsid - DiVA portal

Chapter 9 Conclusion

152

Page 169: levon-titelsid - DiVA portal

References

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

[2] Peter Fritzson. Principles of Object-Oriented Modeling and Simulation withModelica 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öpingsuniversitet, August 2003.

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

[7] L. Saldamli and P. Fritzson. A Modelica-based Language for Object-OrientedModeling 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 inModelica. 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

Page 170: levon-titelsid - DiVA portal

References

[9] L. Saldamli, P. Fritzson, and B. Bachmann. Extending Modelica for PartialDifferential Equations. In Martin Otter, editor, Proc. of the 2nd InternationalModelica 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 forDescribing and Solving PDE Models in Modelica. In Proceedings of the 4thInternational Modelica Conference, Hamburg, Germany, March 7–8 2005.

[12] Modelica Association. Modelica – A Unified Object-Oriented Language forPhysical 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-OrientedModel Libraries using Modelica. PhD thesis, Lund Institute of Technology,2002.

[15] G. D. Smith. Numerical Solution of Partial Differential Equations: FiniteDifference Methods, chapter one, pages 6–9. Oxford University Press, thirdedition, 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 homepage. 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 DifferentialEquations. 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

Page 171: levon-titelsid - DiVA portal

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 Interpreterfor 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 LectureNotes 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 TheoreticalAspects 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 StandardML (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 andInformation 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 ComputerSimulation 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

Page 172: levon-titelsid - DiVA portal

References

[36] K. Sheshadri and P. Fritzson. MathModelica – An Object Oriented Math-ematical Modeling and Simulation Environment. Accepted to MathematicaJournal, 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. InProc. of the Scandinavian Simulation Society (SIMS) Conference, LinköpingUniversity, Linköping, Sweden, September 1999.

[40] P. Fritzson, J. Gunnarsson, and M. Jirstrand. MathModelica - An Exten-sible Modeling and Simulation Environment with Integrated Graphics andLiterate Programming. In Proc. of the 2nd International Modelica Confer-ence, Munich, March 2002. http://www.modelica.org/. See alsohttp://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 DeclarationHandling in Open Source Modelica. In Martin Otter, editor, Proc. of the SIMS- 43rd Conference on Simulation and Modeling, Oulu, Finland, September2002.

[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 DistributedProcesses. PhD thesis, University of London, 1995.

156

Page 173: levon-titelsid - DiVA portal

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 forPDE-Based Applications on Multicomputer Platforms. ACM Transactions onMathematical 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 DifferentialEquation 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

Page 174: levon-titelsid - DiVA portal

References

158

Page 175: levon-titelsid - DiVA portal

159

Page 176: levon-titelsid - DiVA portal

Appendix A UML Notation

Appendix A

UML Notation

ClassName

+attribute: Type

+method(paramType): returnType

ParameterizedClass

ParameterName:

BaseClass

SubClass

Inheritance

ClassA ClassBAssociation

Class

ParameterizedClass

Owner MemberComposition n

Referer ReferenceAggregate n

160

Page 177: levon-titelsid - DiVA portal

Appendix B

Plotting Simulation Results

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

B.1 Visualization of Domain Boundary

f u n c t i o n showboundary ( m a t f i l e , name )% Show t h e boundary o f a domain d e f i n e d u s i n g t h e Model ica PDE L i b r a r y% m a t f i l e : . mat− f i l e c o n t a i n i n g s i m u l a t i o n r e s u l t% name : name o f t h e d i s c r e t e domain c o n t a i n i n g t h e domain boundary% Example : showboundary ( ’ t e s t . mat ’ , ’ pde . ddomain ’ )r e s =dymload ( m a t f i l e ) ;nodes = c e l l 2 m a t ( dymget ( r es , [ name ’ . po lygon ’ ] ) ) ;x= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 1 ) ;y= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 2 ) ;f i l l ( x , y , ’ b ’ ) ;

B.2 Visualization of Meshes

f u n c t i o n showmesh ( m a t f i l e , name )% Show a t r i a n g u l a r mesh g e n e r a t e d by Model ica PDE L i b r a r y% m a t f i l e : . mat− f i l e c o n t a i n i n g s i m u l a t i o n r e s u l t .% name : name o f t h e d i s c r e t e domain c o n t a i n i n g t h e mesh .% Example : showmesh ( ’ t e s t . mat ’ , ’ pde . ddomain ’ )

r e s =dymload ( m a t f i l e ) ;nodes = c e l l 2 m a t ( dymget ( r es , [ name ’ . mesh . x ’ ] ) ) ;t r i s = c e l l 2 m a t ( dymget ( r es , [ name ’ . mesh . t r i a n g l e ’ ] ) ) ;t = t r i s ( 2 : 2 : s i z e ( t r i s , 1 ) , 1 : 3 ) ;x= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 1 ) ;y= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 2 ) ;t r i m e s h ( t , x , y , ’ Color ’ , ’ b l a c k ’ ) ;

B.3 Visualization of Steady-state Fields

161

Page 178: levon-titelsid - DiVA portal

Appendix B Plotting Simulation Results

f u n c t i o n s h o w f i e l d _ i n d ( m a t f i l e , name )% Show an i n d i r e c t f i e l d from a s t e a d y−s t a t e s i m u l a t i o n% I n d i r e c t f i e l d s are used i n t h e FEMForms package i n t h e% Model ica PDE Library , w i t h R h e o l e f as t h e e x t e r n a l s o l v e r .% m a t f i l e : . mat− f i l e c o n t a i n i n g s i m u l a t i o n r e s u l t .% name : Name o f t h e f i e l d v a r i a b l e .% Example : s h o w f i e l d _ i n d ( ’ t e s t . mat ’ , ’ pde . fd ’ )

r e s =dymload ( m a t f i l e ) ;nodes = c e l l 2 m a t ( dymget ( r es , [ name ’ . ddomain . mesh . x ’ ] ) ) ;t r i s = c e l l 2 m a t ( dymget ( r es , [ name ’ . ddomain . mesh . t r i a n g l e ’ ] ) ) ;v a l s u = c e l l 2 m a t ( dymget ( r es , [ name ’ . v a l _ u ’ ] ) ) ’ ;v a l s b = c e l l 2 m a t ( dymget ( r es , [ name ’ . v a l _ b ’ ] ) ) ’ ;u i n d i c e s = c e l l 2 m a t ( dymget ( r es , [ name ’ . u _ i n d i c e s ’ ] ) ) ’ ;b i n d i c e s = c e l l 2 m a t ( dymget ( r es , [ name ’ . b _ i n d i c e s ’ ] ) ) ’ ;t = t r i s ( 2 : 2 : s i z e ( t r i s , 1 ) , 1 : 3 ) ;x= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 1 ) ;y= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 2 ) ;u i = u i n d i c e s ( : , 1 ) ;b i = b i n d i c e s ( : , 1 ) ;z ( u i )= v a l s u ( : , 1 ) ;z ( b i )= v a l s b ( : , 1 ) ;t r i s u r f ( t , x , y , z , ’ FaceColor ’ , ’ i n t e r p ’ , ’ EdgeColor ’ , ’ i n t e r p ’ ) ;

B.4 Visualization of Time-dependent Fields

f u n c t i o n s h o w f i e l d t _ i n d ( m a t f i l e , name , t i m e s t e p )% Show an i n d i r e c t f i e l d from a t ime−d e p e n d e n t s i m u l a t i o n% I n d i r e c t f i e l d s are used i n FEMForms , w i t h t h e R h e o l e f s o l v e r .% m a t f i l e : m a t f i l e c o n t a i n i n g s i m u l a t i o n r e s u l t .% name : Name o f t h e f i e l d v a r i a b l e .% t i m e s t e p : The t i m e s t e p t o show ,% an i n t e g e r i n d e x 1−number o f s i m u l a t i o n s t e p s% Example : s h o w f i e l d t _ i n d ( ’ t e s t . mat ’ , ’ pde . fd ’ , 3000)r e s =dymload ( m a t f i l e ) ;nodes = c e l l 2 m a t ( dymget ( r es , [ name ’ . ddomain . mesh . x ’ ] ) ) ;t r i s = c e l l 2 m a t ( dymget ( r es , [ name ’ . ddomain . mesh . t r i a n g l e ’ ] ) ) ;v a l s u = c e l l 2 m a t ( dymget ( r es , [ name ’ . v a l _ u ’ ] ) ) ’ ;v a l s b = c e l l 2 m a t ( dymget ( r es , [ name ’ . v a l _ b ’ ] ) ) ’ ;u i n d i c e s = c e l l 2 m a t ( dymget ( r es , [ name ’ . u _ i n d i c e s ’ ] ) ) ’ ;b i n d i c e s = c e l l 2 m a t ( dymget ( r es , [ name ’ . b _ i n d i c e s ’ ] ) ) ’ ;t = t r i s ( 2 : 2 : s i z e ( t r i s , 1 ) , 1 : 3 ) ;x= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 1 ) ;y= nodes ( 2 : 2 : s i z e ( nodes , 1 ) , 2 ) ;u i = u i n d i c e s ( : , 1 ) ;b i = b i n d i c e s ( : , 1 ) ;z ( u i )= v a l s u ( : , t i m e s t e p ) ;z ( b i )= v a l s b ( : , t i m e s t e p ) ;t r i s u r f ( t , x , y , z , ’ FaceColor ’ , ’ i n t e r p ’ , ’ EdgeColor ’ , ’ i n t e r p ’ ) ;

162

Page 179: levon-titelsid - DiVA portal

Index

backward difference, 20boundary conditions, 17

central difference, 20

definition domain, 16, 17dependent variables, 16derivative

directional, 17normal, see normal derivativepartial, see partial derivative

differencebackward, 20central, 20forward, 20

differential equationsordinary, 16partial, 17

directional derivative, 17domain, 17

definition, 16

FEM, see finite element methodfield, 16finite element method, 22finite difference methods, 20forward difference, 20

independent variables, 16initial conditions, 18

method of lines, 23

normal derivative, 18

ODE, see ordinary differential equa-tions

ordinary differential equations, 16

package design, 25partial derivative, 17partial differential equations, 17PDE, see partial differential equationsPDE library, 25

stationary problem, 17

time-dependent problem, 17

163

Page 180: levon-titelsid - DiVA portal
Page 181: levon-titelsid - DiVA portal

Department of Computer and Information ScienceLinköpings universitet

Dissertations

Linköping Studies in Science and Technology

No 14 Anders Haraldsson: A Program ManipulationSystem Based on Partial Evaluation, 1977, ISBN91-7372-144-1.

No 17 Bengt Magnhagen: Probability Based Verificationof Time Margins in Digital Designs, 1977, ISBN91-7372-157-3.

No 18 Mats Cedwall: Semantisk analys av process-beskrivningar i naturligt språk, 1977, ISBN 91-7372-168-9.

No 22 Jaak Urmi: A Machine Independent LISP Compil-er and its Implications for Ideal Hardware, 1978,ISBN 91-7372-188-3.

No 33 Tore Risch: Compilation of Multiple File Queriesin a Meta-Database System 1978, ISBN 91-7372-232-4.

No 51 Erland Jungert: Synthesizing Database Structuresfrom a User Oriented Data Model, 1980, ISBN 91-7372-387-8.

No 54 Sture Hägglund: Contributions to the Develop-ment of Methods and Tools for Interactive Designof Applications Software, 1980, ISBN 91-7372-404-1.

No 55 Pär Emanuelson: Performance Enhancement in aWell-Structured Pattern Matcher through PartialEvaluation, 1980, ISBN 91-7372-403-3.

No 58 Bengt Johnsson, Bertil Andersson: The Human-Computer Interface in Commercial Systems, 1981,ISBN 91-7372-414-9.

No 69 H. Jan Komorowski: A Specification of an Ab-stract Prolog Machine and its Application to PartialEvaluation, 1981, ISBN 91-7372-479-3.

No 71 René Reboh: Knowledge Engineering Techniquesand Tools for Expert Systems, 1981, ISBN 91-7372-489-0.

No 77 Östen Oskarsson: Mechanisms of Modifiability inlarge Software Systems, 1982, ISBN 91-7372-527-7.

No 94 Hans Lunell: Code Generator Writing Systems,1983, ISBN 91-7372-652-4.

No 97 Andrzej Lingas: Advances in Minimum WeightTriangulation, 1983, ISBN 91-7372-660-5.

No 109 Peter Fritzson: Towards a Distributed Program-ming Environment based on Incremental Compila-tion,1984, ISBN 91-7372-801-2.

No 111 Erik Tengvald: The Design of Expert PlanningSystems. An Experimental Operations PlanningSystem for Turning, 1984, ISBN 91-7372-805-5.

No 155 Christos Levcopoulos: Heuristics for MinimumDecompositions of Polygons, 1987, ISBN 91-7870-133-3.

No 165 James W. Goodwin: A Theory and System for

Non-Monotonic Reasoning, 1987, ISBN 91-7870-183-X.

No 170 Zebo Peng: A Formal Methodology for AutomatedSynthesis of VLSI Systems, 1987, ISBN 91-7870-225-9.

No 174 Johan Fagerström: A Paradigm and System forDesign of Distributed Systems, 1988, ISBN 91-7870-301-8.

No 192 Dimiter Driankov: Towards a Many Valued Logicof Quantified Belief, 1988, ISBN 91-7870-374-3.

No 213 Lin Padgham: Non-Monotonic Inheritance for anObject Oriented Knowledge Base, 1989, ISBN 91-7870-485-5.

No 214 Tony Larsson: A Formal Hardware Description andVerification Method, 1989, ISBN 91-7870-517-7.

No 221 Michael Reinfrank: Fundamentals and LogicalFoundations of Truth Maintenance, 1989, ISBN 91-7870-546-0.

No 239 Jonas Löwgren: Knowledge-Based Design Supportand Discourse Management in User Interface Man-agement Systems, 1991, ISBN 91-7870-720-X.

No 244 Henrik Eriksson: Meta-Tool Support for Knowl-edge Acquisition, 1991, ISBN 91-7870-746-3.

No 252 Peter Eklund: An Epistemic Approach to Interac-tive Design in Multiple Inheritance Hierar-chies,1991, ISBN 91-7870-784-6.

No 258 Patrick Doherty: NML3 - A Non-Monotonic For-malism with Explicit Defaults, 1991, ISBN 91-7870-816-8.

No 260 Nahid Shahmehri: Generalized Algorithmic De-bugging, 1991, ISBN 91-7870-828-1.

No 264 Nils Dahlbäck: Representation of Discourse-Cog-nitive and Computational Aspects, 1992, ISBN 91-7870-850-8.

No 265 Ulf Nilsson: Abstract Interpretations and AbstractMachines: Contributions to a Methodology for theImplementation of Logic Programs, 1992, ISBN 91-7870-858-3.

No 270 Ralph Rönnquist: Theory and Practice of Tense-bound Object References, 1992, ISBN 91-7870-873-7.

No 273 Björn Fjellborg: Pipeline Extraction for VLSI DataPath Synthesis, 1992, ISBN 91-7870-880-X.

No 276 Staffan Bonnier: A Formal Basis for Horn ClauseLogic with External Polymorphic Functions, 1992,ISBN 91-7870-896-6.

No 277 Kristian Sandahl: Developing Knowledge Man-agement Systems with an Active Expert Methodolo-gy, 1992, ISBN 91-7870-897-4.

No 281 Christer Bäckström: Computational Complexity

Page 182: levon-titelsid - DiVA portal

of Reasoning about Plans, 1992, ISBN 91-7870-979-2.

No 292 Mats Wirén: Studies in Incremental Natural Lan-guage Analysis, 1992, ISBN 91-7871-027-8.

No 297 Mariam Kamkar: Interprocedural Dynamic Slic-ing with Applications to Debugging and Testing,1993, ISBN 91-7871-065-0.

No 302 Tingting Zhang: A Study in Diagnosis Using Clas-sification and Defaults, 1993, ISBN 91-7871-078-2.

No 312 Arne Jönsson: Dialogue Management for NaturalLanguage Interfaces - An Empirical Approach,1993, ISBN 91-7871-110-X.

No 338 Simin Nadjm-Tehrani: Reactive Systems in Phys-ical Environments: Compositional Modelling andFramework for Verification, 1994, ISBN 91-7871-237-8.

No 371 Bengt Savén: Business Models for Decision Sup-port and Learning. A Study of Discrete-Event Man-ufacturing Simulation at Asea/ABB 1968-1993,1995, ISBN 91-7871-494-X.

No 375 Ulf Söderman: Conceptual Modelling of ModeSwitching Physical Systems, 1995, ISBN 91-7871-516-4.

No 383 Andreas Kågedal: Exploiting Groundness in Log-ic Programs, 1995, ISBN 91-7871-538-5.

No 396 George Fodor: Ontological Control, Description,Identification and Recovery from Problematic Con-trol Situations, 1995, ISBN 91-7871-603-9.

No 413 Mikael Pettersson: Compiling Natural Semantics,1995, ISBN 91-7871-641-1.

No 414 Xinli Gu: RT Level Testability Improvement byTestability Analysis and Transformations, 1996,ISBN 91-7871-654-3.

No 416 Hua Shu: Distributed Default Reasoning, 1996,ISBN 91-7871-665-9.

No 429 Jaime Villegas: Simulation Supported IndustrialTraining from an Organisational Learning Perspec-tive - Development and Evaluation of the SSITMethod, 1996, ISBN 91-7871-700-0.

No 431 Peter Jonsson: Studies in Action Planning: Algo-rithms and Complexity, 1996, ISBN 91-7871-704-3.

No 437 Johan Boye: Directional Types in Logic Program-ming, 1996, ISBN 91-7871-725-6.

No 439 Cecilia Sjöberg: Activities, Voices and Arenas:Participatory Design in Practice, 1996, ISBN 91-7871-728-0.

No 448 Patrick Lambrix: Part-Whole Reasoning in De-scription Logics, 1996, ISBN 91-7871-820-1.

No 452 Kjell Orsborn: On Extensible and Object-Rela-tional Database Technology for Finite ElementAnalysis Applications, 1996, ISBN 91-7871-827-9.

No 459 Olof Johansson: Development Environments forComplex Product Models, 1996, ISBN 91-7871-855-4.

No 461 Lena Strömbäck: User-Defined Constructions inUnification-Based Formalisms,1997, ISBN 91-7871-857-0.

No 462 Lars Degerstedt: Tabulation-based Logic Program-ming: A Multi-Level View of Query Answering,1996, ISBN 91-7871-858-9.

No 475 Fredrik Nilsson: Strategi och ekonomisk styrning -En studie av hur ekonomiska styrsystem utformasoch används efter företagsförvärv, 1997, ISBN 91-7871-914-3.

No 480 Mikael Lindvall: An Empirical Study of Require-ments-Driven Impact Analysis in Object-OrientedSoftware Evolution, 1997, ISBN 91-7871-927-5.

No 485 Göran Forslund: Opinion-Based Systems: The Co-operative Perspective on Knowledge-Based Deci-sion Support, 1997, ISBN 91-7871-938-0.

No 494 Martin Sköld: Active Database Management Sys-tems for Monitoring and Control, 1997, ISBN 91-7219-002-7.

No 495 Hans Olsén: Automatic Verification of Petri Nets ina CLP framework, 1997, ISBN 91-7219-011-6.

No 498 Thomas Drakengren: Algorithms and Complexityfor Temporal and Spatial Formalisms, 1997, ISBN91-7219-019-1.

No 502 Jakob Axelsson: Analysis and Synthesis of Hetero-geneous Real-Time Systems, 1997, ISBN 91-7219-035-3.

No 503 Johan Ringström: Compiler Generation for Data-Parallel Programming Langugaes from Two-LevelSemantics Specifications, 1997, ISBN 91-7219-045-0.

No 512 Anna Moberg: Närhet och distans - Studier avkommunikationsmmönster i satellitkontor och flexi-bla kontor, 1997, ISBN 91-7219-119-8.

No 520 Mikael Ronström: Design and Modelling of a Par-allel Data Server for Telecom Applications, 1998,ISBN 91-7219-169-4.

No 522 Niclas Ohlsson: Towards Effective Fault Prevention - An Empirical Study in Software Engi-neering, 1998, ISBN 91-7219-176-7.

No 526 Joachim Karlsson: A Systematic Approach for Pri-oritizing Software Requirements, 1998, ISBN 91-7219-184-8.

No 530 Henrik Nilsson: Declarative Debugging for LazyFunctional Languages, 1998, ISBN 91-7219-197-x.

No 555 Jonas Hallberg: Timing Issues in High-Level Syn-thesis,1998, ISBN 91-7219-369-7.

No 561 Ling Lin: Management of 1-D Sequence Data -From Discrete to Continuous, 1999, ISBN 91-7219-402-2.

No 563 Eva L Ragnemalm: Student Modelling based onCollaborative Dialogue with a Learning Compan-ion, 1999, ISBN 91-7219-412-X.

No 567 Jörgen Lindström: Does Distance matter? On geo-graphical dispersion in organisations, 1999, ISBN

Page 183: levon-titelsid - DiVA portal

91-7219-439-1.

No 582 Vanja Josifovski: Design, Implementation andEvaluation of a Distributed Mediator System forData Integration, 1999, ISBN 91-7219-482-0.

No 589 Rita Kovordányi: Modeling and Simulating Inhib-itory Mechanisms in Mental Image Reinterpretation- Towards Cooperative Human-Computer Creativi-ty, 1999, ISBN 91-7219-506-1.

No 592 Mikael Ericsson: Supporting the Use of DesignKnowledge - An Assessment of CommentingAgents, 1999, ISBN 91-7219-532-0.

No 593 Lars Karlsson: Actions, Interactions and Narra-tives, 1999, ISBN 91-7219-534-7.

No 594 C. G. Mikael Johansson: Social and Organization-al Aspects of Requirements Engineering Methods -A practice-oriented approach, 1999, ISBN 91-7219-541-X.

No 595 Jörgen Hansson: Value-Driven Multi-Class Over-load Management in Real-Time Database Systems,1999, ISBN 91-7219-542-8.

No 596 Niklas Hallberg: Incorporating User Values in theDesign of Information Systems and Services in thePublic Sector: A Methods Approach, 1999, ISBN91-7219-543-6.

No 597 Vivian Vimarlund: An Economic Perspective onthe Analysis of Impacts of Information Technology:From Case Studies in Health-Care towards GeneralModels and Theories, 1999, ISBN 91-7219-544-4.

No 598 Johan Jenvald: Methods and Tools in Computer-Supported Taskforce Training, 1999, ISBN 91-7219-547-9.

No 607 Magnus Merkel: Understanding and enhancingtranslation by parallel text processing, 1999, ISBN91-7219-614-9.

No 611 Silvia Coradeschi: Anchoring symbols to sensorydata, 1999, ISBN 91-7219-623-8.

No 613 Man Lin: Analysis and Synthesis of ReactiveSystems: A Generic Layered ArchitecturePerspective, 1999, ISBN 91-7219-630-0.

No 618 Jimmy Tjäder: Systemimplementering i praktiken- En studie av logiker i fyra projekt, 1999, ISBN 91-7219-657-2.

No 627 Vadim Engelson: Tools for Design, InteractiveSimulation, and Visualization of Object-OrientedModels in Scientific Computing, 2000, ISBN 91-7219-709-9.

No 637 Esa Falkenroth: Database Technology for Controland Simulation, 2000, ISBN 91-7219-766-8.

No 639 Per-Arne Persson: Bringing Power andKnowledge Together: Information Systems Designfor Autonomy and Control in Command Work,2000, ISBN 91-7219-796-X.

No 660 Erik Larsson: An Integrated System-Level Designfor Testability Methodology, 2000, ISBN 91-7219-890-7.

No 688 Marcus Bjäreland: Model-based ExecutionMonitoring, 2001, ISBN 91-7373-016-5.

No 689 Joakim Gustafsson: Extending Temporal ActionLogic, 2001, ISBN 91-7373-017-3.

No 720 Carl-Johan Petri: Organizational Information Pro-vision - Managing Mandatory and Discretionary Useof Information Technology, 2001, ISBN-91-7373-126-9.

No 724 Paul Scerri: Designing Agents for Systems with Ad-justable Autonomy, 2001, ISBN 91 7373 207 9.

No 725 Tim Heyer: Semantic Inspection of Software Arti-facts: From Theory to Practice, 2001, ISBN 91 7373208 7.

No 726 Pär Carlshamre: A Usability Perspective on Re-quirements Engineering - From Methodology to Prod-uct Development, 2001, ISBN 91 7373 212 5.

No 732 Juha Takkinen: From Information Management toTask Management in Electronic Mail, 2002, ISBN91 7373 258 3.

No 745 Johan Åberg: Live Help Systems: An Approach toIntelligent Help for Web Information Systems,2002, ISBN 91-7373-311-3.

No 746 Rego Granlund: Monitoring Distributed Team-work Training, 2002, ISBN 91-7373-312-1.

No 757 Henrik André-Jönsson: Indexing Strategies forTime Series Data, 2002, ISBN 917373-346-6.

No 747 Anneli Hagdahl: Development of IT-suppor-ted In-ter-organisational Collaboration - A Case Study inthe Swedish Public Sector, 2002, ISBN 91-7373-314-8.

No 749 Sofie Pilemalm: Information Technology for Non-Profit Organisations - Extended Participatory De-sign of an Information System for Trade Union ShopStewards, 2002, ISBN 91-7373-318-0.

No 765 Stefan Holmlid: Adapting users: Towards a theoryof use quality, 2002, ISBN 91-7373-397-0.

No 771 Magnus Morin: Multimedia Representations ofDistributed Tactical Operations, 2002, ISBN 91-7373-421-7.

No 772 Pawel Pietrzak: A Type-Based Framework for Lo-cating Errors in Constraint Logic Programs, 2002,ISBN 91-7373-422-5.

No 758 Erik Berglund: Library Communication AmongProgrammers Worldwide, 2002,ISBN 91-7373-349-0.

No 774 Choong-ho Yi: Modelling Object-OrientedDynamic Systems Using a Logic-Based Framework,2002, ISBN 91-7373-424-1.

No 779 Mathias Broxvall: A Study in the Computational Complexity of Temporal Reasoning, 2002, ISBN 91-7373-440-3.

No 793 Asmus Pandikow: A Generic Principle for Enabling Interoperability of Structured and Object-Oriented Analysis and Design Tools, 2002,ISBN 91-7373-479-9.

No 785 Lars Hult: Publika Informationstjänster. En studieav den Internetbaserade encyklopedins bruksegen-skaper, 2003, ISBN 91-7373-461-6.

Page 184: levon-titelsid - DiVA portal

No 800 Lars Taxén: A Framework for the Coordination ofComplex Systems´ Development, 2003, ISBN 91-7373-604-X

No 808 Klas Gäre: Tre perspektiv på förväntningar ochförändringar i samband med införande av informa-tionsystem, 2003, ISBN 91-7373-618-X.

No 821 Mikael Kindborg: Concurrent Comics - program-ming of social agents by children, 2003,ISBN 91-7373-651-1.

No 823 Christina Ölvingson: On Development of Infor-mation Systems with GIS Functionality in PublicHealth Informatics: A Requirements EngineeringApproach, 2003, ISBN 91-7373-656-2.

No 828 Tobias Ritzau: Memory Efficient Hard Real-TimeGarbage Collection, 2003, ISBN 91-7373-666-X.

No 833 Paul Pop: Analysis and Synthesis of Communication-Intensive Heterogeneous Real-Time Systems, 2003, ISBN 91-7373-683-X.

No 852 Johan Moe: Observing the DynamicBehaviour of Large Distributed Systems to ImproveDevelopment and Testing - An Emperical Study inSoftware Engineering, 2003, ISBN 91-7373-779-8.

No 867 Erik Herzog: An Approach to Systems Engineer-ing Tool Data Representation and Exchange, 2004,ISBN 91-7373-929-4.

No 872 Aseel Berglund: Augmenting the Remote Control:Studies in Complex Information Navigation for

Digital TV, 2004, ISBN 91-7373-940-5.No 869 Jo Skåmedal: Telecommuting’s Implications on

Travel and Travel Patterns, 2004, ISBN 91-7373-935-9.

No 870 Linda Askenäs: The Roles of IT - Studies of Or-ganising when Implementing and Using EnterpriseSystems, 2004, ISBN 91-7373-936-7.

No 874 Annika Flycht-Eriksson: Design and Use of On-tologies in Information-Providing Dialogue Sys-tems, 2004, ISBN 91-7373-947-2.

No 873 Peter Bunus: Debugging Techniques for Equation-Based Languages, 2004, ISBN 91-7373-941-3.

No 876 Jonas Mellin: Resource-Predictable and Effi-cient Monitoring of Events, 2004, ISBN 91-7373-956-1.

No 883 Magnus Bång: Computing at the Speed of Paper:Ubiquitous Computing Environments for Health-care Professionals, 2004, ISBN 91-7373-971-5

No 882 Robert Eklund: Disfluency in Swedish human-human and human-machine travel bookingdialogues, 2004. ISBN 91-7373-966-9.

No 887 Anders Lindström: English and other Foreign Lin-quistic Elements in Spoken Swedish. Studies ofProductive Processes and their Modelling using Fi-nite-State Tools, 2004, ISBN 91-7373-981-2.

No 889 Zhiping Wang: Capacity-Constrained Production-inventory systems - Modellling and Analysis inboth a traditional and an e-business context, 2004,ISBN 91-85295-08-6.

No 893 Pernilla Qvarfordt: Eyes on Multimodal Interac-tion, 2004, ISBN 91-85295-30-2.

No 910 Magnus Kald: In the Borderland between Strate-gy and Management Control - Theoretical Frame-work and Empirical Evidence, 2004, ISBN 91-

85295-82-5.No 918 Jonas Lundberg: Shaping Electronic News: Gen-

re Perspectives on Interaction Design, 2004, ISBN91-85297-14-3.

No 900 Mattias Arvola: Shades of use: The dynamics ofinteraction design for sociable use, 2004, ISBN91-85295-42-6.

No 920 Luis Alejandro Cortés: Verification and Sched-uling Techniques for Real-Time Embedded Sys-tems, 2004, ISBN 91-85297-21-6.

No 929 Diana Szentivanyi: Performance Studies ofFault-Tolerant Middleware, 2005, ISBN 91-85297-58-5.

No 933 Mikael Cäker: Management Accounting as Con-structing and Opposing Customer Focus: ThreeCase Studies on Management Accounting andCustomer Relations, 2005, ISBN 91-85297-64-X.

No 937 Jonas Kvarnström: TALplanner and Other Ex-tensions to Temporal Action Logic, 2005, ISBN91-85297-75-5.

No 938 Bourhane Kadmiry: Fuzzy Gain-Scheduled Vis-ual Servoing for Unmanned Helicopter, 2005,ISBN 91-85297-76-3.

No 945 Gert Jervan: Hybrid Built-In Self-Test and TestGeneration Techniques for Digital Systems, 2005,ISBN: 91-85297-97-6.

No 946 Anders Arpteg: Intelligent Semi-Structured In-formation Extraction, 2005, ISBN 91-85297-98-4.

No 947 Ola Angelsmark: Constructing Algorithms forConstraint Satisfaction and Related Problems -Methods and Applications, 2005, ISBN 91-85297-99-2.

No 963 Calin Curescu: Utility-based Optimisation of Re-source Allocation for Wireless Networks, 2005.ISBN 91-85457-07-8.

No 972 Björn Johansson: Joint Control in Dynamic Situ-ations, 2005, ISBN 91-85457-31-0.

No 974 Dan Lawesson: An Approach to DiagnosabilityAnalysis for Interacting Finite State Systems,2005, ISBN 91-85457-39-6.

No 979 Claudiu Duma: Security and Trust Mechanismsfor Groups in Distributed Services, 2005, ISBN91-85457-54-X.

No 983 Sorin Manolache: Analysis and Optimisation ofReal-Time Systems with Stochastic Behaviour,2005, ISBN 91-85457-60-4.

No 986 Yuxiao Zhao: Standards-Based Application Inte-gration for Business-to-Business Communica-tions, 2005, ISBN 91-85457-66-3.

No 1004 Patrik Haslum: Admissible Heuristics for Auto-mated Planning, 2006, ISBN 91-85497-28-2.

No 1005 Aleksandra Tesanovic: Developing Re-usable and Reconfigurable Real-Time Softwareusing Aspects and Components, 2006, ISBN 91-85497-29-0.

No 1008 David Dinka: Role, Identity and Work: Extendingthe design and development agenda, 2006, ISBN91-85497-42-8.

No 1009 Iakov Nakhimovski: Contributions to the Mode-ling and Simulation of Mechanical Systems with

Page 185: levon-titelsid - DiVA portal

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 ScienceNo 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. ISBN91-7219-811-7.

No 5 Mikael Lind: Från system till process - kriterier förprocessbestämning vid verksamhetsanalys, 2001,ISBN 91-7373-067-X

No 6 Ulf Melin: Koordination och informationssystem iföretag och nätverk, 2002, ISBN 91-7373-278-8.

No 7 Pär J. Ågerfalk: Information Systems Actability -Understanding Information Technology as a Toolfor Business Action and Communication, 2003,ISBN 91-7373-628-7.

No 8 Ulf Seigerroth: Att förstå och förändrasystemutvecklingsverksamheter - en taxonomifö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, ISBN91-85297-48-8.

No 12 Malin Nordström: Styrbar systemförvaltning - Attorganisera systemförvaltningsverksamhet medhjälp av effektiva förvaltningsobjekt, 2005, ISBN91-85297-60-7.

No 13 Stefan Holgersson: Yrke: POLIS - Yrkeskunskap,motivation, IT-system och andra förutsättningar förpolisarbete, 2005, ISBN 91-85299-43-X.