Modeling and Simulation in Engineerging Using Modelica
Modeling and Simulation in Engineerging Using Modelica
in Engineering Using
Modelica
www.uned.es/publicaciones
Modelica code
Preface
I Continuous-time modeling
Lesson 1 Modeling methodology and tools
1.1 Introduction
1.2 Physical modeling paradigm
1.3 Object-oriented modeling
1.4 Modeling environments
1.5 Getting started with Modelica
1.6 Further reading
Subject Index
References
9.3. Model of the two-tank and valve system shown in Figure 9.9.
9.4. Bouncing ball model shown in Figure 9.11.
9.5. LibFriction library (1/3)
9.6. LibFriction library (2/3)
9.7. LibFriction library (3/3)
9.8. Heat transfer in the three-layer wall shown in Figure 9.16.
9.9. Heat transfer in the wall, with the B material divided into layers
Preface
The important advances made in the fields of computer hardware and numerical
methods in the 1980s paved the way for the development of general-purpose (i.e.,
not tied to any specific physical domain), equation-based, object-oriented modeling
languages in the early 1990s. These languages were intended to facilitate the des-
cription of physical system models, where phenomena in different physical domains
(e.g., electrical, mechanical, thermo-fluid and chemical) appear interrelated. The
target models, the so-called hybrid DAE models, were dynamic mathematical models
described in terms of ordinary differential equations with derivative with respect to
time, algebraic equations, and events.
In those first years, the use of object-oriented modeling languages was restricted
to some academic groups, mainly in the field of Control Engineering. The coexistence
of a plethora of modeling languages led to dispersion of the efforts in the development
of software tools and model repositories. Similar model libraries were programmed by
different developers from scratch, being unfeasible to reuse code previously made by
others because the models were written in different languages. Likewise, as dedicated
modeling environments (i.e., software tools for editing and simulating models) were
developed for each modeling language, improvements in a software tool were not
easily applicable to other tools and only a reduced number of users were benefited
by them.
The advisability of having a standard object-oriented modeling language that
facilitates the exchange of models among different developers and tools was recog-
nized, and a design group was established in 1996 to propose such a language.
The design group was composed of people who already have been involved in the
design of other modeling languages or the programming of model libraries, and of
people from industry. The proposed modeling language, which was named Modelica,
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The third part of the book is devoted to discuss hybrid modeling and simulation
in Modelica. The formal specification of hybrid models, and the relationship of
this specification with the simulation algorithm and the Modelica description, are
described in Lesson 7. Numerical methods for event detection and handling are
discussed in Lesson 8. Once again, simplicity has been favored over mathematical
rigor. The objective is to provide the reader with the minimum knowledge required
to understand the issues associated with the description of events, and variable
structure models in Modelica. The goal is not to explain how to implement a
simulator, but to explain how to design and implement models that can be simulated
efficiently, without causing errors. Finally, the language features for describing time
and state events, and runtime changes in the model mathematical description, are
illustrated by a series of examples in Lesson 9.
Learning objectives
After studying the lessons and completing the proposed activities, students should
be able to:
– Use Dymola and OpenModelica for editing, debugging and translating Mo-
delica models, experimenting with the models and analyzing the simulation
results.
Continuous-time modeling
Lesson
1
1.1 Introduction
1.2 Physical modeling paradigm
1.3 Object-oriented modeling
1.4 Modeling environments
1.5 Getting started with Modelica
1.6 Further reading
Learning objectives
1.1 Introduction
1. Analyze the system structure and divide the system into parts.
The model typically obtained by applying this paradigm is a hybrid DAE mo-
del, composed of algebraic equations, ordinary differential equations with derivatives
with respect to time, and events. DAE stands for Differential-Algebraic Equation.
The languages conceived to support the physical modeling paradigm allow the
model developer to describe the continuous-time part of the model using equations.
MODELING METHODOLOGY AND TOOLS
For this reason, these modeling languages are known as equation-based langua-
ges. Modelica belong to this type of modeling language.
An equation states an equality relationship between two expressions (i.e., ex-
pression_1 = expression_2) in which one or several model variables intervene.
During the model simulation, the equation is employed to calculate the value of
one of these variables.
In equation-based languages, the way in which the model developer writes an
equation does not determine the variable to be calculated from the equation. Like-
wise, the order in which the model developer writes the model equations does not
determine the evaluation order of the equations during the model simulation.
To illustrate this point, let’s suppose that the constitutive relationship of an ideal
resistor is described using an equation-based modeling language. The resistance has
a constant, known value, R. The voltage drop (v) across the resistor pins and the
electric current that flows through the resistor satisfy a linear relationship: the Ohm’s
Law. This equation can equivalently be written as:
v =i·R i = v/R R = v/i
v/i = R v−i·R =0 0= v−R·i
Name Usage
The definition of the model classes, packages, variable types, data records and
functions is made using the seven classes provided by the Modelica language, which
are shown in Table 1.1.
As discussed previously, the interaction among the components is described in
terms of variables that are grouped in connectors, and classified in each connector
into across and through, depending on whether they are equal at the connection
point or their sum is equal to zero.
The connector variables can be selected in a way that component connections
satisfy the conservation laws. For instance, suppose that the connector variables
are selected as shown in Table 1.2, where the product of the across and through
variable of each connector has power units. The across variables describe physical
quantities that determine whether equilibrium exists, whereas the through variables
describe physical quantities that restore the equilibrium. This selection guaranties
MODELING METHODOLOGY AND TOOLS
Table 1.2: Connector variables in different energy domains (across × through has power units).
C1
u1
i1 i2
u4
C4 C2
u2
i4 i3
u3
u1 = u2 = u3 = u4
C3 i1 + i2 + i3 + i4 = 0
Figure 1.1: Connection among four components (C1 , C2 , C3 and C4 ). Connectors (filled
rectangles) are composed of an across variable (u) and a through variable (i).
that if several connectors of the same domain are connected, then the power is
conserved at the connection point.
Other selections that guarantee the energy conservation are possible. For ins-
tance, the heat flow rate is more frequently used than the entropy flow rate as
through variable of the thermal domain. As the heat flow rate has power units, the
energy conservation is described by the equation stating that the sum of the through
variables at the connection point is zero.
Suppose that we want to model an electric circuit composed of current and
voltage sources, resistors, capacitors, inductances, diodes, transistors, etc. The con-
nection terminals of the electric components are named pins. The connection point
of two or more pins is named circuit node. Let’s consider a connection node of four
components C1 , C2 , C3 and C4 , as shown in Figure 1.1. Pins are represented in the
figure as filled rectangles.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Selecting the electric connector variables as suggested in Table 1.2, the pin is
modeled as a connector composed of an across variable and a through variable: the
voltage (u) and current (i), respectively. Let’s adopt the following sign convention
for through variables: the through variable is defined as entering the connector.
In other words, positive current enters the component. The connection among the
four components is translated by the modeling environment into four equations:
three equations stating the equality of the voltages (u1 = u2 = u3 = u4 ) and one
equations stating the current conservation (i1 + i2 + i3 + i4 = 0).
vial equations, which are added to the model as a result of the connect-sentence
translation.
The set of operations that is performed next on the flat model constitutes the
analysis and optimization stage. An obvious optimization consists in substitu-
ting the alias variables, removing the trivial equations from the simulation model.
Equations don’t contain explicit information on their computational causality,
which is calculated by the modeling environment from analyzing the complete model.
As a result of this analysis, named assignment of the computational causality,
the evaluation order of the equations and algorithms is obtained, and also which
variable has to be evaluated from each equation.
In addition to the assignment of the computational causality, other analyses and
manipulations performed on the model are reduction of the DAE index, symbolic
manipulation of linear equations and systems of simultaneous equations, tearing
of non-linear systems of simultaneous equations, and optimization of expression
evaluations.
The model obtained of performing these operations is named the sorted and
solved model. Its simulation algorithm (typically programmed in C language) is
automatically generated by the modeling environment, and compiled and linked with
libraries of numerical methods, to obtain the simulation executable file.
As Modelica models are hybrid, the simulation algorithm implemented by the
Modelica modeling environments combines the solution of the continuous-time part
of the model, with the detection and handling of the events. The algorithm basically
works as follows:
2. If an event condition is satisfied, it means that the associated event has been
triggered within the last time step of the integration algorithm. Then, the
integration is halted and an iterative method to accurately locate the event
trigger time is started. A small interval that includes the trigger time is
found. The interval length is smaller than a predefined value that depends on
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
the precision of the event-location method. It is assumed that the trigger time
is the right endpoint of the calculated interval.
3. Once the event trigger time has been calculated, the integration method is used
to evaluate the model at the event instant, prior to executing the event actions.
Next, the event actions are executed: the continuous-time part of the model
and the active discrete-time equations are solved simultaneously. This is known
as solving the restart problem. If several events are triggered simultaneously,
the discrete-time equations of all these triggered events are considered in the
restart problem. Observe that two model evaluations are performed at the
event time, one prior to the event execution and the other when executing the
event (for solving the restart problem), resulting in two values of the model
state: the previous value and new value, respectively.
4. Once the restart problem has been solved, the event conditions are checked
again. If one or several events are triggered, then the new restart problem,
which is composed of the continuous-time part of the model and the discrete-
time equations of the triggered events, is posed, solved, and the event condi-
tions are checked again. This process, named execution of an event chain,
continues until no more events are triggered. Then, the numerical integration
of the continuous-time part of the model is resumed, using as initial condition
the values calculated from solving the last restart problem.
The state of hybrid models evolves by continuous change over time of the continuous-
time state variables, and by instantaneous changes in the total state, described by the
continuous-time and discrete-time state variables, known as events. The description
of an event has two parts:
dϕ
= w (1.1)
dt
dw
L· = −g · sin (ϕ) (1.2)
dt
were ϕ represents the pendulum angle with respect to the vertical, w the angular
velocity, L the pendulum length, and g the gravitational acceleration.
This model is described in Modelica as shown in Modelica Code 1.1. The Modelica
description of the model has two sections, containing the variable declaration and
the equations respectively. The variables are declared first. The equation keyword
signals the beginning of the equation section.
The model has two continuous-time variables of real type that represent the
angle (phi) and the angular velocity (w); a parameter of real type that represents
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model pendulum
constant Real g = 9.81 "Gravitational acceleration";
parameter Real L = 1 "Length of the rigid rod";
Real phi(start=0.1, fixed=true) "Angle";
Real w(start=0, fixed=true) "Angular velocity";
equation
der(phi) = w;
// Equation of motion
L*der(w) = -g*sin(phi);
end pendulum;
the pendulum length (L); and a constant of real type that represents the gravitational
acceleration (g).
The values of constants and parameters don’t change during the simulation.
The parameter values may be changed between simulation runs. The setting of
parameter values is a part of the simulation experiment definition. On the contrary,
the constant values cannot be changed at the experiment definition. In this exam-
ple, the parameter and constant values are set in the variable declaration: L = 1,
g = 9.81. The value of L may be modified between simulation runs.
The continuous-time variables phi and w appear differentiated in the model. Both
are selected by-default as continuous-time state variables. In that way, their time
derivatives are calculated from the model equations, and phi and w are calculated
by numerical integration of their time derivatives.
The initial values of phi and w are specified by setting the value of the attribute
start to the variable initial value, and setting the fixed attribute to true. The initial
value of phi is 0.1 radians and the initial value of the angular velocity is zero.
It is possible to include comments in the Modelica code. Comments associated
to a declaration are written within double quotation marks ", before the semicolon
that signals the end of the sentence. These comments are typically shown by the
model editor, accompanying the variable name, as an aid for understanding the
variable meaning.
Modelica allows also to include comments intended only for model developers.
The text written in a line after two slashes // will be ignored by the model editor. It
is also possible to include multi-line comments: the text written between the symbols
/* and */ will be ignored.
The model equations are written after the equation keyword. Observe that the
time derivatives of the phi and w variables are der(phi) and der(w), respectively.
The way of writing the equations and their order are irrelevant. The modeling
MODELING METHODOLOGY AND TOOLS
environment will analyze the model to find out which variable has to be evaluated
from each equation and in which order these evaluations have to be made, and will
manipulate symbolically the equations.
1.5.1 Dymola
Firstly, let’s edit and simulate this model using Dymola. The graphic user inter-
face (GUI) of Dymola version 2017 is shown in Figure 1.2. The modeling view of the
GUI is displayed on launch. The main window is divided into three windows: the
upper left window (Packages) allows to navigate through the model libraries, the
lower left window (Component Browser) shows the components of the model that is
being edited, and the right window allows to edit the model. The library named
Modelica shown in the Packages window is the Modelica Standard Library
(MSL). It is opened by-default when Dymola is launched.
The menu and button bars located at the top of the main window allow to open
files containing Modelica models (text files with .mo extension), save models to file,
and model editing (defining graphic attributes, connecting components, etc.) and
checking. The two buttons at the lower-right part of the main window, labeled as
Modeling and Simulation respectively, allow to switch between the modeling view
(displayed by-default on launch), which allows to load, save, edit and check models,
and the simulation view, which allows to translate and simulate the model, define
the experiment, and plot the results.
The pendulum model can be edited and simulated following these steps:
1. Create a new model. Choose File > New > Model in the menu bar, and
write the name of the new model: pendulum. Dymola asks whether the new
model has to be included within any of the libraries shown in the Packages
window. As our answer is negative in this case, the new model is created in the
upper hierarchical level of the library tree displayed in the Packages window.
2. Write the Modelica code of the model. Choosing Window > View >
Modelica Text or pressing the Modelica Text button, the right window changes
to the code editing mode. Then, we can write the Modelica description of the
model (see Figure 1.3). Choosing File > Save saves the model to file. Modelica
classes are written in text files with .mo extension. The directory where the file
is saved is selected as the working directory for the session. It can be changed
choosing File > Change directory.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
3. Check the model. Choosing Edit > Check > Normal or pressing the Check
button, Dymola checks that the model being edited does not contain syntax
errors. Also, Dymola displays the number of unknown variables and the number
of equations (see Figure 1.4). Both numbers have to be equal for the model to
be simulated.
4. Translate the model. Clicking the Simulation button, located at the lower
part of the main window, Dymola changes to the simulation view (see
Figure 1.5). The name of the model to be translated and simulated is shown
in the upper border of the main window: pendulum. The translation of the
model is performed selecting Simulation > Translate > Normal or pressing
the Translate button. Dymola translates the Modelica model into C language.
The generated C-file, named dsmodel.c, is compiled and an executable file
named dymosim.exe is created. Both files are saved in the working directory.
The Dymola Messages window displays information on the model, including
the number of unknown variables, equations, number and size of the systems
of simultaneous equations, and also lists the variables that have been selected
as continuous-time state variables (see Figure 1.6).
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
5. Initialize the model. After translating the model, the Variable Browser
window (see Figure 1.6) shows the variables whose value can be set to initialize
the model. In the pendulum model, these are the angle and the angular
velocity (state variables), and the length (parameter). The values shown are the
values assigned to these quantities in the model, being now possible to change
these values. From the value of these quantities and the model equations,
Dymola will be able to solve the model at the initial time of the simulation.
The parameter value will be kept constant during all the simulation. The
derivatives of the angle and the angular velocity will be calculated solving the
model equations, and the angular velocity and the angle will be calculated by
numerical integration of their derivatives.
7. Run the simulation and plot the results. The simulation run starts choo-
sing Simulation > Simulate or pressing the Simulate button (see Figure 1.8).
Dymola automatically generates a text file named dsin.txt with the experiment
description, including the information to initialize the model and configure the
numerical methods, a list of all the model variables, and the initial and final
time. The experiment description file can be also obtained by executing the
following command from a Windows shell: dymosim -i
Dymola launches the simulation by executing dymosim.exe, which reads the
experiment file (dsin.txt by-default). The final state of the model is stored in
a file named dsfinal.txt, which has the same form as the file describing the
experiment.
The results can be plotted during the simulation run and once the simulation
is finished. The variable names are displayed in the Variable Browser window.
Click on a variable to visualize it in the Plot window. By default, the horizontal
axis represents time, but any other variable can be selected as independent
variable. The simulation results are saved to a Matlab format file, whose name
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
is the model name with .mat extension. If the option Textual data format
is selected in the Output tab of the Simulation Setup window (see again
Figure 1.7), then the simulation results are also written to a text file. Dymola
writes these files in the working directory.
1.5.2 OpenModelica
1. Create a new model. Choose File > New Modelica class in the menu bar.
Then, a window is displayed (see Figure 1.10). The user can set the name
of the new class in the Name box, and the type of the Modelica class in the
Specialization box. By clicking on the Partial box, we are specifying that this
new class is partial. This means that this new class can be inherited but not
instantiated . If the new model inherits from other models, we can specify the
name of the superclasses in the Extends box. Additionally, if the new model is
part of an existing library, in the Insert in class box we can specify where it
has to be included. In this example, we only fill in the first box with the name
of the model.
2. Write the Modelica code of the model. By clicking on the button Text
View (see Figure 1.11), a window is displayed where the Modelica code of the
new pendulum model can be written. In this window we can choose to show
the model icon, diagram or documentation by clicking the Icon View, Diagram
View or Documentation View buttons, respectively. By clicking on the Check
Model button, OpenModelica checks that the model has no errors, and shows a
dialog window with information about the number of variables and equations.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Figure 1.13: Running the simulation and plotting the results with OMEdit.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
3. Define the experiment. By clicking on the Simulation Setup button (see the
Figure 1.11), the window Simulation Setup is opened (see the Figure 1.12). In
the General tab of this window, the user can set the initial and final time of
the simulation, the length or number of output intervals, and the integration
method and its tolerance. In this example, the final time is set to 5. The format
of the file where the simulation results are stored can be set in the Output tab.
Additionally, we can choose to store or not the protected type variables, the
variable values at the event instants and the variable values at equidistant time
grid.
4. Run the simulation and plot the results. The simulation starts by clicking
on the button Simulate (see Figure 1.11). If an error occurs during the simu-
lation run, OMEdit shows an error message in the message window. OMEdit
shows the output variables in the window Variables Browser (see Figure 1.13).
By clicking on one or several of these output variables, their graphical re-
presentation is displayed. Additionally, simulation results are stored in a file.
OMEdit stores the output file in its working directory. The working directory
can be changed in the Options window that is displayed by clicking on Tools
> Options.
Some of the ideas that motivated the Modelica standardization effort are ex-
plained by Åström et al. (1998), placing them in the context of the evolution of
continuous-time modeling and simulation, since the mid 1920s until the late 1990s.
We strongly recommend reading this article.
An outstanding book on the principles and techniques of continuous-time mode-
ling is (Cellier 1991).
A selection of the connector variables was shown in Table 1.2, so that component
connection satisfies power conservation. This concept is fully developed in the bond
graph modeling formalism, according to which the system is modeled describing the
flow, storage, dissipation and transformation of the energy that takes place in it. As
these concepts are common to all physical domains, the bond graph formalism is
well suited for mixed-domain modeling. Bond graph models reflects simultaneously
the physical structure of the modeled system, and the computational causality of
the model. Some excellent books on bond graph modeling are (Karnopp et al. 1990),
(Thoma 1990) and (Hogan & Breedveld 1995).
MODELING METHODOLOGY AND TOOLS
The use of Dymola and OpenModelica was introduced in Section 1.5. Further
information is provided in the Dymola documentation (Dynasim AB 2004, Dassault
Systèmes AB 2016) and the OpenModelica website (OpenModelica 2017).
It is recommended to navigate around the Modelica Association website (Mo-
delicaWebSite 2017), where there is plenty of information available: the successive
Modelica language specifications, tutorials on the use of the language, conference
papers, links to software tools, books, model libraries, etc.
Lesson
2
2.1 Introduction
2.2 Rectifier circuit
2.3 Translation in one dimension
2.4 Translation in two dimensions
2.5 Radial heat transfer in a pipe
2.6 Further reading
Learning objectives
2.1 Introduction
Consider the circuit shown in Figure 2.1, which is composed of a sinusoidal volta-
ge generator, two resistors, a capacitor and a diode. These electronic components can
be modeled with different level of detail, employing different types of mathematical
model. We will model them using the constitutive relationships shown in Figure 2.2.
This is, assuming that the generator, resistors and capacitor are ideal components,
and the diode obeys the Shockley equation. Their parameter values are shown in
Table 2.1. The circuit model can be built following the next steps.
CONTINUOUS-TIME ATOMIC MODELS
R1
+ D R2 C
−
i + + + i
+ i i
u u u
u +
− − − − −
du
u = U 0 ⋅ sin(ω ⋅ t + ϕ ) i = I S ⋅ ( exp(u / Vt ) − 1) u =i⋅R C⋅ =i
dt
Figure 2.2: Constitutive relationships of the components.
u1 R1 u2
igen iD iR 2 iC
iR1
+ D R2 C
−
u0 = 0
Figure 2.3: Assign names to the voltage nodes, and names and directions to the currents.
2. Assign names to the voltage in the remaining nodes. Nodes are repre-
sented as filled circles in Figure 2.3. The names assigned are u1 and u2 . The
u0 node is the ground node.
3. Assign directions and names to the currents. For each two-pin compo-
nent, a name is given to the current that flows through the component with
an arbitrarily chosen reference direction. In components with three or more
pins, a name is assigned to the current in each pin and the current directions
are chosen to be pointing towards the component. In this example, the names
and directions given to the currents are shown in Figure 2.3. The names are:
igen , iR1 , iD , iR2 , iC .
Observe that the equation that states the current conservation at the ground
node does not provide any additional information and for this reason is not
included in the model. This equation is always a linear combination of the
equations that state the current conservation at the other nodes. For example,
CONTINUOUS-TIME ATOMIC MODELS
the equation at the ground node of this circuit is Eq. (2.3), which can be
obtained adding Eqs. (2.1) and (2.2).
u1 − u0 = U0 · sin(w · t + ϕ) (2.4)
u1 − u2 = iR1 · R1 (2.5)
u2 − u0
iD = Is · exp −1 (2.6)
Vt
u2 − u0 = iR2 · R2 (2.7)
d
C· (u2 − u0 ) = iC (2.8)
dt
u1 = U0 · sin(w · t + ϕ) (2.9)
u1 − u2 = iR1 · R1 (2.10)
u2
iD = Is · exp −1 (2.11)
Vt
u2 = iR2 · R2 (2.12)
du2
C· = iC (2.13)
dt
model circuit1
Real i_gen(unit="A") "Current of the generator";
Real i_R1(unit="A") "Current of R1";
Real i_R2(unit="A") "Current of R2";
Real i_C(unit="A") "Current of the capacitor";
Real i_D(unit="A") "Current of the diode";
Real u_1(unit="V") "Voltage of generator";
Real u_2(start=0, fixed=true, unit="V") "Output voltage";
// Voltage generator
constant Real PI = 3.1415926536;
parameter Real U0( unit="V") = 5;
parameter Real frec( unit="Hz") = 100;
parameter Real w( unit="rad/s") = 2*PI*frec;
parameter Real phi( unit="rad") = 0;
// Resistors
parameter Real R1( unit="ohm") = 100;
parameter Real R2( unit="ohm") = 100;
// Capacitor
parameter Real C( unit="F") = 1e-6;
// Diode
parameter Real Is( unit="A") = 1e-9;
parameter Real Vt( unit="V") = 0.025;
equation
// Node equations
i_gen = i_R1;
i_R1 = i_D + i_R2 + i_C;
// Constitutive relationships
u_1 = U0 * sin( w * time + phi);
u_1 - u_2 = i_R1 * R1;
i_D = Is * ( exp(u_2 / Vt) - 1);
u_2 = i_R2 * R2;
C * der(u_2) = i_C;
end circuit1;
Modelica Code 2.1: Circuit of Figure 2.1, with the parameters of Table 2.1.
– Declaring a variable implies specifying its data type (Real, Integer, Boolean,
etc.), its variability (see Table 2.2), name and dimensionality (scalar, n-dimensional
matrix). Optionally, values can be assigned to the variable attributes at the
variable declaration. The attributes associated to a variable depends on the
variable data type (see Tables 2.3 and 2.4).
– The start and fixed attributes have been employed to specify the initial value
of the u2 variable. This initial value specified in the variable declaration can
be later modified in the experiment definition.
– The units have been indicated in the variable declarations, using the unit
attribute.
CONTINUOUS-TIME ATOMIC MODELS
Keyword Meaning
Attribute Meaning
quantity × × × ×
unit ×
min, max × ×
start, fixed × × × ×
displayUnit ×
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Modelica facilitates declaring new variable types, based on the built-in types, by
setting attribute values. For instance, two new types named Voltage and Current
can be declared as follows:
model circuit1
Modelica.SIunits.Current i_gen "Current of the generator";
Modelica.SIunits.Current i_R1 "Current of R1";
Modelica.SIunits.Current i_R2 "Current of R2";
Modelica.SIunits.Current i_C "Current of the capacitor";
Modelica.SIunits.Current i_D "Current of the diode";
Modelica.SIunits.Voltage u_1 "Voltage of generator";
Modelica.SIunits.Voltage u_2(start=0, fixed=true) "Output voltage";
// Voltage generator
parameter Modelica.SIunits.Voltage U0 = 5;
parameter Modelica.SIunits.Frequency frec = 100;
parameter Modelica.SIunits.AngularFrequency w = 2*Modelica.Constants.pi*frec;
parameter Modelica.SIunits.Angle phi = 0;
// Resistors
parameter Modelica.SIunits.Resistance R1 = 100;
parameter Modelica.SIunits.Resistance R2 = 100;
// Capacitor
parameter Modelica.SIunits.Capacitance C = 1e-6;
// Diode
parameter Modelica.SIunits.Current Is = 1e-9;
parameter Modelica.SIunits.Voltage Vt = 0.025;
equation
// Node equations
i_gen = i_R1;
i_R1 = i_D + i_R2 + i_C;
// Constitutive relationships
u_1 = U0 * sin( w * time + phi);
u_1 - u_2 = i_R1 * R1;
i_D = Is * ( exp(u_2 / Vt) - 1);
u_2 = i_R2 * R2;
C * der(u_2) = i_C;
end circuit1;
Modelica Code 2.3: Circuit of Figure 2.1, described using the Modelica.SIunits types.
Figure 2.4: Voltages of the circuit shown in Figure 2.1 obtained simulating the Modelica Code 2.3.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
u1
iD1
iD 2
u2 u3
igen iD 3
+
−
iR iC
iD 4
u0 = 0
The model is composed of the current conservation equations and the constitutive
relationships of the components. Assuming that the ground node voltage is zero, the
model is described by Eqs. (2.14) – (2.24).
The model description is shown in Modelica Code 2.4. The generator (u1 ) and
output (uC ) voltages obtained simulating the model during 0.05 s are displayed in
Figure 2.6.
CONTINUOUS-TIME ATOMIC MODELS
model circRectifier
Modelica.SIunits.Current i_gen "Current of the generator";
Modelica.SIunits.Current i_R "Current through the resistor";
Modelica.SIunits.Current i_C "Capacitor current";
Modelica.SIunits.Current i_D1 "Current through diode 1";
Modelica.SIunits.Current i_D2 "Current through diode 2";
Modelica.SIunits.Current i_D3 "Current through diode 3";
Modelica.SIunits.Current i_D4 "Current through diode 4";
Modelica.SIunits.Voltage u_1 "Voltage of generator";
Modelica.SIunits.Voltage u_2 "Voltage at node u2";
Modelica.SIunits.Voltage u_3 "Voltage at node u3";
Modelica.SIunits.Voltage u_C(start=0, fixed=true) "Capacitor voltage";
// Generator parameters
parameter Modelica.SIunits.Voltage U0=5;
parameter Modelica.SIunits.Frequency frec=100;
parameter Modelica.SIunits.AngularFrequency w=2*Modelica.Constants.pi*frec;
parameter Modelica.SIunits.Angle phi=0;
// Resistor
parameter Modelica.SIunits.Resistance R=100;
// Capacitor
parameter Modelica.SIunits.Capacitance C=1e-6;
// Diodes
parameter Modelica.SIunits.Current Is=1e-9;
parameter Modelica.SIunits.Voltage Vt=0.025;
equation
// Current conservation equations
i_gen + i_D2 = i_D1;
i_R + i_C = i_D2 + i_D3;
i_D1 + i_D4 = i_R + i_C;
// Constitutive relationships
u_1 = U0*sin(w*time + phi);
i_D1 = Is*(exp((u_1 - u_3)/Vt) - 1);
i_D2 = Is*(exp((u_2 - u_1)/Vt) - 1);
i_D3 = Is*(exp(u_2/Vt) - 1);
i_D4 = Is*(exp(-u_3/Vt) - 1);
u_3 - u_2 = i_R*R;
u_C = u_3 - u_2;
C*der(u_C) = i_C;
end circRectifier;
Modelica Code 2.4: Model of the rectifier circuit shown in Figure 2.5.
Let’s consider the system represented in Figure 2.7. It is composed of a first body
that slides on a horizontal surface, and a second body that slides on the first one.
The two movements are one dimensional and have the same direction. There exists a
friction force between the first body and the surface, and between the two bodies. It
is assumed that this friction force is proportional to the relative velocity of the two
contacting materials. The body masses, m1 and m2 , are constant. The objective is
to develop a model that describes the evolution of the body positions and velocities.
The first step in developing the model is to choose a reference and sign convention
for velocity. We choose the velocity of the horizontal surface as reference, and assign
it the zero value. The body velocities with respect to the horizontal surface are v1
and v2 , respectively. We choose the following sign convention for velocity: positive
if the body moves towards right, and negative if moves towards left.
The evolution of the body velocities can be calculated applying the second Law
of Newton. According to this law, the change in the linear momentum of a body
produced by a net force is directly proportional to the magnitude of the net force
F , in the same direction as the net force.
d
(m · v) = F (2.25)
dt
When the mass of the body is constant, Eq. (2.25) can be written as follows:
dv
m· =F (2.26)
dt
Let’s write Eq. (2.26) particularized for each of the two bodies that compose our
system. Forces of friction are exerted on the first body by the horizontal surface and
the second body. The force exerted on the second body is due to the friction with
the first body.
dv1
m1 · = −bs,1 · v1 −b1,2 · (v1 − v2 ) (2.27)
dt | {z } | {z }
Force exerted by the Force exerted by
horizontal surface on body 1 body 2 on body 1
dv2
m2 · = −b1,2 · (v2 − v1 ) (2.28)
dt | {z }
Force exerted by
body 1 on body 2
CONTINUOUS-TIME ATOMIC MODELS
v2
v1
model TwoBodiesWithFriction
import SI = Modelica.SIunits;
parameter SI.Mass m1=100 "Mass of body 1";
parameter SI.Mass m2=10 "Mass of body 2";
parameter SI.TranslationalDampingConstant b_s1=1.8
"Friction coefficient of surface-body 1";
parameter SI.TranslationalDampingConstant b_12=1.6
"Friction coefficient of body 1-body 2";
SI.Position x1(start=0, fixed=true) "Position of body 1";
SI.Position x2(start=0, fixed=true) "Position of body 2";
SI.Velocity v1(start=0.1, fixed=true) "Velocity of body 1";
SI.Velocity v2(start=0, fixed=true) "Velocity of body 2";
equation
// Body 1
der(x1) = v1;
m1*der(v1) = -b_s1*v1 - b_12*(v1 - v2);
// Body 2
der(x2) = v2;
m2*der(v2) = -b_12*(v2 - v1);
end TwoBodiesWithFriction;
Modelica Code 2.5: Model of the two-body system shown in Figure 2.7.
Figure 2.8: Simulation of Modelica Code 2.5 with two different initial conditions: v1 (0) = 0.1 m/s,
v2 (0) = 0 (left); v1 (0) = 0, v2 (0) = 0.2 m/s (right).
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The bs,1 and b1,2 parameters are the proportionality coefficients that relate the
force of friction and the relative velocities.
Observe that, if the body velocities are known at the initial time, Eqs. (2.27) and
(2.28) allow to calculate the velocities in the successive time instants.
The next step in developing the model is to include the equations that relate
the body positions with their velocities. To this end, we have to choose a reference
and a sign convention for the spatial coordinate. The sign criterion for position is
usually chosen in consonance with the sign criterion for velocity, so that the value of
the spatial coordinate increases if the velocity is positive, and decreases if negative.
As the velocity is positive if the body moves towards right, the spatial coordinate
of our model increases towards right. In this way, the following relationships hold
between velocities (v1 , v2 ) and positions (x1 , x2 ):
dx1
= v1 (2.29)
dt
dx2
= v2 (2.30)
dt
Known the body positions at the initial time, the evolution of the positions can
be calculated from Eqs. (2.29) and (2.30).
Setting an initial value for the body position implies choosing the origin of the
coordinate system. This should be done in a way that facilitates as much as possible
the interpretation of the simulation results. For instance, the origin of the coordinate
system for both bodies could be a certain location in the horizontal surface. Other
option would be to assign the zero value to the initial position of the body, so that the
position of each body measures its displacement with respect to its initial position.
The system model is described by Eqs. (2.27)–(2.30). Setting the constant va-
lues of the body masses (m1 , m2 ) and the friction coefficients (bs,1 , b1,2 ), and the
initial values of the body positions and velocities, the model allows to calculate the
evolution of the body positions and velocities.
The Modelica description of the model is shown in Modelica Code 2.5. The
evolutions of the body velocities for two different initial conditions are shown in
Figure 2.8. The observed behavior is explained considering that the force of friction
exerted by the horizontal surface makes the velocity of the first body to tend to
zero, and the force of friction between the two bodies makes their relative velocity
to tend to zero.
CONTINUOUS-TIME ATOMIC MODELS
In the first simulation run, the first body is initially moving and the second body
is at rest. The force of friction between the bodies makes the second body to start
moving, increasing its velocity. When the relative velocity between the bodies is zero,
the friction force between them vanishes. However, the horizontal surface continues
braking the first body and consequently reducing its velocity. When the velocity of
the first body becomes smaller than the velocity of the second body, the force of
friction between the bodies acts again, but in this case reducing the velocity of the
second body.
In the second simulation run, the first body is initially at rest and is accelerated
by the force of friction exerted by the second body.
Let’s make the system a little more complex by adding some components. Con-
sider the system depicted in Figure 2.9. It consists of two bodies with constant
masses, m1 and m2 , moving on a horizontal surface, and a third body, with constant
mass m3 , that moves on them. There is friction between all contacting materials. A
damper connects the first and second bodies, which are connected by springs to the
lateral walls. A given sinusoidal force, F , is applied to the third body. The horizontal
surface and the lateral walls remain at rest. The model should describe the evolution
of the velocity and position of the three bodies.
The first step in developing the model consists in choosing the reference and
sign convention for velocity. We choose as a reference the velocity of the horizontal
surface and the lateral walls, and assign to this velocity the value zero. In addition,
we consider that a body moving towards right has positive velocity. We adopt the
same sign convention for the force: it is positive if is pointing towards right.
The second Newton’s Law allows to relate the changes in the linear momentum
of each body with the net force applied on it.
dv1
m1 · = −b1{z· v1} −b4 · (v1 − v3 ) −b2 · (v1 − v2 ) −k 1 · e1 (2.31)
dt | | {z }| {z | {z
} }
Force of friction exerted Force of friction Force of Force of
by horizontal surface exerted by body 3 dumper spring 1
dv2
m2 · = −b3{z· v2} −b5 · (v2 − v3 ) −b2 · (v2 − v1 ) +k 2 · e2 (2.32)
dt | | {z }| {z | {z
} }
Force of friction exerted Force of friction Force of Force of
by horizontal surface exerted by body 3 dumper spring 2
dv3
m3 · = −b4 · (v3 − v1 ) −b5 · (v3 − v2 ) +F (2.33)
dt | {z }| {z } |{z}
Force of friction Force of friction External
exerted by body 1 exerted by body 2 force
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
F
m3
k1 b4 b5 k2
m1 m2
b2
b1 b3
Figure 2.9: Movement of three bodies with friction, connected by dumper and springs.
model ThreeBodiesWithFriction
import SI = Modelica.SIunits;
parameter SI.Mass m1=100 "Mass of body 1";
parameter SI.Mass m2=10 "Mass of body 2";
parameter SI.Mass m3=15 "Mass of body 3";
parameter SI.TranslationalDampingConstant b1=1.8 "Body 1 - Surface";
parameter SI.TranslationalDampingConstant b2=3.2 "Body 1 - Body 2";
parameter SI.TranslationalDampingConstant b3=1.8 "Body 2 - Surface";
parameter SI.TranslationalDampingConstant b4=1.6 "Body 1 - Body 3";
parameter SI.TranslationalDampingConstant b5=1.6 "Body 2 - Body 3";
parameter SI.TranslationalSpringConstant k1=1.2 "Spring 1";
parameter SI.TranslationalSpringConstant k2=1.2 "Spring 2";
parameter SI.Force F0=10 "Amplitude of the external force";
parameter SI.AngularFrequency w=0.1 "Frequency of the external force";
SI.Position x1(start=0, fixed=true) "Position of body 1";
SI.Position x2(start=0, fixed=true) "Position of body 2";
SI.Position x3(start=0, fixed=true) "Position of body 3";
SI.Velocity v1(start=0, fixed=true) "Velocity of body 1";
SI.Velocity v2(start=0, fixed=true) "Velocity of body 2";
SI.Velocity v3(start=0, fixed=true) "Velocity of body 3";
SI.Length e1(start=1, fixed=true) "Elongation of spring 1";
SI.Length e2(start=0, fixed=true) "Elongation of spring 2";
SI.Force F "External force applied on body 3";
equation
// Body 1
der(x1) = v1;
m1*der(v1) = -b1*v1 - b4*(v1 - v3) - b2*(v1 - v2) - k1*e1;
// Body 2
der(x2) = v2;
m2*der(v2) = -b3*v2 - b5*(v2 - v3) - b2*(v2 - v1) + k2*e2;
// Body 3
der(x3) = v3;
m3*der(v3) = -b4*(v3 - v1) - b5*(v3 - v2) + F;
// Spring 1
der(e1) = v1;
// Spring 2
der(e2) = -v2;
// External force
F = F0*sin(w*time);
end ThreeBodiesWithFriction;
where e represents the difference between the actual length of the spring and its
natural length. The left end of the first spring is at rest, while the right end moves
with velocity v1 . The right end of the second spring is at rest and the left end moves
with velocity v2 . Therefore:
de1
= v1 (2.34)
dt
de2
= −v2 (2.35)
dt
The relationship between the position and velocity of each body can be expressed
as follows:
dx1
= v1 (2.36)
dt
dx2
= v2 (2.37)
dt
dx3
= v3 (2.38)
dt
The system model consists of Eqs. (2.31) – (2.38), and the constant known
values of the body masses (m1 , m2 , m3 ), the spring coefficients (k1 , k2 ), the dumper
coefficient (b2 ) and the friction coefficients (b1 , b3 , b4 , b5 ).
For setting the initial state of the system, we will give an initial value to the
position and velocity of each body, and to the difference between the actual length
and the natural length of each spring.
As origin of the coordinate system for the displacement of each body, we chose
the body position at the initial time. Therefore, the initial position of the three
bodies is zero. In this way, the x variable of each body indicates its displacement
with respect to its initial position. The Modelica description of the model is listed
in Modelica Code 2.6.
A simplistic model of the Earth’s motion around the Sun will allow us to intro-
duce the use of vectors and matrices in Modelica. Let’s assume that the Earth orbits
in a plane. In this plane, we define a two-dimensional rectangular coordinate system.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The origin of this coordinate system is at the center of the Sun. We represent the
position and velocity of the Earth using two two-dimensional vectors named x and
v respectively (see Figure 2.10).
The attractive force between two bodies with masses M and m can be calculated
by applying Eq. (2.39), where G is the gravitational constant. This equation is known
as the Newton’s law of universal gravitation. The second Newton’s Law relates the
force of gravity and the acceleration of the Earth around the Sun, as shown in
Eq. (2.40). The relationship between velocity and position is given by Eq. (2.41).
M ·m x
F = −G · · (2.39)
x · x |x|
dv
m· = F (2.40)
dt
dx
= v (2.41)
dt
Let’s give the following values to the Earth’s mass (m) and Sun’s mass (M):
m = 5.976 · 1024 kg and M = 1.989 · 1030 kg. The initial state of the system is
specified by setting the initial position and velocity of the Earth. Let’s suppose that
the Earth is initially at the x(0) = {152.1 · 109 , 0} m position and is moving with a
velocity of v(0) = {0, 29.29 · 103 } m/s.
The model is described in Modelica Code 2.7. Two-component vectors (one-
dimensional arrays) are employed to represent the position, velocity and force.
The model equations, Eqs. (2.39) – (2.41), are described in Modelica using vector
equations. The Earth trajectory obtained simulating this model during one year
(=3.1536e7 s) is shown in Figure 2.11.
An array variable is declared indicating between square brackets the number of
its components in each dimension. This size declaration can be indistinctly written
after the variable type or after the variable name. For instance,
where r, v and F are vector variables (one-dimensional arrays) with two compo-
nents, and tabla is a three-dimensional matrix variable (array with dimension
greater than one), with 6-by-2-by-10 components. The declaration of array variables
can also be made indicating only the number of dimensions, for instance,
CONTINUOUS-TIME ATOMIC MODELS
v
F
x
Figure 2.10: Position and velocity of the Earth (left); and gravitational force exerted by the Sun
on the Earth (right).
model SunEarthSystem
import SI = Modelica.SIunits;
SI.Position x[2](start={152.1e9,0}, fixed=true) "Earth position";
SI.Velocity v[2](start={0,29.29e3}, fixed=true) "Earth velocity";
SI.Force F[2] "Gravitational force";
parameter SI.Mass m=5.976e24 "Mass of the Earth";
parameter SI.Mass M=1.989e30 "Mass of the Sun";
equation
// Gravitational force exerted by the Sun on the Earth
F = -(Modelica.Constants.G*m*M/(x*x))*(x/sqrt(x*x));
// Position and velocity of the Earth
m*der(v) = F;
der(x) = v;
end SunEarthSystem;
Figure 2.11: Earth’s orbit obtained simulating the Modelica Code 2.7.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
nevertheless, the model must contain the necessary information for the modeling
environment to calculate the number of components. The modeling environment
calculates the number of components by analyzing the equations in which the array
variables intervene.
In any case, the number of dimensions and the number of components in each
dimension cannot change during the simulation run.
An array component can be referenced specifying its index, whose numbering
starts at one. For instance, x[i] is the i-th component of the vector. If x has two
components, these are x[1] and x[2].
Sub-arrays can be specified indicating a range of indexes. For instance, A[i1:i2,
j1:j2] is an array composed of the i1-to-i2 rows and the j1-to-j2 columns of A.
Some built-in functions useful for working with arrays are listed in Table 2.5.
Examples of array equations are provided in Table 2.6.
Observe in Modelica Code 2.7 that the initial values have been set by giving value
to the start attributes. Vectors are written in this example as comma-separated lists
inside curly braces. Some examples showing how to assign the value of vectors and
matrices can be found in Table 2.7. The array value can also be specified using a for
expression with iterators, whose syntax is basically: { expression for iterators }.
See the examples in Table 2.8.
As shown in Modelica Code 2.7, the model of the Sun-Earth system has been
written using vector equations:
m·M x
F = −G · x·x
· |x|
→ F = - Modelica.Constants.G * m * M / (x*x) *
x / sqrt(x*x);
dv
m· =F
dt
→ m * der(v) = F;
dx
dt
=v → der(x) = v;
For-clauses and if-clauses can also be employed for writing array equations and
assignments. The for-clauses are translated by the modeling environment into a
set of equations or a sequence of assignments. The for-clause syntax is basically (see
examples in Tables 2.9 and 2.10):
Table 2.7: Examples showing how to declare and assign value to parameter arrays.
Table 2.10: Examples of array equations and algorithms. Note that the computational causality
of equations is calculated by the modeling environment, whereas the computational causality of
assignments is explicitly defined by the model developer.
algorithm
x1 := g1(y1,...,ym);
...
xn := gn(y1,...,ym);
In this section, we will analyze the stationary heat transfer in the radial direction
of an insulated steel pipe. The materials have constant thermal conductivities and
there is convection at the boundaries. The system is depicted in Figure 2.12.
The pipe is cylindrical, made of steel, and has a length L = 1 m. The steam that
circulates inside the pipe is at a constant temperature T1 = 418 K. To reduce the
heat loss to the ambient air, the steel pipe is surrounded by an insulation material.
The ambient air temperature oscillates between 283 K and 300 K during the day.
The physical parameters of the system are listed in Table 2.11.
The thermal equivalent circuit model of the system is shown in the lower part of
Figure 2.12. Observe the analogy between the temperature and the voltage; the heat
flow and the electric current; and the thermal resistance and the electric resistance.
Denoting by q the heat power (units: W) that circulates from the steam to the
ambient air, the system model is composed by Eqs. (2.43) – (2.48), and the physical
parameters listed in Table 2.11. The temperatures are expressed in Kelvin.
T1 = 418 (2.43)
1
T1 − T2 = q · (2.44)
h1 · 2 · π · r1 · L
ln (r2 /r1 )
T2 − T3 = q· (2.45)
2 · π · κ1 · L
ln (r3 /r2 )
T3 − T4 = q· (2.46)
2 · π · κ2 · L
1
T4 − T5 = q· (2.47)
h2 · 2 · π · r3 · L
2·π·t
T5 = 291.5 − 8.5 · sin (2.48)
86400
The model can be described as shown in Modelica Code 2.8. The variables
that represent temperatures are of the Modelica.SIunits.Temperature type, which
is declared in the MSL as follows:
type Temperature = ThermodynamicTemperature;
type ThermodynamicTemperature = Real (
final quantity = "ThermodynamicTemperature",
final unit = "K",
min = 0.0,
start = 288.15,
nominal = 300,
displayUnit = "degC" );
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
B
A
Figure 2.12: Temperature profiles for radial heat transfer in an insulated pipe (above) and
equivalent thermal circuit (below). There is heat conduction in material A (the steel pipe) and
material B (the insulation), and convection on the boundaries (the steam inside the pipe and the
surrounding ambient air).
The unit attribute specifies the units employed in the model equations, whereas
the displayUnit attribute indicates the units that the modeling environment should
use when displaying the simulation results of this variable (performing automatically
the operations for units conversion). In this case, the temperature is expressed in
Kelvins when intervening in the model equations and is displayed in Celsius degrees.
The simulated evolution of the temperatures during 86400 s (one day) is dis-
played in Figure 2.13. Observe that the plots have different vertical-axis (ordinate)
scales: the larger drops in temperature are produced in the insulating layer and the
surrounding ambient air.
Let’s elaborate on this model a bit more. Suppose now that the air temperature
(T5 ) is not described by a known function of time, but it has to be interpolated
from the temperature readings recorded at specific times in a day. We will program
a Modelica function to calculate the temperature at any time of the day by linear
interpolation between the available time-temperature recordings. To this end, firstly
we will introduce the declaration and use of functions in Modelica.
Certain functions are built into the Modelica language. Some examples of built-
in functions are abs (absolute value function); sign (sign function); sqrt(v) (square
root function); and div(x,y) and rem(x,y) (quotient and remainder of the division
x/y). The arguments of the built-in functions can be scalars or arrays. In the latter
case, the function is applied to each of the array components, returning an array.
For instance, sqrt( {1,2,3} ) is equivalent to { sqrt(1), sqrt(2), sqrt(3) }; and
rem( {10,20,30}, {2,3,4} ) is equivalent to { rem(10,2), rem(20,3), rem(30,4) }.
User-defined functions must fulfill the following rule: functions cannot have in-
ternal memory. This means that given the same input, the function always must
return the same output.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model HeatTransferPipe
import SI = Modelica.SIunits;
import Modelica.Constants.pi;
import Modelica.Math.log;
parameter SI.Radius r1=0.025 "Inner radius of steel pipe";
parameter SI.Radius r2=0.035 "Outer radius of steel pipe";
parameter SI.Radius r3=0.06 "Outer radius of insulation";
parameter SI.Length L=1 "Pipe length";
constant SI.ThermalConductivity k1=45 "Thermal conductivity of steel pipe";
constant SI.ThermalConductivity k2=0.087 "Thermal conductivity of insulation";
constant SI.CoefficientOfHeatTransfer h1=11350
"Heat transfer coefficient of steam";
SI.CoefficientOfHeatTransfer h2 "Heat transfer coefficient of ambient air";
parameter SI.Temperature T1=418 "Steam temperature";
SI.Temperature T2 "Temperature of pipe inner surface";
SI.Temperature T3 "Temperature of pipe outer surface";
SI.Temperature T4 "Temperature of insulation outer surface";
SI.Temperature T5 "Temperature of ambient air";
SI.HeatFlowRate q "Heat power from the steam to the ambient air";
equation
h2 = 1.32*(abs(T4 - T5)/(2*r3))^0.25;
T1 - T2 = q/(h1*2*pi*r1*L);
T2 - T3 = q*log(r2/r1)/(2*pi*k1*L);
T3 - T4 = q*log(r3/r2)/(2*pi*k2*L);
T4 - T5 = q/(h2*2*pi*r3*L);
T5 = 291.5 - 8.5*sin(2*pi*time/86400);
end HeatTransferPipe;
Figure 2.13: Result obtained of simulating the Modelica Code 2.8 during 86400 s.
CONTINUOUS-TIME ATOMIC MODELS
x
tableX[:]
tableY[:] f y
tableY[2]
tableY[4]
tableY[1]
tableY[3]
tableX[1] tableX[3] x
tableX[2] tableX[4]
Figure 2.14: Function interface (above) and example of linear interpolation (below).
Let’s return to the problem of programming a function that performs linear in-
terpolation. The function interface is depicted in Figure 2.14. The function computes
an output value (y) by interpolating the input value (x) against a set of data points
(tableX and tableY vectors). The function definition and a fragment of the heat
transfer model are shown in Modelica Code 2.9. The air temperature calculated by
interpolation is shown in Figure 2.15.
The assert sentence is employed in the LinearInterpolation function (see Mo-
delica Code 2.9). This sentence allows to specify conditions that must be satisfied du-
ring the simulation run. Its syntax is: assert( logical_expression, error_message );
The logical expression should be true at any time. If it becomes false, the simulation
run is aborted and the error message is shown in the log window.
The LinearInterpolation function returns one value. The definition of functions
that returns more than one value is illustrated by the following example:
function Polar2Cartesian
// Convert from Polar Coordinates to Cartesian Coordinates
input Real ang, r;
output Real x, y;
algorithm
x := r * cos(ang);
y := r * sin(ang);
end Polar2Cartesian;
function LinearInterpolation
input Real x "Independent variable";
input Real tableX[:] "Independent variable points";
input Real tableY[:] "Dependent variable points";
output Real y "Interpolated value";
protected
Integer n;
Real slope;
algorithm
n := size(tableX, 1);
assert(size(tableX, 1) == size(tableY, 1),
"Error: tableX and tableY with different size");
assert(x >= tableX[1] and x <= tableX[n],
"Error: independent variable is out of range");
for i in 1:n - 1 loop
if x >= tableX[i] and x <= tableX[i + 1] then
slope := (tableY[i + 1] - tableY[i])/(tableX[i + 1] - tableX[i]);
y := tableY[i] + slope*(x - tableX[i]);
end if;
end for;
end LinearInterpolation;
model HeatTransferPipeInterp
parameter SI.Time valTime[:]=0:3600:86400;
parameter SI.Temperature valTemp[:]={291.5,293.0,295.5,300.0,302.5,305.5,
306.0,306.5,308.5,310.0,312.5,313.5,313.5,312.5,310.0,309.0,305.5,300.5,
298.5,293.5,290.5,286.0,280.5,275.5,273.0};
...
equation
...
// T5 = 291.5 - 8.5*sin(2*pi*time/86400);
T5 = LinearInterpolation(x=time, tableX=valTime, tableY=valTemp);
end HeatTransferPipeInterp;
By-default values of the inputs can be specified in the function declaration. These
values will be employed if the inputs are not present in the function call. For instance,
given this declaration
function Polar2Cartesian
input Real ang = 0, r = 1;
output Real x, y;
algorithm
x := r * cos(ang);
y := r * sin(ang);
end Polar2Cartesian;
Model libraries
3.1 Introduction
3.2 Electrical library
3.3 Longitudinal vibrations of a bar
3.4 Longitudinal heat conduction in a bar
3.5 Control of level and temperature in a tank
3.6 Dissipation of heat generated in a circuit
3.7 Further reading
Learning objectives
After studying the lesson, students should be able to:
3.1 Introduction
Let’s revisit the modeling of the rectifier circuit shown in Figure 2.1. Instead of
describing the circuit as an atomic model, now we will apply the object-oriented
MODEL LIBRARIES
modeling methodology. To this end, we are going to decompose the circuit into
its components, analyze how to model the interaction among these components,
program model classes describing the components, arrange the classes into a model
library, and finally use the library to compose the circuit model.
The rectified circuit is composed of four different classes of electric component:
voltage source, diode, resistor and capacitor. Their symbols and constitutive rela-
tionships were displayed in Figure 2.2. The components are connected by connecting
their electric pins. The pins connected at a connection point (circuit node) have the
same voltage and the sum of all the currents is zero. The connector class of Modelica
can be used for modeling the electric pin as shown below.
connector Pin
Modelica.SIunits.Voltage u;
flow Modelica.SIunits.Current i;
end Pin;
The class definition starts with the connector keyword followed by the class
name (Pin), and ends with the end keyword followed by the class name and a
semicolon. The class body contains the declaration of the connector’s variables.
The flow keyword allows to distinguish between across and through variables. It is
written preceding the declaration of the through variables, as is the electric current
in this case.
The component interface is composed of the variables that describe the com-
ponent interaction with the rest of the system, and the parameters. A model class
describes a type of system. By setting the value of the model class parameters, an
element in particular (a particular instance) of the model class is specified.
When developing model libraries, it is often a good practice to define the com-
ponents’ interfaces separately. This facilitates the reuse of the interface definitions
and makes easier to tell whether two model classes have the same interface. In this
way, it can be reasoned that two model classes have the same interface if they have a
superclass in common: the interface definition. The interest in knowing whether two
classes have the same interface comes from the fact that having the same interface is
a necessary condition (but not sufficient) for a component of a class to be replaceable
by a component of the other class.
The rectifier circuit components, this is, the voltage source, diode, resistor and
capacitor, are two-pin components. The two pins can be declared in a class that
will be inherited by the four component classes. On the other hand, the physical
quantity describing the voltage drop between the pins intervenes in the constitutive
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
relationships of the four components. The two pins and the voltage drop are declared
in the following class.
Observe that the dot notation is used to reference the variables of the connectors
(e.g., p.u is the u variable of the p connector). The partial keyword indicates that
TwoPins is a partial class, this is, a class that describes the system partially. As a
partial class does not completely describe the system behavior, it is intended to be
inherited, not instantiated.
The protected keyword indicates the beginning of a section in which the decla-
red variables, inherited classes and instantiated components are protected elements.
This means that is not possible to access them from outside the class using dot nota-
tion. By-default, it is assumed that the elements are public. The u variable has been
declared as protected, and the p and n connectors are public. The public keyword
allows to explicitly signal the beginning of a section where public components are
declared. An arbitrary number of public and protected sections can be declared in
a class.
Two-pin components such as resistor, capacitor, induction and diode, have the
following property: the current entering a pin is equal to the current leaving the
other pin. In addition, the sign convention for passive components says that the
current arrow points into the positive voltage terminal of the element. The following
class inherits TwoPins and describes the additional behavior.
Inheritance is declared writing the extends keyword followed by the name of the
superclass, and optionally by the assignation of values to the superclass parameters.
As Modelica supports multiple inheritance, a class can contain an arbitrary
number of extends clauses.
MODEL LIBRARIES
The classes that describe the resistor, diode and capacitor are subclasses of
OnePort. They are defined below.
Observe that we have not assigned a value to the parameters of the Resistor and
Capacitor classes (the R and C parameters). In this situation, the by-default value
is zero if the parameter is of Real or Integer type, and false if Boolean. Parameter
values can be set and modified when declaring instances of the classes or inheriting
them, and at the experiment definition.
The sign convention for the voltage source is the opposite of the sign convention
for passive components. For power sources (active components), the current arrow
points outward the positive voltage terminal (see Figure 2.2). Let’s modify the
OnePort class as shown below, so that the sign convention depends on the value
assigned to the active Boolean parameter. On the other hand, remember the sign
convention for the through variables of connectors: the through variable is positive
while flows into the component.
i = n.i;
else
i = p.i;
end if;
p.i = - n.i;
end OnePort;
The if-clause allows to specify conditional equations. This is, equations that form
part of the model only while certain condition is satisfied. If the active parameter
is true, the current through the component is equal to the current at the negative
terminal (i = n.i;). If active is false, the current through the component is equal
to the current at the positive terminal (i = p.i;).
In general, the logical condition of an if-clause is a Boolean expression that
may be dependent or independent of time. The latter condition is equivalent to state
that the if-clause condition is a Boolean expression that depends only on constants
and parameters. The numerical treatment of the if-clause depends on it, as described
below.
– If the value of the if-clause condition can change during the simulation run,
then it must be monitored during the simulation run. The switching of the
if-clause can be considered an event. In this case, an event condition (see
Section 1.4) is associated to the change in the value of the if-clause condition.
It is also possible to make a treatment of the if-clause that is not based on
events. This will be explained in Lesson 8.
– If the value of the if-clause condition cannot change during the simulation
run, then it is possible to calculate it before starting the dynamical solution
of the model, replacing the if-clause by the equations of its enabled branch.
Modeling environments typically perform this substitution during the model
translation process, before analyzing the computational causality of the model,
and generating the sorted and solved model. As a consequence, the values of
the parameters that intervene in time-independent if-clause conditions can be
changed when the components are inherited or instantiated, but cannot be
changed at the experiment definition.
The voltage source can be defined as shown below. Observe that the OnePort
class is inherited modifying the value of its active parameter.
import SI = Modelica.SIunits;
import Modelica.Constants;
package Interfaces
connector Pin
SI.Voltage u;
flow SI.Current i;
end Pin;
end Interfaces;
package Components
end Components;
package Examples
model Circuit1
// Voltage source
parameter SI.Voltage U0=5;
parameter SI.Frequency frec=100;
parameter SI.Angle phi=0;
// Resistors
parameter SI.Resistance R1=100;
parameter SI.Resistance R2=100;
// Capacitor
parameter SI.Capacitance C=1e-6;
// Diode
parameter SI.Current Is=1e-9;
parameter SI.Voltage Vt=0.025;
// Components
Components.Resistor Resist1(R=R1);
Components.Resistor Resist2(R=R2);
Components.Capacitor Cond(C=C);
Components.Diode Diode(Is=Is, Vt=Vt);
Components.VsourceAC VS(U0=U0, frec=frec, phi=phi);
Components.Ground ground;
equation
connect(VS.p, Resist1.p);
connect(Resist1.n, Diode.p);
connect(Resist1.n, Resist2.p);
connect(Resist1.n, Cond.p);
connect(VS.n, ground.p);
connect(Diode.n, ground.p);
connect(Resist2.n, ground.p);
connect(Cond.n, ground.p);
end Circuit1;
end Examples;
end ElectricLib;
import SI = Modelica.SIunits;
import Modelica.Constants;
The first one makes the Modelica.SIunits class visible from within ElectricLib
and also declares SI as an abbreviation of Modelica.SIunits. Abbreviations such
as SI.Voltage and SI.Current can be used to reference Modelica.SIunits.Voltage
and Modelica.SIunits.Current respectively.
The second sentence makes visible the Modelica.Constants class from within
ElectricLib. This implies that Modelica.Constants can be the starting point of
relative paths. For instance, the Constants.pi constant is employed in the definition
of the VsourceAC class (see Modelica Code 3.2).
The import sentence can be used in a third way, as illustrated by the following
line of code.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
import Modelica.Math.*;
This import sentence makes visible all the classes declared within Modelica.Math
and allows to reference them directly. For instance, the sin function declared within
the Modelica.Math package can be referenced as sin.
In any case, in order to avoid hidden dependencies, the import sentences are
not inherited.
It can be observed in Modelica Code 3.3 that the connection of the component
connectors is described using connect sentences. As was explained, these sentences
are translated into equations by the modeling environment. It is worthy of mention
that if a connector is left unconnected, the modeling environment assumes that
its through variables are zero, adding automatically the corresponding equations to
the model.
It can also be observed in Modelica Code 3.3 how the parameter values are set
when the components are instantiated. If a component is itself a composed class, the
dot notation can be employed for referencing the parameters. This is illustrated
in the following example.
model Resistor
parameter Modelica.SIunits.Resistance R;
...
end Resistor;
model SubCircuit
Resistor R1( R=1 ), R2( R=10 );
...
end SubCircuit;
model Circuit
SubCircuit SC ( R1.R=3, R2.R=30 );
...
end Circuit;
Concerning how packages are saved to file, there are basically the two follo-
wing options.
– Save the entire package to a single file. This has typically the name of the
package and the .mo extension. In this way, the ElectricLib package would
be saved to a file named ElectricLib.mo.
model Circuit
replaceable Resistor R1(R=100), R2(R=200);
Resistor R3(R=300), R4(final R=400);
...
end Circuit;
The class of R1 and R2 can be redeclared when the Circuit class is instantiated
and inherited. For instance, R1 and R2 are redeclared as objects of the ResistorTemp
class in the CircuitT model defined below.
model CircuitT
extends Circuit (
redeclare ResistorTemp R1(alpha=1e-4),
redeclare ResistorTemp R2 );
end CircuitT;
model Circuit
replaceable Resistor R1(R=100) extends Interfaces.OnePort;
replaceable Resistor R2(R=200) extends Interfaces.OnePort;
Resistor R3(R=300), R4(final R=400);
...
end Circuit;
Modelica allows to redeclare the class of several objects without naming them
one by one. Consider the following example.
model CircuitA
replaceable model Device = Resistor;
Device R1, R2;
Resistor R3(R=300), R4(final R=400);
...
end CircuitA;
model CircuitB
extends CircuitA ( redeclare model Device = Capacitor );
end CircuitB;
The exponential waveform can be used in the definition of voltage and current
sources, as shown below.
model Vsource
extends EXP ( redeclare type SignalType=Modelica.SIunits.Voltage );
...
end Vsource;
model Isource
extends EXP ( redeclare type SignalType=Modelica.SIunits.Current );
...
end Isource;
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
dξi
pi = ∆m · with i = 1, . . . , n (3.1)
dt
The stress on each element is modeled as the force exerted by strings connected to
the element, as shown is Figure 3.3. Therefore, the bar is described as the connection
of n masses and n strings. Applying the Newton’s law to each element, it is obtained:
dpi
= Fi+1 − Fi with i = 1, . . . , n − 1 (3.2)
dt
dpn
= F − Fn (3.3)
dt
The force exerted by the strings can be calculated using Eqs. (3.4) and (3.5), and
k can be calculated from Eq. (3.6).
F1 = k · ξ1 (3.4)
Fi = k · (ξi − ξi−1 ) with i = 2, . . . , n (3.5)
E·A
k = (3.6)
∆x
The bar model is composed of Eqs. (3.1) – (3.6), and the parameter values shown
in Table 3.1. Initially, the external force is zero and the bar is at equilibrium.
At time equals 0.001 s, the external force changes abruptly to 2000 N, and this
value is maintained constant during all the simulation time. The bar model and the
experimental setup (Test model) are shown in Modelica Code 3.4. The displacements
MODEL LIBRARIES
ξ ( x, t )
F (t )
x
Figure 3.2: External force F (t) applied at the free end of a uniform bar.
se obtiene:
ξ1 ξ2 ξ n −1 ξn
= ⋅ qi 1 − qi )
k k k k F (t )
.. .
∆m ∆m ∆m ∆m
∆m = ρ ⋅ A ⋅ ∆x
Ε⋅ A
k=
∆x
Figure 3.3: Model to analyze longitudinal vibrations of a uniform bar.
of the elements i = 10, 30 and 100 obtained simulating the Test model during 0.006 s
are shown in Figure 3.4.
Vector variables have been employed in the LVib_UnifBar model to describe the
element displacements and linear momenta, and spring forces. For-clauses have been
employed to describe the equations.
Modelica provides the record class to facilitate grouping the declaration of
related parameters and setting their values. A record class cannot contain equations
or protected sections.
The separation between model equations and parameter values is a guiding
principle in other simulators. An example is the SPICE circuit simulator. The
mathematical equations that describe the supported devices (resistors, capacitors,
inductors, switches, voltage and current sources, transmission lines, diodes, BJT,
JFETs, MOSFETS, MESFETs, etc.) are built into the SPICE simulator. Each of
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
record BarData
import SI = Modelica.SIunits;
parameter SI.Area section;
parameter SI.Length length;
parameter SI.Mass mass;
parameter SI.Pressure Young;
end BarData;
package BarCatalog
end BarCatalog;
model Test
extends LVib_UnifBar( dBar = BarCatalog.Bar21() );
equation
// External force in the longitudinal direction
Fext = if time < 1e-3 then 0 else 2e3;
end Test;
Figure 3.4: Displacement of the elements i = 10, 30 and 100 obtained simulating the Test model
shown in Modelica Code 3.4 during 0.006 s.
these models contains a set of parameters. Specifying the value of these parameters,
the generic behavior described by the device model is particularized for describing
the behavior of a particular device. The values of the SPICE parameters are typically
provided by the device manufacturers, grouped into model parameter libraries.
The Modelica’s record class provides support to this principle. An example of
use can be found in Modelica Code 3.4. The BarData record contains the declaration
of the bar parameters. An instance of BarData, named dBar, has been declared within
the LVib_UnifBar partial model. The content of dBar is accessed using dot notation
(e.g., dBar.section).
The sets of parameters that describe different bar types can be arranged into a
package. The BarCatalog package is declared in Modelica Code 3.4 for this purpose.
The declaration of the Bar21 class contains the parameter values of the particular
bar that is going to be analyzed in this simulation study. Other records describing
other bar types can be included within BarCatalog.
Observe the Test class defined in Modelica Code 3.4. Test inherits LVib_UnifBar,
and BarCatalog.Bar21 is assigned to dBar. The external force exerted on the bar is
also described.
The values declared in BarCatalog.Bar21 could have been modified when assigned
to dBar. For instance, declaring
model Test
extends LVib_UnifBar( dBar = BarCatalog.Bar21(length=2) );
...
the bar length takes the value 2 m, while the other parameters take the values
specified in BarCatalog.Bar21.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
n p
...
model SeriesParts
parameter Integer n = 10;
Device part[n];
equation
for i in 1:n-1 loop
connect( part[i].p, part[i+1].n );
end for;
...
model HeatConductionA
parameter Integer N = 7;
Real Ta (unit="K");
Real Tb (unit="K");
Real T[N-2] (unit="K");
Real q[N-1] (unit="W");
parameter Real L (unit="m") = 1;
parameter Real S (unit="m2") = 0.01;
parameter Real rho (unit="kg/m3") = 7870;
parameter Real Cp (unit="J/(kg.K)") = 449;
parameter Real k (unit="W/(m.K)") = 80;
parameter Real Tstep1 (unit="K") = 300;
parameter Real Tstep2 (unit="K") = 350;
parameter Real tstep (unit="s") = 50;
parameter Real Deltax = L / (N-1);
equation
// Boundary conditions
Ta = if time < tstep then Tstep1 else Tstep2;
Tb = Tstep1;
// Bar
for i in 1:N-2 loop
S*Deltax*rho*Cp*der(T[i]) = q[i] - q[i+1];
end for;
q[1] = S*k*(Ta-T[1])/Deltax;
for i in 2:N-2 loop
q[i] = S*k*(T[i-1]-T[i])/Deltax;
end for;
q[N-1] = S*k*(T[N-2]-Tb)/Deltax;
initial equation
for i in 1:N-2 loop
T[i] = Tstep1;
end for;
end HeatConductionA;
Modelica Code 3.5: Atomic model of the longitudinal heat conduction in a bar.
Figure 3.7: Heat conduction in a bar modeled connecting temperature sources, and thermal
resistors and capacitors.
MODEL LIBRARIES
package ThermalLib
connector ThermalPin
Real T (unit="K");
flow Real q (unit="W");
end ThermalPin;
model ThermalResistor
ThermalPin p1, p2;
parameter Real S (unit="m2");
parameter Real k (unit="W/(m.K)");
parameter Real Deltax (unit="m");
equation
p1.q = S*k*(p1.T-p2.T)/Deltax;
p2.q = -p1.q;
end ThermalResistor;
model ThermalCapacitor
parameter Real S (unit="m2");
parameter Real rho (unit="kg/m3");
parameter Real Cp (unit="J/(kg.K)");
parameter Real Deltax (unit="m");
parameter Real Tinitial (unit="K");
ThermalPin p;
equation
S*Deltax*rho*Cp*der(p.T) = p.q;
initial equation
p.T = Tinitial;
end ThermalCapacitor;
model SourceT
parameter Real Tstep1 (unit="K");
parameter Real Tstep2 (unit="K");
parameter Real tstep (unit="s");
ThermalPin p;
equation
p.T = if time < tstep
then Tstep1
else Tstep2;
end SourceT;
end ThermalLib;
Modelica Code 3.6: Thermal library to model the heat conduction in a bar.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model HeatConductionB
parameter Integer N = 7;
parameter Real L (unit="m") = 1;
parameter Real S (unit="m2") = 0.01;
parameter Real rho (unit="kg/m3") = 7870;
parameter Real Cp (unit="J/(kg.K)") = 449;
parameter Real k (unit="W/(m.K)") = 80;
parameter Real Tstep1 (unit="K") = 300;
parameter Real Tstep2 (unit="K") = 350;
parameter Real tstep (unit="s") = 50;
parameter Real Deltax = L / (N-1);
ThermalLib.SourceT Ta(Tstep1=Tstep1,Tstep2=Tstep2,tstep=tstep);
ThermalLib.SourceT Tb(Tstep1=Tstep1,Tstep2=Tstep1,tstep=tstep);
ThermalLib.ThermalResistor Rth[N-1] (S=fill(S,N-1), k=fill(k,N-1),
Deltax=fill(Deltax,N-1));
ThermalLib.ThermalCapacitor Cth[N-2] (S=fill(S,N-2), rho=fill(rho,N-2),
Cp=fill(Cp,N-2), Deltax=fill(Deltax,N-2),
Tinitial=fill(Tstep1,N-2));
equation
connect (Ta.p, Rth[1].p1);
for i in 1:N-2 loop
connect (Rth[i].p2, Cth[i].p);
connect (Cth[i].p, Rth[i+1].p1);
end for;
connect (Rth[N-1].p2, Tb.p);
end HeatConductionB;
Modelica Code 3.7: Composed model of the longitudinal heat conduction in a bar.
MODEL LIBRARIES
Consider the system depicted in Figure 3.8. It is composed of a liquid storage tank
with a hole in the bottom, a source of liquid and a level control system (labeled as
“LC” in the figure). The tank is filled by the source, and drained by gravity through
the hole in the bottom. The control system measures the height of liquid in the
tank (h) and generates a voltage (uh ) that is applied to the source of liquid. The
mass flow of liquid produced by the source (Fin ) is proportional to the applied input
voltage (uh ) if the voltage is positive, and is zero if the voltage is negative.
The liquid level (h) is controlled using a PI controller, this is, a controller with
both proportional and integral control. The controller has two inputs: the setpoint
(desired or target value for the controlled variable) and the actual value of the
controlled variable. The controller calculates the error signal (e), defined as the
difference between the setpoint (href ) and the actual value of the controlled variable
(h). The controller output (uh ) is calculated as the sum of two terms: one directly
proportional to the error signal, and the other proportional to the integral of the
error signal. The PI controller is described by the following equations:
e = href − h (3.7)
Z
1 t
uh = kP · e + · e · dt (3.8)
| {z } kI 0
Proportional | {z }
term Integral
term
Let I denote the integral of the error signal. Eqs. (3.7) and (3.8) can be written
as follows:
e = href − h (3.9)
dI
= e (3.10)
dt
1
u h = kP · e + ·I (3.11)
kI
The relevant physical quantities of the system are listed in Table 3.2. The gravita-
tional acceleration (g), the cross-sectional area of the tank (A) and the hole (a), the
parameters of the source (kf ) and the PI controller (kP , kI ), and the liquid density
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
uh Fin
h
LC
Fout
Figure 3.8: Level control in a tank with a hole in the bottom.
(ρ) have constant known values. The time-dependent quantities of the system (m,
h, Fout , Fin , e, I, uh , href ) can be calculated from Eqs. (3.12) – (3.19).
dm
= Fin − Fout (3.12)
dt
m = ρ·A·h (3.13)
q
Fout = a · ρ · 2·g·h (3.14)
Fin = max (0, kf · uh ) (3.15)
e = href − h (3.16)
dI
= e (3.17)
dt
1
u h = kP · e + ·I (3.18)
kI
5m si t < 300 s
href = 3m si 300 s ≤ t < 600 s (3.19)
7m si t ≥ 600 s
The mass balance in the tank is described by Eq. (3.12). The relationship between
the liquid mass and height is described by Eq. (3.13). The mass flow rate of liquid
flowing out of the orifice depends on the liquid height as described by Eq. (3.14).
The constitutive relationship of the liquid source is Eq. (3.15), and Eqs. (3.16) –
(3.18) describe the PI controller. The liquid level setpoint is given by Eq. (3.19).
The initial state of the system is determined by setting the initial value of the
mass of liquid inside the tank and the integral of the error signal. The model is
described in Modelica Code 3.8. The result obtained simulating the model during
1000 s is shown in Figure 3.9.
Suppose that we connect to the tank a heating system composed of a heater and
a temperature controller. The system is depicted in Figure 3.10. The temperature
control system (labeled as TC in the figure) measures the liquid temperature (T )
and generates a voltage (uT ) that is applied to the heater input. If uT is positive,
then the thermal power (Q) produced by the heater is proportional to uT . If uT is
negative, Q is zero.
Q = max(0, kc · uT ) (3.20)
The temperature of the liquid stored inside the tank can be calculated from the
energy balance equation for the stored liquid. We assume that the liquid is perfectly
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model ControlTank1
import SI = Modelica.SIunits;
import Modelica.Math.*;
parameter SI.Area a=0.1 "Cross-sectional area of the hole";
parameter SI.Area A=2 "Cross-sectional area of the tank";
SI.Height e "Controller error signal";
SI.MassFlowRate Fin "Input mass flow rate";
SI.MassFlowRate Fout "Output mass flow rate";
constant SI.Acceleration g=9.81 "Gravitational acceleration";
SI.Height h "Height of liquid in the tank";
SI.Height href "Liquid level setpoint";
Real I(unit="m.s", start=0, fixed=true) "Integral of error signal";
parameter Real kf(unit="kg/(s.V)") = 100 "Source coefficient";
parameter Real kI(unit="m.s/V") = 15 "Integral parameter of PI controller";
parameter Real kP(unit="V/m") = 2 "Proportional parameter of PI controller";
SI.Mass m(start=1e3, fixed=true) "Mass of the liquid inside the tank";
SI.Voltage uh "Controller output";
parameter SI.Density rho=760 "Density of the liquid";
equation
der(m) = Fin - Fout;
m = rho*A*h;
Fout = a*rho*sqrt(2*g*h);
Fin = max(0, kf*uh);
e = href - h;
der(I) = e;
uh = kP*e + I/kI;
href = if time < 300 then 5 else if time < 600 then 3 else 7;
end ControlTank1;
Modelica Code 3.8: Tank with level control shown in Figure 3.8.
Figure 3.9: Setpoint (href ) and level (h) obtained simulating Modelica Code 3.8.
MODEL LIBRARIES
Fin ,Tin
uh
uT
h
LC
TC
T
Fout ,T
Figure 3.10: Level and temperature control in a tank with a hole in the bottom.
stirred in the tank, being at uniform temperature T . The temperature of the liquid
produced by the source is Tin . The liquid exists the tank at temperature T . The
energy balance is described in Eq. (3.21).
dH
= FH,in − FH,out + Q (3.21)
dt
|{z} | {z } | {z } |{z}
Input enthalpy Output enthalpy Input heat
Change in enthalpy flow rate flow rate flow rate
of the stored liquid
The total enthalpy (H) of the liquid stored in the tank is proportional to the
liquid mass (m), temperature (T ) and heat capacity at constant pressure (Cp ).
H = m · Cp · T (3.22)
Let’s suppose that the heat capacity of the liquid has a linear dependence with
the temperature,
where Cp,0 and Cp,1 are known constants. The enthalpy of the stored liquid and the
enthalpy flow rates can be calculated as follows:
eT = Tref − T (3.27)
dIT
= eT (3.28)
dt
1
uT = kT,P · eT + · IT (3.29)
kT,I
340 K if t < 500 s
Tref = (3.30)
320 K if t ≥ 500 s
MODEL LIBRARIES
model ControlTank2
import SI = Modelica.SIunits;
import Modelica.Math.*;
// Liquid
parameter SI.Density rho=760 "Density";
parameter SI.SpecificHeatCapacity Cp0=446 "Zero-order term of Cp";
parameter Real Cp1(unit="J/(kg.K2)") = 5.36 "1st-order coeff. of Cp";
// Tank
parameter SI.Area a=0.1 "Cross-sectional area of the hole";
parameter SI.Area A=2 "Cross-sectional area of the tank";
// Level controller
parameter Real kI(unit="m.s/V") = 15 "Integral parameter";
parameter Real kP(unit="V/m") = 2 "Proportional parameter";
// Source of liquid
parameter Real kf(unit="kg/(s.V)") = 100 "Proportionality coefficient";
// Heater
parameter Real kc(unit="W/V") = 8E+6 "Proportionality coefficient";
// Temperature controller
parameter Real kT_I(unit="K.s/V") = 50 "Integral parameter";
parameter Real kT_P(unit="V/K") = 0.3 "Proportional parameter";
equation
// Tank
der(m) = Fin - Fout;
der(H) = FHin - FHout + Q;
m = rho*A*h;
H = m*(Cp0 + Cp1*T)*T;
Fout = a*rho*sqrt(2*g*h);
FHout = Fout*(Cp0 + Cp1*T)*T;
// Source of liquid
Fin = max(0, kf*uh);
FHin = Fin*(Cp0 + Cp1*Tin)*Tin;
// Level controller
e = href - h;
der(I) = e;
uh = kP*e + I/kI;
href = if time < 300 then 5 else if time < 600 then 3 else 7;
// Temperature controller
eT = Tref - T;
der(IT) = eT;
uT = kT_P*eT + IT/kT_I;
Tref = if time < 500 then 340 else 320;
// Heater
Q = max(0,kc*uT);
end ControlTank2;
Modelica Code 3.10: Atomic model of level and temperature control in a tank (2/2).
Figure 3.11: Liquid temperature (T ) and its setpoint (Tref ) obtained simulating Modelica
Code 3.9 and 3.10. The liquid level and its setpoint are shown in Figure 3.9.
MODEL LIBRARIES
(1)
(9)
(4)
(8)
(3) (2) (7)
LC TC
(5) (6)
href Tref
Figure 3.12: System decomposition into parts (left) and library architecture (right).
The initial state of the thermal model is defined by setting the initial temperature
of the liquid stored in the tank, and setting IT to zero. The physical quantities
employed to describe the thermal behavior are listed in Table 3.3. The model is
described in Modelica Code 3.9 and 3.10. Simulating the model during 1000 s, the
temperature of the stored liquid evolves as shown in Figure 3.11.
Let’s adopt now another approach. Instead of describing the model equations
as an atomic Modelica model, we are going to model the system by applying the
object-oriented modeling methodology. The first step is to decompose the system
into its parts, deciding which model classes need to be programmed. The system
can be decomposed into the following components (see the left side of Figure 3.12):
a tank, two PI controllers (LC and TC in the figure), a source of liquid, a heater
and two setpoint signal generators (href and Tref in the figure), and a sink.
There are three classes of interaction among the system components: liquid flow,
heat transfer and signal transmission. A different symbol has been used in Figu-
re 3.12 to represent the connectors describing each class of interaction. Connectors
describing liquid flow are filled squares, connectors describing heat transfer are filled
triangles, and connectors describing signal transmission are hollow circles.
We define a library named TankControl, whose architecture is shown on the right
side of Figure 3.12. Within the TankControl package, two packages (Interface and
ProcessUnits) and the model of the complete system (ControlledTank) are defined.
The library is described in Modelica Code 3.11 – 3.13.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
import SI = Modelica.SIunits;
import Modelica.Math.*;
package Interface
connector Liquid
flow SI.MassFlowRate Fm "Mass flow rate";
flow SI.EnthalpyFlowRate FH "Enthalpy flow rate";
end Liquid;
connector Heat
flow SI.HeatFlowRate Q "Heat flow rate";
end Heat;
connector Signal
Real s;
end Signal;
end Interface;
package ProcessUnits
model PIcontroller
Interface.Signal y;
Interface.Signal ref;
Interface.Signal u;
parameter Real kI "Integral parameter";
parameter Real kP "Proportional parameter";
protected
Real e;
Real I(start=0, fixed=true) "Integral of e";
equation
e = ref.s - y.s;
der(I) = e;
u.s = kP*e + I/kI;
end PIcontroller;
model SourceLiq
Interface.Signal u;
Interface.Liquid portLiq;
parameter SI.Temperature T "Temperature of liquid";
parameter Real kf(unit="kg/(s.V)") "Coefficient of proportionality";
parameter SI.SpecificHeatCapacity Cp0 "Zero-order term of Cp";
parameter Real Cp1(unit="J/(kg.K2)") "First-order coeff. of Cp";
equation
portLiq.Fm = -max(0, kf*u.s);
portLiq.FH = portLiq.Fm*(Cp0 + Cp1*T)*T;
end SourceLiq;
Modelica Code 3.11: Composed model of level and temperature control in a tank (1/3).
MODEL LIBRARIES
model Tank
Interface.Liquid portLiqSup;
Interface.Liquid portLiqBase;
Interface.Heat portCalor;
Interface.Signal signal_h;
Interface.Signal signal_T;
equation
der(m) = portLiqSup.Fm + portLiqBase.Fm;
der(H) = portLiqSup.FH + portLiqBase.FH + portCalor.Q;
m = rho*A*h;
H = m*(Cp0 + Cp1*T)*T;
portLiqBase.Fm = -a*rho*sqrt(2*g*h);
portLiqBase.FH = portLiqBase.Fm*(Cp0 + Cp1*T)*T;
signal_h.s = h;
signal_T.s = T;
end Tank;
model Sink
Interface.Liquid portLiq;
end Sink;
model Heater
Interface.Signal cntrl;
Interface.Heat portCalor;
parameter Real kc(unit="W/V") "Coefficient of proportionality";
equation
portCalor.Q = -max(0, kc*cntrl.s);
end Heater;
model SetpointLevel
Interface.Signal ref;
equation
ref.s = if time < 300 then 5
else if time < 600 then 3 else 7;
end SetpointLevel;
Modelica Code 3.12: Composed model of level and temperature control in a tank (2/3).
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model SetpointTemp
Interface.Signal ref;
equation
ref.s = if time < 500 then 340 else 320;
end SetpointTemp;
end ProcessUnits;
model ControlledTank
import TankControl.ProcessUnits.*;
// Liquid
parameter SI.Density rho=760 "Density of liquid";
parameter SI.SpecificHeatCapacity Cp0=446 "Zero-order term of Cp";
parameter Real Cp1(unit="J/(kg.K2)") = 5.36 "First-order coeff. of Cp";
// Tank
parameter SI.Area a=0.1 "Cross-sectional area of the hole";
parameter SI.Area A=2 "Cross-sectional area of the tank";
// Source
parameter SI.Temperature Tin=300 "Temperature of input liquid";
parameter Real kf(unit="kg/(s.V)") = 100 "Coeff. of source";
// Heater
parameter Real kc(unit="W/V") = 8E+6 "Coeff. of heater";
// Level controller
parameter Real kI(unit="m.s/V") = 15 "Integral parameter of LC";
parameter Real kP(unit="V/m") = 2 "Proportional parameter of LC";
// Temperature controller
parameter Real kT_I(unit="K.s/V") = 50 "Integral parameter of TC";
parameter Real kT_P(unit="V/K") = 0.3 "Proportional parameter of TC";
// Declaration of components
SourceLiq source(kf=kf,Cp0=Cp0,Cp1=Cp1,T=Tin);
Heater heater(kc=kc);
Tank tank(a=a,A=A,rho=rho,Cp0=Cp0,Cp1=Cp1);
PIcontroller LC(kI=kI, kP=kP);
PIcontroller TC(kI=kT_I, kP=kT_P);
Sink sink;
SetpointLevel levelSP;
SetpointTemp tempSP;
equation
connect (tank.portLiqSup, source.portLiq); // (1)
connect (tank.portLiqBase, sink.portLiq); // (2)
connect (tank.signal_h, LC.y); // (3)
connect (LC.u, source.u); // (4)
connect (levelSP.ref, LC.ref); // (5)
connect (tempSP.ref, TC.ref); // (6)
connect (tank.signal_T, TC.y); // (7)
connect (heater.cntrl, TC.u); // (8)
connect (heater.portCalor, tank.portCalor); // (9)
end ControlledTank;
end TankControl;
Modelica Code 3.13: Composed model of level and temperature control in a tank (3/3).
MODEL LIBRARIES
If you compare Figure 3.10 with Figure 3.12, you may wonder why the Sink
component is included in the composed model. The reason is that if a connector
is left unconnected, the modeling environment automatically adds to the model
equations setting to zero the through variables of this connector. In this system in
particular, if the liquid flow connector at the tank bottom is left unconnected, the
modeling environment includes in the model two equations setting to zero the mass
and enthalpy flow rates through the tank hole.
This rule (i.e., flow variables of unconnected connectors are automatically set to
zero) is applied by the modeling environment not only when translates a model, but
also when checks it. For instance, if you ask Dymola to check the SourceLiq model
(see Modelica Code 3.11), you get a message indicating that the model contains
3 unknown variables (portLiq.Fm, portLiq.FH and u.s) and 4 equations: the two
equations written in the equation section of the class
portLiq.Fm = 0;
portLiq.FH = 0;
Up to this point, we have seen two ways of accessing the variables of a component.
Interface variables, this is, variables declared within connectors, can be accessed by
connecting connectors. On the other hand, dot notation allows to access inter-
face variables, and local variables not declared as protected. As will be explained in
this section, Modelica provides a third way of accessing a component: the inner/outer
construct.
Consider the following example. The Circuit class is composed of three compo-
nents of the Capacitor class, named C1, C2 and C3.
model Circuit
Capacitor C1, C2, C3;
...
end Circuit;
It is assumed that all circuit components are at the same temperature as the
ambient air, T0 . Assuming that the T0 variable is declared in the Circuit and
Capacitor classes, the condition on temperature can be described using dot notation
as follows.
model Capacitor
Real T0; // Capacitor temperature
...
end Capacitor;
model Circuit
Real T0; // Environment temperature
Capacitor C1, C2, C3;
...
equation
C1.T0 = T0;
C2.T0 = T0;
C3.T0 = T0;
end Circuit;
The use of dot notation implies in this case writing as many equations as compo-
nents. If an additional capacitor is connected to the circuit, an additional equation
equaling the capacitor and environment temperatures has to be written in the circuit
model. This does not facilitate the graphical model edition, dragging and dropping
components from a model library.
The inner/outer construct was introduced in Modelica to facilitate equaling
variables of a class with variables of its inner components. Taking advantage of this
feature, the circuit model can be described as follows.
MODEL LIBRARIES
model Capacitor
outer Real T0; // Capacitor temperature
...
end Capacitor;
model Circuit
inner Real T0; // Environment temperature
Capacitor C1, C2, C3;
...
end Circuit;
connector HeatTransfer
...
end HeatTransfer;
model Capacitor
outer HeatTransfer Qenv;
HeatTransfer Qcomp;
...
equation
connect(Qcomp, Qenv);
...
end Capacitor;
model Circuit
inner HeatTransfer Qenv;
Capacitor C1, C2, C3;
...
end Circuit;
A connector named Qenv has been declared as outer in Capacitor, and as inner in
Circuit. Therefore, the modeling environment recognizes that the Qenv connectors
of C1, C2 and C3 are alias of the Qenv connector of Circuit. As the connect sentence is
written in the Capacitor class, declaring a component of the Capacitor class implies
establishing the connection.
Modelica also supports inner/outer functions. Let’s see an example. Suppose
that the temperature T0 of the ambient air that surrounds the circuit depends on
position. It is described by a function that, given the three-dimensional coordinates
of a point, returns the temperature at that point. The interface of the function is
defined as follows.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Suppose that N different functions describing the spatial dependence of the am-
bient temperature are defined. These functions are subclasses of InterfTempAmbient.
The function that describes the ambient temperature is the same for all circuit
components. A convenient way of specifying the function as follows.
model Capacitor
outer function AmbientTemp = InterfTempAmbient;
Real r[3]; // Capacitor position
Real T0; // Temperature at the capacitor position
...
equation
r = ...
T0 = AmbientTemp(r);
...
end Capacitor;
model Circuit
inner function AmbientTemp = TempAmbient1;
Capacitor C1, C2, C3;
...
end Circuit;
Simulation of continuous-time
models
Lesson
4
Computational causality
4.1 Introduction
4.2 Classification of the model variables
4.3 Structural singularity
4.4 Partition algorithm
4.5 Overdetermined and underdetermined systems
4.6 Example: simulation of an electrical circuit
4.7 Further reading
Learning objectives
4.1 Introduction
The two following actions are performed before starting the analysis of the
computational causality.
COMPUTATIONAL CAUSALITY
For the sake of simplicity, let’s suppose by now (we will eliminate this assumption
in the next lesson) that all variables that appear differentiated can be selected as
state variables. This is equivalent to assume that the model has an equal number of
degrees of freedom, and differentiated variables.
Attending to this classification of the model variables, we can represent the set
of model equations as
F (x, y) = 0 (4.1)
where the x and y vectors represent the known and unknown variables respectively.
On the basis of this representation of the model, the incidence matrix of the
model, also known as structural Jacobian matrix, is a matrix of Boolean elements
that indicates which unknown variables intervene in each equation. The incidence
matrix can be defined as follows.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
If the j-th unknown variable does not appear in the i-th equation of the
model, then the (i, j) element of the incidence matrix is zero. Otherwise,
the element is one, and it is represented by a cross (X).
f1 (x, y, z) = 0 (4.2)
f2 (x, ẋ, y) = 0 (4.3)
f3 (x, z) = 0 (4.4)
f1 (x, y, z) = 0 (4.5)
f2 (x, derx, y) = 0 (4.6)
f3 (x, z) = 0 (4.7)
As the derivative of x appears in the model, let’s assume that x can be selected
as state variable. Selecting x as state variable, the model has the following three
unknown variables: derx, y and z. The incidence matrix is:
derx y z
f1 0 X X
f2 X
X 0
(4.8)
f3 0 0 X
The incidence matrix obtained directly from the model, before any manipulation
is applied, is named the original incidence matrix of the model.
COMPUTATIONAL CAUSALITY
The next step in the analysis of the model computational causality is to check
whether the model is structurally singular. To this end, it is checked whether:
2. Each unknown variable can be associated with an equation that satisfies the
following two conditions simultaneously: the variable intervenes in the equa-
tion, and another unknown variable has not been associated to this equation
previously.
derx y z y derx z
f1 0 X X f1 X 0 X
f2 X
X 0
→ f2 X
X 0
(4.9)
f3 0 0 X f3 0 0 X
derx y z
f1 (x, z) = 0 f1 (x, z) = 0 f1 0 0 X
f2 (x, ẋ, y) = 0 → f2 (x, derx, y) = 0 → f2 X
X 0
(4.10)
f3 (x) = 0 f3 (x) = 0 f3 0 0 0
This model contains only one equation (the equation named f2 ) to calculate two
variables (derx and y), and one equation (the equation named f3 ) does not contain
any unknown variable. As x appears differentiated in the model, we have assumed
that x is a state variable and, therefore, it is classified as a known variable: it is not
calculated from the model equations, but by numerical integration of derx.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
2. The number of equations (E) and the number of unknown variables (V ) are
not equal. In this case, the model is said to be overdetermined (E > V )
or underdetermined (E < V ). The analysis of these types of model will be
discussed in Section 4.5.
Let’s suppose that the model is not structurally singular. This is equivalent to
suppose that, by permuting the columns of the incidence matrix, it is possible to
obtain a matrix with no zeros in the main diagonal. The next step is to transform the
incidence matrix into a block lower triangular (BLT) matrix, with diagonal blocks
as smaller as possible. This transformation, known as partitioning the model,
is made by permuting rows and permuting columns of the incidence matrix. The
incidence matrix written in BLT form is named the sorted incidence matrix of
the model.
The incidence matrix in BLT form has the following property. The unknown
variables that intervene in the equations of each diagonal block are calculated from
the equations in this block, or from the equations in previous blocks.
In the particular case in which the sorted incidence matrix has all its diagonal
blocks with dimension 1 × 1, the model variables can be calculated in sequence, one
after another, using one equation to calculate each unknown variable. A diagonal
block with one element, (Ei , Vi ), indicates that the Vi variable has to be calculated
from the Ei equation. The other variables that intervene in the Ei equation (in
general, V1 , . . . , Vi−1 ) are calculated from the E1 , . . . , Ei−1 equations. If the variable
COMPUTATIONAL CAUSALITY
Rule 1. Suppose that one or more unknown variables appear in an equation, and
only one of these variables has not been evaluated yet. Then, the equation
must be employed to calculate this unevaluated unknown variable.
Rule 2. Suppose that an unknown variable has not been evaluated yet, and this
variable only appears in one of the equations whose computational causality
has not been assigned yet. Then, the unevaluated unknown variable must be
calculated from this equation.
The following example allows to illustrate this procedure for partitioning the
model. Let’s consider again the model with incidence matrix (4.8). The model and
the original incidence matrix are shown again for the reader’s convenience.
derx y z
f1 (x, y, z) = 0 f1 (x, y, z) = 0 f1 0 X X
f2 (x, ẋ, y) = 0 → f2 (x, derx, y) = 0 → f2 X
X 0
(4.11)
f3 (x, z) = 0 f3 (x, z) = 0 f3 0 0 X
1. The f3 equation contains only one unknown variable: the z variable. Therefore,
f3 must to be employed to evaluate z (Rule 1). As z not only appears in f3 , but
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
z y derx
f3 X 0 0
f1 X
X 0
(4.12)
f2 0 X X
z y derx
f3 X 0 0
f1 X
X 0
(4.13)
f2 0 X X
The sorted model, with the computational causality annotated, is shown below.
Observe that the variable to be evaluated from each equation is signaled by including
the variable within square brackets.
Then, this extended matrix is partitioned. As all the unknown variables intervene
in each dummy equation, all these dummy equations will be in the last diagonal
block of the sorted incidence matrix. All diagonal blocks except the last one define
the unknown variables that can be calculated from the model equations, and the
sequence in which these calculations must be performed.
An example is shown below. Let’s consider a model composed of two equations,
and three variables: x, y, z. The computational structure is as follows. The x, y and z
variables, and the derivative of x, appear in the first equation. The x and y variables
appear in the second equation. Therefore, the model has three unknown variables
(derx, y, z) and two equations. In order to analyze which unknown variables can be
calculated from the model, a dummy equation is added to the model.
derx y z
f1 X X X
f1 (x, ẋ, y, z) = 0
→ f2 0 X 0 (4.17)
f2 (x, y) = 0
dummy eq. X X X
y derx z
f2 X 0 0
f1 X
X X
(4.18)
dummy eq. X X X
it is necessary to know the value of the dummy variables for calculating all the
unknown variables of the model.
The E − V redundant equations (as many as dummy variables) are among the
equations of the first diagonal block. The variables of the first diagonal block are
all the dummy variables, and the unknown variables that appear in the redundant
equations.
An example is shown below. The model is composed of four equations, and has
three variables: x, y, z. The computational structure of the model equations, and
the extended incidence matrix, are shown in (4.19). Observe that a dummy variable
named α has been included in all equations.
derx y z α
f1 (y) = 0 f1 0 X 0 X
f2 (y, z) = 0 f2
0 X X X
→ (4.19)
f3 (x, y, z) = 0 f3
0 X X X
f4 (ẋ, x, z) = 0 f4 X 0 X X
y z α derx
f1 X 0 X 0
f2
X X X 0
(4.20)
f3
X X X 0
f4 0 X X X
u R1 u1 R2 u2
i i1 i2
+ 2
− 1
u0 = 0
(w) of the source, are known parameters. The circuit model is composed of the
following six equations:
u = U · sin(w · t) (4.21)
u − u1 = i · R1 (4.22)
du1
C1 · = i1 (4.23)
dt
u1 − u2 = i2 · R2 (4.24)
du2
C2 · = i2 (4.25)
dt
i = i1 + i2 (4.26)
Eqs. (4.21) – (4.25) are the constitutive relationships of the five components, and
Eq. (4.26) imposes the current conservation at node u1 .
The first step is to replace in the model the derivatives by dummy variables:
du1
dt
→ deru1 , du
dt
2
→ deru2. Making these substitutions, it is obtained:
u = U · sin(w · t) (4.27)
u − u1 = i · R1 (4.28)
C1 · deru1 = i1 (4.29)
u1 − u2 = i2 · R2 (4.30)
C2 · deru2 = i2 (4.31)
i = i1 + i2 (4.32)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The next step is to classify the model variables into known variables (time, para-
meters and state variables) and unknown variables (remaining model variables and
dummy variables introduced by replacing the derivatives). Assuming that the two
variables that appear differentiated can be selected as state variables, the variables
are classified as follows.
– Known: t
U, w, R1 , C1 , R2 , C2
u1 , u2
– Unknown: i, i1 , i2 , u
deru1, deru2
The original incidence matrix of the model is built from Eqs. (4.27) – (4.32),
taking into account the previous classification of the variables.
deru1 deru2 i i1 i2 u
u=U ·sin(w·t) 0 0 0 0 0 X
u−u1 =i·R1
0 0 X 0 0 X
C1 ·deru1 =i1 X 0 0 X 0 0
(4.33)
u1 −u2 =i2 ·R2 0 0 0 0 X 0
C2 ·deru2 =i2
0 X 0 0 X 0
i=i1 +i2 0 0 X X X 0
1. The number of equations and the number of unknown variables are equal. This
model has six equations, and six unknown variables: deru1, deru2, i, i1 , i2 , u.
u i deru1 i2 deru2 i1
u=U ·sin(w·t) X 0 0 0 0 0
u−u1 =i·R1
X X 0 0 0 0
C1 ·deru1 =i1 0 0 X 0 0 X
(4.34)
u1 −u2 =i2 ·R2 0 0 0 X 0 0
C2 ·deru2 =i2
0 0 0 X X 0
i=i1 +i2 0 X 0 X 0 X
The sorted incidence matrix can be obtained by applying the two rules, as is
described next.
1. The constitutive relationship of the voltage source contains only one unknown
variable: u. The constitutive relationship of the R2 resistor contains only one
unknown variable: i2 . Therefore, these variables must be calculated from these
equations. As these unknown variables intervene in other equations, these two
equations are moved to the firsts rows, and these variables to the firsts columns.
The deru1 variable only appears in one equation: the constitutive relationship
of the C1 capacitor. The deru2 variable only appears in one equation: the
constitutive relationship of the C2 capacitor. As the values of these variables
are not employed in calculating other variables, these two equations are moved
to the lasts rows and these variables to the lasts columns.
u i2 i i1 deru1 deru2
u=U ·sin(w·t) X 0 0 0 0 0
u1 −u2 =i2 ·R2
0 X 0 0 0 0
i=i1 +i2 0 X X X 0 0
(4.35)
u−u1 =i·R1 X 0 X 0 0 0
C1 ·deru1 =i1
0 0 0 X X 0
C2 ·deru2 =i2 0 X 0 0 0 X
2. Assuming that u and i2 have already been evaluated, the constitutive rela-
tionship of the R1 resistor has only one unevaluated variable: i. Moving this
equation to the third row and i to the third column, the following incidence
matrix is obtained.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
u i2 i i1 deru1 deru2
u=U ·sin(w·t) X 0 0 0 0 0
u1 −u2 =i2 ·R2
0 X 0 0 0 0
u−u1 =i·R1 X 0 X 0 0 0
(4.36)
i=i1 +i2 0 X X X 0 0
C1 ·deru1 =i1
0 0 0 X X 0
C2 ·deru2 =i2 0 X 0 0 0 X
3. Assuming that u, i2 and i have already been evaluated, the current conserva-
tion equation contains only one unevaluated variable: i1 . Therefore, i1 must
be calculated from the current conservation equation. The incidence matrix is
now written in BLT form.
u i2 i i1 deru1 deru2
u=U ·sin(w·t) X 0 0 0 0 0
u1 −u2 =i2 ·R2
0 X 0 0 0 0
u−u1 =i·R1 X 0 X 0 0 0
(4.37)
i=i1 +i2 0 X X X 0 0
C1 ·deru1 =i1
0 0 0 X X 0
C2 ·deru2 =i2 0 X 0 0 0 X
Therefore, the sorted model equations, with the computational causality anno-
tated, are the following:
u1 − u2
[i2 ] = (4.45)
R2
u − u1
[i] = (4.46)
R1
[i1 ] = i − i2 (4.47)
i1
[deru1] = (4.48)
C1
i2
[deru2] = (4.49)
C2
Observe that the decision on which variable to evaluate from each equation is
unique in this model. However, the equations can be sorted in several equivalent
ways. For instance, the order of Eqs. (4.44) and (4.45) can be exchanged. The same
applies to Eqs. (4.48) and (4.49).
An algorithm to simulate the circuit model is shown in Figure 4.2. The numerical
integration is performed applying the forward Euler method. Observe that the
classification of the model variables into parameters (time-independent variables),
state variables, and algebraic variables (time-dependent variables not selected as
state variables) is used as the basis for writing the simulation algorithm.
– The parameter values are set at the starting of the algorithm and are kept
constant during all the simulation.
dx
= f (x, t) (4.50)
dt
the step formula of the forward Euler method is:
where xi and xi+1 represent the value of the x variable at time ti and ti + ∆t
respectively, and f (xi , ti ) represents the derivative value (i.e., dx
dt
) at time ti .
– The values of the algebraic variables are calculated from the sorted and
solved model, which was obtained by applying the partition algorithm.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Start
∆t = 0.01
t =0
u1 ( 0 ) = 2, u2 ( 0 ) = 0
u ( t ) = U ⋅ sin ( w ⋅ t )
u ( t ) − u2 ( t )
i2 ( t ) = 1
R2
u ( t ) − u1 ( t )
i (t ) =
R1
i1 ( t ) = i ( t ) − i2 ( t )
i (t )
deru1 ( t ) = 1
C1
i2 ( t )
deru2 ( t ) =
C2
Yes End
t = t + ∆t t > 10
No
u1 ( t + ∆t ) = u1 ( t ) + deru1 ( t ) ⋅ ∆t
u2 ( t + ∆t ) = u2 ( t ) + deru2 ( t ) ⋅ ∆t
Figure 4.2: Simulation algorithm for the circuit shown in Figure 4.1.
5.1 Introduction
5.2 Structurally singular DAE systems
5.3 Index of DAE systems
5.4 Initialization of DAE systems
5.5 Selection of the state variables
5.6 Further reading
Learning objectives
– Discuss how high-index DAE systems are manipulated to reduce their index
by Modelica tools such as Dymola and OpenModelica.
5.1 Introduction
The system shown in Figure 5.1 is composed of two liquid storage tanks, con-
nected in parallel to a source of liquid. The symbols p and FV represent the bottom
pressure and the volumetric flow rate respectively, and f (t) is a known function of
time. The liquid density (ρ) and the cross-sectional area of the tanks (S1 , S2 ) have
known constant values. The model parameters C1 and C2 are calculated as shown
below, where g represents the gravitational acceleration.
S1 S2
C1 = C2 = (5.1)
ρ·g ρ·g
INDEX AND INITIALIZATION OF DAE SYSTEMS
dp1
C1 = FV ,1
FV ,1 dt
p1
dp
• C2 2 = FV , 2
FV = f (t ) dt
pS = p1
•
FV ,2 p1 = p2
pS p2 FV = FV ,1 + FV , 2
•
FV = f (t )
Figure 5.1: Two tanks connected in parallel to a liquid source.
Let’s analyze the computational causality of the model. Firstly, we replace the
derivatives by dummy variables:
dp1 dp2
→ derp1 → derp2 (5.2)
dt dt
The model shown in Figure 5.1, with the derivatives replaced by dummy varia-
bles, is the following:
Assuming that the two variables that appear differentiated (p1 and p2 ) can be
selected as state variables, the model variables are classified as follows:
– Known: t
C1 , C2
p1 , p2
– Unknown: FV,1 , FV,2 , FV , pS
derp1 , derp2
The original incidence matrix is shown below.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
As all the elements of the fourth row are zero, the model is structurally singu-
lar. Let’s analyze the computational causality applying the rules of the partition
algorithm.
1. Eq. (5.5) contains one unknown variable: pS . Eq. (5.8) contains one unknown
variable: FV . These variables have to be evaluated from these equations. The
variables are moved to the first columns and the equations to the first rows.
derp1 only appears in Eq. (5.3). derp2 only appears in Eq. (5.4). Therefore,
these variables have to be calculated from these equations. As the values of
derp1 and derp2 are not employed in calculating other unknown variables
(derp1 and derp2 only intervene in one equation), the variables are moved
to the last columns, and the equations Eqs. (5.3) and (5.4) to the last rows.
2. There are two equations, Eqs. (5.6) and (5.7), and two unknown variables, FV,1
and FV,2 , without annotated computational causality. However, the partition
algorithm cannot proceed: Eq. (5.6) does not contain any unknown variable,
and there is only one equation, Eq. (5.7), to calculate two unknown variables
(FV,1 and FV,2 ).
The partition algorithm fails in this case because we have supposed that the
model has two DoF, and we have selected p1 and p2 as state variables, but the
two-tank model does not have two DoF, but only one.
INDEX AND INITIALIZATION OF DAE SYSTEMS
The model of each tank, considered individually, has one DoF. Its initial state is
set by specifying the amount of liquid stored initially, for instance, giving an initial
value to the bottom pressure.
However, connecting the two tanks imposes their bottom pressures to be equal
(p1 = p2 ), and this constraint reduces the number of DoF. The initial value of one
pressure determines the initial value of the other pressure.
As the two-tank model has only 1 DoF, let’s select as state variable only one of
the pressures, for instance p1 . In this way, p2 is not state variable. It is classified
as unknown variable and has to be calculated from the model variables. The model
with the computational causality annotated is shown below.
This computational causality implies numerical differentiation and, for this reason,
it is not a good method from the numerical solution standpoint. Let’s explore a
different approach.
Eq. (5.6), this is, p1 = p2 , is the constraint that reduces the number of DoF. A
solution could be to replace this equation by its derivative (over-dot notation is
used to represent derivative with respect to time):
In this way, the model has 2 DoF and both pressures can be selected as state
variables.
pS = p1 (5.21)
ṗ1 = ṗ2 ← derivative of the constraint (5.22)
FV = FV,1 + FV,2 (5.23)
FV = f (t) (5.24)
For this model to have the same solution as the original one, the initial values of
the pressures must satisfy the original constraint: the initial value of p1 must be equal
to the initial value of p2 . The model, with the computational causality annotated,
is shown below.
where derp1 , derp2 , FV,1 and FV,2 are calculated by solving the system of simulta-
neous equations composed of the four last equations.
By reasoning as previously, we are assuming that p1 (t) = p2 (t) is equivalent to
impose both the equality of the initial values, p1 (t0 ) = p2 (t0 ), and the equality of
the derivatives, ṗ1 (t) = ṗ2 (t).
This assumption is mathematically correct, but it can be lead to erroneous results
if the model is solved numerically. If the numerical integrations of derp1 and derp2
are performed separately, the obtained values of p1 and p2 can be slightly different,
due to the numerical errors. This difference in the values of p1 and p2 , which is a
numerical artifice that does not correspond to the behavior described by the original
model, can be non-negligible in some applications of the model. In consequence, the
method consisting in replacing the constraint by its derivative is not adequate for
our purposes.
Let’s explore another approach. It consists in adding to the model (instead of
replacing) the derivative of the constraint that reduces the number of DoF, this is,
including the equation ṗ1 = ṗ2 in the model; and selecting only one of the pressures as
INDEX AND INITIALIZATION OF DAE SYSTEMS
state variable, for instance, p1 . In this way, the model has 7 equations and 7 unknown
variables: p2 , FV,1 , FV,2 , FV , pS , derp1 , derp2 . The model, with the computational
causality annotated, is shown below.
where derp1 , derp2 , FV,1 and FV,2 are calculated by solving the system of simultaneo-
us equations formed by the last four equations. This approach produces a satisfactory
result. In fact, this is the procedure employed by Modelica modeling environments
such as Dymola and OpenModelica. The procedure for simulating structurally
singular DAE systems is based on the following principles:
– The time derivatives are replaced by dummy variables. These dummy varia-
bles are classified as unknown variables for the assignment of computational
causality and have to be calculated from the model equations.
– The variables that appear differentiated in the model and have not been selec-
ted as state variables are classified as unknown variables for the assignment of
computational causality. These variables have to be calculated from the model
equations.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The following question arises: is there a criteria to decide which model equations
to differentiate, and how many times? Essentially, the answer to this question is:
equations are differentiated if the new equations obtained by differentiating provide
additional useful information. Another question arises: is there a criteria to calculate
the number of DoF of a DAE system?
There are algorithms that automatically provide answers to these questions. One
of these algorithms is the Pantelides algorithm. By analyzing the computational
structure of the model, the Pantelides algorithm allows to determine which model
equations have to be differentiated and how many times.
Dymola and OpenModelica implement variants of the Pantelides algorithm, sym-
bolic formula manipulation and simplification algorithms, and algorithms for selec-
ting the state variables. As a result, the complete process is performed automatically.
An example is shown below.
The model of the system depicted in Figure 5.1 is described in Modelica Code 5.1.
Before translating the model, we can ask Dymola to write the differentiated
equations in the log window. This is accomplished by selecting Output informa-
tion when differentiating for index reduction in the Simulation Setup window (see the
option (3) in Figure 5.2). In this way, during the translation of Modelica Code 5.1,
Dymola shows the following message in the log window:
giving
der(p2) = der(p1);
model TwoTanks
import SI = Modelica.SIunits;
SI.Pressure p1;
SI.Pressure p2;
SI.Pressure pS;
SI.VolumeFlowRate Fv;
SI.VolumeFlowRate Fv1;
SI.VolumeFlowRate Fv2;
parameter Real C1(unit="m3/Pa") = 1e-5;
parameter Real C2(unit="m3/Pa") = 3e-5;
equation
C1*der(p1) = Fv1;
C2*der(p2) = Fv2;
pS = p1;
p1 = p2;
Fv = Fv1 + Fv2;
Fv = sin(time);
end TwoTanks;
Modelica Code 5.1: Two-tank and source system shown in Figure 5.1.
(1)
(2)
(3)
Figure 5.2: Simulation Setup window of Dymola. (1): save to text file the flat model; (2): save to
text file the solved and sorted model; and (3): show the differentiated equations in the log window.
As will be explained in Section 5.5, Modelica allows the model developer to select
the state variables. This is accomplished through the stateSelect attribute of Real
variables. If the StateSelect.always value is assigned to this attribute, the modeling
environment selects this variable as state variable. For instance, by declaring the p2
variable as shown below, it is selected as state variable.
is defined as
the minimum number of times that all or part of (5.40) must be differen-
tiated with respect to t in order to determine ẋ as a continuous function
of x, t.
INDEX AND INITIALIZATION OF DAE SYSTEMS
ẋ = F (t, x) (5.41)
Example 2. The semi-explicit DAE shown in Eqs. (5.42) – (5.43) has index-1 if
and only if the Jacobian matrix of F2 with respect to x2 is non-singular, this
is, the Jacobian matrix has a non-zero determinant and, consequently, has an
inverse.
If ∂F2
∂x2
is non-singular, then ẋ2 can be calculated from Eq. (5.44). Replacing ẋ1
with F1 (x1 , x2 , t), then ẋ2 is obtained as a continuous function of x1 , x2 , t.
ẋ = x + y (5.45)
0 = x + 2 · y + a(t) (5.46)
ẋ = x + y (5.47)
ẋ + ȧ(t)
ẏ = − (5.48)
2
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
and replacing Eq. (5.47) in (5.48), the explicit ODE shown below is obtained.
Therefore, the DAE system shown in Eqs. (5.45) and (5.46) has index-1.
ẋ = x + y (5.49)
x + y + ȧ(t)
ẏ = − (5.50)
2
Example 4. The DAE system shown in Eqs. (5.51) – (5.52) has index-2 if and
only if the Jacobian matrix of F1 with respect to x2 , and the Jacobian matrix
of F2 with respect to x1 are non-singular. Observe that, in order to obtain
the system as an explicit ODE, Eq. (5.51) has to be differentiated once and
Eq. (5.52) has to be differentiated twice.
Example 5. Let’s consider the DAE system composed by Eqs. (5.53) and (5.54).
ẋ1 = x2 (5.53)
x1 = t2 + t + 2 (5.54)
The second equation contains only one variable: x1 . Therefore, the derivative
of x1 has to be obtained from this equation, and the derivative of x2 has to be
obtained from the first equation. Differentiating the system, it is obtained:
ẍ1 = 2 (5.57)
ẋ1 = 2 · t + 1 (5.58)
ẋ2 = 2 (5.59)
Observe that ẍ1 and ẍ2 appear in Eqs. (5.63) and (5.64), respectively.
To obtain these second-order derivatives as a function of the variables (x1 ,
x2 , x3 ), the first-order derivatives (ẋ1 , ẋ2 , ẋ3 ) and time (t), Eq. (5.64) is
differentiated:
...
x 2 = f¨2 (t) − ẍ1 (5.66)
Replacing, it is obtained:
...
f¨2 (t) − f 3 (t) = f˙1 (t) − ẋ3 (5.69)
f¨3 (t) = f˙2 (t) − ẋ1 (5.70)
ẋ2 = f˙3 (t) (5.71)
Example 7. The following property may be useful for calculating the index of DAE
systems. If the DAE system
ẋ = z (5.76)
F (t, x, z) = 0 (5.77)
has index-(n+1).
If the DAE shown in Eq. (5.75) has index-n, then ẋ is obtained as a function
of x, t by differentiating n times part or all the system. On the other hand,
as described by Eq. (5.76), ẋ is equal to z. In consequence, z is obtained as a
function of x, t by differentiating n times part or all the system. Therefore, ż
is obtained by differentiating one more time.
INDEX AND INITIALIZATION OF DAE SYSTEMS
Example 8. Let’s revisit the two-tank model described in Section 5.2. The model
equations are as follows.
In order to calculate the index of the DAE system composed of Eqs. (5.78)
– (5.83), we analyze what equations have to be differentiated to obtain an
explicit ODE
ẋ = g (x, t) (5.84)
where
Let’s analyze whether ẋ can be obtained from Eqs. (5.86) – (5.91). To this end,
we calculate the computational causality of these equations, assuming that the
unknown variables are ẋ. The original incidence matrix is shown below.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
1. There are three equations that contain only one unknown variable. These
are: Eq. (5.86) – ṗ1 ; Eq. (5.87) – ṗ2 ; and Eq. (5.91) – ḞV . Therefore, these
equations have to be employed to calculate these unknown variables.
These equations are moved to the firsts rows of the matrix and the
variables to the firsts columns.
The ṗS variable only appears in one equation: Eq. (5.88). Therefore, this
variable has to be calculated from this equation. As this variable does
not intervene in any other equation, it is moved to the last column and
Eq. (5.88) is moved to the last row.
2. Eq. (5.89) is redundant, given that ṗ1 and ṗ2 are evaluated from other
equations. On the other hand, there is only one equation, Eq. (5.90), to
calculate two unknown variables: ḞV,1 and ḞV,2 .
The conclusion is that Eqs. (5.86) – (5.91) are not a well-defined ODE system.
We proceed differentiating. The equations to be differentiated are selected
attending to the following reasoning.
– ṗS appears in only one equation: Eq. (5.88). This is the reason because
Eq. (5.88) has to be employed for evaluating ṗS . If Eq. (5.88) is differen-
tiated, a new variable is introduced, p̈S , which has to be evaluated from
this new equation. As differentiation of Eq. (5.88) does not impose an
additional constraint on the unknown variables, Eq. (5.88) is not selected
for differentiation.
INDEX AND INITIALIZATION OF DAE SYSTEMS
– The same reasoning applies to Eqs. (5.90) and (5.91), whose differentia-
tion introduces new unknown variables: F̈V , F̈V,1 and F̈V,2 .
– In consequence, we select to differentiate Eqs. (5.86), (5.87) and (5.89).
It is obtained:
Adding these three equations to the system, and removing from the system
the redundant equation (5.89), it is obtained:
Considering that the unknown variables are {ṗ1 , ṗ2 , ṗS , ḞV , ḞV,1 , ḞV,2 , p̈1 , p̈2 },
the computational causality can be assigned as described below.
– Eq. (5.97) contains only one unknown variable: ṗ1 . Therefore, this equa-
tion has to be employed to evaluate ṗ1 . For the same reason, ṗ2 has to be
evaluated from Eq. (5.98) and ḞV from Eq. (5.101).
– ṗS has to be evaluated from Eq. (5.99), where ṗ1 can be replaced with
FV,1
C1
.
– Finally, ḞV,1 , ḞV,2 , p̈1 and p̈2 can be calculated from solving the following
linear system of simultaneous equations
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The expressions to calculate ḞV,1 and ḞV,2 can be obtained by eliminating p̈1
and p̈2 in Eqs. (5.105) – (5.108)
ḞV
ḞV,1 = C1 · (5.110)
C1 + C2
ḞV
ḞV,2 = C2 · (5.111)
C1 + C2
f˙ (t)
ḞV,1 = C1 · (5.112)
C1 + C2
f˙ (t)
ḞV,2 = C2 · (5.113)
C1 + C2
The explicit ODE system shown below is obtained. In consequence, the original
DAE system has index-2.
INDEX AND INITIALIZATION OF DAE SYSTEMS
FV,1
ṗ1 = (5.114)
C1
FV,2
ṗ2 = (5.115)
C2
ḞV = f˙ (t) (5.116)
FV,1
ṗS = (5.117)
C1
f˙ (t)
ḞV,1 = C1 · (5.118)
C1 + C2
f˙ (t)
ḞV,2 = C2 · (5.119)
C1 + C2
The index is not an intrinsic property of the modeled physical system, but a
property of the equations employed to describe the model. In fact, we have seen
that the index can be reduced by differentiating a number of times certain equations
of the model.
Numerical algorithms work well for solving index-0 and index-1 DAE systems,
and in some cases, also for solving index-2 DAE systems. However, they usually
don’t work well for DAE systems whose index is higher than 2. The reason is that
the numerical solution of high-index (larger than one) DAE systems typically implies
numerical differentiation. High-index DAE systems are symbolically manipulated by
the Modelica modeling environments in order to reduce their index, before computing
their numerical solution.
To illustrate this point, let’s consider the following index-2 DAE system:
ẋ1 = x2 (5.120)
x1 = t2 + t + 2 (5.121)
Applying the implicit trapezoidal rule to the first equation, the following discre-
tized system is obtained:
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
x2 (tk+1 ) + x2 (tk )
x1 (tk+1 ) = x1 (tk ) + h · + O h2 (5.122)
2
2
x1 (tk+1 ) = tk+1 + tk+1 + 2 (5.123)
where h is the time step of the integration method. The second equation can be
employed to calculate x1 (tk+1 ), and then the first equation can be employed to
calculate x2 (tk+1 ). Solving, it is obtained that x2 (tk+1 ) is calculated by numerical
differentiation, and the error term is not O (h2 ), but O (h):
x1 (tk+1 ) − x1 (tk )
x2 (tk+1 ) = 2 · −x2 (tk ) + O (h) (5.124)
| h
{z }
Numerical differentiation
As x2 (tk+1 ) does not appear in the equations, the system cannot be solved em-
ploying the explicit Euler method and, for the same reason, any explicit integration
method.
On the other hand, let’s consider the initialization of the DAE system (5.120) –
(5.121). If x1 can be selected as state variable, then an arbitrary initial value, x1 (t0 ),
can be assigned to this variable at the initial time t0 . However, the initial value of
x1 must satisfy Eq. (5.121): the value of x1 (t0 ) is t20 + t0 + 2. Therefore, the initial
value of x1 cannot be assigned arbitrarily. The number of initial values that can be
assigned arbitrarily in this system (i.e., the number of DoF) is zero, and the number
of variables that appear differentiated is one. The number of DoF is smaller than the
number of differentiated variables. This is a common property to high-index DAE
systems.
INDEX AND INITIALIZATION OF DAE SYSTEMS
In order to analyze the initialization problem, let’s represent the DAE system in
the form shown in Eq. (5.127), where an explicit distinction is made between those
variables that appear differentiated (x ∈ ℜn ) and those that don’t (y ∈ ℜm ).
– If the original DAE system does not contain hidden constraints, then it is
structurally non-singular and its BLT incidence matrix can be obtained.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The examples shown in this section try to illustrate the search of hidden cons-
traints, the index reduction and the assignment of computational causality. The
applied procedure is as follows. Firstly, we analyze whether the original DAE system
has hidden constraints. Then, we proceed in one of two ways.
– If the DAE system has not hidden constraints, then the computational causa-
lity is assigned selecting as state variables the variables that appear differen-
tiated in the model.
1. The hidden constraints are added to the system. The resultant system,
composed of the original equations and the hidden constraints, is named
extended DAE system. The extended and original systems have the
same mathematical solution and the same number of DoF, but the index
of the extended DAE system is lower and the extended system is less
difficult numerically.
2. The number of DoF of the extended DAE system is calculated. This num-
ber will be smaller than the number of variables that appear differentiated
in the original DAE system.
3. The computational causality of the extended DAE system is assigned,
selecting as many state variables as DoF has the DAE system.
Example 1. Consider again the DAE system discussed in the previous section.
ẋ1 = x2 (5.129)
x1 = t2 + t + 2 (5.130)
As Eq. (5.131) contains only the ẍ1 and ẋ2 variables, this equation does not
impose a constraint on the initial value of (x1 , ẋ1 , x2 ).
Eq. (5.132) imposes a constraint on the initial value of ẋ1 , which must be equal
to 2 · t0 + 1.
The equations obtained by differentiating Eqs. (5.131) and (5.132) contain
new variables, not imposing any additional constraint of the initial values of
(x1 , ẋ1 , x2 ).
The extended DAE system is:
ẋ1 = x2 (5.133)
x1 = t2 + t + 2 (5.134)
ẋ1 = 2 · t + 1 (5.135)
Let’s name (x10 , ẋ10 , x20 ) the initial value of (x1 , ẋ1 , x2 ), and t0 the initial time.
The following three equations have to be satisfied:
The initial values are completely determined by the equations of the extended
DAE system. The model has zero DoF, this is, zero state variables. Observe
that the extended DAE system, composed of Eqs. (5.133) – (5.135), is equiva-
lent to the original DAE system, and the numerical solution of the extended
DAE system does not represent any difficulty. The extended model, sorted and
solved, is shown below.
[x1 ] = t2 + t + 2 (5.139)
[derx1 ] = 2 · t + 1 (5.140)
[x2 ] = derx1 (5.141)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Example 2. This example illustrates the case in which the differentiation of the
DAE system equations does not bring up any additional constraint. Let’s
consider the following DAE system
ẋ = x + y (5.142)
0 = x + 2 · y + a(t) (5.143)
ẍ = ẋ + ẏ (5.144)
0 = ẋ + 2 · ẏ + ȧ(t) (5.145)
If the initial values of the new variables are selected as shown below, then these
two new equations are satisfied by all initial values (x0 ,ẋ0 ,y0 ) of the original
variables (x, ẋ, y). In consequence, differentiating the equations with respect
to time does not produce additional constraints on the original variables.
ẋ0 + ȧ(t0 )
ẏ0 = − (5.146)
2
ẍ0 = ẋ0 + ẏ0 (5.147)
Differentiating again with respect to time, we are in the same situation. Suc-
cessive differentiation introduces new variables: the successive derivatives of ẋ,
y. In consequence, the equations obtained by differentiating successively don’t
introduce additional constraints on the original variables (x, ẋ, y).
For this reason, the initial values (x0 ,ẋ0 ,y0 ) only have to satisfy the original
DAE system. The vector of initial values has three components, which have to
satisfy two equations. Therefore, the DAE system has one DoF. One variable
can be selected as state variable. Selecting x as state variable and assigning the
computational causality, the following sorted and solved model is obtained:
x + a(t)
[y] = − (5.148)
2
[derx] = x + y (5.149)
INDEX AND INITIALIZATION OF DAE SYSTEMS
The first equation introduces two new variables (ẍ1 , ẍ2 ) and does not con-
tain the original variables (x1 , x2 , ẋ1 , ẋ2 ). The second equation is an addi-
tional constraint on the original variables. Therefore, the initial conditions
(x10 , x20 , ẋ10 , ẋ20 ) must satisfy:
d3 x1 d3 x2
+ 3 = ä(t) (5.157)
dt3 dt
2
ẍ1 + 2 · ẋ2 + 2 · x2 ẍ2 = b̈(t) (5.158)
3 3
The first equation introduces two new variables ( ddtx31 , ddtx32 ). The second equa-
tion contains ẋ2 and x2 , but it does not impose an additional constraint if, for
any initial value of ẋ2 and x2 , it is possible to find initial values of ẍ1 , ẍ2 that
satisfy the system
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
or equivalently
are identical.
Differentiating again, it is obtained:
d4 x1 d4 x2 d3 a(t)
+ = (5.166)
dt4 dt4 dt3
d3 x1 d3 x2 d3 b(t)
+ 4 · ẋ2 · ẍ2 + 2 · ẋ2 · ẍ2 + 2 · x2 · = (5.167)
dt3 dt3 dt3
4 4
The first equation introduces two new variables ddtx41 , ddtx42 . The second equa-
tion contains ẋ2 and ẍ2 , but it does not represent an additional constraint. For
any initial value of ẋ2 and ẍ , and assuming that x2 6= 0.5, it is possible to
32 3
d x1 d x2
obtain an initial value of dt3 , dt3 that satisfies the system
INDEX AND INITIALIZATION OF DAE SYSTEMS
d3 x1 d3 x2
+ 3 = ä(t) (5.168)
dt3 dt
3
d x1 d3 x2 d3 b(t)
+ 6 · ẋ2 · ẍ2 + 2 · x2 · = (5.169)
dt3 dt3 dt3
or equivalently,
d3 x1 d3 x2
+ 3 = ä(t) (5.170)
dt3 dt
d3 x1 d3 x2 d3 b(t)
+ 2 · x2 · = − 6 · ẋ2 · ẍ2 (5.171)
dt3 dt3 dt3
And so on. Therefore, the initial value vector (x10 , x20 , ẋ10 , ẋ20 ) must satisfy
the following extended DAE system, which is mathematically equivalent to the
original DAE system:
As the initial value vector has four components and must satisfy three equa-
tions, the DAE system has one DoF. Selecting x2 as state variable and assigning
the computational causality, the following sorted and solved model is obtained:
The Pantelides algorithm analyzes the structure of the DAE system to find the
minimum subset of equations whose differentiation introduces additional constraints
on the initial value vector. These constraints, together with the original equations,
must be satisfied by the initial value vector.
The algorithm employs bipartite graphs for representing the computational struc-
ture of the DAE system, and it does not require performing arithmetic operations
or symbolic differentiation.
The algorithm converges if the DAE system is well posed. The following two
examples illustrate the algorithm application to a well-posed and an ill-posed DAE
system. Both examples are based on the following model of a dynamical system:
0 = f1 (x, u1 , u2 ) (5.178)
0 = f2 (x, ẋ, y1 ) (5.179)
0 = f3 (x, y2 ) (5.180)
where u1 and u2 are the manipulated variables of the system (inputs); y1 and y2
are the observed variables (outputs); and x is an internal variable that appears
differentiated in the model. The objective is to simulate the system for the following
two computational causalities (see Figure 5.4).
– Direct problem: the evolution of the input variables is known, and the objective
is to calculate the evolution of the output variables.
– Inverse problem: the desired evolution of the output variables is known, and
the objective is to calculate the inputs that have to be applied for obtaining
these outputs.
Let’s analyze the direct problem firstly. Assuming that u1 and u2 are known
variables, and x is state variable, the computational causality is as follows
u1 y1 u1 y1
0 = f1 ( x, u1 , u2 ) 0 = f1 ( x, u1 , u2 )
0 = f 2 ( x, x& , y1 ) 0 = f 2 ( x, x& , y1 )
u2 y2 u2 y2
0 = f 3 ( x, y2 ) 0 = f 3 ( x, y2 )
Figure 5.4: Computational causality of the direct (left) and inverse (right) problems.
This DAE system is structurally singular. Let’s analyze whether the DAE system
has high index or is mathematically incorrect. To this end, let’s search for hidden
constraints on the initial value of (x, ẋ, y1 , y2 ) by differentiating the system equa-
tions. Differentiating with respect to time, it is obtained:
where:
Differentiating Eq. (5.185), a new variable appears, ẍ. The initial value of this
new variable can be selected so that the equation is satisfied for the given initial
values of x, ẋ, y1 and y2 .
Once the initial values of x, ẋ, ẍ, y1 and y2 have been determined, the initial
values of ẏ1 and ẏ2 can be selected so that Eqs. (5.186) and (5.187) are satisfied,
respectively.
...
Differentiating the equations again, the new variables x , ÿ1 and ÿ2 appear.
Therefore, new constraints on the original variables are not introduced.
Adding Eq. (5.185) to the system and assuming that x is an algebraic variable,
the computational causality of the extended DAE system is:
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
0 = f1 ([x] , u1 , u2 ) (5.188)
∂f1 ∂f1 ∂f1
0 = · [derx] + · u̇1 + · u̇2 (5.189)
∂x ∂u1 ∂u2
0 = f2 (x, derx, [y1 ]) (5.190)
0 = f3 (x, [y2 ]) (5.191)
Observe that x and its derivative (derx) are algebraic variables, which are cal-
culated from the system equations. The system has zero DoF.
Now, let’s analyze the inverse problem. The y1 and y2 variables are known,
and the objective is to calculate u1 and u2 . However, observe that u1 and u2 only
appear in the first equation of the system:
0 = f1 (x, u1 , u2 ) (5.192)
This indicates that the system does not contain enough information to calculate
both u1 and u2 . The DAE system is ill-posed for the inverse problem. It is not
possible to calculate the input trajectories that allow to obtain the desired outputs.
Let’s search for additional constraints on the initial values of (x, ẋ, u1, u2). The
Pantelides algorithm analyzes which variables intervene in the successive derivatives
of the system equations, with the purpose of identifying if any of these derivatives
is an additional constraint.
Observe that the first equation of the system,
0 = f1 (x, u1 , u2 ) (5.193)
depends, in general, on x, u1 , u2 , ẋ, u̇1 and u̇2 . Two new unknown variables are
introduced, which don’t appear in any other equation: u̇1 and u̇2 . Each of the
successive derivatives of this equation introduces two new variables that only appear
in it: the successive derivatives of u1 and u2 . Therefore, differentiating the first
equation does not introduce an additional constraint.
INDEX AND INITIALIZATION OF DAE SYSTEMS
Let’s analyze the second and third equations of the DAE system:
In general, the selection of the state variables is not unique. Different sets of
variables can be selected as state variables. This is equivalent to say that it is
possible to write the system in different ways, so that different sets of variables
appear differentiated.
An adequate selection of the state variables can, in some models, improve the
precision and reduce the computational load of the simulation. The state variables
can be selected by the model developer and the modeling environment. In the latter
case, the modeling environment can modify during the simulation the selection of
the state variables. This feature is known as dynamic selection of the states.
This section is structured into three parts. A symbolic manipulation technique
for selecting the state variables is described in Section 5.5.1. Dynamic selection of
the states is addressed in Section 5.5.2. Finally, the state variable selection by the
model developer in Modelica is discussed in Section 5.5.3.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
where x represents the variables that appear differentiated and y the variables that
don’t. Suppose that we want to select as state variables the variables (x1 , y1 ). The
technique described below allows to manipulate the system so that only (x1 , y1 )
appear differentiated. The resultant system is:
ẏ1 = a (5.199)
where a is a vector of dummy variables. The a and y1 vectors have the same
number of components. Observe that these dummy equations don’t modify
the system solution. As the dummy variables only intervene in the dummy
equations, the dummy equations must be employed to calculate the dummy
variables.
2. The extended system, composed of the original system and the dummy equa-
tions,
is a high-index DAE system. Therefore, the next step is to reduce its index,
selecting (x1 , y1 ) as state variables.
E = f (T ) (5.202)
dE
= g(T, Q) (5.203)
dt
Q = h(T ) (5.204)
where E is the internal energy of the gas stored within the control volume, T is the
gas temperature, and Q is the heat flow rate exchanged with the environment. The
f function, which relates the temperature and internal energy of the stored gas, is
in general a non-linear function.
The internal energy (E) of the gas appears differentiated in the model. Selecting
E as state variable, the model has the following computational causality:
E = f ([T ]) (5.205)
" #
dE
= g(T, Q) (5.206)
dt
[Q] = h(T ) (5.207)
Observe that the gas temperature is calculated from solving the first equation.
If f is a non-linear function, this computation can be computationally expensive.
Another approach is to select the temperature (T ) as state variable, instead of the
energy (E). In this way, the first equation is employed for calculating the energy,
which is given explicitly.
Let’s manipulate the model for obtaining the temperature as the only differen-
tiated variable. A dummy equation, Eq. (5.211), is included in the model.
E = f (T ) (5.208)
dE
= g(T, Q) (5.209)
dt
Q = h(T ) (5.210)
dT
= a (5.211)
dt
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
As the dummy variable a only intervenes in the dummy equation, Eq. (5.211)
must be employed for calculating a. Including the dummy equation does not modify
the value of the E, T and Q variables.
The extended DAE system is structurally singular: two variables appear diffe-
rentiated (E, T ) and the system has only one DoF. Let’s replace the derivatives by
dummy variables:
dE dT
→ derE → derT (5.212)
dt dt
and reduce the DAE system index. To this end, the derivative of Eq. (5.208) is added
to the system. It is obtained:
E = f (T ) (5.213)
derE = g(T, Q) (5.214)
Q = h(T ) (5.215)
derT = a (5.216)
df (T )
derE = · derT (5.217)
dT
The dummy equation has already served its purpose and can be removed from the
model. The obtained model is composed of Eqs. (5.219) – (5.222), with T selected
as state variable.
INDEX AND INITIALIZATION OF DAE SYSTEMS
The example discussed in this section illustrates the necessity of using different
sets of variables as state variables in different parts of the simulated trajectory. This
implies modifying the selection of state variables during the simulation run.
An ideal pendulum oscillating in a vertical plane is depicted in Figure 5.5. The
model is described employing Cartesian coordinates x-y. Two forces are exerted on
the mass: gravity force (m · g) and tension force (F ). The pendulum length is L.
The string has negligible mass. The model is shown below. The equations have been
labeled as (a), (b), etc. to facilitate referencing them.
m · v̇x = − Lx · F (a)
m · v̇y = − Ly · F − m · g (b)
x2 + y 2 = L2 (c)
ẋ = vx (d)
ẏ = vy (e)
Four variables (x, y, vx , vy ) appear differentiated in this model, which has two
DoF and index-3. In order to reduce the index, Eq. (c) is differentiated twice, and
Eqs. (d) and (e) are differentiated once. Adding these equations to the model and
simplifying, it is obtained:
m · v̇x = − Lx · F (a)
m · v̇y = − Ly · F − m · g (b)
x2 + y 2 = L2 (c)
ẋ = vx (d)
ẏ = vy (e)
x · ẋ + y · ẏ = 0 (c’)
x · v̇x + ẋ2 + y · v̇y + ẏ 2 = 0 (c”,d’,e’)
The computational causality depends on the state variable selection. In the four
cases, the {F , dervx, dervy} variables are evaluated from Eqs. (a), (b) and (c”,d’e’).
As this is common to the four cases, it is omitted in the following discussion. The
computational causality of the equations employed to evaluate {y, vy , derx, dery}
is as follows:
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
[derx] = vx (d)
x2 + [y]2 = L2 (c)
x · derx + y · [dery] = 0 (c’)
dery = [vy ] (e)
[derx] = vx (d)
[x]2 + y 2 = L2 (c)
x · derx + y · [dery] = 0 (c’)
dery = [vy ] (e)
[dery] = vy (e)
x2 + [y]2 = L2 (c)
x · [derx] + y · dery = 0 (c’)
derx = [vx ] (d)
[dery] = vy (e)
[x]2 + y 2 = L2 (c)
x · [derx] + y · dery = 0 (c’)
derx = [vx ] (d)
m⋅ g
Figure 5.5: Ideal pendulum oscillating in a vertical plane.
v
r y = 0, x = L, dery state variable
x ⋅ [ derx ] + y ⋅ dery = 0 → derx = 0
r
v
y = − L, x = 0, derx state variable
x ⋅ derx + y ⋅ [ dery ] = 0 → dery = 0
Figure 5.6: Mandatory causality of pendulum at vertical and horizontal positions.
Therefore, the four selections of the state variables are able to produce a divide-
by-zero error when evaluating Eq. (c’). The physical interpretation of Eq. (c’) is that
the position and velocity vectors are perpendicular. The computational causality
that Eq. (c’) should have, when the pendulum is in the vertical or horizontal position,
is shown in Figure 5.6.
It is obvious that this difficulty does not appear when the pendulum is modeled
using polar coordinates. However, this example illustrates the need of selecting the
state variables dynamically during the simulation run.
Dymola supports the dynamic selection of the state variables. To illustrate this
feature, let’s translate and simulate the model of the pendulum. The model is shown
in Modelica Code 5.2. Observe that the initial values of x and vy are specified when
the variables are declared:
The initial values are the following: x0 = 0.9, vy0 = 0. The initial value of y is
calculated from solving Eq. (c) numerically. The equation admits two solutions:
q √
y0 = ± L2 − x20 = ± 12 − 0.92 = ±0.43589 (5.224)
Depending on the initial value given to the iterative method employed for solving
Eq. (c), the method converges to the positive or negative solution. The initial value
for the iterative method is specified in the declaration of the y variable:
Setting fixed to false indicates that the value assigned to the start attribute is
the initial value of the iterative method employed for calculating the variable at the
initial time. Using 0.5 as initial value for the iterative method, it converges to the
solution with positive sign. This is, y0 = 0.43589.
It is shown in Figure 5.7 how to configure the options in the Simulation Setup
window so that Dymola displays: (1) the equations differentiated and added to the
model when the DAE index is reduced; and (2) the state variable selection during
the simulation run.
During the translation of the model shown in Modelica Code 5.2, Dymola writes
the following text in the log window:
model pendulumSelecDinVE
constant Real g(unit="m/s2") = 9.81 ;
parameter Real L(unit="m") = 1 ;
parameter Real m(unit="kg") = 5 ;
Real x(unit="m", start=0.9, fixed=true) ;
Real y(unit="m", start=0.5, fixed=false) ;
Real vx(unit="m/s") ;
Real vy(unit="m/s", start=0, fixed=true) ;
Real F(unit="N") ;
equation
m*der(vx) = -x/L*F;
m*der(vy) = -y/L*F - m*g;
x^2 + y^2 = L^2;
der(x) = vx;
der(y) = vy;
end pendulumSelecDinVE;
(2)
(1)
Figure 5.7: Simulation Setup window of Dymola, where the user configures the information to be
written in the log window during the translation and simulation. (1): equations differentiated and
added to the model for reducing the DAE index; and (2): state variable selection made during the
simulation run.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Figure 5.8: Variable Browser window after translating the model shown in Modelica Code 5.2.
In addition, Dymola writes to the log window the message shown below, indica-
ting that one state variable will be selected from {x, y}, and one from {vx, vy}.
Once the model translation is completed, the variables whose value can be
modified are displayed in the Variable Browser window (see Figure 5.8).
The model is simulated during during 3 s. The following report about the state
variable selection is written to the Dymola log window.
Selected at 0:
y.stateSelect=StateSelect.always
Selected at 0:
vy.stateSelect=StateSelect.always
Selected at 0.534:
x.stateSelect=StateSelect.always
Selected at 0.534:
vx.stateSelect=StateSelect.always
Selected at 0.84:
y.stateSelect=StateSelect.always
Selected at 0.84:
vy.stateSelect=StateSelect.always
Selected at 1.872:
INDEX AND INITIALIZATION OF DAE SYSTEMS
x.stateSelect=StateSelect.always
Selected at 1.872:
vx.stateSelect=StateSelect.always
Selected at 2.184:
y.stateSelect=StateSelect.always
Selected at 2.184:
vy.stateSelect=StateSelect.always
From time equals zero to 0.534 s, {y, vy} have been selected as state variables;
from time 0.534 s to 0.84 s, {x, vx} have been selected as state variables; etc. Dymola
alternates during the simulation run between two state variable selections: {y, vy}
and {x, vx}. Dymola employs the first selection when the pendulum trajectory is
near the horizontal axis, and the second selection when the trajectory is near the
vertical axis.
Dymola names stateSelect.set1.x[1] to the state variable that selects from set1
= {x, y}, and stateSelect.set2.x[1] to the state variable that selects from set2 =
{vx, vy}. The evolution of stateSelect.set1.x[1] and stateSelect.set2.x[1] is shown
in Figure 5.9. It can be observed that stateSelect.set1.x[1] is equal to x in part of the
trajectory, and equal to y in the rest of the trajectory; and that stateSelect.set2.x[1]
is equal to vx in part of the trajectory and equal to vy in the rest of the trajectory.
There exist several reasons why a model developer may be interested in selecting
the model state variables. Some of these reasons may be:
– Reduce the number of equations that are nonlinear with respect to the variables
to evaluate from them.
– Describe events, given that only the state variables can be reinitialized at event
instants using the reinit operator (this will be explained in later lessons).
vy
vx
Figure 5.9: Simulation of the pendulum model using Cartesian coordinates, with dynamic
selection of the state variables. Dymola defines two sets of variables: set1 = {x, y}, set2
= {vx, vy}. The model has two state variables, which Dymola name {stateSelect.set1.x[1],
stateSelect.set2.x[1]}. The stateSelect.set1.x[1] variable is selected among the variables of set1
= {x, y}, and stateSelect.set2.x[1] among the variables of set2 = {vx, vy}. During part of the
trajectory, {stateSelect.set1.x[1], stateSelect.set2.x[1]} is equal to {x, vx}, and it is equal to {y, vy}
during the rest of the trajectory. The selection of the state variables is automatically performed by
Dymola during the simulation run.
INDEX AND INITIALIZATION OF DAE SYSTEMS
Table 5.1: Possible values of the stateSelect attribute of the Real variables.
Value Meaning
The stateSelect attribute of the Real variables facilitates the model developer to
select the state variables. This is referred to as static selection of the state variables,
because the selection cannot be changed during the simulation run. The possible
values of the attribute are shown in Table 5.1. For instance:
Real w ( stateSelect = StateSelect.prefer );
A key point is that the state variable selection in Modelica does not
depend on how the model initial conditions are specified. The value assigned
to the fixed attribute does not affect the state variable selection. For instance, the
initialization of the pendulum model has been performed by setting the value of the
{x, vy} variables (see Modelica Code 5.2 and Figure 5.8), and the initial selection of
the state variables made by Dymola was {y, vy}.
The definition of DAE index and examples of its calculation can be found in
(Brenan et al. 1996).
The Pantelides algorithm is proposed in (Pantelides 1988), and the technique for
solving high-index DAE using dummy derivatives in (Mattsson & Söderlind 1992)
and (Mattsson & Söderlind 1993).
The structural analysis of DAE systems and the DAE index reduction are ex-
plained in Chapter 7 of (Cellier & Kofman 2006).
The selection of state variables in Modelica is discussed in (Mattsson et al. 2000)
and (Otter & Olsson 2002), and their dynamic selection by the modeling environment
in (Mattsson et al. 2000).
Lesson
6
Numerical methods
6.1 Introduction
6.2 Systems of simultaneous equations
6.3 Numerical solution of ODE
6.4 Numerical solution of DAE
6.5 Further reading
Learning objectives
– Discuss the principles of the DASSL integration algorithm, and the inline and
mixed-mode integration methods.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
6.1 Introduction
Once the model has been transformed into an efficiently solvable form, numerical
methods are automatically applied to simulate its evolution over time. Some basic
concepts related to these numerical methods are introduced in this lesson. The
discussion is structured into three parts: solution of algebraic loops, and numerical
integration of ODE and DAE.
A rigorous discussion on numerical methods for DAE systems requires of a solid
mathematical background and, therefore, is out of the scope of this introductory
book. The approach adopted for selecting which material to include in this lesson has
been to introduce only those concepts that we consider useful for model developers,
in order to use the Modelica modeling environments, and understand the diagnosis
and error messages generated by them.
A set of equations that form a main diagonal block of size greater than 1 × 1 in
the BLT incidence matrix is known as a system of simultaneous equations, or
equivalently, an algebraic loop. Algebraic loops may be linear and non-linear. In
the first case, the unknown variables (i.e., the variables that are evaluated from the
algebraic loop) intervene linearly in the algebraic loop. In the second case, at least
one of the unknown variables intervene non-linearly.
Algebraic loops typically arise of making the simplification that a fast dynamic
phenomenon occurs instantaneously. Let’s consider, for instance, a system composed
of pipes, liquid storage tanks and valves, which is controlled using electronic circuits.
This system has hydraulic, mechanical and electronic parts, whose time constants
are very different. The response time of the electronic circuits is typically in the
order of microseconds, while the response times of the mechanical and hydraulic
parts are in the order of 0.1 and 10 seconds, respectively. The time constants of the
mechanical and hydraulic parts differ in two orders of magnitude. However, these
parts are approximately six orders of magnitude slower than the electronic part.
Systems involving phenomena whose response times differ in three or more orders
of magnitude are known as stiff systems. If the response times differ in six or more
orders of magnitude, then the system is said to be strongly stiff.
The slowest time-constant of the system typically determines the time scale of the
system’s global response, while its fastest time-constant affects the maximum time
NUMERICAL METHODS
0 = f (x) (6.1)
dx
ε· = f (x) (6.2)
dt
where a small value is given to ε, and the sign that makes the equation to have a
stable solution.
Some basic concepts about the numerical solution of algebraic loops, that need to
be known by model developers, are explained in this section. The detailed description
of symbolic and numerical algorithms for solving algebraic loops is out of the scope
of this text.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Linear algebraic loops (i.e., those in which all unknown variables intervene li-
nearly) can be solved automatically by symbolic manipulation. However, if the num-
ber of unknown variables is large, it is typically more efficient to employ numerical
methods for solving the algebraic loop, than to evaluate the expressions obtained
from the symbolic manipulation of the algebraic loop.
Non-linear algebraic loops (i.e., those in which at least one unknown variable
intervenes non-linearly), and non-linear scalar equations, are solved using numerical
methods. In some simple cases, it is possible to manipulate the non-linear equation
in order to obtain explicitly the unknown variable. For instance, y can be obtained
explicitly from the equation:
x2 + y 2 = 1 (6.3)
Manipulating the equation, the following two solutions for y are obtained:
√
y = 1 − x2
√ (6.4)
y = − 1 − x2
The problem in this case is that the symbolic manipulator does not known
which of these two expressions to employ for calculating y. When Eq. (6.3) is solved
numerically, depending on the root-finding algorithm employed, the value used as
the initial guess, and how the mathematical problem is formulated, the algorithm
may converge to the positive root, to the negative root, or may not converge if
started too far away from a root.
Modelica allows the model developer to provide initial values for iterating the
algebraic loops of the model initialization problem. The start and fixed attributes
can be used for this purpose. If the fixed attribute is set to false, the value assigned
to the start attribute is used as initial guess by the root-finding algorithm for solving
the initialization problem. As the simulation progresses, the variable value at a time
instant is used as initial guess for calculating the solution at the next time instant.
In the Modelica models, only continuous-time variables can be calculated by
solving algebraic loops. This implies that only variables of the Real type or a type
derived from Real can be calculated from an algebraic loop. Discrete-time variables,
such as variables of Integer or Boolean types, can not be calculated from algebraic
loops.
The solution of the initialization problem is, in some models, problematic. For
this reason, some specific-purpose simulation tools implement numerical techniques
dedicated to solve the initialization problem. An example is the SPICE electronic
circuit simulator. In electronic circuit simulation, one of the challenges is convergence
of the root-finding algorithms employed in calculating the circuit operating point.
The reason is that, if the initial value of the iterative method is not selected adequa-
tely, there is no guarantee that the algorithm converges. The method implemented
in SPICE is described below.
Firstly, SPICE assumes that all independent current and voltage sources of
the circuit are at zero, and all active devices are in cut-off mode. The circuit
operating point is trivial: the voltage at all nodes is zero. Next, a transient analysis
is performed, ramping the sources up to their initial values and maintaining these
values for a while, so that the circuit is allowed to approach its steady state. Finally,
the obtained voltages are employed as initial values for computing the operating
point by Newton iteration.
The underlying idea of the SPICE method for solving the initialization problem
is of general application. Suppose that solving the model at an initial state I is
problematic, but there is another state, T , in which the model can be trivially
calculated. Then, the model is simulated, starting from the trivial state T , ramping
up the model inputs to their values at the initial state I. Once these values have
been reached, they are kept for a while, allowing the model to evolve towards the
corresponding steady state. Finally, the state obtained from this simulation is used
as initial guess for iterating the initialization problem, this is, calculating the initial
state I.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Tearing is a technique for solving non-linear algebraic loops in which at least one
unknown variable appears linearly in one equation. The objective of this technique
is to reduce the number of iterated variables.
Let’s consider the following system of simultaneous equations.
G (y) = 0 (6.5)
G (y , y ) = 0
1 1 2
(6.6)
G2 (y1 , y2 ) = 0
dx
= f (x, t) (6.7)
dt
The value of the x variable is calculated at predefined instants t0 , t1 , t2 , . . . , where
t0 is the initial time of the simulation (see Figure 6.1). The time-interval between two
consecutive instants is the integration step length: ∆t = ti −ti−1 with i = 1, 2, . . .
As x is a continuous-time variable, its evolution is typically represented interpolating
between the calculated values.
Let’s suppose that the simulation has been computed until the instant ti . This
implies that the values of x at the time instants t0 , . . . , ti are known. These are x0 ,
. . . , xi . The numerical integration method has, in general, the following form:
∆t ∆t ∆t ∆t ∆t
L
t0 t1 ti − 2 ti −1 ti ti +1 ti + 2
Figure 6.1: Temporal discretization.
The numerical integration methods differ in the form of the F function. They
are classified according to the form of F .
– Explicit and implicit method. The method is explicit if f (xi+1 ) does not
intervene in F . Otherwise, the method is implicit. For instance, the implicit
and explicit versions of the Euler’s method are shown in Table 6.1.
Table 6.1: Euler’s methods.
– Order of the method. The order of the integration method is the maximum
order of the polynomial x(t) that can be exactly represented by xi . Let’s
suppose, for instance, that f is a constant value c. The exact solution of the
equation
dx
=c (6.9)
dt
is
x = x0 + c · t (6.10)
dx
=a+b·t (6.11)
dt
NUMERICAL METHODS
1
x = x0 + a · t + · b · t2 (6.12)
2
An integration method of second order would give precise results in this case.
1. Approximating x with the first few terms of a Taylor series. The number
of terms corresponds to the order of the method. An example is the Runge-
Kutta methods. Some are shown in Table 6.2. Observe that these are explicit,
single-step methods.
The higher the order of the integration method, the more accurate the results
and also the faster the simulation, because larger time steps can be used. Integration
methods most commonly used in Engineering have order four and five.
The time step length ∆t is selected searching a compromise between accuracy
and computational cost. The smaller the time step ∆t, the more accuracy and
stability, at the expense of increased computational cost and longer simulation run-
times.
The error associated to a certain value of ∆t can be estimated by comparing
the results obtained using this value with the results obtained using a smaller time
step, for instance, ∆t
2
. If the difference is negligible for the purpose of the study,
then the value of ∆t is adequate. Otherwise, the results obtained using ∆t 2
and ∆t4
are compared. If the error is negligible, then ∆t
2
is used. If the error is too large. the
results obtained using ∆t4
and ∆t
8
are compared, and so on.
This automatic method of step size adjustment is conceptually simple, but it is
not efficient from the computational standpoint. For this reason, the variable step
size methods don’t employ it.
A more efficient procedure is to employ two embedded integration algorithms,
one with higher precision (higher order) than the other. The difference between the
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
k1 = ∆t · f (xi , ti )
Runge-Kutta 2nd order k2 = ∆t · f (xi + k1 , ti + ∆t)
1
xi+1 = xi + 2 · (k1 + k2 )
k1 = ∆t · f (xi , ti )
k1 ∆t
k2 = ∆t · f xi + 2 , ti + 2
Runge-Kutta 4th order k2 ∆t
k3 = ∆t · f xi + 2 , ti + 2
k4 = ∆t · f (xi + k3 , ti + ∆t)
k1 k2 k3 k4
xi+1 = xi + 6 + 3 + 3 + 6
Table 6.3: Some integration methods based on polynomial approximations. Note that f (xi , ti ) is
abbreviated as fi .
Order Adams-Bashforth
1 xi+1 = xi + ∆t · fi
∆t
2 xi+1 = xi + 2 · (3 · fi − fi−1 )
∆t
3 xi+1 = xi + 12 · (23 · fi − 16 · fi−1 + 5 · fi−2 )
∆t
4 xi+1 = xi + 24 · (55 · fi − 59 · fi−1 + 37 · fi−2 − 9 · fi−3 )
Order Adams-Moulton
1 xi+1 = xi + ∆t · fi+1
∆t
2 xi+1 = xi + 2 · (fi+1 + fi )
∆t
3 xi+1 = xi + 12 · (5 · fi+1 + 8 · fi − fi−1 )
∆t
4 xi+1 = xi + 24 · (9 · fi+1 + 19 · fi − 5 · fi−1 + fi−2 )
NUMERICAL METHODS
k1 = ∆t · f (xi , ti )
k1 ∆t
k2 = ∆t · f xi + 4 , ti + 4
3 9 3
k3 = ∆t · f xi + 32 · k 1 + 32 · k2 , t i + 8 · ∆t
1932 7200 7296 12
k4 = ∆t · f xi + 2197 · k1 − 2197 · k2 + 2197 · k3 , ti + 13 · ∆t
439 3680 845
k5 = ∆t · f xi + 216 · k1 − 8 · k2 + 513 · k3 − 4104 · k4 , ti + ∆t
8
k6 = ∆t · f xi − 27 · k1 + 2 · k2 − 3544 1859
2565 · k3 + 4104 · k4
− 11 ∆t
40 · k5 , ti + 2
25 1408 2197 k5
4th order xi+1 = xi + 216 · k1 + 2565 · k3 + 4104 · k4 − 5
16 6656 28561 9 2
5th order xi+1 = xi + 135 · k1 + 12825 · k3 + 56430 · k4 − 50 · k5 + 55 · k6
q−1
X
xi+1 = αk · xi−k + β0 · f (xi+1 , ti+1 ) · ∆t (6.13)
k=0
where q is the order of the method, and αk , β0 are constants, dependent on the
order, selected so that the resulting algorithm has good numerical properties. At
the beginning of the simulation, only the initial value x0 is known. Therefore, the
algorithm starts with order one. As the solution is being calculated at successive
instants, the order may be incremented. As the method also adjusts the time step
size, this is a variable order and variable step size integration method.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
6.4.1 DASSL
f (ẏ, y, t) = 0 (6.14)
and the following discretization scheme, which is employed by many implicit inte-
gration algorithms (e.g., BDF methods),
where the y and ẏ vectors represent the values at the new instant; and h is a known
scalar. The dependence of h with respect to the time step length varies from one
algorithm to another. old (y) is a function of the known values of y, calculated at the
previous time instants. For instance, the third order BDF discretization falls within
this category:
6 18 9 2
yn+1 = · h̄ ·ẏn+1 + · yn − · yn−1 + · yn−2 (6.16)
|11{z } |
11 11 {z
11 }
h old(y)
NUMERICAL METHODS
!
y − old (y)
f , y, t = 0 (6.17)
h
Newton’s method is used in DASSL for solving y from the nonlinear system of
simultaneous equations (6.17). The Newton’s method iterates over the index k:
!
k+1 k −1 yk − old (y) k
y =y −J ·f ,y ,t (6.18)
h
J−1 represents the matrix inverse of the Jacobian matrix. The Jacobian matrix
of f is defined as:
df ∂f 1 ∂f
J= = + (6.19)
dy ∂y h ∂ ẏ
7.1 Introduction
7.2 The OHM formalism
7.3 Model specification and simulation algorithm
7.4 Model specification and Modelica description
7.5 Models with a variable structure
7.6 Model initialization
7.7 Further reading
Learning objectives
7.1 Introduction
The state of hybrid models is described using both continuous-time and discrete-
time variables. The hybrid model state evolves over time as a continuous change in
the value of the continuous-time state variables, and as instantaneous changes in
the total state, continuous and discrete, named events. The simulation algorithm
of hybrid models is devised to switch between the solution of the continuous-time
problem, and the execution of the events.
A formalism for hybrid models, specially intended to facilitate their simulation,
is described in this section. The relationship of the formalism with the simulation
algorithm, and with the Modelica description is discussed. The Modelica features
for describing instantaneous changes in the model state, and changes in the model
structure, are described. Modelica support to models with a variable structure is
discussed. Finally, initialization of Modelica models is explained.
There are several formalisms for describing hybrid models. The formalism dis-
cussed in this section is based on the OHM (Omola Hybrid Model) formalism, which
was proposed in the early 1990s together with the Omola modeling language. Omola
is nowadays no longer used, but it had a relevant influence on the first proposal, and
initial development of the Modelica language.
A hybrid model M is represented as the following tuple (i.e., finite ordered
sequence of elements):
M = hq, x, y, E, G, H, Φ, ∆i (7.1)
n o
q = q1 , ..., qnq is a vector that contains the model discrete-time variables.
Discrete-time variables can be of real, integer, Boolean and string type.
x = {x1 , ..., xnx } is a vector that contains the continuous-time state variables.
Continuous-time variables can only be of real type.
n o
y = y1 , ..., yny is a vector that contains the continuous-time algebraic varia-
bles. As indicated previously, these variables are of real type.
HYBRID SYSTEM SPECIFICATION
E = {e1 , ..., ene } is a set that contains all the possible types of events.
n o
G = g1 , ..., gng is the set of expressions that define the continuous-time beha-
vior of the model. Each of these expressions represents a continuous-time
equation, so that the model equations are:
Note that we are assuming that the DAE system has been manipulated (if
necessary), so that the variables that appear differentiated are the state varia-
bles.
1. The set of admissible states, which are those that make the value of every
Boolean expression hi to be true.
2. The set of non-admissible states, which are those that make the value of
at least one of the Boolean expression to be false.
When the model trajectory crosses the boundary between these two regions,
exiting from the set of admissible states, an event is triggered. Therefore, the
invariant expressions describe (when the expression value changes from true
to false) trigger conditions of events.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The Boolean complements of the invariant expressions are named event con-
ditions. An event condition that depends on at least one continuous-time
variable is named continuous-time event condition. If an event condition
depends only on discrete-time variables, then it is named discrete-time event
condition. Time events have invariant expressions of the form:
hi = t < ti (7.5)
∆ = {δ1 , ..., δne } is a set of vector expressions that describes the instantaneous
change in the model variables produced by the execution of each event type.
These vector expressions describe vector equations with the following form:
where {xa , ẋa , ya , qa } represents the value of the variables after the event
execution, {xb , ẋb , yb , qb } the value before the event execution, and te is the
value of the time variable at the event execution instant.
At the event execution time te , a discontinuous change in the model variables
takes place. The value of the model variables changes from {xb , ẋb , yb , qb } to
{xa , ẋa , ya , qa }. The former are referred to as the previous values and the
latter as the new values.
The vector expression δi is associated to the event ei . Being known the value of
the variables before the event, the event execution is performed as follows: the
vector equation associated to the event, together with all the continuous-time
equations of the model, are solved jointly to calculate the value of the variables
after the event.
The formal specification described in Section 7.2 is closely related to the si-
mulation algorithm implemented by the Modelica modeling environments. This
algorithm, which was outlined in Section 1.4, is composed of the following parts.
HYBRID SYSTEM SPECIFICATION
4. The execution of the event. The new values of the model variables, calcu-
lated at the event time as a result of executing the event, must be consistent
initial values for the continuous-time problem, which will be resumed after
executing the event. These new values must satisfy all the equations that
describe the continuous-time behavior of the model. For this reason, the event
execution is also referred to as solving the restart problem. The execution
of the ei event consists in calculating {xa , ẋa , ya , qa } solving the following
system of equations:
Being known the previous values of the model variables, the new values of
the discrete-time variables are trivially calculated from Eq. (7.9). Next, the
new values of the continuous-time state variables are trivially calculated from
Eq. (7.10). Finally, the new values of the continuous-time algebraic variables
and derivatives are calculated from the DAE system (7.11).
Continuing with the discussion on the specification of hybrid DAE models, the
description of events in Modelica is explained below. Events are described in Mode-
lica using when clauses, and if sentences and clauses.
When clauses allow to describe changes in the value of discrete-time variables,
and to reinitialize (i.e., change discontinuously) the value of continuous-time state
variables. A when clause is composed of a logical expression describing the clause
trigger condition, and a set of equations, named instantaneous equations, in
which the new values of the variables appear explicitly indicated. The syntax of the
when clause is essentially the following:
At the time in which the logical expression changes from false to true, the changes
in the variable values described by the instantaneous equations are made. The
instantaneous equations have to be written so that the restart problem is formulated
in the form described by Eqs. (7.9) – (7.11).
indicates that while cond equals true, it must be satisfied 0 = f 1, and while cond
equals false, it must be satisfied 0 = f 2. This if sentence is automatically translated
by the modeling environment into the following equation
0 = α · f1 + (1 − α) · f2 (7.14)
where α is a discrete-time dummy variable, whose value is one while cond equals true,
and zero while cond equals false. The changes in the value of α can be performed
at events. The relationship with the OHM formalism is as follows: Eq. (7.14), which
represents the if sentence, belongs to the G set, and the α variable is a component
of the q vector.
With the purpose of making the formal specification of hybrid models more
similar to their Modelica description, we will perform the specification as follows:
2. Writing the equations (instead of the expressions) that describe the continuous-
time behavior, including the equations equivalent to the if sentences.
– The table has ne rows: one row per event type in the E set. The first
column of the table contains the consecutive numbering of its rows. The
i-th row of the table corresponds to the ei event type.
– The second column of the table contains the trigger condition of each
event type (instead of the corresponding invariant expression), this is,
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The following examples illustrate how the specification of some hybrid models
can be described.
dh
= v (7.15)
dt
dv
= −g (7.16)
dt
The initial position and velocity of the ball are denoted as h0 y v0 respectively.
The ball bounces when touches the floor. It is assumed that the direction of
the ball velocity is reversed and its magnitude is reduced by 20 %. Naming vb the
velocity before the bounce and va the velocity after the bounce, it is verified when
the bounce takes place:
HYBRID SYSTEM SPECIFICATION
va = −0.8 · vb (7.17)
For instance, if the ball velocity before bouncing is −10 m/s, then after bouncing
is 8 m/s. The negative sign of the velocity indicates that the ball is falling, while the
positive sign indicates that it is ascending. Eq. (7.17) can be described in Modelica
employing a when clause and the reinit function, as shown below.
when h ≤ 0 then
reinit(v, −0.8 · v); (7.18)
end when;
The reinit function has two arguments. The first one is the continuous-time state
variable, and the second one is a real type expression. When the reinit function is
called, the expression of the second argument is evaluated and the obtained value is
assigned to the state variable passed as first argument.
The ball position at the event execution time will be very close to zero, but
probably it will not be exactly zero. Including within the when clause another call to
the reinit function, the ball position is reinitialized to zero after the event execution.
when h ≤ 0 then
reinit(v, −0.8 · v);
(7.19)
reinit(h, 0);
end when;
The Boolean expression (h ≤ 0) is the logical condition, and the two reinit
sentences are the instantaneous equations of the when clause.
The formal specification of this model can be described as follows. The vectors
containing the model variables are shown below. As the model does not contain
discrete-time variables and continuous-time algebraic variables, the corresponding
vectors are empty.
q = {} (7.20)
x = {h, v} (7.21)
y = {} (7.22)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
va = −0.8 · vb
1 h≤0
ha = 0
The continuous-time equations are Eqs. (7.15) and (7.16). The events are descri-
bed in Table 7.1.
This model has only one type of event. Observe that the restart problem for this
event consists in calculating {ha , va , derha , derva } from the system of four equations
composed by the instantaneous equations of the event (see the second column of
Table 7.1), and the two equations that describe the continuous-time behavior, this
is, Eqs. (7.15) and (7.16). The system is written below.
va = −0.8 · vb (7.23)
ha = 0 (7.24)
derha = va (7.25)
derva = −g (7.26)
V
Fin
Fout
hmax h
h0
The drain pipe is connected at h0 height. Therefore, liquid flows through the drain
pipe only if the following two conditions are simultaneously satisfied: the liquid level
in the tank (h) is greater than h0 , and the valve is not closed. The output flow of
liquid is described by the following two-branch equation:
0 if h ≤ h0
Fout = √ (7.29)
K · V · h − h0 if h > h0
where K and h0 are parameters with known values. Eq. (7.29) can be described in
Modelica employing an if sentence, which will be automatically translated by the
modeling environment into an equation of the form:
q
Fout = α · K · V · h − h0 (7.30)
dh
A· = Fin − Fout (7.31)
dt
where the tank section, denoted as A, is a known parameter.
The system has an overflow alarm that is triggered when the liquid level inside the
tank becomes greater than a known predefined value, hmax . The alarm is described
by a Boolean variable named Alarm, whose value is calculated evaluating the logical
expression h > hmax .
The formal specification of the model is shown below. The model variables are:
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
1 α == 0 and h > h0 αa = 1
2 α == 1 and h ≤ h0 αa = 0
The equations that describe the continuous-time behavior are Eqs. (7.27), (7.28),
(7.30) and (7.31). The events are described in Table 7.2. Observe that there are four
types of events.
If the change in the value of a state variable is not explicitly indicated by an
instantaneous equation, then it is assumed that the value of this state variable does
not change at the event. An equation stating that the “before” and “after” values of
this state variable are equal is automatically included in the restart problem.
For instance, assuming that the event is triggered at time te , the restart problem
for the first type of event (see Table 7.2) is:
αa = 1 (7.35)
Alarma = Alarmb (7.36)
ha = hb (7.37)
Fina = f1 (te ) (7.38)
Va = f2 (te ) (7.39)
q
Fouta = αa · K · Va · ha − h0 (7.40)
A · derha = Fina − Fouta (7.41)
HYBRID SYSTEM SPECIFICATION
Eq. (7.35) is the instantaneous equation indicated in the event table. Eqs. (7.36)
and (7.37) indicate that the values of the Alarm and h variables don’t change at
the event. Eqs. (7.38) – (7.41) describe the continuous-time behavior. The unknown
variables to calculate from these seven equations, Eqs. (7.35) – (7.41), are: {αa ,
Alarma , ha , derha , Fina , Va , Fouta }.
Let’s consider the system depicted in Figure 7.2 that is composed of two liquid
storage tanks connected through a valve. The mass of the liquid stored in the tanks
is denoted as m1 and m2 , and the temperature of the liquid as T1 and T2 . The tank
sections, S1 and S2 , and the gravitational acceleration, g, are known parameters of
the model. The mass flow rate from tank 1 to tank 2 is denoted as F m .
The first tank is modeled writing the mass and energy balances, and the re-
lationship between the pressure at the bottom and the mass of liquid. The heat
capacity of the liquid (Cp ) is a known parameter of the model.
dm1
= −F m (7.42)
dt
T1
m1 · Cp · = −F m · Cp · (Tf − T1 ) (7.43)
dt
m1 · g
p1 = (7.44)
S1
dm2
= Fm (7.45)
dt
T2
m2 · Cp · = F m · Cp · (Tf − T2 ) (7.46)
dt
m2 · g
p2 = (7.47)
S2
The mass flow rate between the tanks (F m ) is proportional to the valve opening
(θ), and to the Kv parameter. We assume that the flow is positive if exits Tank 1
and enters Tank 2. The constitutive relationship of the valve is:
K · θ · √p − p
v 1 2 if p1 > p2
Fm = √ (7.48)
−Kv · θ · p2 − p1 if p1 ≤ p2
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
θ
m1 ,T1 m 2 ,T2
p1 p2
Fm
Figure 7.2: Liquid storage tanks connected through a valve.
The temperature of the liquid flowing through the valve (Tf ) depends on the flow
direction:
T if p1 > p2
1
Tf = (7.49)
T2 if p1 ≤ p2
The two-branch equations (7.48) and (7.49) can written as shown below, intro-
ducing a dummy variable α whose value is one while p1 > p2 , and zero otherwise.
√ √
F m = α · Kv · θ · p1 − p2 + (1 − α) · −Kv · θ · p2 − p1 (7.50)
Tf = α · T1 + (1 − α) · T2 (7.51)
The formal specification of this model is shown below. The model variables are:
q = {θ, α} (7.53)
x = {m1 , m2 , T1 , T2 } (7.54)
m
y = {F , Tf , p1 , p2 } (7.55)
HYBRID SYSTEM SPECIFICATION
1 α == 0 and p1 > p2 αa = 1
2 α == 1 and p1 ≤ p2 αa = 0
3 t > t0 θa = θ0
Tf = α · T1 + (1 − α) · T2 (7.56)
√ √
F m = α · Kv · θ · p1 − p2 + (1 − α) · −Kv · θ · p2 − p1 (7.57)
dm1
= −F m (7.58)
dt
dT1
m1 · Cp · = −F m · Cp · (Tf − T1 ) (7.59)
dt
m1 · g
p1 = (7.60)
S1
dm2
= Fm (7.61)
dt
dT2
m2 · Cp · = F m · Cp · (Tf − T2 ) (7.62)
dt
m2 · g
p2 = (7.63)
S2
The events are described in Table 7.3. Three types of events have been defined.
The two firsts types of event describe the changes in the flow direction. The third
type of event describes the abrupt change in the valve opening.
We have assumed that the mass flow through the valve is an algebraic function
of the pressure difference. This is equivalent to neglect the inertia of the circulating
liquid. Let’s now take a different approach in modeling the valve. Instead of neglec-
ting the liquid inertia, we assume now that the linear momentum of the liquid (P )
changes over time in response to the pressure difference. The valve model is shown
below. When clauses are employed to describe the change in the valve opening, and
to reinit the linear momentum when the valve becomes closed. The L parameter
represents the effective length of the valve, and Kv∗ is a characteristic parameter of
the valve.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
T if P > 0
1
Tf = (7.64)
T2 otherwise
dP
= Kv∗ · θ2 · (p1 − p2 ) (7.65)
dt
P = Fm · L (7.66)
The formal specification of the model is written next. The model variables are:
q = {θ, α} (7.69)
x = {m1 , m2 , T1 , T2 , P } (7.70)
m
y = {F , Tf , p1 , p2 } (7.71)
Tf = α · T1 + (1 − α) · T2 (7.72)
dP
= Kv∗ · θ2 · (p1 − p2 ) (7.73)
dt
P = Fm · L (7.74)
dm1
= −F m (7.75)
dt
dT1
m1 · Cp · = −F m · Cp · (Tf − T1 ) (7.76)
dt
m1 · g
p1 = (7.77)
S1
dm2
= Fm (7.78)
dt
dT2
m2 · Cp · = F m · Cp · (Tf − T2 ) (7.79)
dt
m2 · g
p2 = (7.80)
S2
HYBRID SYSTEM SPECIFICATION
Table 7.4: Events considering the inertia of the liquid that flows through the valve.
1 α == 0 and P > 0 αa = 1
2 α == 1 and P ≤ 0 αa = 0
3 t > t0 θa = θ0
4 θ≤0 Pa = 0
The model events are described in Table 7.4. There have been defined four types
of events. The two first types describe the change in the flow direction. The third
type describes the abrupt change in the valve opening. The fourth type of event sets
to zero the linear momentum of the liquid when the valve becomes closed.
A variable structure model that appears in different domains is the ideal switch.
The model has two connectors. Each connector has an across (e) and a through
(f ) variable. Let’s represent the variables of the first connector as e1 /f1 , and the
variables of the second connector as e2 /f2 . The through quantity is conserved, but is
not accumulated inside the ideal switch: f1 = −f2 . The ideal switch has two modes:
Open and Close. The constitutive relationship of the ideal switch is f1 = 0 while in
the Open mode, and it is e1 = e2 while in the Close mode.
To illustrate the previous description, a model of an ideal switch in the hydraulic
domain is represented in Figure 7.3. The actual mode of the switch is determined
by the value of a Boolean variable named OpenSw. The connector variables are
pressure (p), and volumetric flow rate (FV ).
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
OpenSW = true
Open Close
pA pB pA pB
FV = 0 p A = pB
FV FV
OpenSW = false
Figure 7.3: Two-mode model of an ideal switch in the hydraulic domain.
– While OpenSw equals true, the switch is in the Open mode: there is no flow
through the switch, and the pressure drop is determined by the rest of the
hydraulic circuit. The constitutive relationship is:
FV = 0 (7.81)
– While OpenSw equals false, the switch is in the Close mode. The pressure
drop is zero, and the flow through the switch is determined by the rest of the
hydraulic circuit. The constitutive relationship is:
pA = pB (7.82)
As described in the Section 7.4, models with a variable structure can be described
in Modelica employing if sentences. These sentences are automatically translated by
the modeling environment into equations. The constitutive relationship of the ideal
switch represented in Figure 7.3 can be described in Modelica using this if sentence:
0 = α · FV + (1 − α) · (pA − pB ) (7.84)
where the discrete-event dummy variable α is equal to one while OpenSw is true,
and is equal to zero while OpenSw is false.
The computational causality of the switch’s constitutive relationship depends on
the value of the OpenSw variable. While the value of OpenSw is true, the volumetric
HYBRID SYSTEM SPECIFICATION
flow rate is evaluated from the constitutive relationship: [FV ] = 0. While OpenSw
is false, the pressure at a connector is evaluated from the constitutive relationship:
[pA ] = pB or pA = [pB ].
The computational causality of the switch’s constitutive relationship can change
during the simulation run. Therefore, assigning the computational causality of the
complete model, the switch’s constitutive relationship will be part of an algebraic
loop. The model discussed in Section 7.5.2 illustrates it.
Let’s consider the model depicted in Figure 7.4. The main hydraulic circuit is
composed of a primary pipe connected to a source of liquid. An ideal switch and a
secondary pipe are connected in parallel to the primary pipe.
The hydraulic circuit is regulated as follows. During normal operating conditions,
the switch is open and all the liquid flows through the primary pipe (FV,2 = 0). When
the volumetric flow rate through the primary circuit is larger than a certain critical
value, the switch is closed, circulating part of the liquid flow through the secondary
hydraulic circuit (p1 = p2 ).
Let’s assume for constructing this model that the constitutive relationship of a
pipe is Eq. (7.85), where FV is the volumetric flow rate through the pipe, ∆p the
pressure drop between the pipe connectors, S is the cross sectional area of the pipe,
and cdesc is a coefficient whose value can be calculated from Eq. (7.86).
q
FV = S · cdesc · ∆p (7.85)
s
2·D
cdesc = (7.86)
κF anning · L · ρ
S · cdesc
FV = FV,0 + √ · (∆p − ∆p0 ) (7.87)
2 · ∆p0
pA − pB = R∗ + R · FV (7.88)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
OpenSw secundaria
Controlador patm
de flujo
FV ,2 p2
FV , S
FV ,1 principal
patm
p1
Figure 7.4: Hydraulic system composed of a liquid source, two pipes, and an ideal switch.
The following equations describe the hydraulic circuit shown in Figure 7.4. We
have made the simplifying assumption that the atmospheric pressure (patm ) is cons-
tant. For the sake of simplicity, the equations to calculate α have not been included
in the model.
The denominator of Eq. (7.95) is different from zero in both modes (i.e., in the
cases α = 0 and α = 1), meaning that the model is valid for the two modes of the
ideal switch. If the hydraulic system would contain N ideal switches, the complete
HYBRID SYSTEM SPECIFICATION
model would have the required algebraic loops for it to be valid in any of the 2N
possible combinations of the switches’ modes.
In this model, the number of DoF is independent of the switch mode. However,
there exist models in which the mode transitions introduce or eliminate constraints
on the state variables, which change the DoF number of the model. An example is
shown in Section 7.5.3.
P = ρ · L · S ·v = ρ · L · FV (7.99)
| {z } |{z}
Mass of liquid =S·v
The derivative of the liquid’s linear momentum is equal to the force exerted on
the liquid (Newton’s second law of motion). It is assumed that the pressure difference
between the pipe terminals is the only force exerted on the liquid that is inside the
pipe. The model is represented on the left side of Figure 7.5. In analogy with the
electrical domain, the I coefficient calculated in Eq. (7.100) is named inductance.
ρ·L
I= (7.100)
S
On the right side of Figure 7.5, the resistive behavior discussed in Section 7.5.2
is represented. Energy dissipation by friction between the liquid and the pipe wall is
described as a nonlinear algebraic relationship involving the pressure drop and the
volumetric flow rate.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
FV pA pB
pA pB
FV
2
1
ρ ⋅ L dFV p A − pB = ⋅ FV
2
⋅ = p A − pB S ⋅ cdesc
S dt
Figure 7.5: Inductive (left) and resistive (right) behavior in the hydraulic domain.
patm
OpenSw
p1 p2
p3 patm
FV
Figure 7.6: Diagram of the tank and drain pipe system.
p1 = f ( t )
1
2
OpenSw = 0
p1 − p2 = 2 p1 p2
FV
S ⋅ cdesc p3 patm
p2 − p3 = 0
FV
dFV
I⋅ = p3 − patm
dt
Figure 7.7: Drain pipe while the ideal switch is closed.
p1 = f ( t )
OpenSw = 1
2
1
p1 − p2 = FV
2
p1 p2
S ⋅ cdesc p3 patm
FV = 0
dFV FV
I⋅ = p3 − patm
dt
Figure 7.8: Drain pipe while the ideal switch is open.
HYBRID SYSTEM SPECIFICATION
Let’s consider the hydraulic circuit shown in Figure 7.6. The liquid stored in
the tank is drained through a valve-regulated pipe that is modeled as a resistive
component, an ideal switch, and an inductive component. It is assumed that the
pressure at the tank bottom is a known function of time, p1 = f (t), and the
atmospheric pressure (patm ) is a known constant.
The model equations depend on the switch mode, as described in Figures 7.7 and
7.8. Observe that the number of DoF depends on the switch mode.
– While the ideal switch is closed, the model has one DoF. The volumetric flow
rate (FV ) can be selected as state variable.
– While the ideal switch is open, the model has zero DoF. The volumetric flow
rate (FV ) is an algebraic variable that is calculated from the equation FV = 0.
The DAE index can be reduced by differentiating this equation (i.e., FV = 0)
and adding the obtained equation ( dFdtV = 0) to the system.
At the time of writing this book, the Modelica modeling environments don’t
support the simulation of models with variable number of DoF. The model developer
needs to modify the modeling hypotheses, in order to avoid runtime changes in the
number of DoF.
An approach consists in describing the switch as a resistive component with low
resistance while closed, and high resistance while open. In this way, the switch’s
constitutive relationship contains both the volumetric flow rate and the pressure
drop in the two modes. If the ideal switch is replaced by the resistive switch, the
drain pipe model depicted in Figure 7.6 has one DoF with independence of the switch
mode.
In the example discussed in Section 7.5.3, the high-index problem arises because
the constitutive relationship of the open ideal switch (FV = 0) only contains FV
(having, in consequence, FV to be calculated from this equation), and FV appears
differentiated in the constitutive relationship of the hydraulic inductor.
The dual problem arises, for instance, when two storage tanks are connected in
parallel to a liquid source, so that the flow to one of the tanks is regulated by an
ideal switch. The tank is described as a hydraulic capacitor that stores potential
energy. The number of DoF of this model depends on the switch mode, as shown in
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Figures 7.9 and 7.10. While the ideal switch is closed, its constitutive relationship
only contains the pressures at the switch connectors. As these variables appear
differentiated in the tank’s constitutive relationships, it is a high-index DAE system.
pA − pB = ε · FV if OpenSw = 0 (7.101)
1
pA − pB = · FV if OpenSw = 1 (7.102)
ε
where in this case ε is a parameter small enough for the term in which intervenes to
be negligible. As shown in Figures 7.12 – 7.15, this resistive switch produces models
with the same number of DoF in the open and closed modes.
HYBRID SYSTEM SPECIFICATION
patm
S1 dp1
⋅ = FV ,1 p1
ρ ⋅ g dt
S2 dp2
⋅ = FV ,2
ρ ⋅ g dt FV ,1
FV ,2 = 0 FV , S
patm
FV , S = FV ,1 + FV ,2 FV ,2
FV , S = f ( t ) p2
OpenSw = 1
Figure 7.9: Ideal switch is open. The model has two DoF.
patm
S1 dp1
⋅ = FV ,1 p1
ρ ⋅ g dt
S2 dp2
⋅ = FV ,2
ρ ⋅ g dt FV ,1
p1 = p2 FV , S
patm
FV , S = FV ,1 + FV ,2 FV ,2
FV , S = f ( t ) p2
OpenSw = 0
Figure 7.10: Ideal switch is closed. The model has one DoF.
OpenSw = 1 OpenSw = 0
pA pB pA pB
FV FV
FV + ε ( p A , pB ) = 0 p A − pB + ε ( FV ) = 0
[ p1 ] = f ( t )
2 OpenSw = 1
1 p1 p2
p1 − [ p2 ] = ⋅ FV
2
p3 patm
S ⋅ cdesc
1
p2 − [ p3 ] = ⋅ FV FV
ε
dF
I ⋅ V = p3 − patm
dt
Figure 7.12: Drain pipe with resistive switch open. FV is state variable.
[ p1 ] = f ( t ) OpenSw = 0
2 p1 p2
1
p1 − [ p2 ] = ⋅ FV
2
p3 patm
S ⋅ cdesc
p2 − [ p3 ] = ε ⋅ FV FV
dF
I ⋅ V = p3 − patm
dt
Figure 7.13: Drain pipe with resistive switch closed. FV is state variable.
patm
FV , S = f ( t )
p1
1
p1 − p2 = ⋅ FV ,2
ε
FV , S = FV ,1 + FV ,2 FV ,1
FV , S
S1 dp1 patm
⋅ =F
ρ ⋅ g dt V ,1 FV ,2
S2 dp2 p2
⋅ = FV ,2
ρ ⋅ g dt
OpenSw = 1
Figure 7.14: Tanks connected in parallel with resistive switch open. p1 and p2 are state variables.
patm
FV , S = f ( t )
p1
p1 − p2 = ε ⋅ FV ,2
FV , S = FV ,1 + FV ,2
FV ,1
S1 dp1 FV , S
⋅ =F patm
ρ ⋅ g dt V ,1
FV ,2
S2 dp2
⋅ = FV ,2 p2
ρ ⋅ g dt
OpenSw = 0
Figure 7.15: Tanks connected in parallel with resistive switch closed. p1 and p2 are state variables.
HYBRID SYSTEM SPECIFICATION
The model initialization, this is, the calculation of the model variables at the
initial time, is problematic in some cases. If the model contains nonlinear algebraic
loops, these are solved by applying iterative methods, using as initial guesses the
corresponding values provided by the model developer. Depending on the problem
in particular and on the proximity of the initial guess to the actual solution, the
iterative method may not converge.
Once the model has been solved at the initial time, the solution of the algebraic
loops is much less problematic during the integration of the continuous-time problem.
The initial guess for iterating the algebraic loop is the value of the variable calculated
at the previous time step. If the iterative method does not converge, the length of
the integration time step can be reduced, so that the searched solution gets closer
to the initial guess.
Observe that when an event produces instantaneous changes in the model state,
the situation can be as problematic as solving the initialization problem. The values
of the variables before the event are used as initial guess for Newton’s iteration. The
abrupt change in the model state can make the actual solution of the algebraic loop
to be “too far” from the initial guess, so that the iteration of the restart problem
does not converge.
The features provided by the Modelica language for defining the initialization
problem are discussed in this section. These are based on supporting separated
definition of the initialization problem and the dynamic problem, so that they can
be defined using different sets of equations and, consequently, their computational
causality is analyzed separately.
The initialization problem consists in calculating consistent values for all the
model variables at the initial time. The vector of unknown variables to evaluate is:
where the vector components represent the derivatives (der(x)), the variables that
appear differentiated (x), the algebraic continuous-time variables (y), the discrete-
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model Example1
parameter Real x0=1;
parameter Real a=2;
parameter Real b=3;
parameter Boolean steadyState=true;
Real x(start=x0, fixed= not steadyState);
equation
der(x) = a*x + b;
initial equation
if steadyState then
der(x) = 0;
end if;
end Example1;
time variables (q), the “previous” value of the discrete time variables (pre (q)), the
parameters (p), and the Boolean conditions of the if and when clauses c.
These unknown variables are calculated by solving the equations and algorithms
that describe the continuous-time behavior of the model, and a set of additional
constraints named initial conditions. The number of these initial conditions has
to be equal to the number of continuous-time state variables (≤ dim(x)), plus the
number of parameters (= dim(p)), plus the number of discrete-time variables (=
dim(q)).
The initial value of the continuous-time variables can be specified using the start
and fixed attributes. For instance, declaring the x variable as
Real x (start = x0, fixed = true);
these values of the start and fixed attributes are translated by the modeling environ-
ment into the following initial condition for the x variable:
x = x0
this model, the set of equations that defines the initialization problem depends on the
value of the Boolean steadyState parameter. In consequence, the modeling environ-
ment needs to be able to calculate the value of this parameter before analyzing the
computational causality of the model, and the model developer will not be allowed
to modify the value of this parameter after the model translation.
If steadyState equals true, then the following equation is an initial condition:
der(x) = 0
Additional initial conditions are the values assigned to the parameters a and b,
this is, a = 2, b = 3.
The equations and algorithms that define the continuous-time behavior of the
model have to be satisfied also at the model initialization. The continuous-time
behavior of the model shown in Modelica Code 7.1 is described using only one
equation, which has to be satisfied at the initial time:
der(x) = a*x + b
The gravitational acceleration is g = 9.81 m·s−2 . The angle with respect to the
vertical (ϕ) and the angular velocity (w) are described by the following equations:
ϕ̇ = w (7.104)
J · ẇ = −m · g · L · sin (ϕ) (7.105)
The Cartesian coordinates (x, y) are related with the angle (ϕ) and length (L):
Three different ways of initializing the pendulum model are shown in Modelica
Code 7.2.
1. Initial values are assigned to the parameters and the variables that appear
differentiated (ϕ(0) = 1 rad, w(0) = 0 rad·s−1 ).
2. Initial values are assigned to the vertical Cartesian coordinate (y(0) = 0.9 m)
and the angular velocity (w(0) = 0 rad·s−1 ). As two different values of ϕ(0)
may correspond to the same value of y(0), an initial guess for the iterative
calculation of ϕ(0) is provided: ϕ(0) ≃ 0.1 rad.
3. Initial values are assigned to the Cartesian coordinates (x(0) = 0.5 m, y(0) =
0.9 m) and the angular velocity (w(0) = 0 rad·s−1 ). The length of the pendulum
(L) and the initial value of the angle (ϕ(0)) are not specified, but initial guesses
are provided for their iterative calculation: L ≃ 1 m, ϕ(0) ≃ 0.1 rad.
1. Setting the value of the start and fixed attributes. For instance, the following
declarations
HYBRID SYSTEM SPECIFICATION
ϕ L
m
y
Figure 7.16: Simple plane pendulum.
model pendulum
parameter Real m=1, g=9.81;
parameter Real L=1;
parameter Real J=m*L^2;
Real phi (start=1, fixed=true);
Real w (start=0, fixed=true);
Real x;
Real y;
equation
der(phi) = w;
J*der(w) = -m*g*L*sin(phi);
x = sin(phi)*L;
y = cos(phi)*L;
end pendulum;
model pendulum
parameter Real m=1, g=9.81;
parameter Real L=1;
parameter Real J=m*L^2;
Real phi (start=0.1, fixed=false);
Real w (start=0, fixed=true);
Real x;
Real y (start=0.9, fixed=true);
equation
der(phi) = w;
J*der(w) = -m*g*L*sin(phi);
x = sin(phi)*L;
y = cos(phi)*L;
end pendulum;
model pendulum
parameter Real m=1, g=9.81;
parameter Real L (fixed=false) = 1;
parameter Real J=m*L^2;
Real phi (start=0.1, fixed=false);
Real w (start=0, fixed=true);
Real x (start=0.5, fixed=true);
Real y (start=0.9, fixed=true);
equation
der(phi) = w;
J*der(w) = -m*g*L*sin(phi);
x = sin(phi)*L;
y = cos(phi)*L;
end pendulum;
Modelica Code 7.2: Three different ways of initializing the pendulum model.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
pre(b) = false;
pre(i) = 1;
2. Writing the initial conditions within initial equation and initial algorithm
sections. For instance,
initial equation
pre(xd) = 0;
pre(u) = 0;
equation
when { initial(), condition1, ...} then
v = ...
end when;
Observe that a when clause is active during the initialization if and only if the
clause condition is the initial() function. It is not possible to specify initial conditions
using other conditions, such as not time < 0, or time >= 0.
If an initial condition is not specified for a discrete-time variable, it is then by-
default assumed that the value of the variable is equal to its previous value. For
instance, if the when clause where the v variable is evaluated does not contain
the initial() function as a trigger condition, then the following initial condition is
assumed: v = pre(v).
The model of the control loop shown in Figure 7.17 allows to illustrate the
initialization of the discrete-time variables. The control loop is represented as a block
diagram. The circle indicates the subtraction operation performed to calculate the
HYBRID SYSTEM SPECIFICATION
xref u x
PI xɺ = −x + u
difference between the setpoint value (xref ), and the actual output of the plant (x).
The result of this operation, which is named error signal (= xref − x), is the input
to the PI controller. The output of the PI controller (u) is the input to the plant.
The controller is a discrete-time PI controller, with sampling period TS , that is
described by the following difference equations:
TS
xd = pre (xd ) + · (xref − x) (7.108)
T
u = k · (xref − x) + xd (7.109)
where xref − x is the error signal, k and T are the proportional and integral parame-
ters respectively, xd is the integral term, which is calculated from Eq. (7.108), and
k · (xref − x) is the proportional term. As described by Eq. (7.109), the controller
output (u) is calculated by adding the proportional and integral terms.
The plant is described by the following equation:
ẋ = −x + u (7.110)
Four different ways of initializing this model are described next. In each case, the
fragment of Modelica code and the associated initialization problem are shown.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Case 1
Let’s suppose that the model of the control loop shown in Figure 7.17 is described
as indicated in the following fragment of code:
model ControlLoop
parameter Real k=10, T=1; // PI controller parameters
parameter Real Ts=0.01 "Sampling period";
Real xref "Reference";
Real x (fixed=true, start=2);
discrete Real xd (fixed=true, start=0);
discrete Real u (fixed=true, start=0);
equation
// Reference
xref = sin(time);
// Plant
der(x) = -x + u;
// Discrete PI controller
when sample(Ts,Ts) then
xd = pre(xd) + Ts/T*(xref-x);
u = k*(xref-x)+xd;
end when;
end ControlLoop;
k, T, Ts
xref
x, der(x)
xd, u, pre(xd), pre(u)
The when clause is not active during the initialization. Therefore, the following
equations are added to the initialization problem:
xd := pre(xd)
u := pre(u)
k := 10, T := 1, Ts := 0.01
xref := sin(0) // = 0
x := x.start // = 2
pre(xd) := xd.start // = 0
pre(u) := u.start // = 0
xd := pre(xd) // = 0
u := pre(u) // = 0
der(x) := -x+u // = -2
HYBRID SYSTEM SPECIFICATION
Case 2
Let’s consider another initial conditions for the control loop model:
model ControlLoop
parameter Real k=10, T=1; // PI controller parameters
parameter Real Ts=0.01 "Sampling period";
Real xref "Reference";
Real x (fixed=true, start=2);
discrete Real xd (fixed=true, start=0);
discrete Real u (fixed=true, start=0);
equation
// Reference
xref = sin(time);
// Plant
der(x) = -x + u;
// Discrete PI controller
when {initial(),sample(Ts,Ts)} then
xd = pre(xd) + Ts/T*(xref-x);
u = k*(xref-x)+xd;
end when;
end ControlLoop;
xd := pre(xd) + Ts/T*(xref-x)
u := k*(xref-x) + xd
k := 10, T := 1, Ts := 0.01
xref := sin(0) // = 0
x := x.start // = 2
pre(xd) := xd.start // = 0
pre(u) := u.start // = 0
xd := pre(xd)+Ts/T*(xref-x) // = -0.02
u := k*(xref-x)+xd // = -20.02
der(x) := -x+u // = -22.02
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Case 3
Let’s suppose that the control loop model is initialized as shown below. In this
case, the when clause is active during the initialization, and the previous values of
the discrete-time variables are assigned in the initial equation section.
model ControlLoop
parameter Real k=10, T=1; // PI controller parameters
parameter Real Ts=0.01 "Sampling period";
Real xref "Reference";
Real x (fixed=true, start=2);
discrete Real xd;
discrete Real u;
equation
// Reference
xref = sin(time);
// Plant
der(x) = -x + u;
// Discrete PI controller
when {initial(),sample(Ts,Ts)} then
xd = pre(xd) + Ts/T*(xref-x);
u = k*(xref-x)+xd;
end when;
initial equation
pre(xd) = 0;
pre(u) = 0;
end ControlLoop;
k := 10, T := 1, Ts := 0.01
xref := sin(0) // = 0
x := x.start // = 2
pre(xd) := 0 // = 0
pre(u) := 0 // = 0
xd := pre(xd)+Ts/T*(xref-x) // = -0.02
u := k*(xref-x)+xd // = -20.02
der(x) := -x+u // = -22.02
HYBRID SYSTEM SPECIFICATION
Case 4
In this case, the control loop model is initialized imposing that it is at steady
state:
model ControlLoop
parameter Real k=10, T=1; // PI controller parameters
parameter Real Ts=0.01 "Sampling period";
Real xref "Reference";
Real x (fixed=false, start=2);
discrete Real xd;
discrete Real u;
equation
// Reference
xref = sin(time);
// Plant
der(x) = -x + u;
// Discrete PI controller
when {initial(),sample(Ts,Ts)} then
xd = pre(xd) + Ts/T*(xref-x);
u = k*(xref-x)+xd;
end when;
initial equation
pre(xd) = xd;
pre(u) = u;
der(x) = 0;
end ControlLoop;
k := 10, T := 1, Ts := 0.01
xref := sin(0) // =0
der(x) = 0
// Linear system of 4 simultaneous equations
// Unknown variables: xd, pre(xd), u, x
| pre(xd) = xd
| xd = pre(xd)+Ts/T*(xref-x)
| u = k*(xref-x)+xd
| der(x) = -x+u
pre(u) = u
k := 10, T := 1, Ts := 0.01
xref := sin(0) // = 0
der(x) := 0 // = 0
xd := xref // = 0
u := xref // = 0
x := xref // = 0
pre(xd) := xd // = 0
pre(u) := u // = 0
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The model developer can specify initial conditions using the start and fixed
attributes, and the initial equation and initial algorithm sections. These initial
conditions, the by-default initial conditions, and the equations and algorithms that
describe the continuous-time behavior, constitute the initialization problem.
In posing the initialization problem, Modelica allows to replace some of these
equations that describe the model continuous-time behavior, by other equations
that are only used at the model initialization. To this end, if sentences with the
initial() function as condition can be employed. For instance,
equation
y = if initial() then
// expression used only at the model initialization
else
// expression used during the simulation
The OHM formalism and the Omola algorithm for hybrid model simulation are
described in (Andersson 1990) and (Andersson 1994). We have used these two theses
as references in preparing this lesson.
The event detection and iteration are discussed in (Cellier 1979) and (Cellier
et al. 1993).
The initialization procedure for Modelica models is described in (Mattsson et al.
2002). The explanations given in Section 7.6 are extracted from this article.
Simulation of variable structure models is discussed in (Elmqvist 1993), (Elmqvist
et al. 1993) and (Cellier et al. 1995). We have employed these three articles as
references in preparing this lesson.
The Modelica features for hybrid modeling are described in (ModelicaTM 2000),
(Otter 2009), (Fritzson 2011) and (Tiller 2001). As their reading was recommended
in previous lessons, probably the reader is now familiar with these books.
Lesson
8
8.1 Introduction
8.2 Simultaneous events
8.3 Crossing function
8.4 Determination of the event instant
8.5 Chattering
8.6 Further reading
Learning objectives
8.1 Introduction
In this section, the detection and handling of events are analyzed more in-depth.
The concept of the crossing function is also explained, showing how the Modelica
modeling environments use crossing functions to detect the events. Finally, the
chattering is explained.
The execution of an event can generate the triggering, in that same instant, of
another event. This happens when the solution of the restart problem does not satisfy
one of the invariants, and, consequently, the event corresponding to this invariant is
immediately executed. In this way, several events can be sequentially executed until
all invariants are satisfied, and then, the solution of the continuous-time problem is
resumed. The execution of a sequence of events is called an event chain.
When only one invariant is not satisfied, there is no doubt about how to proceed.
However, several events can be detected simultaneously during the solution of the
continuous-time problem. Also, several invariants can be not satisfied at certain
step in the execution of an event chain. In both cases, it is necessary to establish a
criterion to decide how to execute these simultaneously triggered events.
The order in which simultaneously triggered events are executed may be irrele-
vant. This is typically the case when these events affect to different parts of the model
that don’t interact among them. However, the execution order may be relevant,
affecting to the solution of the restart problem. Let’s consider, for instance, the
model described by Eqs. (8.1) – (8.5).
dx1
= 1 (8.1)
dt
dx2
= −1 (8.2)
dt
x1 + x2 = y (8.3)
1. If all the invariant expressions are satisfied, then the solution of the continuous-
time problem is resumed.
2. If only one invariant expression is not satisfied, the event associated to this
invariant is executed.
3. If several invariant expressions are not satisfied, the event with less order of
definition, among the events associated to these invariant, is executed.
Table 8.1: Result of executing the event whose condition is (x1 ≥ 0.5 · y).
Before the event execution After the event execution
x1 = 5 x1 = 0
x2 = 5 x2 = 5
y = 10 y=5
(x1 ≥ 0.5 · y) = true (x1 ≥ 0.5 · y) = f alse
(x2 ≤ 0.5 · y) = true (x2 ≤ 0.5 · y) = f alse
Table 8.2: Result of executing the event whose condition is (x2 ≤ 0.5 · y).
Before the event execution After the event execution
x1 = 5 x1 = 5
x2 = 5 x2 = 10
y = 10 y = 15
(x1 ≥ 0.5 · y) = true (x1 ≥ 0.5 · y) = f alse
(x2 ≤ 0.5 · y) = true (x2 ≤ 0.5 · y) = f alse
model dispEvent
Real x1(start=0, fixed=true);
Real x2(start=10, fixed=true);
Real y;
equation
der(x1) = 1;
der(x2) = -1;
x1 + x2 = y;
when x1 >= 0.5*y then
reinit(x1,0);
end when;
when x2 <= 0.5*y then
reinit(x2,10);
end when;
end dispEvent;
Modelica Code 8.1: Model used to illustrate the simultaneous triggering of two events.
EVENT DETECTION AND HANDLING
Algorithm:
Step 1. Execute the event with less order of definition among the
triggered events. An event is triggered when the value of its
invariant expression is false.
Step 2. Check whether there are triggered events. If this is the
case, go to Step 1. Otherwise, resume the solution of the
continuous-time problem.
Other different algorithm would be:
Algorithm:
Step 1. Determine and sort out, according to the definition order,
the set of triggered events. This set is named E ′ .
Step 2. If the set E ′ is empty, resume the solution of the continuous-
time problem, finishing this algorithm.
Step 3. Execute the first event of the E ′ set.
Step 4. Consider the next event of the sorted set E ′ . If this event
has not been executed yet and it is still triggered, this event
is executed.
Step 5. If every event of E ′ has been examined, go to Step 1.
Otherwise, go to Step 4.
Another approach consists in executing simultaneously all the triggered events.
This is the approach adopted in Modelica. To this end, the single-assignment rule
is imposed. This rule states that all the instantaneous changes in a continuous-time
or discrete-time state variable must be described in a single instantaneous equation.
This guarantees that the same state variable is not changed by two instantaneous
equations simultaneously active. The potential risk of executing simultaneously
several events that assign different values to a same state variable is eliminated.
Applying this criterion (i.e., executing simultaneously all the triggered events)
to the previous example, the result shown in the Table 8.3 is obtained. To check it,
let’s describe the model in Modelica as shown in Modelica Code 8.1, and simulate
it using Dymola.
Dymola can be configured for writing information on the executed events in the
message window during the simulation. To this end, the option Event logging has
to be selected in the Debug tab of the Simulation Setup window, before translating
the model (see Figure 8.1). The results obtained by executing the simulation during
16 s with Dymola are shown in Figure 8.2. Dymola writes in the message window
the following report, describing the events detected and iterated (determination of
the event trigger time) during the simulation.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Figure 8.1: Configuring Dymola so that the information on the event detection and iteration
during the model initialization and simulation is written in the message window.
– The numerical integration algorithm advances, using its own method for ad-
justing the time step size. The algorithm proceeds until it is detected that
one or several event conditions have become true. The two event conditions of
this model become true when time becomes greater that t = 5 s. As events
have been detected, the numerical integration of the continuous-time problem
is halted.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
– The restart problem is solved at the calculated event trigger time. If the
solution of the restart problem triggers events, these are executed. In this
way, the event chain is executed until all the event conditions are false. There
is no event chain in this model: the event conditions calculated solving the
restart problem are false.
– Events are detected when time becomes greater than t = 15 s. The same
procedure is applied.
eveps
t
− eveps
Figure 8.3: When z crosses −eveps with negative slope, the event condition is considered to
change its value from true to false. When z crosses +eveps with positive slope, the event condition
is considered to change its value from false to true.
Let’s see an example. Suppose that the y variable is described by means of the
following if sentence,
This sentence states that while x > xLimit, the y variable is equal to the y1
variable. Otherwise, the y variable is equal to the y2 variable. The event detection
can be made by associating the event condition x > xLimit to the following crossing
function (named z):
z = x − xLimit (8.9)
– The change of the event condition from false to true is detected when z crosses
eveps with positive slope.
– The change of the event condition from the true to false is detected when z
crosses −eveps with negative slope.
This is equivalent to associate to the event condition the two crossing functions
shown below, and to watch their cross through the zero value.
zp = z + eveps (8.10)
zn = z − eveps (8.11)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
If the z crossing function initially remains inside the interval (−eveps, eveps)
due to the initial conditions, the value of the crossing function is assumed to be zero
during this time and it is used the corresponding branch of the if expression.
The value of eveps is very small. The by-default value used by Dymola and Open-
Modelica is 1E-10. This value can be changed, although this is not recommended: it
is preferable to re-scale the model than modify eveps. In any case, the procedure to
change eveps in Dymola is explained below.
To change the eveps value, the experiment file generated by Dymola (dsin.txt)
has to be manually edited, after the model has been translated and before running
the simulation. For avoiding Dymola to re-write the dsin.txt file when the simulation
is launched, the simulation must not be executed from the user-interface of Dymo-
la. Instead, it has to be launched by executing the following command from the
operating system shell, in the working directory (where Dymola has generated the
dymosim.exe and dsin.txt files):
dymosim dsin.txt
When the simulation finishes, Dymola stores the results in a file named dsres.mat.
This file can be opened from the graphical-user-interface of Dymola (Plot > Open
Result) to represent graphically the model variables.
To illustrate how Dymola performs the event detection, we are going to simulate
the model shown in Modelica Code 8.2 using two different values of eveps. The first
simulation of the model has been performed using the by-default value of eveps, i.e.,
1E-10. In the second simulation, the value 0.6 has been manually assigned to eveps.
To this end, the following line of the dsin.txt file has been replaced
1.0000000000000000E-010 # eveps Hysteresis epsilon at event points
by:
0.6000000000000000 # eveps Hysteresis epsilon at event points
and then dymosim.exe has been executed from a MS-DOS shell. Afterwards, the
results have been loaded from Dymola to obtain a graphical representation.
The results of the two simulations are shown in Figure 8.4. The event condition
(x > 0) is translated into two crossing functions: zp = x + eveps, zn = x − eveps.
The event condition is detected to change from false to true when x crosses +eveps
with positive slope, and from true to false when x crosses −eveps with negative
slope. This is clearly visible in the plot placed in the lower part of Figure 8.4.
EVENT DETECTION AND HANDLING
model ejemEveps
Real x;
Real y;
equation
y = if x > 0 then 1 else -1;
x = sin(time);
end ejemEveps;
Figure 8.4: Simulation results for two values of eveps: 1E-10 (upper plot) and 0.6 (lower plot).
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model BouncingBall1
Modelica.SIunits.Distance x(start=10, fixed=true);
Modelica.SIunits.Velocity v(start=0, fixed=true);
parameter Real c = 0.8 "Coeff. elastic bouncing";
parameter Modelica.SIunits.Acceleration g = 9.8;
equation
der(v) = -g;
der(x) = v;
when x <= 0 then
reinit(v, -c*v);
end when;
end BouncingBall1;
Modelica Code 8.3: Vertical fall and bouncing of a ball.
( x ≤ 0) : true → false
eveps
− eveps
( x ≤ 0) : false → true ( x ≤ 0) : false → true
Figure 8.6: Results of simulating the Modelica Code 8.3, but with an initial height of 5E − 9 m.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Depending on its trigger condition, events can be classified into time events and
state events.
Likewise, time events can be classified into exogenous and endogenous. If the
trigger time is specified in the model, the event is said to be exogenous. If this
time is computed during the simulation execution as a result of the execution of a
previous time event or state event, the time event is said to be endogenous.
During the solution of the continuous-time problem, when the next time event
is scheduled within the next time step of the integration algorithm, the time step
length is modified so that the evaluation time is equal to the time event. Once the
event is executed, the integration algorithm is resumed, using its own method to set
the size of the integration step.
The state events are triggered when the system state satisfies certain conditions.
The trigger time of state events is not known in advanced and must be calculated
during the simulation (event iteration).
To illustrate the iterative method employed to calculate the event trigger time,
let’s consider a two-branch equation, so that each branch is valid only in a certain
domain of the state space. State events indicate the end of the validity domain of a
branch and the start of the validity domain of the other. The modeling environment
automatically define crossing functions for detecting state events. These functions
indicate the crossing of the trajectory in the space state from one domain to the
other one. When a state event is detected, the integration is halted, and the event
iteration (iterative algorithm to determine the time instant in which the event is
triggered) is started. This calculation implies the evaluation of the equation. To this
end, the “old” branch is used, extending the “old” branch beyond its validity
domain. Once the event trigger time is determined, the “old” branch of the equation
is switched to the “new” branch. The restart problem is solved using the “new”
branch of the equation. The integration algorithm is resumed, starting at the event
instant, using the “new” branch of the function.
The model developer needs to take into account that the event detection proce-
dure requires evaluating equation branches beyond their definition domain. If this
is not possible, a runtime numerical error will be generated when the trajectory in
the state space crosses the definition domains of the equation branches.
EVENT DETECTION AND HANDLING
The following example illustrates this problem. Suppose that the mass flow rate
of liquid (F ) through a valve is related with the pressure drop (∆p) by means of the
constitutive relationship of the valve:
q
F = sgn (∆p) · K · ∆p (8.12)
where the sign function returns one if its argument is positive or zero, and minus
one if negative. K is a constant that depends on the valve geometry, the friction
factor and the liquid density.
If the constitutive relationship of the valve is described as follows,
F = if ∆p > 0
then K · (∆p)0.5 (8.13)
else −K · (−∆p)0.5
numerical error will be produced at runtime, when the sign of ∆p changes. The
reason is that the branch switching event is detected (evaluating and checking the
crossing functions) after every algebraic variable has been evaluated. That is, after
the square root of a real negative number has been attempted to be calculated,
producing the corresponding numerical error.
The numerical error would be avoided if the simulation algorithm checks, before
evaluating the two-branch equation, which of the two branches to use, which depends
on the value of the condition in that time instant. The Modelica language provides
an operator, named noEvent(), to indicate this way to proceed with a particular
equation.
For example, writing in Modelica
F = if noEvent(difPresion > 0)
then K*difPresion^0.5 else -K*(-difPresion)^0.5;
the modeling environment will check, before evaluating the right-hand side expres-
sion of the equation, which of the two branches to use.
Additionally, the noEvent() operator indicates to the modeling environment that,
in case of a change of branch, it must not iterate to find the precise time instant in
which the event was triggered. This way of evaluating variable structure equations,
avoiding event iteration, is called performing a textual handling of the equation,
as opposed to the event-based handling.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
8.5 Chattering
model BouncingBall2
Modelica.SIunits.Distance x(start=10, fixed=true);
Modelica.SIunits.Velocity v(start=0, fixed=true);;
parameter Real c = 0.8 "Coeff. elastic bouncing";
parameter Modelica.SIunits.Acceleration g = 9.8;
equation
der(v) = if (x <= 0) then 0 else -g;
der(x) = v;
when x <= 0 then
reinit(v, -c*v);
end when;
end BouncingBall2;
Modelica Code 8.4: Model with chattering of the vertical fall and bouncing of a ball.
number of state events has been 141128. As the number of state events is very high,
Dymola indicates that the model may be exhibiting chattering. Part of the message
generated by Dymola is reproduced below.
Figure 8.8: The ball reaches a stationary periodic behavior, which is a numerical artifact originated
by the event detection procedure.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
9.1 Introduction
9.2 Ideal electric switch
9.3 Ideal diode
9.4 Two-tank and valve system
9.5 Bouncing ball
9.6 Dry fiction
9.7 Heat conduction in a wall
9.8 Further reading
Learning objectives
9.1 Introduction
Hybrid models are those that combine continuous-time behavior with events.
An event is a set of actions that are triggered when a certain condition is satisfied.
Therefore, the definition of an event consists of specifying the logic condition that
triggers it, and the actions to be performed.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
The execution of the actions associated to the event does not consume simulated
time. For this reason, those variables that change due to the event have two values
at the time in which the event is triggered: the value before the event execution and
the value after the event execution.
Modelica provides the function pre() to distinguish between the variable value
before the event, pre(variable), and the new value of the variable after the event
execution, which is referred using the name of the variable. For example, if the
instantaneous equation that describes the action associated to an event is:
x = 2 · pre(x) (9.1)
then the value of the x variable is doubled each time this event is executed.
The actions that Modelica allows to perform in an event are basically of the
following three types:
If sentences and if clauses are employed to describe the first type of action. For
the last two, the when clause is employed. This is explained in detail below.
The if-sentence and the if-clause allow to describe models with a variable struc-
ture. Both can be included in equation and algorithm sections.
HYBRID MODELING PRACTICE
if cond then
equations
else (9.4)
equations
end if ;
if cond1 then
equations
elseif cond2 then
equations (9.5)
else
equations
end if ;
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
the modeling environment evaluates in first place the Boolean condition, to choose
which one of the two branches of the if expression must use, and then computes the
corresponding variable using the chosen branch.
As discussed in Section 8.4, the noEvent() function also allows to avoid runtime
numerical errors when the branches cannot be extended beyond its validity range.
For example, the if sentence
can generate an execution error of the type “attempt to compute the square root of
a negative number”. This error is avoided using noEvent():
where cond (the clause’s trigger condition) is a Boolean expression. In this case, the
instantaneous equations included in the body of the when clause are executed only
at the time instant in which the Boolean expression value changes from false to true.
The trigger condition of a when clause can also be a vector of Boolean expressions,
as shown below. In this case, the when clause is triggered each time any of the vector
components changes its value from false to true.
To illustrate the difference between these two ways of specifying the trigger
condition, consider the two when clauses shown below:
The clause written on the left-hand side is triggered when the value of the Boolean
expression (u1>0 or u2>0) changes from false to true. The clause on the right-hand
side is triggered when the value of u1>0 changes from false to true, and also when
the value of u2>0 changes from false to true. See Figure 9.1.
The instantaneous equations can be of two types:
u1>0 u1>0
u2>0 u2>0
Figure 9.1: Trigger conditions expressed as a Boolean expression (left), and as an array of Boolean
expressions (right). Trigger instants are indicated by arrows.
The pre() function allows to refer to the variable value before the event, e.g.,
pre(variable). Observe that the difference equations have to be written in
explicit form. This is, with the variable to evaluate written on the left-hand
side of the “=” or “:=” symbol. The new value of the variable is the result
of evaluating the expression written on the right-hand side of the difference
equation.
– In the case of a when clause written within an equation section, the order
in which the model developer writes the instantaneous equations is irrelevant.
The modeling environment sorts automatically the instantaneous equations.
For this to be possible, the single-assignment rule must be fulfilled, of which
it is being guaranteed that each variable is evaluated from a single equation.
change their order. Therefore, the single assignment rule doesn’t apply inside
an algorithm section: several assignments to the same variable can be written
within an algorithm section. For example, it is possible to write:
algorithm
when h1>3 then
closed := true;
end when;
when h2>1 then
closed := false;
end when;
If these two events are triggered simultaneously, then they are executed in
order and, therefore, the new value of the closed variable would be false.
Nevertheless, the algorithm sections have to be sorted together with the rest
of the model. For this reason, a variable calculated in an algorithm section
cannot be calculated in any other algorithm section, or from an equation.
The sample(), initial() and terminal() built-in functions can be used in the
Boolean condition of the when clause as described below.
– As discussed in Section 7.6.4, the initial() function triggers the when clause
at the model initialization.
– The terminal() function triggers the when clause when the ending condition
of the simulation is satisfied. It has the following syntax:
The when clause can also be used to force the simulation termination. The
ending condition in the examples discussed so far is the simulated time to reach
a predefined value, which is specified in the experiment definition. However, the
termination condition of some simulation studies depends not only on time, but also
on some model variables.
These termination conditions, dependent on model variables, can be described
by calling the terminate() function inside the body of a when clause. This built-
in function has one argument of String type: the message written by the modeling
environment to the message window when the function is executed, forcing the
simulating to finish. For example:
Let’s consider the model of an electric circuit shown in the Figure 9.2, that
is composed of a voltage generator, a resistor and an ideal switch. The Boolean
variable open, whose time evolution is shown on the right-hand side of the figure,
is a known function of time. The Modelica description of this circuit is shown in
Modelica Code 9.1.
The if sentence shown below has been used to describe the constitutive rela-
tionship of the ideal electric switch. Comparing this constitutive relationship with
Eq. (7.83), it can be observed the analogy between the electrical and hydraulic
domains.
When the model is translated, Dymola shows a warning stating that the units
of the if-expression branches are different: the i branch is expressed in amperes, and
the uD branch in volts. This is not an error in this model, so we can ignore the
warning.
The results obtained executing the simulation during 16 s are shown in Figure
9.3. While the switch is open, the current is zero and the voltage drops across the
switch. While the switch is closed, there is a flow of electrical current and the voltage
drops across the resistor.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
0 5 10
R time
i
+ uR − + uD −
+
U −
Figure 9.2: Electric circuit, and evolution of the open Boolean variable.
model ResistConmutCircuit
Modelica.SIunits.Voltage U, uR, uD;
Modelica.SIunits.Current i;
Boolean open;
parameter Modelica.SIunits.Resistance R = 10;
parameter Modelica.SIunits.Voltage U0 = 5;
parameter Modelica.SIunits.AngularFrequency w = 2;
equation
U = U0*sin(w*time); // Generator
uR = i*R; // Resistor
0 = if open then i else uD; // Switch
open = time < 5 or time > 10; // Control of switch
U = uR + uD;
end ResistConmutCircuit;
Modelica Code 9.1: Model of the electric circuit shown in Figure 9.2.
The model of the switch can be modified to describe an ideal diode. In the diode,
the opening condition depends on internal variables of the device, instead of being
determined by a particular function of time.
An ideal diode can be in two modes, conduction and cutoff, that are analogous
to the closed and open modes of an ideal switch. The behavior of the ideal diode is
modeled in the following way (see Figure 9.4):
– While in the conduction phase, the voltage drop across the diode terminals
is zero, and the current flowing through it must have a positive sign. When
this last condition is not satisfied, the diode changes to the cutoff phase.
– While in the cutoff phase, the current flowing through the diode is zero, and
the voltage drop across the diode terminals must be less or equal to zero. When
this condition on the voltage drop is not satisfied, the diode changes to the
conduction phase.
To illustrate the application of the previous model, let’s consider the rectifier
circuit shown in Figure 9.5, whose model is described by the following equations.
u = U0 · sin(w · t) (9.17)
u − u1 = i1 · R1 (9.18)
0 = if corte then i1 else u1 − u2 (9.19)
corte = i1 ≤ 0 and not u1 − u2 > 0 (9.20)
u2 = i2 · R2 (9.21)
du2
C· = iC (9.22)
dt
i1 = i2 + iC (9.23)
265
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
+ uD −
i≤0
i
Conduction Cutoff
i
Conduction uD = 0 i=0
Cutoff
uD > 0
uD
Figure 9.4: I-V characteristic curve of an ideal diode and its two-phase model.
The results shown in Figure 9.6 are obtained simulating Modelica Code 9.2 during
0.1 s. The circuit behavior is as follows.
– While the diode is in the cutoff mode (corte = true), the current through the
diode (i1 ) is zero. Therefore, there is no voltage drop in the R1 resistor, and
u1 is equal to u.
In analogy to the problem discussed for the ideal switch, the ideal diode model
produces an error if the mode change implies a change in the number of DoF of the
complete model. For example, the ideal diode model cannot be used to model the
circuit shown in Figure 9.7. The reason is as follows.
– The circuit model has one DoF while the diode is in the cutoff mode. The
constitutive relationship of the diode forces that no current flows through it.
Thus, the current provided by the generator, that flows completely through
R1 , is distributed between R2 and C. The voltage drop across the capacitor
can be selected as state variable.
– However, while the diode is in the conduction mode, the constitutive rela-
tionship of the diode forces the voltage drop across its terminals to be zero.
As a consequence, the voltage drop across the condenser is computed from the
diode constitutive relationship and this variable is not a state variable. The
model has zero DoF.
HYBRID MODELING PRACTICE
R1 u1
D u2
u
i2 iC
+ i1
u R2 C
−
model idealDiodeCircuit
import SI = Modelica.SIunits;
SI.Current i_1, i_2, i_C;
SI.Voltage u, u_1, u_2(start=0, fixed=true);
Boolean corte "Diode mode";
parameter SI.Voltage U0=5;
parameter SI.Frequency frec=50;
parameter SI.AngularFrequency w=2*Modelica.Constants.pi*frec;
parameter SI.Resistance R1=10, R2=50;
parameter SI.Capacitance C=1e-3;
equation
u = U0*sin(w*time);
u - u_1 = i_1*R1;
0 = if corte then i_1 else u_1 - u_2;
corte = i_1 <= 0 and not u_1 - u_2 > 0;
u_2 = i_2*R2;
C*der(u_2) = i_C;
i_1 = i_2 + i_C;
end idealDiodeCircuit;
Modelica Code 9.2: Rectifier circuit shown in Figure 9.5 with ideal diode.
R1
+ D R2 C
−
Figure 9.7: The ideal diode model cannot be employed in modeling this circuit.
+ uD −
s<0
C utoff
s≥0
uD
U knee
Figure 9.8: Diode model included in the Modelica Standard Library 3.2.1.
To avoid that a change in the diode mode generates a change in the number
of DoF of the complete circuit model, the diode model included in the Modelica
Standard Library (MSL) includes a little resistance (Ron ) while in conduction, and
a little conductance (Gof f ) while in cutoff. The constitutive relationship of this
resistive diode, in the version 3.2.1 of the MSL distributed with Dymola 2015, is
the following (see Figure 9.8):
corte = s < 0
uD = (s · unitCurrent) · (if corte then 1 else Ron ) + Uknee (9.24)
i = (s · unitV oltage) · (if corte then Gof f else 1) + Gof f · Uknee
where the Uknee parameter is the threshold voltage of the diode, i.e., the value of uD
for which the slope of the I-V characteristic changes (see Figure 9.8). By default,
Uknee is zero, the Ron resistance is 10−5 ohm, and the Gof f conductance is 10−5
ohm−1 . The values of these three parameters can be modified when the component
is instantiated, and when the experiment is defined.
HYBRID MODELING PRACTICE
Let’s consider the system described in Section 7.4.3, which is composed of two
tanks connected by a valve. For readers’ convenience, the system diagram is shown
again in Figure 9.9. The system is modeled as shown in Modelica Code 9.3. If
sentences are used to describe the mass flow rate and the temperature of the liquid
that flows through the valve. A when sentence is used to describe the change of
the valve opening, which occurs when time becomes greater than t0 = 50 s. The
simulation result is shown in Figure 9.10.
Observe that while the value of the theta variable is zero, the flow between
the two tanks is zero. Thus, the mass and temperature remain constant in each
tank. When the valve opening theta is set to the value 0.5 (at t = 50 s), the mass
flow between the two tanks becomes instantaneously different from zero. Since the
liquid level is at that moment higher in the second tank, the liquid flows from the
second tank to the first one. The liquid that flows through the valve is at the same
temperature as the liquid stored in the upstream tank. Therefore, the flowing liquid
is at the temperature of the second tank. The liquid temperature in the second tank
is higher than the liquid temperature in the first tank, and consequently the liquid
temperature in the first tank increases.
As the liquid level difference tends to zero, the flow through the valve tends
to zero. When the levels (and thus the pressures) become equal, the flow becomes
zero. As no more liquid enters the first tank, the temperature of the stored liquid
remains constant from that instant. The liquid in the second tank maintains the
same temperature during the entire simulation.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
θ
m1 ,T1 m2 ,T2
p1 p2
m
F
model TanksValve
import SI = Modelica.SIunits;
constant SI.Acceleration g=9.81 "Gravitational acceleration";
parameter SI.Area S1 = 1, S2 = 2;
parameter Real Kv = 0.2;
parameter Real theta0(unit="1") = 0.5;
parameter SI.Time t0 = 50;
parameter SI.Density rho = 1000;
SI.Mass m1(start=1000,fixed=true), m2(start=4000,fixed=true);
SI.Temperature T1(start=300,fixed=true), T2(start=350,fixed=true), Tf;
SI.Height h1, h2;
SI.Pressure p1, p2;
SI.MassFlowRate Fm;
Real theta( start=0, fixed=true, unit="1");
equation
// Tank 1
der(m1) = -Fm;
m1 * der(T1) = -Fm * (Tf-T1);
p1 = m1 * g / S1;
m1 = rho * h1 * S1;
// Tank 2
der(m2) = Fm;
m2 * der(T2) = Fm * (Tf-T2);
p2 = m2 * g / S2;
m2 = rho * h2 * S2;
// Valve
Tf = if p1 > p2 then T1 else T2;
Fm = if p1 > p2 then Kv*theta*sqrt(abs(p1-p2))
else -Kv*theta*sqrt(abs(p2-p1));
when time > t0 then
theta = theta0;
end when;
end TanksValve;
Modelica Code 9.3: Model of the two-tank and valve system shown in Figure 9.9.
HYBRID MODELING PRACTICE
The vertical movement of a ball falling under the gravity action and bouncing
on the floor was modeled in Section 7.4.1. Two different models were proposed that,
as we have seen, were not satisfactory: the Modelica Code 8.3 allows the ball to fall
below the floor level, and the Modelica Code 8.4 exhibits chattering. Let’s adopt a
different approach in modeling the bouncing ball behavior.
The specific energy (energy per mass unit) of the ball is defined by Eq. (9.25).
The first term in the right-hand side expression is the ball’s kinetic energy, and the
second term its potential energy.
1 2
e= ·v +g·x (9.25)
2
The ball’s specific energy is computed at the beginning of the simulation, einicial ,
and after each bounce. When the specific energy after a bounce becomes less than a
determined proportion of the initial one, the ball enters in a mode, named Stoppe-
dOnFloor, in which the position and the velocity are forced to be zero. Notice that
the computational load of the model while in the StoppedOnFloor mode is very low,
and the chattering problem is avoided.
To avoid the ball to fall below the floor level, it is checked after each bounce
whether the ball’s kinetic energy is large enough to ascend over the (2 · eveps)
height. Otherwise, the simulation is finished, and a message warning that the model
is out of its experimental frame is written to the log window. This indicates that the
model is being used in an experimental context for which the model is not valid.
The behavior of the model is shown in Figure 9.11. The point filled in black is
the entry to the diagram. From this point, it is triggered an unconditional transition
from the Moving mode, where the model describes the fall and bounce of the ball.
The ball energy changes with each bounce.
If the ball goes out of its experimental frame, the simulation is finished. The
simulation end is represented by two concentric circles, so that the outer circle is
hollow and the inner circle is filled in black.
If, inside the experimental frame, the specific energy is lower than coef · einicial ,
a transition to the StoppedOnFloor mode takes place, and the model stays in this
mode indefinitely.
The model description is shown in Modelica Code 9.4. Notice that:
HYBRID MODELING PRACTICE
der(v) = -g;
der(x) = v;
when x < 0 then
x = 0;
reinit(v, -c*v);
end when;
e ≤ g ⋅ ( 2 ⋅ eveps )
Figure 9.11: Model of the bouncing ball with two modes: Moving and StoppedOnFloor.
model BouncingBall3
import SI = Modelica.SIunits;
constant Real eveps(unit="1") = 1E-10;
constant SI.Acceleration g=9.8 "Gravitational acceleration";
parameter Real c(unit="1")=0.8 "Elastic bouncing coeff.";
parameter Real coef(unit="1")=1e-3 "Coeff. transition to StoppedOnFloor";
SI.Distance x(start=10, fixed=true) "Vertical distance of ball to the floor";
SI.Velocity v(start=0, fixed=true) "Ball velocity";
Real eInicial(unit="J/kg") "Initial specific energy";
Boolean parada(start=false, fixed=true) "Ball in StoppedOnFloor mode?";
equation
der(v) = if parada then 0 else -g;
der(x) = v;
when initial() then
eInicial = 0.5*v^2 + g*x;
end when;
when x < 0 then
assert(0.5*(c*v)^2 > g*2*eveps, "Model out of its experimental frame");
parada = (0.5*(c*v)^2 < coef*eInicial);
reinit(v, if parada then 0 else -c*v);
end when;
when parada then
reinit(x, 0);
end when;
end BouncingBall3;
– The initial specific energy is computed using a when clause, whose condition is
the initial() function. A value is assigned to the eInicial variable at the start
time, and this value remains constant during the simulation.
– An assert sentence is used to check whether the model has gone out of its
experimental frame.
– The model has two state variables in both modes. When the transition to the
StoppedOnFloor mode takes place, the x and v state variables are reinitialized
to zero, and the time derivatives of both variables are zero while the model
remains in this mode. So, the ball position and velocity are zero while in the
StoppedOnFloor phase.
In this section, we are going to model the friction force between two contacting
solid objects. The proposed model is described by the characteristic curve shown in
HYBRID MODELING PRACTICE
fr
R0
Rm
f r = Rv ⋅ v + Rm
v
f r = Rv ⋅ v − Rm − Rm
− R0
Figure 9.13, which depends on three parameters: R0 , Rm and Rv . This curve has the
following meaning.
– While the relative velocity (v) between the two objects is different from zero,
the friction force (fr ) depends linearly on this relative velocity.
R ·v−R if v < 0
v m
fr = (9.26)
Rv · v + Rm if v > 0
– Suppose that the relative velocity between the two objects is zero, and an
external force is applied. The friction force is modeled as follows.
• If the module of the external force is not larger than a certain value R0 ,
the friction force exactly counteracts the applied force, so that the objects
remain in relative rest.
• If the module of the external force is larger than R0 , then the friction
force is not able to avoid the relative movement of the objects, and the
friction force is described by Eq. (9.26).
This behavior of the friction force can be described using the following two-mode
model.
1. In this mode, the velocity between the two bodies is different from zero, and
the friction force is related to the relative velocity by Eq. (9.26). The transition
condition to leave this mode is the relative velocity to become zero.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
2. In this mode, that we name Stuck, the relative velocity between the objects
is zero. The friction force has the value that makes the relative velocity to
continue being zero. The friction force is this mode, named fc , is calculated by
imposing v = 0. The transition condition to leave this mode is |fc | > R0 .
The model in the Stuck mode has one more equation (v = 0) and one more
variable (fc ) than in the other mode. As Modelica does not allow to declare variables
local to a particular mode, a value has to be assigned to the fc variable while the
model is not in the Stuck mode. This value is arbitrary, because fc only has a
physical meaning while the model is in the Stuck phase. By simplicity, we set this
variable to zero. Therefore, the friction force is described by the following constitutive
relationship.
fr = if v>0 then Rv · v + Rm
elseif v<0 then Rv · v − Rm
else fc (9.27)
0 = if Stuck then v
else fc
However, the model should not be formulated in this way. The reason is that, in
mechanical system models, velocities are typically either state variables or calculated
from state variables. In consequence, the friction model in the Stuck mode, by
imposing v = 0, reduces the number of DoF of the complete model. Let’s explore
another approach.
As accelerations typically are not state variables of mechanical system models,
let’s replace the equation v = 0 by dv dt
= 0. This is, instead of imposing the relative
velocity to be zero while in the Stuck phase, it is imposed the relative acceleration
to be zero. In addition, when the model enters in the Stuck phase, the relative
velocity is reinitialized to zero. To goal is to avoid the numeric drifting of the relative
displacement, which may become relevant if the model stays in the Stuck mode for
a long time.
The next step is to specify the transition conditions among the model modes.
We suppose that the model can be in any of the following five modes:
– Stuck. The relative velocity is zero while in this mode, and the friction force
satisfies −R0 ≤ fr ≤ R0 .
– Forward and Backward. The relative velocity between the bodies is different
from zero. In the Forward mode, the relative velocity satisfies v > 0 and
HYBRID MODELING PRACTICE
Mode Condition
Start
v<0 v>0
v≥0 v≤0
Figure 9.14: Transitions among the modes of the dry friction model.
The conditions to stay in each mode are summarized in Table 9.1. The transi-
tions among the modes can be described by means of a finite state machine, as in
Figure 9.14. The diagram has six modes: the five previously described and the Start
mode, in which the model is at the initialization.
Finite state machines can be described in Modelica by declaring a Boolean
variable for each mode, and describing the condition for staying in each mode in
the following way:
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
where modeP re1, modeP re2, . . . are the modes from which a transition to mode
can occur if the conditionIn1, conditionIn2, . . . conditions are fulfilled, respectively.
The Boolean expressions conditionOut1, conditionOut2, . . . are the conditions for
the exit transitions from mode.
The Modelica description of the finite state machine shown in Figure 9.14 is the
following.
To illustrate the application of the friction model, a Modelica library named Lib-
Friction has been programmed. See Modelica Code 9.5 – 9.7. The library architecture
is shown in Figure 9.15.
The Port connector describes the mechanical port, that is composed of two
variables: the position and the force. The velocity could have been chosen as across
variable, instead of the position.
The Transbody model describes an object that can move in one dimension. The
object has only one connector. The force variable of the connector is the net force
applied to the object, which accelerates it. The position variable of the connector
represents the position where the object is.
The Inertial model describes an object fixed in the origin of coordinates. This
model will be used to represent the floor.
HYBRID MODELING PRACTICE
package LibFriction
import SI = Modelica.SIunits;
connector Port
SI.Position p;
flow SI.Force f;
end Port;
model TransBody
Port port;
parameter SI.Mass m = 1;
parameter SI.Position p_Initial = 0;
parameter SI.Velocity v_Initial = 0;
SI.Position p( start=p_Initial, fixed=true);
SI.Velocity v( start=v_Initial, fixed=true);
SI.Acceleration a;
equation
port.f = m*a;
port.p = p;
der(p) = v;
der(v) = a;
end TransBody;
model Inertial
Port port;
equation
port.p = 0;
end Inertial;
model ExtForce
Port port;
SI.Force f;
parameter Real Tstart = 50;
parameter Real Tend = 75;
parameter Real Kf = 1;
equation
f = if time > Tstart and time < Tend
then Kf*(time-Tstart)
else 0;
port.f = -f;
end ExtForce;
model TransForce
Port port1;
Port port2;
SI.Position p;
SI.Velocity v(stateSelect = StateSelect.always);
SI.Acceleration a;
equation
p = port2.p - port1.p;
der(p) = v;
der(v) = a;
end TransForce;
model FrictionLin
extends TransForce;
SI.Force fr "Friction force";
parameter Real Kf=1;
equation
port2.f = -fr;
port1.f = fr;
fr = -Kf*v;
end FrictionLin;
model Friction
extends TransForce;
SI.Force fr "Friction force";
SI.Force fc "Dummy variable";
parameter Real R0 = 1 "Threshold value";
parameter Real Rm = 0.5;
parameter Real Rv = 1;
Boolean Start(start=true, fixed=true);
Boolean Stuck(start=false, fixed=true);
Boolean StartBackward(start=false, fixed=true);
Boolean StartForward(start=false, fixed=true);
Boolean Backward(start=false, fixed=true);
Boolean Forward(start=false, fixed=true);
constant SI.Mass unitMass = 1;
equation
port2.f = -fr;
port1.f = fr;
fr = if Forward then -(Rv*v+Rm) else
if Backward then -(Rv*v-Rm) else
if StartForward then -Rm else
if StartBackward then Rm else fc;
0 = if Stuck then unitMass*a else fc;
Stuck = not (Forward or Backward or StartForward or
StartBackward or Start);
Forward = pre(Start) and v>0 or
pre(StartForward) and v>0 or
pre(Forward) and not v<=0;
Backward = pre(Start) and v<0 or
pre(StartBackward) and v<0 or
pre(Backward) and not v>=0;
StartForward = pre(Stuck) and fc < -R0 or
pre(StartForward) and not (v>0 or a<=0 and not v>0);
StartBackward = pre(Stuck) and fc > R0 or
pre(StartBackward) and not (v<0 or a>=0 and not v<0);
Start = if initial() then true else false;
// reinit() has effect because v is state variable
//See the value of the stateSelect attribute in the TransForce model
when Stuck then
reinit(v,0);
end when;
end Friction;
Modelica Code 9.6: LibFriction library (2/3).
HYBRID MODELING PRACTICE
package Examples
model OneBodyFloor
TransBody body(p_Initial=0, v_Initial=0, m=10);
Friction friction;
Inertial floor;
ExtForce extForce1(Tstart=10, Tend=50, Kf=0.1);
ExtForce extForce2(Tstart=100, Tend=150, Kf=-0.1);
equation
connect(body.port, friction.port2);
connect(friction.port1, floor.port);
connect(extForce1.port, body.port);
connect(extForce2.port, body.port);
annotation (experiment(StopTime=250));
end OneBodyFloor;
model TwoBodies
TransBody body1(p_Initial=0, v_Initial=2, m=10);
TransBody body2(p_Initial=0, v_Initial=0, m=10);
Friction friction;
ExtForce extForce_c2(Tstart=100, Tend=150, Kf=-0.1);
equation
connect( body1.port, friction.port2);
connect( friction.port1, body2.port);
connect( extForce_c2.port, body2.port);
annotation (experiment(StopTime=250));
end TwoBodies;
model TwoBodiesFloor
// body2 - body1 - floor
TransBody body1(p_Initial=0, v_Initial=2, m=10);
TransBody body2(p_Initial=0, v_Initial=-2, m=10);
Friction friction_c2_c1;
Friction friction_c1_floor;
Inertial floor;
ExtForce extForce_c1(Tstart=50, Tend=100, Kf=0.1);
ExtForce extForce_c2(Tstart=200, Tend=250, Kf=-0.1);
equation
connect( body2.port, friction_c2_c1.port2);
connect( friction_c2_c1.port1, body1.port);
connect( body1.port, friction_c1_floor.port2);
connect( friction_c1_floor.port1, floor.port);
// External forces
connect( extForce_c1.port, body1.port);
connect( extForce_c2.port, body2.port);
annotation (experiment(StopTime=350));
end TwoBodiesFloor;
end Examples;
end LibFriction;
The ExtForce model describes an external force that can be applied to an object.
The model has three parameters: Tstart , Tend and Kf . The force is zero outside the
(Tstart , Tend ] time interval. Within this time interval, the force increases linearly with
slope Kf N/s, stating from the zero value at the Tstart time.
The TransForce model has two mechanical ports, and defines the relative position
and velocity of the two ports. This model will be used as a superclass of the friction
models.
The library contains two different models of the friction. In the FrictionLin
model, the friction force depends linearly on the relative velocity for any value of the
relative velocity. The Friction model describes the six-mode friction model shown in
Figure 9.14, whose characteristic curve is shown in Figure 9.13.
The Examples package includes three models. The OneBodyFloor model des-
cribes the sliding motion with dry friction of a body over the floor. An external
force is applied to the body during two different time intervals. The TwoBodies
model describes the sliding motion with dry friction of two bodies. Additionally, the
TwoBodiesFloor model includes the floor model, so that the sliding with friction
occurs between the two bodies, and between the lower body and the floor. The
simulation of these examples is left to the reader.
The heat conduction in the wall of a cooling chamber is analyzed in this section.
The wall is composed of three layers of different materials, named A, B and C, with
width LA = 15 mm, LB = 100 mm and LC = 75 mm respectively. A transversal cut
of the wall is represented in the upper part of Figure 9.16.
The inner surface of the wall is at a constant temperature of 0 0 C, while the outer
temperature varies between −20 0 C and 20 0 C along 24 hours. The temperatures of
the inner and outer surfaces of the wall, T1 and T5 , are described by Eqs. (9.29) and
(9.30), where time (t) is expressed in seconds (24 hours are equivalent to 24·60·60 =
86400 seconds), and temperature in Kelvin.
T1 = 273.15 (9.29)
2·π·t
T5 = 273.15 + 20 · sin (9.30)
86400
HYBRID MODELING PRACTICE
The goal is to calculate the heat flow rate per unit of cross-sectional area, and
the temperatures at the interfaces between the different materials (T2 , T3 ) and at
the wall’s outer surface (T4 ). To this end, the system is described as the equivalent
thermal circuit shown in the lower part of Figure 9.16. The S parameter that appears
in the thermal resistance denominator is the wall surface. This parameter is set to
S = 1 m2 , so that Q is equal to the heat flow rate per unit of cross-sectional area. The
thermal conductivities, κA , κB and κC , are expressed in W·m−1 ·K−1 in Eqs. (9.31)
– (9.33).
κA = 0.151 (9.31)
−1225
κB = 2.5 · exp (9.32)
T
κC = 0.762 (9.33)
!
−1225
κB = 2.5 · exp (9.34)
0.5 · (T2 + T3 )
T5 − T4 1/4
h = 1.37 · (9.35)
6
Naming Q to the heat flow rate (watts) from the inner to the outer surface of
the wall, the constitutive relationships of the four thermal resistors are:
LA
T1 − T2 = Q · (9.36)
κA · S
LB
T2 − T3 = Q· (9.37)
κB · S
LC
T3 − T4 = Q· (9.38)
κC · S
1
T4 − T5 = Q· (9.39)
h·S
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
A B C
T1 T2 T3 T4 T5
fi
ci Su p er
LA LB LC e
LA LB LC 1
κ AS κ BS κCS hS
T1 T2 T3 T4 T5
Figure 9.16: Structure of the chamber wall (above) and equivalent thermal circuit (below).
model MultilayerWall
import SI = Modelica.SIunits;
// Thickness of the layers
parameter SI.Length La = 15E-3;
parameter SI.Length Lb = 100E-3;
parameter SI.Length Lc = 75E-3;
// Cross-sectional area of the wall
parameter SI.Area S = 1;
// Thermal conductivities of the layers
parameter SI.ThermalConductivity Ka = 0.151;
SI.ThermalConductivity Kb;
parameter SI.ThermalConductivity Kc = 0.762;
// Convective heat transfer coefficient
SI.CoefficientOfHeatTransfer h;
// Temperatures
parameter SI.Temperature T1 = 273.15;
SI.Temperature T2(start=273,fixed=false);
SI.Temperature T3(start=273,fixed=false);
SI.Temperature T4(start=273,fixed=false);
SI.Temperature T5;
// Heat flow rate
SI.HeatFlowRate Q;
equation
// Outer temperature
T5=273.15+20*sin(time*2*Modelica.Constants.pi/86400);
// Thermal conductivity of the B material
Kb= 2.5*exp(-1225*2/(T2+T3));
// Convective heat transfer coefficient
h= if noEvent(T4>T5) then 1.37*((T4-T5)/6)^0.25 else
if noEvent(T5>T4) then 1.37*((T5-T4)/6)^0.25 else
1;
// Constitutive relationships of the thermal resistors
T1 - T2 = Q * La/(Ka*S);
T2 - T3 = Q * Lb/(Kb*S);
T3 - T4 = Q * Lc/(Kc*S);
T4 - T5 = Q * 1 /(h*S);
end MultilayerWall;
Modelica Code 9.8: Heat transfer in the three-layer wall shown in Figure 9.16.
HYBRID MODELING PRACTICE
Executing the simulation of Modelica Code 9.8 during 86400 s, the result shown
in Figure 9.17 is obtained. The biggest thermal step occurs in the B material, as
shown in the upper plot of the figure. The heat flow rate Q is positive while it goes
out from the cooling chamber, i.e., while T1 > T5 .
Remember that the thermal conductivity of the B material is a function of the
temperature, and that we have assumed the temperature of the B material to be
equal to the average of the temperatures at the A-B and B-C interfaces. To estimate
the error associated to this modeling hypothesis, the B material is split into NelemB
equal layers, each one with a thickness equal to LB /NelemB . We define a vector of
temperatures, whose components are:
so that
TB [1] = T2 (9.42)
TB [NelemB + 1] = T3 (9.43)
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
T4 T5
T3
T2
T1
and where
is the temperature at the interface between the (i − 1)-th and the i-th layer in which
the B material has been split. The thermal conductivity at the i-th layer of the B
material is:
!
−1225
κB [i] = 2.5 · exp (9.45)
0.5 · (TB [i] + TB [i + 1])
The constitutive relationship of the thermal resistor describing the i-th layer of
the B material is:
LB /NelemB
TB [i] − TB [i + 1] = Q · (9.46)
κB [i] · S
The model is described in Modelica Code 9.9. The simulation has been performed
by dividing the B material into NelemB = 50 layers, and the obtained results have
been compared with the results obtained by simulating Modelica Code 9.8. The
result of this comparison is shown in Figure 9.18, where can be seen the order of
magnitude of the error in the heat flow rate, and the T2 and T3 temperatures.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
model NMultilayerWall
import SI = Modelica.SIunits;
// Number of layers of the B material
constant Integer NelemB = 50;
// Thickness of the layers
parameter SI.Length La = 15E-3;
parameter SI.Length Lb = 100E-3;
parameter SI.Length Lc = 75E-3;
// Wall cross-sectional area
parameter SI.Area S = 1;
// Thermal conductivities of the layers
parameter SI.ThermalConductivity Ka = 0.151;
SI.ThermalConductivity Kb[NelemB];
parameter SI.ThermalConductivity Kc = 0.762;
// Coefficient of convection heat transfer
SI.CoefficientOfHeatTransfer h;
// Temperatures
parameter SI.Temperature T1 = 273.15;
SI.Temperature T2(start=273,fixed=false);
SI.Temperature T3(start=273,fixed=false);
SI.Temperature T4(start=273,fixed=false);
SI.Temperature T5;
SI.Temperature TB[NelemB+1]( start=273*ones(NelemB+1),fixed=false);
// Heat flow rate
SI.HeatFlowRate Q;
equation
// Outer temperature
T5=273.15+20*sin(time*2*Modelica.Constants.pi/86400);
// Coeff. of convection heat transfer
h= if noEvent(T4>T5) then 1.37*((T4-T5)/6)^0.25 else
if noEvent(T5>T4) then 1.37*((T5-T4)/6)^0.25 else
1;
// Constitutive relationships of the thermal resistors
T1 - T2 = Q * La/(Ka*S);
T3 - T4 = Q * Lc/(Kc*S);
T4 - T5 = Q * 1 /(h*S);
// Layer B
TB[1] = T2;
for i in 1:NelemB loop
TB[i] - TB[i+1] = Q * (Lb/NelemB)/(Kb[i]*S);
Kb[i] = 2.5*exp(-1225*2/(TB[i] + TB[i+1]));
end for;
TB[NelemB+1] = T3;
end NMultilayerWall;
Modelica Code 9.9: Heat transfer in the wall, with the B material divided into layers.
HYBRID MODELING PRACTICE
Figure 9.18: Comparison of the results obtained with NelemB = 50 and NelemB = 1.
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
Some of the examples discussed in this lesson have been extracted from biblio-
graphy. Modeling and simulation of an ideal diode is discussed in (Elmqvist et al.
2001). The dry friction model, implemented using the Dymola language, is described
in (Elmqvist et al. 1993). Although the Dymola language is no longer in use, the
event detection procedure described in this article is essentially the same as the
procedure employed by the Modelica modeling environments nowadays. The model
of heat conduction in a wall is described in (Cutlip & Shacham 1999).
Subject Index
cross, 58 ndims, 58
der(), 24 noEvent, 237, 246
diagonal, 58 ones, 58
discrete, 44 outer, 106
div, 64 package, 18, 75, 80
event, 16, 244 encapsulated, 79
extends, 72 package.mo, 81
external function, 16 parameter, 17, 44
fill, 58 by-default value, 73
fixed, 169, 212, 214 parametrization, 17
flow, 71 partial model, 72
for, 57 physical field, 106
for with iterators, 57 pre(), 244
function, 16, 18, 64 product, 58
internal memory, 64 protected, 72, 85
identity, 58 public, 72
if, 74, 202, 222, 244 Real, 44
import, 79 record, 18, 85
information encapsulation, 17 redeclare, 82
inheritance, 17, 72 reinit, 167, 193, 248
import, 80 rem, 64
initial, 216, 219, 222, 249 replaceable, 81
initial algorithm, 216 sample, 249
initial equation, 89, 216 script file, 30
initialization, 211 sign, 64
inner, 106 simulation termination, 250
Integer, 44 size, 58
linspace, 58 sqrt, 64
LogVariable, 251 start, 212, 214
max, 58 state variable, 136
message writing, 251 stateSelect, 169
min, 58 String, 44, 250
model, 18 concatenation, 250
save, 80 integerString, 250
MODELICAPATH, 81 realString, 250
modularity, 17 sum, 58
MSL terminal, 249
Constants, 45 terminate, 250
SIunits, 45 time, 43
MODELING AND SIMULATION IN ENGINEERING USING MODELICA
transpose, 58 simulation
type, 18, 45 algorithm, 125
variable hybrid model, 21
attribute, 44 single-assignment rule, 61, 248
built-in types, 44 SPICE, 85, 174
vector, 55 stiff system, 171
when, 247 structural singularity, 115, 122
within, 81 switch
zeros, 58 ideal, 201
modeling resistive, 208
causal, 16
Tarjan’s algorithm, 117
environment, 20
tearing, 175
equation-based, 15
temporal discretization, 176
non-causal, 15
time, 113
object-oriented, 17
physical paradigm, 14 variable
across, 17
node, 19
algebraic, 125
numerical differentiation, 146
alias, 20
Omola, 186 auxiliar, 113
OpenModelica, 32 classification, 122
Check Model, 33 effort, 17
OMEdit, 32 flow, 17
Diagram View, 33 parameter, 125
Documentation View, 33 state variable, 125, 157
Icon View, 33 through, 17
Options, 36
Simulate, 36
simulation interval, 36
Simulation Setup, 36
Text View, 33
working directory, 36
Åström, K. J. & Hagglund, T. (1995), PID Controllers: Theory, Design and Tuning,
ISA Press.
Cellier, F. E., Elmqvist, H., Otter, M. & Taylor, J. H. (1993), Guidelines for modeling
and simulation of hybrid systems, in ‘IFAC World Congress’, Sydney, Australia.
Cellier, F., Otter, M. & Elmqvist, H. (1995), Bond graph modeling of variable
structure systems, in ‘2nd Intl. Conference on Bond Graph Modeling and
Simulation, ICBGM’95, Las Vegas’, Las Vegas, USA, pp. 49–55.
Dynasim AB (2004), Dymola. User’s Manual. Version 5.3a, Dynasim AB, Lund,
Sweden.
Elmqvist, H., Cellier, F. E. & Otter, M. (1995), Inline integration: a new mixed
symbolic/numeric approach for solving differential-algebraic equation systems, in
‘ESM’95, SCS European Simulation MultiConference’, Prague, Czech Republic.
Elmqvist, H., Mattsson, S. & Olsson, H. (2002), New methods for hardware-in-the-
loop simulation of stiff models, in ‘2nd Intl. Modelica Conference’, Oberpfaffenho-
fen, Germany, pp. 59–64.
Elmqvist, H. & Otter, M. (1994), Methods for tearing systems of equations in object-
oriented modeling, in ‘ESM’94, European Simulation Multiconference’, Barcelona,
Spain.
Franke, R., Casella, F., Otter, M., Sielemann, M., Elmqvist, H., Mattson, S. &
Olsson, H. (2009), Stream connectors - an extension of Modelica for device-
oriented modeling of convective transport phenomena, in ‘7th Intl. Modelica
Conference’, Como, Italy.
Froment, G. & Bischoff, K. (1979), Chemical Reactor Analysis and Design, John
Wiley & Sons.
Incropera, F. & DeWitt, D. (1996), Fundamentals of Heat and Mass Transfer, Fourth
Edition. John Wiley & Sons.
Luyben, W. (1990), Process Modeling, Simulation and Control for Chemical Engi-
neers, McGraw-Hill.
Mattsson, S. E., Elmqvist, H., Otter, M. & Olsson, H. (2002), Initialization of hybrid
differential-algebraic equations in Modelica 2, in ‘2nd Intl. Modelica Conference’,
Oberpfaffenhofen, Germany.
Olsson, H., Otter, M., Mattsson, S. & Elmqvist, H. (2008), Balanced models in
Modelica 3.0 for increased model quality, in ‘6th Intl. Modelica Conference’,
Bielefeld, Germany, pp. 21–33.
Otter, M. (2009), Modeling, simulation and control with Modelica 3.1 and Dymola
7.
Otter, M. & Olsson, H. (2002), New features in Modelica 2.0, in ‘2nd Intl. Modelica
Conference’, Oberpfaffenhofen, Germany, pp. 7.1–7.12.