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

3. The MathModelica Integrated Interactive Environment

The MathModelica system consists of three major subsystems that are used during different phases of the modeling and simulation process, as depicted in Figure 9.

Figure 9. The MathModelica system architecture.

These subsystems are the following.

  • The graphic Model Editor used for designing models from library components.
  • The interactive Notebook facility used for for literate programming, documentation, running simulations, scripting, graphics, and symbolic mathematics with Mathematica.
  • The Simulation Center used for specifying parameters, running simulations, and plotting curves.

A menu palette enables the user to select whether to use the notebook interface for editing and simulations, or the Model Editor combined with the Simulation Center graphical user interface.

Additionally, MathModelica is loosely coupled to two optional subsystems for 3D graphics visualization and automatic translation of CAD models to Modelica. In order to provide the best possible facilities available on the market for the user, MathModelica also integrates and extends several professional software products that are included in the three subsystems. For example, one version of the simulation kernel includes simulation algorithms from Dynasim [23, 32], and the notebook facility includes the technical Mathematica computing system [9].

A key aspect of MathModelica is that the modeling and simulation is done within an environment that also provides a variety of technical computations. This can be utilized both in a preprocessing stage in the development of models for subsystems as well as for postprocessing of simulation results such as signal processing and further analysis of simulated data.

3.1. Graphic Model Editor

The MathModelica Model Editor is a graphical user interface for model diagram construction by "drag-and-drop" of model classes from the Modelica Standard Library or from user-defined component libraries, visually represented as graphic icons in the editor. A screen shot of the Model Editor is shown in Figure 10. In the left part of the window three library packages have been opened, visually represented as overlapping windows containing graphic icons. The user can drag models from these windows and drop them on the drawing area in the middle of the tool.

Figure 10. The graphic Model Editor showing an electrical motor with the Inertia parameter J modified.

The Model Editor can be viewed as a user interface for graphical programming in Modelica. Its basic functionality consists of selecting components from libraries, connecting components in model diagrams, and entering parameter values for different components.

For large and complex models it is important to be able to intuitively navigate quickly through component hierarchies. The Model Editor supports such navigation in several ways. A model diagram can be browsed and zoomed.

The Model Editor is well integrated with notebooks. A model diagram stored in a notebook is a tree-structured graphical representation of the Modelica code of the model, which can be converted into textual form by a command.

3.2. Simulation Center

The simulation center is a subsystem with a graphical user interface for running simulations, setting initial values and model parameters, plot results, etc. These facilities are accessible via a graphic user interface accessible through the simulation window (see Figure 11). However, remember that it is also possible to run simulations from the textual user interface available in the notebooks. The simulation window currently (MathModelica in 2005) consists of five areas or subwindows with different functionality:

  • The uppermost part of the simulation window is a control panel for starting and running simulations. It contains two fields for setting start and stop times for simulation, followed by Build, Run Simulation, Plot, and Stop buttons.
  • The left subwindow in the middle section shows a tree-structure view of the model selected and compiled for simulation, including all its submodels and variables. Here variables can be selected for plotting.
  • The center subwindow is used for diagrams of plotted variables.
  • The right subwindow in the middle section contains the legend for the plotted diagram (i.e., the names of the plotted variables).
  • The subwindow at the bottom is divided into three sections: Parameters, Variables, and Messages, of which only one at a time is visible. The Parameters section, shown in Figure 11, allows changing parameter values, whereas the Variables section allows modifying initial (start) values, and the Message section allows viewing possible messages from the simulation process.

Figure 11. The simulation window with plots of the signals Inertia1.flange_a.tau and Inertia1.w selected in the menus.

If a model parameter or initial value has been changed, it is possible to rerun the simulation without rebuilding the executable code if the changed parameter does not influence the equation structure. Structure changing parameters are sometimes called structural parameters.

3.3. Interactive Notebooks with Literate Programming

