Mathematica Journal
Volume 10, Issue 1


In This Issue
Trott's Corner
New Products
New Publications
News Bulletins
New Resources

Download This Issue 

About the Journal
Editorial Policy
Staff and Contributors
Back Issues
Contact Information

MathModelica--An Object-Oriented Mathematical Modeling and Simulation Environment
Peter Fritzson

5. Using the Symbolic Internal Representation

In order to satisfy the requirement of a well-integrated environment and language, the new MathModelica internal representation was designed with a Mathematica-compatible version of the syntax. Note that the Mathematica version of the syntax has the same internal abstract syntax tree representation and the same semantics as Modelica, but different concrete syntax. Which syntax to use-the standard Modelica textual syntax or the Mathematica-style syntax for Modelica-is however largely a matter of taste.

The fact that the Modelica abstract syntax tree representation is compatible with the Mathematica standard representation means that a number of symbolic operations, such as simplifying model equations, performing Laplace transformations, and performing queries on code as well as automatically constructing new code, is available to the user. The capability of automatically generating new code is especially useful in the area of model diagnosis, where there is often a need for generating a number of erroneous models for diagnosis based on corresponding fault scenarios.

5.1. Mathematica-Compatible Internal Form

An inherent property of Mathematica is that code or models are normally not written as free formatted text. Instead, Mathematica expressions (also called terms) are used, internally represented as abstract syntax trees. These can be conveniently written in a tree-like prefix form or entered using standard mathematical notation. Every term is a number, an identifier, or a form such as:

For example, an expression such as a+b is represented as Plus[a,b] in prefix form, also called FullForm syntax. A while loop is represented as the term While[test,body].

In order to satisfy the requirement of a well-integrated environment, we designed the new MathModelica internal representation with a Mathematica-compatible version of the concrete syntax, called MathModelicaForm. Note that MathModelicaForm has the same abstract syntax trees and the same semantics as ModelicaForm representing standard Modelica, but different concrete syntax. This means that essentially the same language constructs are written differently, as illustrated in the following. Since the same internal representation is used, a cell expressed in ModelicaForm can easily be converted to MathModelicaForm or vice versa by just calling GetDefinition with a different value of the Format parameter.

The Mathematica language syntax uses some special operators and arbitrary arithmetic expressions composed from terms.

Internally the MathModelica system uses the MathModelicaFullForm format. This format is the abstract syntax of the MathModelica language where all the elements of the language have been defined to be easy to extract and compare for the functions operating on the MathModelica language representation, as well as achieving a high degree of compatibility with both Modelica and Mathematica.

The following is a simple constant declaration inside a model Arr.

This definition is stored internally in the MathModelicaFullForm format, which can be retrieved by calling the function GetDefinition that returns the internal abstract syntax tree representation of the model:

The tree is wrapped into the node Hold[] to prevent symbolic evaluation of the model representation while we are manipulating it. All nodes are shown in prefix form except the array/list nodes shown as {...} instead of the prefix form List[...] for arrays.

A declaration of a variable such as unitarr is represented by the Declaration node in the abstract syntax. This node has two arguments: the type and the variable instance. The type is represented by the TYPE node which stores the name, array dimension, type attributes (Constant), and type modifications, which is empty in this case. The instance argument contains a VariableComponent including the name of the variable, the initialization (ValueBinding), at the end of the comment string that is associated with the variable.

There are several goals behind the design of the MathModelicaFullForm format, which are fulfilled in the current system:

  • Abstract syntax. The format systematically sorts out the different constructs in the language making the navigation of types and code easier.
  • Preservation of the syntactic structure of both Modelica and Mathematica code. This means that the mapping from Modelica to MathModelicaFullForm format should be injective (e.g.. the source code can be recreated from the intermediate form), and that transformations from Modelica via MathModelicaFullForm into Mathematica-style Modelica form should be reversible.
  • Explicit semantic structure. The format has reserved fixed attribute positions for certain kinds of semantic information to simplify semantic analysis and queries. There is also a canonical subset of the format that is even simpler for semantic analysis, but does not always recreate exactly the same source code since the same declaration often can be stated in several ways.
  • Symbol table and type representation format. The MathModelicaFullForm format should be possible to use in the symbol table, e.g. to represent types. Types are represented by anonymous type expressions such as the TYPE node in the previous example. Anonymous means that the type representation is separate from the entity having the type.
  • Internal standard. The MathModelicaFullForm format should be used by all the parts of the MathModelica system.

Here we show a small model SecondOrderSystem in the different representations. First, the Modelica model is in the Mathematica-style Modelica syntax.

This model is parsed and stored internally as Modelica in the abstract syntax MathModelicaFullForm representation. This can be retrieved and unparsed into standard textual Modelica as follows.

We retrieve the model once more, but specify unparsing into the Mathematica-style Modelica syntax by setting the format argument to MathModelicaForm. The model is returned in a Hold node to prevent symbolic evaluation.

Finally we obtain the MathModelicaFullForm of the model. Certain operators like {}, Equal, +, etc. are still unparsed as infix notation. To get the prefix notation List[], Equal[], Plus[], etc., for these operators, use the FullForm command on the result (not done here).

5.2. Extracting and Simplifying Model Equations

