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
“...toboldlygowhere no man has gone before.” James T. Kirk
Abstract
This thesis describes work on a new high-level mathematical modeling language and framework called PDEModelica for modeling with partial differential equa- tions. It is an extension to the current Modelica modeling language for object- oriented, equation-based modeling based on differential and algebraic equations. The language extensions and the framework presented in this thesis are consistent with the concepts of Modelica while adding support for partial differential equa- tions and space-distributed variables called fields. The specification of a partial differential equation problem consists of three parts: 1) the description of the definition domain, i.e., the geometric region where the equations are defined, 2) the initial and boundary conditions, and 3) the ac- tual equations. The known and unknown distributed variables in the equation are represented by field variables in PDEModelica. Domains are defined by a geo- metric description of their boundaries. Equations may use the Modelica derivative operator extended with support for partial derivatives, or vector differential opera- tors such as divergence and gradient, which can be defined for general curvilinear coordinates based on coordinate system definitions. The PDEModelica system also allows the partial differential equation models to be defined using a coefficient-based approach, where PDE models from a library are instantiated with different parameter values. Such a library contains both con- tinuous and discrete representations of the PDE model. The user can instantiate the continuous parts and define the parameters, and the discrete parts containing the equations are automatically instantiated and used to solve the PDE problem numerically. Compared to most earlier work in the area of mathematical modeling languages supporting PDEs, this work provides a modern object-oriented component-based approach to modeling with PDEs, including general support for hierarchical mod- eling, and for general, complex geometries. It is possible to separate the geometry definition from the model definition, which allows geometries to be defined sep- arately, collected into libraries, and reused in new models. It is also possible to separate the analytical continuous model description from the chosen discretization and numerical solution methods. This allows the model description to be reused, independent of different numerical solution approaches. The PDEModelica field concept allows general declaration of spatially distributed
v variables. Compared to most other approaches, the field concept described in this work affords a clearer abstraction and defines a new type of variable. Arrays of such field variables can be defined in the same way as arrays of regular, scalar variables. The PDEModelica language supports a clear, mathematical syntax that can be used both for equations referring to fields and explicit domain specifica- tions, used for example to specify boundary conditions. Hierarchical modeling and decomposition is integrated with a general connection concept, which allows connections between ODE/DAE and PDE based models. The implementation of a Modelica library needed for PDEModelica and a pro- totype implementation of field variables are also described in the thesis. The PDEModelica library contains internal and external solver implementations, and uses external software for mesh generation, requisite for numerical solution of the PDEs. Finally, some examples modeled with PDEModelica and solved using these implementations are presented.
vi Acknowledgments
First of all, I would like to thank my supervisor Peter Fritzson, for the inspiration and the motivation I needed to finish this thesis, and for commenting both my work and my language. I would also like to thank my co-supervisor Bernhard Bach- mann, for help with parts of the implementation in this work, and for his valuable comments on the contents of this thesis. Thanks also to Hansjürg Wiesmann for help with the implementation and for interesting discussions. Other colleagues at PELAB I would like to thank, who have contributed to the OpenModelica platform, where I could experiment with language extensions, are Peter Aronsson, Kaj Nyström, Adrian Pop, Peter Bunus, Håkan Lundvall, and David Broman. Thanks to the rest of the PELAB members for interesting dis- cussions about both work and other more or less relevant subjects, especially to Jens Gustavsson, Andreas Borg, and John Wilander for our very interesting work together on research methodology and computer science. Special thanks to An- drzej Bednarski for being both a colleague and a friend. Many thanks to Bodil Mattsson-Kihlström for her support in many ways, and to Lillemor Wallgren for her administrative help. Finally, I would like to thank my parents for enhancing my motivation, and my friends, for their company and support that helped me finish this work.
This work has been supported by the Swedish Foundation for Strategic Research in the ECSEL graduate school and the VISIMOD project, the European Commis- sion in the RealSim project, and by Vinnova in the VISP project.
vii viii Contents
1 Introduction 1 1.1PDE-basedModelExample...... 2 1.1.1 ConnectiontoODE/DAEmodels...... 4 1.2ResearchMethod...... 6 1.3Contributions...... 8 1.4OverviewoftheThesis...... 9
2 Background 11 2.1Modelica...... 11 2.1.1 Classes...... 12 2.1.2 VariableDeclarations...... 12 2.1.3 SubtypingandInheritance...... 13 2.1.4 Modifications...... 15 2.1.5 EquationsandAlgorithms...... 16 2.1.6 Replaceable Elements ...... 16 2.2DifferentialEquations...... 18 2.2.1 Fields...... 18 2.2.2 Ordinary Differential Equations and Differential and Alge- braicEquations...... 18 2.2.3 PartialDifferentialEquations...... 19 2.2.4 Boundary Conditions ...... 20 2.2.5 Initial Conditions ...... 21 2.2.6 Classification...... 21 2.3 Numerical Solution Methods ...... 22 2.3.1 Finite Difference Methods ...... 22 2.3.2 Finite Element Methods ...... 23 2.3.3 MethodofLines...... 25
3 A Modelica Library for PDE-based Modeling 27 3.1 Introduction ...... 27 3.1.1 Separation into Continuous and Discrete Parts ...... 28 3.2 Continuous Part Design ...... 28
ix Contents
3.2.1 Standard Boundaries ...... 30 3.3ThePackageDesign...... 31 3.4 Continuous Part ...... 34 3.4.1 Boundary Definition ...... 34 3.4.2 Domain Definition ...... 34 3.4.3 Fields...... 35 3.4.4 Included Boundaries ...... 36 3.4.5 EquationModels...... 42 3.4.6 Boundary Conditions ...... 44 3.5DiscretePartDesign...... 45 3.5.1 DomainDiscretization...... 46 3.5.2 ModelDiscretization...... 49 3.6TheFEMpackage...... 53 3.6.1 DiscreteDomain...... 54 3.6.2 DiscreteField...... 55 3.6.3 ThePoissonEquation...... 56 3.6.4 TheDiffusionEquation...... 56 3.6.5 PDELibraryInterface...... 56 3.7RheolefFiniteElementSolver...... 57 3.7.1 Forms...... 57 3.7.2 Boundary Conditions ...... 58 3.8TheFEMFormspackage...... 59 3.8.1 DiscreteField...... 59 3.8.2 Form...... 60 3.8.3 ThePoissonEquation...... 61 3.8.4 TheDiffusionEquation...... 61 3.8.5 PDELibraryInterface...... 61 3.9Example...... 62 3.10Discussion...... 67
4 Language Elements for Space-distributed Models 69 4.1 Introduction ...... 69 4.2Fields...... 70 4.2.1 FieldVariables...... 70 4.2.2 FieldConstructor...... 71 4.2.3 FieldTypeinExpressions...... 71 4.2.4 AccessingFieldValues...... 73 4.3 Future Language Extensions ...... 74 4.3.1 Domain Geometry Definition ...... 74 4.3.2 DifferentialOperators...... 78 4.3.3 DomainSpecifierinEquations...... 81 4.3.4 FieldReduction...... 82
x Contents
4.3.5 Discussion...... 83
5 Implementation 85 5.1ModelicaCompiler...... 85 5.1.1 ModelicaParser...... 86 5.1.2 ModelicaTranslator...... 88 5.2ThePDELibrary...... 94 5.2.1 TheFiniteElementPackage...... 95 5.3PDEModelicaSolverEnvironment...... 99 5.3.1 SpatialDiscretizationofEquations...... 99
6 Examples 105 6.1StationaryHeatTransfer...... 105 6.1.1 Neumann and Robin Boundary Conditions ...... 107 6.2Time-dependentHeatTransfer...... 108 6.2.1 HeatTransferwithController...... 109 6.3Discussion...... 110
7 Previous Approaches With Examples 113 7.1Mathematica-basedTranslator...... 113 7.1.1 SpaceVariables...... 113 7.1.2 DomainClasses...... 114 7.1.3 SolverGeneratorinMathematica...... 115 7.2Coefficient-BasedTranslator...... 116 7.2.1 Domains...... 116 7.2.2 Equations and Boundary Conditions ...... 117 7.2.3 ImplementationDetails...... 118 7.2.4 NumericalSolver...... 132 7.2.5 Issues with the Coefficient-Based Translator ...... 134
8 Related Work 137 8.1 Libraries and Programming Language-Based Packages ...... 137 8.1.1 Diffpack...... 138 8.1.2 Overture...... 138 8.1.3 Compose...... 138 8.2 High-Level Packages and Problem Solving Environments . . . . . 139 8.2.1 gPROMS...... 139 8.2.2 PELLPACK ...... 140 8.2.3 PDESpec...... 142 8.2.4 FEMLAB...... 142 8.3Discussion...... 143
xi Contents
9 Conclusion 145 9.1Summary...... 145 9.2Contributions...... 147 9.3FutureWork...... 148 9.3.1 ModelicaPDELibrary...... 148 9.3.2 Connectors...... 149 9.3.3 Language Implementation ...... 150
References 153
A UML Notation 159
B Plotting Simulation Results 161 B.1 Visualization of Domain Boundary ...... 161 B.2VisualizationofMeshes...... 161 B.3VisualizationofSteady-stateFields...... 161 B.4VisualizationofTime-dependentFields...... 162
xii Glossary
class A user-defined, reusable component type in Modelica, containing variables, instances of other classes, algorithms and equations. restricted class A specialized Modelica class, with some restrictions on the contents it may have, for example occurence of equations. extends Term used for subclassing of Modelica classes, for defining inheritance hierarchies of classes. modification In Modelica, a mechanism to change values of parameters, types of declared elements etc., while inheriting or instantiating a class. connector A specialized Modelica class to represent interfaces between compo- nents, that can be used with the connect operator to automatically generate equations. domain The definition domain of the independent variables. For time-dependent functions, the domain is the time interval where the variable is defined. For two or three-dimensional space-dependent functions, the domain is the two and three-dimensional geometric regions where the function is defined, re- spectively. boundary The bounding limit of the definition domain. field A function of independent variables, for example a space-dependent, two dimensional function f(x,y). field value Value of a field at a point in the definition domain. partial derivative Derivative of an expression or function with respect to one of the independent variables, e.g., one of the space coordinates. PDE Partial differential equation, i.e., an equation containing partial derivatives of functions. ODE Ordinary differential equation. containing functions of one independent variable and derivatives of functions and expressions with respect to that independent variable.
xiii Contents
DAE Differential and algebraic equations. An algebraic system of equations con- taining ordinary derivatives. boundary condition Conditions to determine a unique solution to a PDE, de- fined on the boundary of the definition domain where the PDE is solved. The PDE is usually valid only in the interior of the domain, while the boundary conditions give the values of the unknown or its derivatives on the boundary of the domain. initial condition In time-dependent equations, the starting values of the unknown variables, needed to determine a unique solution to the time-dependent prob- lem.
Dirichlet A type of boundary condition, specifying the value of the unknown vari- able on the boundary.
Newman A type of boundary condition, specifying the value of the derivative of the unknown variable on the boundary.
Robin A type of boundary condition, consisting of an equation containing both the unknown variable and its derivative. Also called mixed boundary condi- tion. elliptic Usually steady-state PDEs containing no time derivatives, e.g., the Pois- son equation. parabolic Usually time-dependent PDEs containing first-order time derivatives, e.g., the time-dependent heat transfer equation. hyperbolic Usually time-dependent PDEs containing second-order time deriva- tives, e.g., the wave equation. stationary (steady-state) The time-independent equation, corresponding to the time-dependent equation with the time elapsed enough long so that the solu- tion becomes time-independent, e.g., the transients have vanished.
finite difference An approximation of the derivative using the derivative defini- tion and the values of the unknown at discrete grid points and the distance between the grid points. central difference A finite difference method using discrete values from both previous and next discrete point. forward difference A finite difference method using discrete values from the next discrete point.
xiv Contents backward difference A finite difference method using discrete values from the previous discrete point. finite difference method A method to solve PDE problems using finite differ- ences to approximate partial derivatives and solve the resulting equation sys- tems. finite element method (FEM) A method to solve PDE problems by subdivid- ing the domain in for example triangles and expressing the unknown in terms of known basis functions and solving the resulting equation systems. method of lines A method to solve time-dependent PDE problems by replacing the time- or space-dependent parts of the equations with discrete formula- tions, resulting in a only time- or only space-dependent problem. In this work, spatial discretization is used, generating DAEs from time-dependent PDEs.
xv Contents
xvi Chapter 1 Introduction
“Its five year mission: To explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.” Captain Kirk, Starship Enterprise
In mathematical modeling of physical systems, the behavior of a system is typi- cally modeled using differential equations or a system of differential and algebraic equations, i.e. algebraic equations containing derivatives. For large scale models, some properties of the physical system that is modeled are often approximated; for example when controlling the temperature of a fluid in a container, the temperature can be assumed to be the same everywhere inside the container. This way, the space dependency is eliminated, resulting in models con- taining only ordinary differential equations (ODEs), or differential and algebraic equations (DAEs), i.e. equations where all derivatives are with respect to time only. This greatly simplifies the solution of the equations and the simulation. However, sometimes a more detailed model with explicit space dependency is needed for the whole or some part of the system. Such space-dependent models are used to study the behavior in more detail, and contain partial derivatives, i.e., derivatives with respect to space variables like x, y and z in a Cartesian coordinate system. Differential equations containing partial derivatives are called partial dif- ferential equations (PDEs), and are used in many fields to model physical behavior, for example structural mechanics, computational fluid dynamics, and electrostat- ics. There are many tools for modeling and simulation with ordinary differential equations as well as with partial differential equations. Most are however spe- cialized for certain application domains or special kinds of models.
1 Chapter 1 Introduction
An effort to define a general, application domain and tool-independent model- ing language is made by Modelica Association, with the Modelica language as a result. Modelica® [1, 2] is a standard language designed for component-based modeling, where previously defined models can be reused as components in new models. Object oriented constructs, equation-based and declarative modeling sup- port, as well as a connection concept make this possible. Currently, Modelica only supports models with ordinary differential equations, algebraic equations, discrete equations, hybrid (mixed time-discrete and time-continuous) equations but not par- tial differential equations. Several Modelica implementations and simulation tools exist [3,4]. Thanks to the progress in computer performance, the use of detailed models con- taining partial differential equations is becoming increasingly common. The aim of this work is to define a language based on Modelica, in order to handle partial differential equations in models in addition to differential and algebraic equations. This language is called PDEModelica, and this thesis discusses the initial language extensions needed for the desired support.
1.1 PDE-based Model Example
Consider a simplified model of heat distribution in a room where only the distri- butioninthex and y directions is studied and the temperature in the z direction is assumed to be constant. A heater is installed on one of the walls and there is a window on another wall. The domain of this problem, i.e., the region (including geometry) on which it is defined, can be seen in Figure 1.1. A heater is represented by assigning constant temperature boundary condition to the middle part of the upper wall. The window is modeled by non-zero heat flow through the left wall. The heat flow is proportional to the temperature difference between the inside tem- perature and the outside temperature. The rest of the walls are insulated, i.e., no heat flow occurs through these walls. The right wall is curved in order to illustrate modeling with complex geometries. Heat transfer by conduction in two dimensions can be modeled using Poisson’s equation:
∂2T (x, y) ∂2T (x, y) −( + )=g(x, y) on Ω ∂x2 ∂y2 The possible boundary conditions are the following:
• Dirichlet1 boundary condition for the heated wall:
T (x, y)=h1(x, y) on ∂Ω
1The value of the unknown variable is known on the boundary. See also Section 2.2.4.
2 1.1 PDE-based Model Example
Heater
top3top2 top1
h Window right left y
bottom x
w
Figure 1.1: Example of time-dependent heat transfer by conduction.
•Neumann2 boundary condition for insulated walls: ∂T(x, y) = h2(x, y) on ∂Ω ∂n
• Robin3 (also called mixed) boundary condition for the window which is not perfectly insulated: ∂T(x, y) + qT(x, y)=h3(x, y) on ∂Ω ∂n If heat distribution over time is studied, a time derivative is added to the Laplace equation which gives the heat diffusion equation: ∂T(x, y, t) ∂2T (x, y, t) ∂2T (x, y, t) ρC − k( + )=g(x, y, t) on Ω ∂t ∂x2 ∂y2 with ρ, C and k being material constants, and a given initial condition:
T (x, y, 0) = T0(x, y) on Ω
This problem can be modeled in PDEModelica with the geometry and the model description shown in Figure 1.2. The domain geometry is defined by describing
2The value of the outward normal derivative of the unknown variable is known on the boundary. The outward normal derivative is the space derivative in the outward normal direction. See also Section 2.2.4. 3A linear combination of the unknown variable and its outward normal derivative is known on the boundary. See also Section 2.2.4.
3 Chapter 1 Introduction its boundary in a specific direction in order to find out on what side of the bound- ary the actual domain is. The boundary is built up of several sections defined as named components in the domain description. Hence, when defining the PDE model, boundary conditions can be assigned to each section using the name of each boundary component. The definition of the boundary conditions and the PDE are not shown in this example; they can be defined as described in Chapter 4. The solution to a similar example can be found in Section 6.2.1.
1.1.1 Connection to ODE/DAE models
A system with active temperature control can be modeled using a time-dependent model as shown in the previous section. A temperature sensor can be approximated by reading the computed temperature at some point in the domain, and the temper- ature can be used as input to a heat controller. The model overview is illustrated in Figure 1.3, and the PDEModelica code is listed in Figure 1.4. The controller is a proportional, integrating controller (PI-controller), which contains an ordinary differential equation:
T = T − T error sensor goal
Theater(t)=kpTerror + ki Terror dt
The resulting problem consists of a PDE part modeling temperature distribution, and an ODE part modeling the controller. This can be compared to a simplified, lumped system where the temperature is assumed to be the same at all points, i.e. where the temperature distribution in the domain is instant. Temperature dis- tribution in such a system is modeled using an ODE-based model, resulting in a complete system with only ODEs. However, if a more realistic temperature model is used, involving PDEs, where spatial variation in temperature is studied as well, coupled ODE and PDE models are needed. Spatial dependency can then be re- moved by spatial discretization as a first step, using the method of lines, resulting in an equation system of ODEs also for the spatially distributed temperature model. Thus, the final discretized system will only contain ODEs which is solved using ex- isting ODE/DAE solvers. This example is simplified by the fact that the sensor is replaced with a simple field access to read the temperature value. The connection between the controller and the PDE model is accomplished manually by writing down the equations. In the future, the connection between PDE and ODE models can be more complex, using connectors and field reduction, see Section 4.3.4 and Section 9.3.2.
4 1.1 PDE-based Model Example
class CurvedRectangular "Geometry" extends Cartesian2D (boundary={bottom , right , top1 , top2 , top3 , left });
parameter Point p0; parameter Real w; parameter Real h; parameter Real cw;
parameter Real ch=h; parameter Point cc=p0 + {w,h/2};
Line2D bottom (p1=p0 , p2=p0 + {w,0}); Line2D top1 (p1=p0 + {w, h} , p2=p0 + {2*w/3 ,h }); Line2D top2 (p1=p0 + {2*w/3 ,h} , p2=p0 + {w/3 ,h }); Line2D top3 (p1=p0 + {w/3 , h} , p2=p0 + {0 ,h }); Line2D l e f t (p1=p0 + {0 ,h} , p2=p0 );
Bezier2D right (n=8, p= f i l l (cc , 8) + {{0.0,−0.5}, {0.0,−0.2}, {0.0 ,0.0} , { −0.85,−0.85}, { −0.85,0.85}, {0.0 ,0.0} , {0.0 ,0.2} , {0.0 ,0.5} } *{{cw,0},{0 ,ch}}); end CurvedRectangular ;
model Diffusion "Heat diffusion with heater" ... import Modelica . SIUnits . Temperature ; parameter Temperature heaterValue ; parameter Real h_3 ; parameter Real q; CurvedRectangular omega; Diffusion2D pde(domain=omega); equation der( pde .u , n) = 0 on omega . bottom ; der( pde .u , n) = 0 on omega . right ; der( pde .u , n) = 0 on omega . top1 ; pde.u = heaterValue on omega. top2 ; der( pde .u , n) = 0 on omega . top3 ; der( pde .u , n) + q* pde . u = h_3 on omega . l e f t ; end Diffusion ;
Figure 1.2: The PDEModelica code to define the heat diffusion problem in Sec- tion 1.1. Predefined PDE model Diffusion2D and detailed parameter declarations have been left out. The syntax is explained in Chapter 4.
5 Chapter 1 Introduction
PI-Controller
Heater
Glass layer Sensor
Figure 1.3: A coupled PDE and ODE model. Time dependent heat transfer model with a controller.
1.2 Research Method
The research method used in this work can be called explorative design [5]. The approach starts with a design hypothesis which is believed to be a possible solution to the problem. A prototype implementation of this design is developed. During implementation, flaws in the design are discovered and new knowledge about the problem is acquired. The implementation is modified to handle these issues. Thus, the system that is implemented differs from that in the original design. On the other hand, the implementation also differs from the one that would have been implemented from start using the new knowledge. For this reason, at some point, the prototype is discarded and a new design and prototype are developed. See Figure 1.5 for an illustration of the work flow when using this method.
Thus, important parts of the research results are the original design, the actual implemented prototype, and a proposed, improved design. In this thesis, we present the previous iterations of the design and implementation in Chapter 7. The final design of PDEModelica in this thesis work is presented in Chapter 4 and the final implementation is described in Chapter 3 and Chapter 5.
6 1.2 Research Method
class CurvedRectangular "Geometry" extends Cartesian2D (boundary={bottom , right , top1 , top2 , top3 , left });
parameter Point p0; parameter Real w; parameter Real h; parameter Real cw;
parameter Real ch=h; parameter Point cc=p0 + {w,h/2};
Line2D bottom (p1=p0 , p2=p0 + {w,0}); Line2D top1 (p1=p0 + {w, h} , p2=p0 + {2*w/3 ,h }); Line2D top2 (p1=p0 + {2*w/3 ,h} , p2=p0 + {w/3 ,h }); Line2D top3 (p1=p0 + {w/3 , h} , p2=p0 + {0 ,h }); Line2D l e f t (p1=p0 + {0 ,h} , p2=p0 );
Bezier2D right (n=8, p= f i l l (cc , 8) + {{0.0,−0.5}, {0.0,−0.2}, {0.0 ,0.0} , { −0.85,−0.85}, { −0.85,0.85}, {0.0 ,0.0} , {0.0 ,0.2} , {0.0 ,0.5} } *{{cw,0},{0 ,ch}}); end CurvedRectangular ;
model ControlledDiffusion "Heat diffusion with controlled heater" ... import Modelica . SIUnits . Temperature ; parameter Temperature goalValue ; parameter Real h_3 ; parameter Real q; // Use PI regulator from Standard Library Modelica . Blocks . Continuous . PI regulator ; CurvedRectangular omega; Diffusion2D pde(domain=omega); Temperature heaterValue ; Temperature sensorValue ; equation der( pde .u , n) = 0 on omega . bottom ; der( pde .u , n) = 0 on omega . right ; der( pde .u , n) = 0 on omega . top1 ; pde.u = heaterValue on omega. top2 ; der( pde .u , n) = 0 on omega . top3 ; der( pde .u , n) + q* pde . u = h_3 on omega . l e f t ; heaterValue = regulator .y[1]; regulator . inPort . signal [1] = goalValue − sensorValue ; sensorValue = pde.u(2.61, 2.33); end ControlledDiffusion ;
Figure 1.4: The PDEModelica code to define the heat diffusion problem with a con- trolled heater in Section 1.1.1. Predefined PDE model Diffusion2D and detailed parameter declarations have been left out. The syntax is explained in Chapter 4.
7 Chapter 1 Introduction
Iterations
Design Modified Improved Hyptohesis Design Design Hyptohesis Hyptohesis
New knowledge
Prototype implementation
Figure 1.5: Explorative design.
1.3 Contributions
The result of this work is two-fold. First, a design and implementation of a Model- ica library for PDEs is presented, which illustrates the concepts needed to specify and simulate PDE-based models. Second, a design and a partial implementation of language extensions for the Modelica language is presented, which integrates the concepts from the PDE library into the Modelica language. The proposed lan- guage design for an object-oriented modeling language, PDEModelica, supports the following: • Object-oriented, component-based modeling with PDEs. • General, complex geometry description with lines, polygons, parametric curves and a combination of these. • Component-based geometry definition, i.e., separation of geometry defini- tion from model definition. • Separation of analytical, continuous model description from discretization and numerical solution. • Field concept for general declaration of spatially distributed variables inte- grated in the language.
8 1.4 Overview of the Thesis
• Clear, mathematical syntax for equations containing fields and explicit do- main specification. • Hierarchical modeling and decomposition. • Modeling of combined ODE/DAE and PDE problems. We believe that the combination of these aspects in a single modeling language is rather new. See also the discussion and comparison to other related systems in Section 8.3. A prototype translator and solver environment is set up as well, with a basic PDE solver interface for adding new solvers and mesh generators. Some of the work discussed in this thesis has been published previously in the following publications:
1. L. Saldamli and P. Fritzson. Object-Oriented Modeling with Partial Differ- ential Equations. In Proceedings of the Modelica Workshop 2000, Lund, Sweden, October 2000 [6]. 2. L. Saldamli and P. Fritzson. A Modelica-Based Language for Object-Orient- ed Modeling with Partial Differential Equations. In Proceedings of the 4th International EUROSIM Congress, Delft, The Netherlands, June 2001 [7]. 3. L. Saldamli and P. Fritzson. Domains and Partial Differential Equations in Modelica. In Proceedings of the 42nd SIMS Conference, Porsgrunn, Norway, October 2001 [8]. 4. L. Saldamli, P. Fritzson and B. Bachmann. Extending Modelica for Partial Differential Equations. In Proceedings of the 2nd International Modelica Conference, Oberpfaffenhofen, Germany, March 2002 [9]. 5. L. Saldamli and P. Fritzson. Field Type and Field Constructor in Model- ica. In Proceedings of SIMS 2004, the 45th Conference on Simulation and Modelling, Copenhagen, Denmark, September 2004 [10]. 6. L. Saldamli, B. Bachmann, H Wiesmann and P. Fritzson. A Framework for Describing and Solving PDE Models in Modelica. In Proceedings of the 4th International Modelica Conference, Hamburg, Germany, March 2005 [11].
Section 4.3 contains material not previously published.
1.4 Overview of the Thesis
This thesis is organized as follows. Chapter 2 contains background information rel- evant for the thesis: a short overview of the Modelica language, a basic introduction
9 Chapter 1 Introduction to partial differential equations and some existing numerical solution methods for partial differential equations. Chapter 3 describes a PDE library consisting of Modelica packages written us- ing standard Modelica. The PDE library can be used to describe and solve PDE models on general domains using the finite element method and the method of lines discretization. Chapter 4 presents proposed extensions to the Modelica language for definition of space-distributed models, e.g. models containing fields and partial derivatives. Chapter 5 contains the implementation details. The PDE library, prototypes for language extensions and the interface to external solvers are described here. Chapter 6 contains examples to demonstrate the use of the PDE library and the language extensions. Chapter 7 discusses the previous design iterations that were implemented and tested. Chapter 8 presents an overview of related work. Different low- and high-level tools with varying modeling language support are summarized here. Finally, some conclusions and possible future work directions are discussed in Chapter 9.
10 Chapter 2 Background
“Logic is the beginning of wisdom; not the end.” Mr. Spock
The basic concepts of Modelica are presented in the first part of this chapter. In the second part, the topic of partial differential equations (PDEs) and classifica- tion of PDEs are briefly presented, and finally an overview of different numerical solution methods is given.
2.1 Modelica
Modelica [2, 12] is a modeling language for equation-based, object-oriented mod- eling and simulation of physical systems. Using object-oriented concepts, it allows hierarchical, component-based modeling which in turn makes reuse of existing models possible. The general modeling concepts in Modelica allow it to be used in different application domains and in multi-domain modeling, for example when defining a combined electrical and mechanical model. There is a free Modelica Standard Library [13] and other free Modelica libraries with packages of existing models from different domains that can be used as components in specific models. Acausal modeling, i.e., modeling using equations - not assignment statements, al- lows single models to be used in different data flow contexts since variables are not explicitly declared as input or output. This causality information is rather derived from the context where the model is used. In his PhD thesis [14], H. Tummescheit discusses design and implementation of modeling libraries using Modelica.
11 Chapter 2 Background
Models in Modelica are built hierarchically from sub-models that are defined separately, which in turn can be defined in the same way. Hence, a model can con- tain one or more instances of other models with a different set of parameter values for each instance, and a set of connections between these components/instances. Additionally, each model can have variables of built-in types, and equations that define the relationship between these variables as well as between variables in sub- models.
2.1.1 Classes The basic structural unit in Modelica is class. A class can contain other classes, variable declarations, equations, and algorithms. An example of a class can be seen in Figure 2.1. Other keywords can be used to denote classes, restricted classes that are special cases of classes with some restrictions. These are record, type, connector, model, block, package and function. Different restricted classes and restrictions that apply to them can be seen in Table 2.1.
model MyModel "Short description of this model" Real x,y; equation x+y=5; x + 2y = 11; end MyModel ;
Figure 2.1: Example of a Modelica class.
2.1.2 Variable Declarations Variable declarations consist of a type and a variable name. The type can be one of the primitive types or another class name. The primitive types are Real, In- teger, String, Boolean and Enumeration. Each declaration can also have type modifiers, such as the variability type prefix constant, discrete,orpa- rameter, or a causality prefix, input or output, used in function and block classes to declare the direction of a variable. Variables with the constant or parameter prefix keep their value constant during a simulation, i.e., they are constants. The difference between parameters and constants is that values of parameters can be changed before each simula- tion without needing to recompile the Modelica code. An exception is structural parameters , which require recompilation of the model because they change the model structure. A parameter used as number of components in an array declara- tion is an example of a structural parameter. Parameters also appear in tool menus
12 2.1 Modelica
Table 2.1: Restricted classes in Modelica. Restricted class Restrictions record No equations are allowed. type May only be used to extend primitive types, enumerations, or records. connector No equations are allowed. model Model instances may not be used in connections. block Fixed causality. Each variable must be declared as input or output. package May only contain classes and constants. Is allowed to import from. function Similar to block. No equations, at most one algorithm section. May be called using positional arguments. May be recursive. to allow the user to change them before simulation. Variables of type Real de- clared without the constant or parameter modifiers are implicitly time-dependent, i.e. functions of time. Time derivatives of variables can be represented using the der() operator. Using the time derivatives, ordinary differential equations can be expressed, and full systems of differential and algebraic equations (DAEs) can be specified.
2.1.3 Subtyping and Inheritance Modelica models can be defined using inheritance. The extends clause is used together with a class name to inherit that class. Multiple inheritance is allowed us- ing several extends clauses, one for each inherited class. Inheritance is equiva- lent to inserting the contents of the inherited class at the place where the extends clause resides. Type equivalence in Modelica is defined as follows: Two types T and U are equivalent if and only if
• they denote the same primitive type (see Section 2.1.2), or
• T and U are classes containing the same elements (according to their names) and the elements types are equivalent.
Subtypes in Modelica are defined independently from the inheritance mecha- nism. A class C is a subtype of a class S if
• S and C are type equivalent, or
13 Chapter 2 Background
• both of the following statements hold: – every public element of S also exists in C (according to its name). – the type of each such element in C is a subtype of the type of the corre- sponding element in S. If a class C is a subtype of a class S then S is called the supertype of C. Subtypes and supertypes do not necessarily need to be in an inheritance hierarchy, but a class that is inherited from, a base class, is a supertype of a class that inherits from it, a derived class. An example is shown in Figure 2.2.
partial model OnePort Pin p ,n; Voltage v "Voltage drop"; equation v=p.v− n.v; p.i + n.i = 0; end OnePort ;
model Resistor ; extends OnePort ; parameter Real R( unit="Ohm" ) "Resistance "; equation v=p.i * R; end Resistor ;
model TempResistor "Temperature dependent resistor " extends OnePort ; parameter Real R( unit="Ohm" ) "Resistance at reference temperature "; parameter Real RT( unit="Ohm/ degC" )=0 "Temperature dependent resistance "; parameter Real Tref ( unit="degC")=20"Reference temp . "; Real Temp = 20 "Actual temperature "; equation v=p.i * (R + RT * (Temp − Tref )); end TempResistor ;
Figure 2.2: Subtyping in Modelica. TempResistor does not inherit from Re- sistor, but it is a subtype of Resistor. They both inherit from OnePort.
The TempResistor class cannot extend the Resistor class because it has a different equation in the equation section, but it is still a subtype of Resistor because it contains all the elements in Resistor, and additional elements. Both classes inherit from the OnePort1 class, though.
1The term OnePort is used by specialists in the electrical modeling community to denote electrical
14 2.1 Modelica
2.1.4 Modifications
A modification in Modelica is a short-hand Modelica syntax for expressing class specialization. For example, the modification compa(pa=1) in ModelB in Figure 2.3 expresses that the equation pa=0 in ModelA should be replaced by the equation pa=1 to create a temporary, specialized class derived from ModelA and used for creation of the compa instance. Since models are built up hierarchically, modifications can be overridden, in which case the topmost (outermost) modification is applied. A modification can also be hierarchical, in order to modify a lower level parameter directly. Each modification consists of a component reference and an expression that is evaluated in the context where the declaration resides. Example of modifications can be seen in Figure 2.3. Declarations preceded by the final keyword are final elements and cannot be modified using modifications. The final keyword can also precede modifications, in which case it prevents further modifications of that variable in outer modifications.
model ModelA parameter Real pa = 0; // default value end ModelA ;
model ModelB ModelA compa ( pa =1); // modification parameter Real pb = 0; end ModelB ;
model MyModel parameter Real mypa=3 , mypb=4; // hierarchical modification ModelB compb ( pb=mypb , compa ( pa=mypa ) ) ; end MyModel ;
Figure 2.3: Modifications in Modelica. The resulting value of the variable compb- .compa.pa is mypa, i.e., 3.
Modifications can also be applied directly when extending a class, in the ex- tends clause. For example:
model MyNewModel extends MyModel(mypb =5);
When instantiating components of MyNewModel the default value of mypb will be 5.
components with two physical connection points, i.e., two physical ports.
15 Chapter 2 Background
2.1.5 Equations and Algorithms The keywords equation and algorithm denote equation and algorithm sec- tions, respectively. There can be several such sections of each kind in a class. During compilation, all equation sections are merged into a single equations sec- tion. Equation sections can contain standard equation clauses, connect equations, con- ditional equations, for equations and when equations. Standard equations consist of two expressions and the equality operator denoted by =. The assignment oper- ator := is not allowed in equation sections, whereas the equality operator = is not allowed in algorithm sections. Besides the common operators like arithmetic operators and function calls, Modelica has if-expressions, which can be used in situations like: equation x= if (z > 0) 2* z else (−2*z); Connect equations consist of the connect() operator with two arguments that are references to connectors. Connectors are instances of connector restricted classes and usually contain two kinds of variables, flow (e.g. current) and non-flow (e.g. potential) variables, the former being denoted by the flow keyword. Connect equations are translated into standard equations during compilation, where for each connection the non-flow variables of the involved connectors are set equal, and the sum of all the flow variables is set to be equal to zero. Figure 2.4 illustrates the use of connectors and connections, and the resulting equations. Conditional equations can be written using the if-elseif-else construct with equations in the body. for equations are useful for repetitive equation struc- tures involving arrays, whereas when equations and when statements are used for discrete event simulation. Algorithm section can contain assignments, conditional statements, for-loops, while-loops and when-statements. The difference from equation sections is that algorithm sections contain assignments instead of equations, and the contents of the algorithms are executed sequentially. An assignment consists of a variable reference as the left-hand side, the assignment operator := and an expression as the right-hand side.
2.1.6 Replaceable Elements Elements in classes in Modelica can be declared as replaceable, in which case they can be replaced by another type of element that is type compatible when the containing class is extended or instantiated. Generic classes with type parameters is supported in Modelica through the replaceable mechanism. The type restriction of a redeclaration is that the new declared type must be a subtype of the original declared type, a constraining type.
16 2.1 Modelica
A B
p p
p
C
(a) Visual view of a connector and connection example.
connector Pin "Electrical pin" flow Current i ; Voltage v; end Pin ;
model OnePin Pin p; end OnePin ;
model Test OnePin a , b , c ; equation connect (a.p, b.p); connect (b.p, c.p); end Test ;
(b) Textual view of a connector and connection example.
equation a.p.i + b.p.i + c.p.i = 0; a.p.v = b.p.v; b.p.v = c.p.v;
(c) Resulting equations
Figure 2.4: Example of connectors and connections and the resulting simple equa- tions after compilation.
17 Chapter 2 Background
2.2 Differential Equations
Differential equations are commonly used in mathematical models of physical phe- nomena that are distributed in time and/or space. Examples include heat transfer, fluid flow, structural mechanics, wave propagation, etc. Such mathematical models relate certain variables, called dependent variables, and their derivatives to other variables, called independent variables. For example the time variable or space coordinates occur commonly as independent variables.
2.2.1 Fields A field is a mapping from a domain to scalar or vector values. The geometrical region, i.e., the domain where the field is defined, is called the fields definition domain. A field can be seen as a continuous variable distributed in spatial coordi- nates. Example of a scalar field and a vector field can be seen in Figure 2.5. The scalar field is a mapping R2 → R while the vector field is a mapping R2 → R2, i.e. for each tuple (x, y), the fields give a value u and (u, v), respectively. u
v
u
y y
omega omega x x
Figure 2.5: Two examples of fields. A scalar field defined on two-dimensional do- main is depicted on the left. A vector field defined on the same domain can be seen on the right.
2.2.2 Ordinary Differential Equations and Differential and Algebraic Equations In some cases a variable that is distributed in space and/or time, e.g. a temperature field, can be approximated by a scalar variable. For example, when the temperature of a fluid in a container is studied, the temperature could be assumed to be the same throughout the entire container at each specific time instant, and one can study the temperature change as a function of time based on the incoming and outgoing fluid flow. Since the simplified model depends only on one variable, time, derivatives that occur are time derivatives, and the equations of the model
18 2.2 Differential Equations are ordinary differential equations (ODEs) or differential and algebraic equations (DAEs).
2.2.3 Partial Differential Equations In more detailed models when the temperature distribution over the container is studied, with different temperature values at different positions inside the container, the temperature is a function of the independent variables. representing the space coordinates inside the container, and also of the time variable if time-dependent be- havior is studied. Derivatives that occur in such models can be partial derivatives , i.e. derivatives with respect to one of the space variables or the time variable. Dif- ferential equations involving partial derivatives are thus called partial differential equations (PDEs). If the equations contain the time variable or any time-dependent variable, the problem is called time-dependent, otherwise it is called stationary. The order of a partial differential equation is defined as the highest differentia- tion order that occurs in that equation. The most commonly used PDEs in models of many practical systems are second-order PDEs, containing second order deriva- tives. A partial derivative can be stated in different ways. The first-order partial derivative of a dependent variable u with respect to the independent variable x is represented using the following three variants of mathematical notation:
∂u = ∂ u = u ∂x x x A second order derivative can be written accordingly as
∂2u = ∂ u = u ∂x2 xx xx The second differentiation can be done with respect to a different variable y than the first differentiation, e.g. ∂xyu = uxy, which is also a second order derivative, a mixed partial derivative. A general, second order PDE with an unknown dependent variable u and the independent variables x and y can be stated as
f(u, ux,uxx,uy,uyy,uxy,uyx,x,y)=0 (x, y) ∈ Ω (2.1)
The definition domain, i.e., the geometric region on which the PDE is defined, denoted Ω, is an open2 and in most cases bounded region in space as defined by the independent variables, see Figure 2.6.
2An open region is a region where any point in the region can be enclosed by a ball that is completely inside the region.
19 Chapter 2 Background
n
∂Ω Ω
Figure 2.6: The definition domain Ω, its boundary ∂Ω and the outward normal vec- tor n.
2.2.3.1 Vector notation The differential operators gradient and divergence are commonly used to express PDEs using vector notation. These operators are dimension and coordinate name independent. The gradient operator is defined as follows: ∂(u) ∂(u) ∇u = grad u(x1,...,xn)= ... ∂x1 ∂xn The divergence operator is defined as follows:
∂u1 ∂un ∇·u = div u(x1,...,xn)= + ...+ ∂x1 ∂xn
2.2.4 Boundary Conditions Boundary conditions in a PDE problem specify the behaviour of the model on the boundary of the domain Ω, denoted ∂Ω, and usually contain derivatives of one order less than the PDE. A general boundary condition corresponding to Equa- tion (2.1) can be expressed as
g(u, ux,uy,x,y)=0 (x, y) ∈ ∂Ω (2.2) Boundary conditions usually contain a directional derivative instead of the partial derivative with respect to one variable. A common directional derivative is the outward normal derivative, which is obtained by the scalar product of the outward normal on the domain boundary and a vector of the partial derivatives. The outward normal derivative is denoted ∂n and is commonly used in boundary conditions to specify e.g. heat flux through the boundary.
20 2.2 Differential Equations
Three kinds of boundary conditions that often occur have been given special names:
Dirichlet : u = h1 on ∂Ω
: ∂ = Ω Neumann ∂nu h2 on ∂
: ∂ + = Ω Robin ∂nu qu h3 on ∂
In cases where the right-hand side is zero, the corresponding condition is called homogeneous,otherwisenon-homogeneous.
2.2.5 Initial Conditions Initial conditions are needed in order to find a unique solution to a time-dependent differential equation. Due to the zero derivatives of constants, infinite number of solutions can satisfy a differential equation. Giving the value of the dependent vari- able at some point in time, usually time value where simulation starts, the constant can be determined and a unique solution can be found.
2.2.6 Classification PDEs are classified based on linearity properties. An equation expressed using the linear operator3 L() in the form
L(αu + βv)=f is linear if L(αu + βv)=αL(u)+βL(v) If a PDE with the dependent variable u and the independent variables x and y can be expressed in the following form:
auxx +2buxy + cuyy = d (2.3) where the coefficients a, b and c are constants, the PDE is linear. If the coefficients are functions of the independent variables only, x and y in this example, the PDE is semi-linear, and if the coefficients also depend on u or its first-order derivatives the PDE is quasi-linear. Equations that cannot be expressed linearly in the second order derivatives as in Equation (2.1) are nonlinear. In this text, semi-linear PDEs will be regarded as linear, while quasi-linear PDEs will be classified together with the nonlinear. 3An example of a linear operator is the derivative operator.
21 Chapter 2 Background
Equation (2.3) is classified further into three categories depending on the value of b2 − ac: Elliptic : b2 − ac < 0
Parabolic: b2 − ac =0
Hyperbolic : b2 − ac > 0
Elliptic equations typically occur in stationary heat conduction models, whereas parabolic equations arise in time-dependent models. The wave equation used for modeling propagation of waves such as sound waves in gas or electro-magnetic waves is an example of a hyperbolic equation.
2.3 Numerical Solution Methods
A very small number of PDE problems can be solved symbolically, and even fewer of these are solvable with practically useful boundary conditions. For this rea- son, much research has been done on numerical solution of PDEs and different methods have been developed. Unlike the case for solution of ordinary differential equations, there is no unified method for solution of general PDE problems, how- ever, and an appropriate numerical solver must be selected for the specific kind PDE being solved. The solution method depends on whether a stationary or a time-dependent PDE is solved. Only space discretization is needed for stationary problems, whereas time-dependent problems need both space and time discretization. The methods described below can be used for both these cases. Discretization of only time or space variables can be done as well. For example, an equation can be discretized with respect to space coordinates, leaving a system of algebraic equations contain- ing only time derivatives (the method of lines). Time-dependency can be removed similarly, replacing time derivatives with a finite difference, leaving a stationary PDE problem which can be solved iteratively at different time steps. Space discretization is performed in different ways, depending on the numerical solution method. The finite difference method requires a grid, which is usually regular, i.e., with equidistant discrete points. This also requires that the definition domain is rectangular. The finite element method can be used on more general domains, because the domain is discretized using a triangular mesh.
2.3.1 Finite Difference Methods In order to find the unknown function, the domain, i.e. the geometry on which the problem is defined is discretized into a set of grid points and the values of the
22 2.3 Numerical Solution Methods function at these points are calculated. When the domain is discretized, the partial derivatives can be approximated by equations using the values at the grid points. Using Taylor’s theorem, different approximations can be derived [15]. The first- order derivative of u with respect to x using a grid with the distance h between the points can be approximated by for instance: ∂u u(x + h) − u(x − h) = + O(h2) ∂x 2h Here, O(h2) represents the approximation error. This equation is called a central- difference approximation. Other approximations can be derived, for example ( + ) − ( ) ∂u u x h u x ∂x h which is called a forward-difference formula, and ( ) − ( − ) ∂u u x u x h ∂x h which is called a backward-difference formula. Higher-order derivatives can be ap- proximated similarly. The derivatives in the PDE are then replaced by the approx- imations and repeated for each grid point, generating an equation system with the values of u at the grid points as unknowns. The boundary conditions are applied at the grid points neighboring the boundary, depending on the kind of boundary con- ditions. With Dirichlet boundary conditions, the values on the boundary are known and can be used directly. With Neumann and Robin conditions, the derivative is ap- proximated in the same way as in the PDE and equations involving the grid points outside the domain are generated, that can be used to express the unknown values on the boundary. When solving time-dependent problems, the time derivatives can be approxi- mated with finite differences as well. Note however that especially when using finite difference methods, the discretization steps must be chosen according to cer- tain conditions in order to maintain numerical stability during simulation.
2.3.2 Finite Element Methods A common way of solving a PDE numerically is to approximate the dependent variable u with a function uˆ belonging to a finite dimensional space with known basis functions βk(x), also called trial functions. Using a vector space of dimen- sion N, the approximate function is defined as