In addition to purely graphical programming of models using the Model Editor, MathModelica also provides a text-based programming environment for building textual models using Modelica. This is done using Mathematica notebooks, which are documents that may contain technical computations and text as well as graphics. Hence, these documents are suitable to be used for simulation scripting, model documentation and storage, model analysis and control system design, etc. In fact, this article is written as such a notebook and in the live version the examples can be run interactively. A number of sample notebooks are shown in Figure 12.

The Mathematica notebook facility is actually an interactive What-You-See-Is-What-You-Get (WYSIWYG) realization of Literate Programming, a form of programming where programs are integrated with documentation in the same document, originally proposed in [33]. A noninteractive prototype implementations of Literate Programming in combination with the document processing system has been realized [34]. However, MathModelica is one of very few interactive WYSIWYG systems so far realized for Literate Programming and to our knowledge the only one yet for Literate Programming in modeling, which also might be called Literate Modeling.

Figure 12. Examples of MathModelica notebooks.

Integrating Mathematica with MathModelica does not only give access to the notebook interface but also to thousands of available functions and many application packages, as well as the ability of communicating with other programs and import and export data in different formats. These capabilities make MathModelica more of a complete workbench for the innovative engineer than just a modeling and simulation tool. Once a model has been developed, there is often a need for further analysis such as linearization, sensitivity analysis, transfer function computations, control system design, parametric studies, Monte Carlo simulations, etc.

In fact, the combination of the ability of making user defined libraries of reusable components in Modelica and the notebook concept of living technical documents provides an integrated approach to model and documentation management for the evolution of models of large systems.

Tree-Structured Hierarchical Document Representation

Traditional documents (e.g., books and reports) essentially always have a hierarchical structure. They are divided into sections, subsections, paragraphs, etc. Both the document itself and its sections usually have headings as labels for easier navigation. This kind of structure is also reflected in Mathematica notebooks used in the MathModelica system.

Figure 13. The MyPackage package in a notebook.

In the MathModelica system, Modelica packages including documentation and test cases are primarily stored as notebooks as in Figure 13. Those cells that contain Modelica model classes intended to be used from other models, e.g. library components or certain application models, should be marked as export cells. This means that when the notebook is saved, such cells are automatically exported into a Modelica package file in the standard Modelica textual representation (.mo file) that can be processed by any Modelica compiler and imported into other models. For example, when saving the notebook MyPackage.nb of Figure 13, a file would be created with the following textual contents in Modelica syntax.

This can be expressed in the Mathematica style of Modelica syntax as:

Program Cells, Documentation Cells, and Graphic Cells

A notebook cell can include other cells and/or arbitrary text or graphics. In particular, a cell can include a code fragment or a graph with computational results.

The contents of cells can, for example, be one of the following forms.

  • Model classes and parts of models (i.e., formal descriptions) that can be used for verification, compilation, and execution of simulation models.
  • Mathematical formulas in the traditional mathematical two-dimensional syntax.
  • Text/documentation used as comments to executable formal model specifications.
  • Dialogue forms for specification and modification of input data.
  • Result tables whose results can be automatically represented in (live) tables, which can even be automatically updated after recomputation.
  • Graphical result representation with 2D vector and raster graphics as well as 3D vector and surface graphics.
  • 2D structure graphs that, for example, are used for various model structure visualizations such as connection diagrams and data structure diagrams.

A number of examples of these different forms of cells are available throughout this article.

Mathematics with 2D-Syntax, Greek Letters, and Equations

MathModelica uses the syntactic facilities of Mathematica to allow writing formulas in the standard well-known mathematical notation from textbooks in mathematics and physics. Certain parts of the Mathematica language syntax are however a bit unusual compared to many common programming languages. The reason for this design choice is to make it possible to use traditional mathematical syntax. The following three syntactic features are unusual:

  • Implied multiplication is allowed (i.e., a space between two expressions, such as x and f(x), means multiplication just as in traditional mathematics notation). A multiplication operator * can be used if desired, but is optional.
  • Square brackets are used around the arguments at function calls. Round parentheses are only used for grouping of expressions. The exception is TraditionalForm, which is discussed later in this section.
  • Support for two-dimensional mathematical syntactic notation such as integrals, division bars, square roots, matrices, etc.

