Volume 10, Issue 1 Articles Trott's Corner New Products New Publications Calendar News Bulletins New Resources Classifieds Download This Issue Editorial Policy Staff and Contributors Submissions Subscriptions Advertising Back Issues Contact Information 
MathModelicaAn ObjectOriented Mathematical Modeling and Simulation Environment
2. The MathematicaStyle Modelica Language for SimulationThe details of the Mathematicastyle Modelica language briefly mentioned in the previous section, will be described using an example of an electric circuit model that is given in the form of Modelica expressions in Mathematica syntax. The subset of the Modelica language described in this section can be used in the simulation models, not in general Mathematica programming. Note that here we only describe modeling in terms of textually programming Modelica. The MathModelica environment also includes a graphical modeling tool and standardized graphic model representation based on the Modelica language, which is briefly described in Section 3 of this article. Visual constructs in the graphical environment have a onetoone correspondence with constructs or classes in the textual Modelica language. Modelica models are built from classes. Like other objectoriented languages, a class contains variables (i.e., class attributes representing data). The main difference compared to traditional objectoriented languages is that instead of functions (methods) we use equations to specify behavior. Equations can be written explicitly, like ab, or can be inherited from other classes. Equations can also be specified by the Connect equation construct. The equation (although it has function call syntax) Connect[v1,v2] expresses coupling between the variables v1 and v2. These variables are instances of connector classes and are attributes of the connected objects. This gives a flexible way of specifying topology of physical systems described in an objectoriented way using Modelica. In the following sections we introduce some basic and distinctive syntactical and semantic features of Modelica, such as connectors, encapsulation of equations, inheritance, declaration of parameters and constants. Powerful parameterization capabilities, which are advanced features of Modelica, are discussed in Section 2.4. 2.1. Connection DiagramsAs an introduction to the Modelica language we will present a model of a simple electrical circuit shown in Figure 1. The circuit can be broken down into a set of standard connected electrical components. We have a voltage source, two resistors, an inductor, a capacitor and a ground point. Models of such standard components are available in Modelica class libraries. Figure 1. Connection diagram of the electric circuit. A declaration like the following specifies R1 to be an object or instance of the class Resistor and sets the default value of the resistance parameter, R, to 10, shown in Mathematicastyle Modelica syntax.
A Mathematicastyle Modelica description of the complete circuit appears as follows.
The same Circuit model in standard Modelicastyle syntax appears in the following. The relation between these two syntactic forms is explained in Section 3.4, including a discussion regarding our choice of Mathematica syntax for certain Modelica language features. For the rest of this article, we will primarily use Mathematicastyle syntax for examples and Modelica language constructs.
A composite model like the circuit model described earlier specifies the system topology (i.e., the components and the connections between the components). The connections specify interactions between the components. In some previous objectoriented modeling languages, connectors are referred to as cuts, ports, or terminals. The Connect construct is a special equation form that generates standard equations taking into account what kind of interaction is involved as explained in Section 2.3. Variables declared within classes are public by default if they are not preceded by the keyword Protected, which has the same semantics as in Java. Additional Public or Protected sections can appear within a class, preceded by the corresponding keyword. 2.2. Type DefinitionsThe Modelica language is a strongly typed language with both predefined and userdefined types. The builtin "primitive" data types support boolean, integer, real, and string values. These primitive types contain data that Modelica understands directly. The type of every variable must be stated explicitly. The primitive data types of Modelica are listed in Table 1.
Table 1. Predefined data types in Modelica. It is possible to define new userdefined types.
Here is an example defining a temperature measured in Kelvin, K, which is of type Real with the minimum value zero.
Here the userdefined types of Voltage and Current are defined.
This defines the symbol Voltage to be a specialization of the type Real that is a basic predefined type. Each type (including the basic types) has a collection of default attributes such as unit of measure, initial value, minimum, and maximum value. These default attributes can be changed when declaring a new type. In the previous case, the unit of measure of Voltage is changed to "V". Here is a corresponding definition made for Current.
In Modelica, the basic structuring element is a class. The general keyword Class is used for declaring classes. There are also seven restricted class categories with specific keywords, such as Type (a class that is an extension of builtin classes, such as Real, or of other defined types) and Connector (a class that does not have equations and can be used in connections). For a valid model, replacing the Type and Connector keywords by the keyword Class still keeps the model semantically equivalent to the original because the restrictions imposed by such a specialized class are already fulfilled by a valid model. Other specific class categories are Model, Record, and InOutBlock. Moreover, functions and packages are regarded as special kinds of restricted and enhanced classes, denoted by the keywords ModelicaFunction for functions and Package for packages. The idea of restricted classes is advantageous because the modeler does not have to learn several different concepts, but just onethe class concept. All basic properties of a class, such as syntax and semantics of definition, instantiation, inheritance, and generic properties are identical to all kinds of restricted classes. Furthermore, the construction of MathModelica translators is simplified considerably because only the syntax and semantics of the class construct have to be implemented along with some additional checks on restricted classes. The basic types, such as Real or Integer, are builtin type classes (i.e., they have all the properties of a class). The previous definitions have been expressed using the keyword Type, which is equivalent to Class, but limits the defined type to be an extension of a builtin type, a record type, or an array type. Note however that the restricted classes that are packages and functions have some special properties that are not present in general classes. 2.3. Connector ClassesWhen developing models and model libraries for a new application domain, it is good to start by defining a set of connector classes that are used as templates for interfaces between model instances. A common set of connector classes used by all models in the library supports compatibility and connectability of the component models. PinThe following is a definition of an electrical connector class Pin, used as an interface class for electrical components. The voltage, , is defined as a "potential" nonflow variable, and the current, , as a flow variable by being prefixed by the keyword Flow. This implies that voltages will be set equal when two or more components are connected (i.e., ) and currents are summed to zero at the connection point, .
Connect equations are used to connect instances of connector classes. A Connect equation Connect[Pin1,Pin2], with the instances Pin1 and Pin2 of connector class Pin, connects the two pins so that they form one node (in this case one electrical connection). This implies two standard equations, namely:
The first equation says that the voltages of the connected wire ends are the same (i.e., ). The second equation corresponds to Kirchhoff's current law saying that the currents sum to zero at a connection point (assuming positive value while flowing into the component), . The sumtozero equations are generated when the prefix Flow is used in the declaration. Similar laws apply to flow rates in a piping network and to forces and torques in mechanical systems. 2.4. Partial (Abstract) ClassesA useful strategy for reuse in objectoriented modeling is to try to capture common properties in superclasses that can be inherited by more specialized classes. For example, a common property of many electrical components such as resistors, capacitors, inductors, and voltage sources, is that they have two pins. This means that it is useful to define a generic "template" class, or superclass, that captures the properties of all electric components with two pins. This class is partial (i.e., abstract in standard objectoriented terminology) since it does not specify all properties needed to instantiate the class.
The class (or model) TwoPin has two pins, p and n, a quantity, v, that defines the voltage drop across the component, and a quantity, i, that defines the current into the pin p, through the component and out from the pin n. This can be summarized in the following points.
Figure 2. Structure of a TwoPin class with two pins. The equations define generic relations between quantities of a simple electrical component. In order to be useful a constitutive equation must be added. The keyword Partial indicates that this model class is incomplete. The keyword is optional and is meant as an indication to a user that it is not possible to use the class as it is to instantiate components. The string after the class name is a comment that is a part of the language (i.e., these comments are associated with the definition and are normally displayed by dialogues and forms presenting details about class definitions). 2.5. Equations and Acausal ModelingAcausal modeling means modeling based on equations instead of assignment statements. Equations do not specify which variables are inputs and which are outputs, whereas in assignment statements variables on the lefthand side are always outputs (results) and variables on the righthand side are always inputs. Thus, the causality of equationbased models is unspecified and fixed only when the equation systems are solved. This is called acausal modeling. The main advantage of acausal modeling is that the solution direction of equations will adapt to the data flow context in which the solution is computed. The data flow context is defined by specifying which variables are needed as outputs and which are external inputs to the simulated system. The acausality of MathModelica (Modelica) library classes makes these more reusable than traditional classes containing assignment statements where the inputoutput causality is fixed. Consider for example the constitutive equation from the following Resistor class.
This equation can be used in three ways. The variable v can be computed as a function of i, the variable i can be computed as a function of v, or the resistance R can be computed as a function of v and i, as shown in these three statements.
In the same way, consider the following equation from the class TwoPin.
This equation gives rise to one of the following three assignment statements, depending on the data flow context where the equation appears.
2.6. Inheritance, Parameters, and ConstantsWe will use the following Resistor example to explain inheritance, parameters, and constants. The Resistor inherits TwoPin using the Extends construct (inspired from extends in Java). A model parameter, R, is defined for the resistance and is used to state the constitutive equation for an ideal resistor, namely Ohm's Law: . We add a definition of a parameter for the resistance and Ohm's law to define the behavior of the Resistor class in addition to what is inherited from TwoPin.
The keyword Parameter specifies that the variable is constant during a simulation run, but can change values between runs. This means that a model parameter is a special kind of constant, which is implemented as a static variable that is initialized once and never changes its value during a specific execution. A parameter is a variable that makes it simple for a user to modify the behavior of a model by changing the parameter value. There are also Modelica constants that never change and can be substituted inline, which are specified by the keyword Constant. Here are additional examples of constants and parameters with default values defined via socalled declaration equations that appear in declarations.
There are several predefined constants in the Modelica.Constants package (e.g., Planck, Boltzmann, and molar gas constants). In contrast to constants, parameters can be defined later via input to a model. Thus a parameter can be declared without a declaration equation. For example:
The keyword Extends specifies inheritance from a parent class. All variables, equations, and connects are inherited from the parent. Multiple inheritance is supported in Modelica. Just like in C++, the parent class cannot be replaced in a subclass. In Modelica similar restrictions also apply to equations and connections. In C++ and Java a virtual function can be replaced/specialized by a function with the same name in the child class. In Modelica 2.1 equations in an Equation section cannot be directly named (but indirectly using a local class for grouping a set of equations) and therefore we cannot directly replace equations. When classes are inherited into a class, equations from those classes are copied into the class. This makes the equationbased semantics of the child classes consistent with the semantics of the parent class since the equation constraints of the parent class are fulfilled. 2.7. Time and Model DynamicsModels of dynamic systems are models where behavior evolves as a function of time. We use a predefined Modelica variable time, which steps forward during system simulation. The following classes defined for electric voltage sources, capacitors, and inductors have dynamic timedependent behavior and can also reuse the TwoPin superclass. In the differential equations in the classes Capacitor and Inductor, the forms v' and i' denote the time derivatives of v and i, respectively. During system simulation the variables and evolve as functions of time. The differential equations solver will compute the values of and ( is time) so that for all values of . VsourceACA class for the voltage source can be defined as follows. This VsourceAC class inherits TwoPin since it is an electric component with two connector attributes, n and p. A parameter, VA, is defined for the amplitude, and a parameter, f, for the frequency. Both are given default values, 220 V and 50 Hz, respectively, that can easily be modified by the user when running simulations (e.g., through the graphical user interface). A constant PI is also declared using the value for defined in the Modelica Standard Library, just to demonstrate the declaration of a constant. The input voltage v is defined by . Note that time is a builtin Modelica primitive.
CapacitorThe Capacitor inherits TwoPin using Extends. A parameter, C, is defined for the capacitance and is used to state the constitutive equation for an ideal capacitor; namely, .
InductorThe Inductor inherits TwoPin using Extends. A parameter, L, is defined for the inductance and is used to state the constitutive equation for an ideal inductor; namely, .
GroundFinally, we define a Ground class, which in the circuit model is instantiated as a ground point that serves as a reference value for the voltage levels.
2.8. Definition and Simulation of the Complete Circuit ModelAfter all the component classes have been defined, it is possible to construct a circuit. First the components are declared, then the parameter values are set, and finally the components are connected using Connect. Figure 3. Connection diagram of the electric circuit (repeat of Figure 1). Here we reproduce the Circuit model.
SimulationWe simulate the model with the default initial values and parameter settings in the range . The status bar in the lowerleft corner of the notebook shows the status of the simulation. Since this is the first time we simulate the circuit model, Simulate will generate C code and compile the code before the simulation.
Let us plot the current in the inductor for the first 0.1 seconds.
Note that the current starts at 0 Ampere, which is the default initial value. Let us change the initial values for the inductor current and the inductance using the options InitialValues and ParameterValues, respectively. This time Simulate will use the compiled code from the previous simulation as we have only changed initial and parameter values, and not the structure of the problem.
Here is a plot that shows the result. Note the differences in initial current and amplitude due to the changed inductance.
2.9. The MathModelica Notion of SubtypesThe notion of subtyping in Modelica is influenced by a type theory of Abadi and Cardelli [31]. The notion of inheritance in Modelica is independent of the notion of subtyping. According to the definition, a class A is a subtype of a class B if and only if the class A contains all the public variables declared in the class B, and the types of these variables are subtypes of types of corresponding variables in B. The main benefit of this definition is additional flexibility in the definition and usage of types. For instance, the class TempResistor is a subtype of Resistor, without being a subclass of Resistor.
Subtyping compatibility is checked, for example, in class instantiation, redeclarations, and function calls. If a variable a is of type A, and A is a subtype of B, then a can be initialized by a variable of type B. Redeclaration is a way of modifying inherited classes, as discussed in the next section. Note that TempResistor does not inherit the Resistor class. There are different definitions for the evaluation of v. If equations are inherited from Resistor, then the set of equations will become inconsistent in TempResistor, since there would be two definitions of v. For example, the following specialized equation from TempResistor:
and the general equation from class Resistor:
are incompatible. MathModelica currently does not support explicitly named equations and replacement of equations, except for the cases when the equations are collected into local class, or when a declaration equation occurs as part of a variable declaration. 2.10. Class ParameterizationA distinctive feature of objectoriented programming languages and environments is the ability to reuse classes from standard libraries for particular needs. Obviously, this should be done without modification of the library code. The two main mechanisms that serve for this purpose are:
In Modelica we can use redeclaration to control class parametrization. Assume that a library class is defined as follows.
Assume also that in our particular application we would like to reuse the definition of SimpleCircuit: we want to use the parameter values given for R1.R and R2.R and the circuit topology, but exchange Resistor for the previously mentioned temperaturedependent resistor model, TempResistor. This can be accomplished by redeclaring R1 and R2 as in the following type definition that defines RedefinedSimpleCircuit to be a special variant of SimpleCircuit.
Since TempResistor is a subtype of Resistor, it is possible to replace the ideal resistor model by a more specific temperaturedependent model. Values of the additional parameters of TempResistor can also be added in the redeclaration:
Replacing Resistor by TempResistor is a very strong modification. However, it should be noted that all equations that are defined in the previous Circuit example model are still valid. 2.11. Discrete and Hybrid ModelingMacroscopic physical systems in general evolve continuously as a function of time, obeying the laws of physics. This includes the movements of parts in mechanical systems, current and voltage levels in electrical systems, chemical reactions, etc. Such systems are said to have continuoustime dynamics. On the other hand, it is sometimes beneficial to make the approximation that certain system components display discretetime behavior (i.e., changes of values of system variables over time may occur instantaneously and discontinuously). In a real physical system the change can be very fast, but not instantaneous. Examples are collisions in mechanical systems (e.g., a bouncing ball that almost instantaneously changes direction), switches in electrical circuits with quickly changing voltage levels, valves and pumps in chemical plants, etc. The reason for making the discrete approximation is to simplify the mathematical model of the system, making the model more tractable and usually speeding up the simulation of the model by several orders of magnitude. Since the discrete approximation can only be applied to certain subsystems, we often arrive at system models consisting of interacting continuous and discrete components. Such a system is called a hybrid system and the associated modeling techniques hybrid modeling. The introduction of hybrid mathematical models creates new difficulties for their solution, but the disadvantages are far outweighed by the advantages. Modelica provides two kinds of constructs for expressing hybrid modelsconditional expressions and conditional equationsto describe discontinuous and conditional models. Whenequations are a particular kind of conditional equation, here instantaneous equations, that express equations that are only valid at instants in timeat discontinuitieswhen certain conditions become true. If[cond, thenpart, elsepart] is the Modelica form of conditional expressions that allows modeling of phenomena with different expressions in different operating regions, as seen in the following equation describing a limiter.
A more complete example of a conditional model is the model of an ideal diode. The characteristic of a real physical diode is depicted in Figure 4, and the ideal diode characteristic in parameterized form is shown in Figure 5. Figure 4. Real diode characteristic. Figure 5. Ideal diode characteristic. Since the voltage level of the ideal diode would go to infinity in an ordinary voltagecurrent diagram, a parameterized description is more appropriate, where both the voltage u and the current i, here the same as i1, are functions of the parameter s. When the diode is off, no current flows and the voltage is negative; whereas, when it is on, there is no voltage drop over the diode and the current flows.
Whenequations have been introduced in MathModelica to express instantaneous equations (i.e., equations that are valid only at certain points (e.g., at discontinuities)) when specific conditions become True. The syntax of Whenequations for the case of a vector of conditions is shown as follows. The equations in the Whenequation are activated when at least one of the conditions become True. A single condition is also possible.
A bouncing ball is a good example of a hybrid system for which the Whenequation is appropriate when modeled. The motion of the ball is characterized by the variable height above the ground and the vertical velocity. The ball moves continuously between bounces, whereas discrete changes occur at bounce times, as depicted in Figure 6. When the ball bounces against the ground, its velocity is reversed. An ideal ball would have an elasticity coefficient of 1 and would not lose any energy at a bounce. A more realistic ball, as the following modeled one, has an elasticity coefficient of 0.9, making it keep 90 percent of its speed after the bounce.
The bouncing ball model contains the two basic equations of motion relating height and velocity as well as the acceleration caused by the gravitational force. At the bounce instant, the velocity is suddenly reversed and slightly decreased (i.e., velocity (after bounce) = c*velocity (before bounce)) which is accomplished by the special syntactic form of instantaneous equation: Reinit[velocity,c*Pre(velocity)]. Figure 6. A bouncing ball. Example simulations of the bouncing ball model can be found in Section 4. 2.12. Discrete EventsIn the previous section on hybrid modeling we briefly mentioned the notion of discrete events. But what is an event? Using everyday language an event is simply something that happens. This is also true for events in the abstract mathematical sense. An event in the real world (e.g., a music performance) is always associated with a point in time. However, abstract mathematical events are not always associated with time but they are usually ordered (i.e., an event ordering is defined). By associating an event with a point in time, as in Figure 7, we will automatically obtain an ordering of events to form an event history. Since this is also the case for events in the real world, we will in the following always associate a point in time to each event. However, such an ordering is partial since several events can occur at the same point in time. To achieve a total ordering, we can use causal relationships between events, priorities of events, or, if these are not enough, simply pick an order based on some other event property. Figure 7. Events are ordered in time and form an event history. The next question is whether the notion of event is a useful and desirable abstraction, i.e., do events fit into our overall goal of providing an objectoriented declarative formalism for modeling the world? There is no question that events, such as a cocktail party event, a car collision event, or a voltage transition event in an electrical circuit, actually exist.. A set of events without structure can be viewed as a rather lowlevel abstractionan unstructured mass of small lowlevel items that just happen. The trick to arriving at declarative models about what is, rather than imperative recipes of how things are done, is to focus on relations between events, and between events and other abstractions. Relations between events can be expressed using declarative formalisms such as equations. The objectoriented modeling machinery provided by Modelica can be used to bring a highlevel model structure and grouping of state variables affected by events, relations between events, conditions for events, and behavior in the form of equations associated with events. This brings order into what otherwise could become a chaotic mess of lowlevel items. Our abstract "mathematical" notion of an event is an approximation compared to real events. For example, events in Modelica take no timethis is the most important abstraction of the synchronous principle to be described later. This abstraction is not completely correct with respect to our cocktail party event example since there is no question that a cocktail party actually takes some time. However, experience has shown that abstract events that take no time are more useful as a modeling primitive than events that have duration. Instead, our cocktail party should be described as a model class containing state variables, such as the number of guests that are related by equations active at primitive events like opening the party, the arrival of a guest, ending the party, serving the drinks, etc. To conclude, an event in Modelica is something that happens that has the following four properties.
DiscreteTime and ContinuousTime VariablesThe so called discretetime variables in Modelica only change value at discrete points in time (i.e., at event instants) and keep their values constant between events. This is in contrast to continuoustime variables, which may change value at any time, and usually evolve continuously over time. Figure 8 shows graphs of two variables, one continuoustime and one discretetime. Figure 8. Example graphs of continuoustime and discretetime variables. Note that discretetime variables change their values at an event instant by solving the equations active at the event. The previous value of a variable (i.e., the value before the event) can be obtained via the Pre function. Variables in Modelica are discretetime if they are declared using the Discrete prefix (e.g., Discrete Real y) or if they are of type Boolean, Integer, or String, or of types constructed from discrete types. A variable being on the lefthand side of an equation in a Whenequation is also discretetime. A Real variable not fulfilling the conditions for discretetime is continuoustime. It is not possible to have continuoustime Boolean, Integer, or String variables.


About Mathematica  Download Mathematica Player © Wolfram Media, Inc. All rights reserved. 