This section will illustrate a few user-accessible symbolic operations on equations, such as obtaining the system of equations and the set of variables from a Modelica model, and symbolically simplifying this system of equations with the intention of performing symbolic Laplace transformation.

Definition and Simulation of Model1

The example class Model1 has been drawn in the graphic model editor and imported into the following notebook.

Figure 41. Connection diagram of Model1.

Here is the model code.

We simulate the model, smooth the result, and make two plots, where the first is a plot of the product of the voltage and current over Resistor1.

Figure 42. Plot of the current-voltage product over Resistor1 in Model1.

The second plot is parametric, where we plot the Resistor1 current against its derivative.

Figure 43. Parametric plots of the Resistor1 current against its derivative.

Some Symbolic Computations

Now, flatten Model1 and extract the model equations and the model variables as lists, and compute the lengths of these lists.

There is one equation less than the number of variables. Therefore, add an equation for zero torque on the right flange to the equation system.

We would like to simplify the equations by eliminating the connector variables before further symbolic processing. First, we obtain the connector variables from the flattened model.

Here we use the Eliminate function for symbolic elimination of some variables from the system of equations.

5.3. Symbolic Laplace Transformation and Root Locus Computation

We would now like to perform a Laplace transformation of the symbolic equation system obtained in the previous section. This can be done by the application of two transformation rules: , der[b_]->s b. Note that is the inverse of taking a derivative (i.e., an integration operation). Note also that the second rule contains an implied multiplication.

Here we introduce short names for the model parameter to obtain a more concise symbolic notation.

Then we derive the relation between Inertia2.w and the input voltage.

The transfer function H is obtained by symbolically solving for Inertia2.w in the equation system eq4 and using the obtained solution on a form Inertia2.w -> expr to eliminate Inertia2.w, thus obtaining H.

A Root Locus Computation

Here a list of model parameter values is defined for subsequent use.

Here we compute the poles of the transfer function to obtain the root locus.

Here is a root locus plot that substitutes values for the model parameters.

Figure 44. Root locus plot over the complex plane.

5.4. Queries and Automatic Generation of Models

The following example of advanced scripting shows how the easily accessible internal representation in the form of abstract syntax trees can be used for automatic generation of models. The CircuitTemplateFn is a function returning a symbolic representation of a model. This function has two formal pattern parameters where the second one specifies an internal structure. The first parameter is name_, which matches symbolic names. The underscore in name_ is not part of the parameter identifier itself, it is just a short form of the syntax name:_, which means that name will match any item.

The second pattern parameter is the list {type1_,type2_,type3_}, internally containing the three pattern parameters type1_,type2_,type3_. This second parameter will therefore only match lists of length 3, thereby binding the pattern variables type1, type2, and type3 to the three type names presumably occurring in the list at pattern matching. For example, matching {type1_,type2_,type3_} against the list {Capacitor,Conductor,Resistor} will bind the variable type1 to Capacitor, type2 to Conductor, and type3 to Resistor.

The aim of this exercise is to automatically generate models based on this template for all combinations of the types that extend the type OnePort in the library package Modelica.Electrical.Analog.Basic.

First, we need to extract all the types that extend the type OnePort in the library package Modelica.Electrical.Analog.Basic. This is done by performing a query operation on the internal form using the Select function that has two arguments: the list to be searched, and a predicate function returning True or False. Only the elements for which the predicate is True are returned. In this case the query is performed on the list of model names in the package Modelica.Electrical.Analog.Basic. This list is returned by the function ListModelNames.

First, we call GetDefinition to load the Modelica.Electrical.Analog.Basic package into the internal symbol table.

Then we perform the actual query.

All 64 three-type combinations (e.g., {Inductor,Inductor,Inductor}, {Inductor,Inductor,Capacitor}, etc.), whose prefixes are not shown for brevity, of the four types {Inductor,Capacitor,Conductor,Resistor} are computed by taking a generalized outer product of the three types lists, which is flattened.

We generate a list of 64 synthetic model names by concatenating the string "foo" with numbers, using the Mathematica string concatenation operation "<>".

Here all 64 test models are created by the call to MapThread, which applies CircuitTemplateFn to each combination.

Here we retrieve the definition of one of the automatically generated models, foo53, and unparse it from its internal representation to the Modelica textual form.

Now we create a Total model within which all 64 generated models will be instantiated. First, create the an empty model.

Then we use the Within statement to move the current scope inside the model and make a declaration (i.e., instantiation of the first test model).

Since we are free to use Mathematica scripting, we should use a loop for the 63 remaining declarations.

Finally, we move the scope back to the global scope.

Here we retrieve the generated model Total, where we have abbreviated the output to save some space.

Finally, we simulate the Total model to verify that the test models are semantically correct.

5.5. Language Extension Example for PDEs

As previously stated, the uniform prefix syntax makes it easy to experiment with language extensions since both the syntax and the internal representation are obtained automatically. The following example is from an experiment in extending Modelica with partial differential equations [42]. Here we have added a new restricted class called Domain, the prefix Space, and a new kind of equation section called Boundary containing equations that specify boundary conditions.

Here is a plotted result of a solution at a specific time instant from running the prototype simulator on this model.

Figure 45. Plot of PDEs solution at a specific time instant.

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