The reason for the unusual choice of square brackets around function arguments is that the implied multiplication makes the interpretation of round parenthesis ambiguous. For example, f(x+1) can be interpreted either as a function call to f with the argument x+1 or f multiplied by (x+1). The integral in the following cell contains examples of both implied multiplication and two-dimensional integral syntax. The cell style is called MathModelica input form (StandardForm in Mathematica) and is used for mathematics and Modelica code in Mathematica syntax.

There is also a purely textual input form using a linear sequence of characters. For example, this is used for entering Modelica models in the standard Modelica syntax and is currently the only cell format in MathModelica that can interpret standard Modelica syntax. However, all mathematics can also be represented in this syntax. The previous example in this textual format appears as follows.

Finally, there is also a cell format called TraditionalForm, which is very close to traditional mathematical syntax, avoiding the square brackets. The aforementioned syntactic ambiguities can be avoided if the formula is first entered using one of the earlier input forms and then converted to TraditionalForm.

The MathModelica environment allows easy conversion between these forms using keyboard characters or menu items. In the following, we show a small example of a Modelica model class called SimpleDAE represented in the Mathematica-style syntax of Modelica that allows Greek characters and two-dimensional syntax. The apostrophe (') is used for the derivatives just as in traditional mathematics and in a MathModelica derivative with respect to time, corresponding to the Modelica der() operator. The initial conditions of the variables, if not explicitly specified in the declarations, are the default start-attribute values of the variables, which is zero for Real variables. Initial conditions for variables and derivatives can also be given in a special InitialEquation section.

We simulate the model for ten seconds by giving a Simulate command.

We use the command PlotSimulation for plotting the solutions for the two state variables, which of course are both functions of time, here denoted by t in Mathematica syntax.

A phase plane plot appears as follows.

3.4. Environment and Language Extensibility

Programming environments need to be flexible to adapt to changing user needs. Without flexibility, a programming tool becomes too hard to use for practical needs and therefore obsolete. Adaptability and flexibility are especially important for integrated environments, since they need to interact with a number of external tools and data formats, contain many different functions, and usually need to add new ones.

There are two major ways to extend a programming environment:

  • Extension of functionality (e.g., through user-defined commands, user-extensible menus, and a scripting language for programmability).
  • Extension of language and notation (e.g., by facilities to add new syntactic constructs and new notation or extending the meaning of existing ones).

Mathematica has been designed from the start to be an inherently extensible environment, which is what is used in MathModelica. Almost anything can be redefined, extended, or added.

Scripting for Extension of Functionality

An interactive scripting language is a common way of providing extensibility of flexibility in functionality. The MathModelica environment primarily uses the Mathematica language and its interpreter as a scripting language, as can be seen from a number of examples in this article. Another possibility is to use the Modelica language itself as a scripting language (e.g., by providing an interpreter for the algorithmic and expression parts of the language). This can easily be realized in MathModelica since the intermediate form has been designed to be compatible with Mathematica, and we already have Modelica input cells-just use Modelica input cells for commands, which are sent to the Mathematica interpreter instead of the simulator.

Extensible Syntax and Semantics

As was already apparent in the section on mathematical syntax, MathModelica provides a Mathematica-like input syntax for Modelica in addition to the usual Modelica syntax. One reason is to give support for mathematical notation, as explained previously. Another reason is to provide user-extensible syntax.

This is easy since syntactic constructs in Mathematica, apart from the operators, use a simple prefix syntax: a keyword followed by square brackets surrounding the contents of the construct (i.e., the same syntax as for function calls). If there is a need to add a new construct, no changes are needed in the parser, and no reserved words need to be added. Just define a Mathematica function to do the desired symbolic or numeric processing.

The other major class of syntactic constructs are operators. There are special facilities in Mathematica to add new operators by defining their priority, operator syntax, and internal representation. It is also possible to extend the meaning of existing operators like +, *, -, etc. However, it is not possible to just use any Mathematica function or operator without a Modelica definition within a Modelica class. For this to work, a MathModelica/Modelica definition of the function or operator must be provided.

Mathematica versus Modelica Syntax

In order to show the difference between the standard Modelica textual syntax and the extensible Mathematica-like syntax, we first show a simple Modelica model in a Modelica-style input cell.

The same model in the Mathematica-like Modelica syntax appears later. Note the use of the simple prefix syntax: a keyword followed by square brackets surrounding the contents of the construct. All reserved words, and by convention also predefined functions, and types in MathModelica start with an upper-case letter just as in Mathematica. Equation equality is represented by the Equal operator since = is the assignment operator in Mathematica. The derivative operator is the mathematical apostrophe (') notation rather than der(). The semicolon (;) is a sequencing operator to combine more than one declaration, statement, or expression.

Note that the Start attribute values, e.g. for x and xdot, are defined using declaration modifier equations StartEqual0. These Start attributes are used as hints for the initial conditions when the simulation starts. The simulator is free to deviate somewhat from these hints if needed to obtain a consistent set of initial values by solving an equation system for the initial values. However, if the attribute Fixed is True (default False), then the initial variable value is required to be the Start attribute value.

Choice of Mathematica Representation of Modelica Syntax

In order to represent Modelica in a Mathematica-compatible way and thereby potentially extend the Mathematica language, certain choices were made during the design and implementation of the MathModelica environment. Some of these design tradeoffs were not easy, and a number of variants have been implemented and tried out. Here we give a short motivation for our design in a few tricky cases.

  • Type prefixes. In declarations type prefixes are separated from the declared entity using one or more space characters. This happens to be standard notation in common programming languages such as Java, C++, or C. This choice is unambiguous also in Mathematica since the usual Mathematica interpretation of space as a multiplication operator is not valid in a type declaration and is instead interpreted as a type prefix operation. Such type prefixes are represented using the Prefixed[...] node that is always unparsed into space. Space is still parsed as implied multiplication in the usual expression context. Our implementation prevents the usual evaluation of declarations, which must be prohibited anyway regardless of the syntax, and converts multiplications in the type declaration prefix parts to Prefixed[...] nodes.

Some people have suggested using the Mathematica @ operator to represent such prefixes. This is however ambigous since @ is equivalent to function application. At unparsing it would be hard to know whether Real@x should be unparsed as Real@x or Real[x]. Moreover, the ambiguity is really serious and unsolvable in some cases such as array declarations, for example, the array declarations inside WaveEquationSample and initialPressure in Section 4.4.

  • Dot notation. Accessing the member of an object using dot notation (.), for example, person.length is an almost universally accepted notation in object-oriented programming languages. However, this clashes with the (rather rare) use of . in Mathematica for inner product as the Dot[...] operator. We experimented with several different operators, including the use of backtick (`). However, all these attempts eventually failed because of inappropriate priority and precedence of other operators. For example, assuming persons is an array of person records, persons[[2]].length accesses the length field of the second record. However, when using backtick, persons[[2]]`length is incorrectly parsed into implied multiplication of persons[[2]] and `length due to the high priority of backtick. Therefore, MathModelica redefines . to be parsed into Member[...] nodes, that is, a.b means Member[a,b]. To perform dot product between a and b, use the FullForm Dot[a,b]
  • Underscore. Most programming languages, including Modelica, allow underscore in identifiers. This is not possible in Mathematica since underscore is mapped to the Blank[...] pattern-matching operator. Our solution is to use the Mathematica \[ UnderBracket ] character (UnderBracket), which is very similar to underscore in appearance. For example, see its use in the design optimization model in Section 4.2 with the idealGearR2T1.flangeUnderBracketb variable.

3.5. Simulation, Translation, and Graphic Animation of CAD Models

The Model Editor provides an easy-to-use high-level user interface that works quite well for most application areas. However, for certain application areas, such as the design of 3D mechanical parts and assemblies of such parts, the two-dimensional user interface of the Model Editor is not very intuitive and sometimes hard to use. On the other hand, tools with 3D-interactive user interfaces for design of mechanical systems already exist. These are known as CAD systems for mechanical applications.

For these reasons we have developed an integration mechanism or a translator between existing CAD systems and the MathModelica environment. A CAD system is used as the interactive user interface to design the geometry, constraints, and connection structure of the mechanical application. This design is then automatically translated into a mechanical Modelica model for dynamic simulation. The generated Modelica model consists of connected instances of classes from the Modelica MultiBody System (MBS) library [35, 36]. Such translators integrated with the simulation environment have so far been developed for the two CAD systems SolidWorks [37] and AutoDesk's Mechanical Desktop [38].

We have also developed an OpenGL-based 3D visualizer and animation system called MVIS (Modelica VISualizer) [39] that provides an online dynamic display of the mechanical assembly during simulation, or an offline display based on saved state information for each time step.

Both the MVIS visualizer and the CAD translators are separate subsystems that communicate with the rest of the MathModelica environment using files and other means. They are not yet official parts of the MathModelica product release and are therefore indicated by a dotted line in the previously presented MathModelica structure diagram. The interplay between the simulation environment and the CAD environment is shown in Figure 14.

Figure 14. Functional structure of the information flow between the MathModelica simulation environment, the MIVS 3D visualizer, and the CAD environment.

Both translators are implemented as CAD system plug-ins that extract geometry, mass, inertia, and constraints information, and translate this information to Modelica source code. This code is combined with other code fragments (e.g., control system models) and simulated. The output can subsequently be visualized as a data plot of the system variables and/or as a 3D or 2D dynamic model animation. The 3D visualizations are scenes that display the geometry of the parts in motions prescribed by the simulation results. The graphical user interface of the CAD model and the output visualization capabilities of the simulation environment make it easy to describe and modify model geometry as well as examine analysis results at the same time. A more detailed picture of the translation and visualization mechanisms including associated data flows is shown in Figure 15.

Figure 15. The path from a static CAD model to a dynamic system simulation and visualization.

Figure 15 shows a mechanical model designed in the AutoDesk's Mechanical Desktop environment serving as the starting point of the specification of the virtual prototype with dynamic properties. The model is first saved in the DWG format, which contains all the information, including connections and mates constraints, related to the geometrical properties of the parts and the whole mechanical assembly.

The geometry of each part is exported to the .stl file format [40] for use by the MVIS visualizer. At the same time, the mass and inertia of the parts are extracted with mates information from the mechanical assembly. The translator uses this information to generate a corresponding set of Modelica class instances coupled by connections. This automatically generated Modelica file is processed by the MathModelica simulation environment. The simulation code can be enhanced by adding components from other Modelica libraries or by adding externally defined C code. In this phase electrical, control, or hydraulics components can be added to the generated mechanical model, providing multidomain simulation. The translated CAD model contains a set of dynamic equations of motion. The solution of these equations during simulation computes the dynamic response to a given set of initial conditions including force and/or torque loads, which might even be functions of time.

We might ask why develop yet another tool for multibody simulation of mechanical systems? There are already commercially available MBS simulation packages like ADAMS or WorkingModel3D. Many CAD systems are integrated with some multibody simulation tool. However, the primary limitation of these environments is the difficulty of integrating multidomain simulation within the same environment. Usually an interface to common simulation tools, like MATLAB and Simulink, is provided, but such solutions are not very flexible and do not give good performance because of the loose integration. By contrast, the MathModelica environment provides solutions to both of the following two major requirements:

  • The need to integrate multidomain simulation in the same environment.
  • The generation of quality documentation coupled to the design and code.

The main advantage of the MathModelica solution is that multidomain modeling and simulation is available in an integrated way in the same environment. This is provided in a way that is both very flexible and gives very efficient simulations, which, for example, is needed for tightly interacting system components like controllers embedded in mechanical systems. The control algorithms can, for example, be tested in parallel with the design of the mechanical parts of the system.

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