To try your own models by adding new cells or practising exercises chapters by creating new cell and evaluate, click DynamicWebBook
Copyright: (c) Link ping University, PELAB, 2003-2009, Wiley-IEEE Press, Modelica Association.
Contact: OpenModelica@ida.liu.se; OpenModelica Project web site: www.openmodelica.org
Book web page: www.openmodelica.org; Book author: Peter.Fritzson@ida.liu.se
Getting started information: OMWebbook
DrModelica Authors: (2003 version) Susanna Monemar, Eva-Lena Lengquist Sandelin, Peter Fritzson, Peter Bunus
DrModelica Authors: (2005 and later updates): Peter Fritzson, Adrian Pop, Alachew Shitahun, Arunkumar Palanisamy
This DrModelica notebook has been developed to facilitate learning the Modelica language as well as providing an introduction to object-oriented modeling and simulation. It is based on and is supplementary material to the Modelica book: Peter Fritzson: "Principles of Object-Oriented Modeling and Simulation with Modelica" (2004), 940 pages, Wiley-IEEE Press, ISBN 0-471-471631. All of the examples and exercises in DrModelica and the page references are from that book. Most of the text in DrModelica is also based on that book.
Detailed Copyright and Acknowledgment Information
A number of the examples in this document (DrModelica) and in the Modelica book are reproduced from the Modelica Language specification and Users Guide, copyrighted by the Modelica Association, and are free to use under the Modelica License (www.modelica.org). A number of examples have been published in papers and contributed by researchers (gratefully acknowledged in the book) for free use in the Modelica book and supplementary teaching material such as DrModelica. The rest of the examples in DrModelica are only from the Modelica Book, (c) by Wiley-IEEE Press, and are allowed for free usage if you and/or the teacher using this material have acquired that book.
General notice: All rights reserved. Reproduction or use of editorial or pictorial content in any manner is prohibited without expressed permission, if such content is not available by permission from another source. No patent liability is assumed with respect to the use of the information contained herein. While every precaution has been taken in the preparation of this manual, the publisher assumes no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained.
|Evaluate Cell||Click the Cell and Press "Evaluate Cell"||Click the Cell and Press "Shift+Enter"|
|Evaluate All Cells||Press "Eval all" button||Press "Shift+Ctrl"|
|Add Cells||Click "Add cells" button||Press "Ctrl+i"|
|Delete Cells||Click the Cell and Press "Delete Cells"||Click the Cell and Press "Delete"|
|Insert Cells between||Click the Cell and Press "Insert Between"||Click the Cell and Press "Ctrl+b"|
|Save to pdf||Click the "Save"||Press "Ctrl+s"|
The functionalities Add cells, Delete Cells , Insert Cells between and save to pdf are available only for DynamnicWebbook.
Instantiates a model/class and returns a string
containing the flat class definition.
Return a string containing all class definitions.
Return a string containing the class definition of
the named class.
Return a vector of the currently defined variable
Load model, function, or package relative to $MODELICAPATH.
Note: if e.g. loadModel(Modelica) fails, you may have
MODELICAPATH pointing at the wrong location.
Plot a variable from the most recently simulated model.
Plot variables from the most recently simulated model
given as a vector.
Plot var2 relative to var1 from the most recently simulated model.
Translates a model and simulates it.
Ex: simulate(dcmotor,startTime=0, stopTime=10, numberOfIntervals=1000)
This file is part of OpenModelica.
Copyright (c) 1998-2010, Link ping University,
Department of Computer and Information Science,
SE-58183 Link ping, Sweden.
All rights reserved.
THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3
AND THIS OSMC PUBLIC LICENSE (OSMC-PL).
ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S
ACCEPTANCE OF THE OSMC PUBLIC LICENSE.
The OpenModelica software and the Open Source Modelica
Consortium (OSMC) Public License (OSMC-PL) are obtained
from Link ping University, either from the above address,
from the URLs: http://www.ida.liu.se/projects/OpenModelica or
http://www.openmodelica.org, and in the OpenModelica distribution.
GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
This program is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS
See the full OSMC Public License conditions for more details.
There is a long tradition that the first sample program in any computer language is a trivial program printing the string "Hello World" (p. 19 in Peter Fritzson's book). Since Modelica is an equation based language, printing a string does not make much sence. Instead, our Hello World Modelica program solves a trivial differential equation. The next example Planar Pendulum (p.21) a mathematical model of physical system shows how you can write a model that solves Differential Algebraic Equation The second example shows how you can write a model that solves a Differential Algebraic Equation System (p. 19). In the Van der Pol (p. 22) example declaration as well as initialization and prefix usage are shown in a slightly more complicated way.
In Modelica objects are created implicitly just by Declaring Instances of Classes (p. 26). Almost anything in Modelica is a class, but there are some keywords for specific use of the class concept, called Restricted Classes (p. 29). The concept Reuse of Modeling Knowledge (p. 28) is an important part of Modelica. Modelica has several built-in types (like Real, Integer, Boolean and String), which has most of the properties a class has and it is possible to change the value of them during run-time. You can read more about classes in Chapter 3 below and in Chapter 3 in Peter Fritzson's book. Note that the chapter numbering in this electronic notebook corresponds to the numbering in Peter Fritzson's book in order to make it easy to use them together.
Inheritance (p. 29) is the ability to extend the behavior and properties of an existing class. This way the properties of a specific class can be reused. See Chapter 4 below and in Peter Fritzson's book for additional details concerning inheritance.
In many situations it is advantageous to be able to express Generic Patterns (p. 31) for programs. By doing so a substanitial amount of coding and software maintenance can be avoided by directly expressing the general structure of the problem and providing the special cases as parameters. In Modelica the class construct is general enough to handle generic modeling and programming. You can learn more about generic classes in Chapter 4 below and in Chapter 4 in Peter Fritzson's book .
Modelica is an equation-based language. The key to the physical modeling capabilities and increased reuse potential of Modelica classes is that Equations (p. 33) are more flexible than assignments, since they do not prescribe a certain data flow direction. Modelica also provides repetitive equation structures, like for-loop equations. See Chapter 8 to learn more about equations.
Partial (p. 43) is in Modelica the same as abstract in other object-oriented languages. A partial class is an incomplete class, i.e., not complete enough to be instantiated. Some more advanced examples concerning partial classes are presented in Chapter 3.
An Array (p. 47) is a collection of variables, all of the same type. Elements of an array are accessed through simple integer indexes, ranging from 1 to the size of the respective dimension. You can read more about arrays in Chapter 7.
Even though equations are eminently suitable for modeling physical systems, and for a number of other tasks, there are situations where non-declarative algorithmic constructs are needed. This is typically case for algorithms, i.e., stepwise procedural descriptions on how to carry out specific computations. In Modelica an algorithmic statement can only occur within Algorithm Sections, starting with the keyword algorithm (p. 44). Apart for the assignment statement, there are several kinds of Algorithmic Statements (p. 50) in Modelica, including if-then-else statements, for-loops, and while-loops. Functions (p. 51) are a natural part of any mathematical model. You can find more about Algorithms in Chapter 9.
In Modelica there are two different constructs for expressing hybrid models: Conditional Expressions or Equations (p. 55) and When-Equations used for the Bouncing Ball (p. 57). Too read more about if- and when-equations see Chapter 8.
Starting from Modelica version 3.3 two main groups of discrete-time and hybrid modeling features are available in the language: built-in synchronous clocks with constructs for clock-based modeling and synchronous clock-based state-machines.
Packages (p. 58) in Modelica may contain definitions of constants and classes including all kinds of restricted classes, functions and subpackages. By subpackage we mean that the package is declared inside another package, not any implied inheritance relationship. Regarding inheritance we talk about parent packages and child packages or derived packages. To learn more about packages, see Chapter 10.
The class concept is the most fundamental concept in Modelica. Different categories of class definitions, like Short Class Definitions (p. 86) Local Classes (p.86), Restricted Classes (p. 87) and Partial Classes (p. 39) are discussed in this section.
A variable is a class instance, always a member of (i.e., declared in) some other class instance or function. The Declaration of a Variable (p. 88) states the type, access, variability, data flow and other properties of the variable. Both class and variable declarations can contain various Variability Prefixes (p. 89), which associate certain properties with the declaration and are placed at the beginning of the declaration. A variable can be Initialized (p. 94) by using the start attribute. The variables that belong to a class are also called Fields (p. 74).
What is a Type? A Type (p. 100) can conceptually be viewed as a set of values. When we say that the variable x has the type Real we mean that the value of x belongs to the set of values represented by the type Real. The concepts of Subtype and Supertype (p. 100) are discussed further in Peter Fritzson's book.
One of the major benefits of object-orientation is Inheritance (p. 136), i.e., the ability to extend the behavior and properties of an existing class. A class can inherit from several classes, this is called Multiple Inheritance (p. 137). How are Public Respectively Protected Elements (p. 145) inherited? All these concepts are used in the Moon Landing (p. 143) example using inheritance.
There are three kinds of constructs in the Modelica language in which Modifications (p. 148) can occur: variable declarations, Short Class Definitions (p. 151) and Extends Clauses (p. 152). Hierarchical Modification (p. 155) means that elements one or more levels down in the instantiation hierarchy are modified.
A more dramatic change than just changing the default value in a declaration, is to modify the type and/or the prefixes of a declared element. The original declaration is replaced by the "new declaration", by using the Prefix redeclare (p. 160), merged with the modifiers of the original declaration. Redeclarations (p. 156) usually require the modified element to be declared with the replaceable Prefix (p. 156), but there are also kinds of redeclarations that do not need the Prefix replaceable (p. 158). In order to prevent certain modifications the final Prefix (p. 161) can be used. The rules concerning the Constraining Type of Replaceable Elements (p. 162) can be found in the book. Apart from textual Modelica programming, redeclarations may also be specified through a graphical user interface (GUI) of a Modelica modeling tool, e.g. via menu choices, in order to achieve this, Annotation Choices (s. 167) are used.
By expressing generic patterns for models or programs a large amount of coding and software maintenance can be avoided. This is done using Parameterized Generic Classes (p. 168). Parameterization and extension of Interfaces (p. 171).
It is important to Design a Class to be Extended (p. 173), otherwise inheritance might lead to errors.
Modelica Connectors are instances of Connector Classes (p. 188). Connectors specify the interface for interaction between a component and its surroundings.
Connections (p. 191) between components can only be established between connectors of equivalent type.
Each Mechanical Component (p. 195) has an associated coordinate system, called frame. It is possible to connect several connections to one connector, this is called Multiple Connections to a Single Connector (p. 198). The model of an Oscillating Mass Connected to a Spring (p. 199) gives rise to some dynamic movement when simulated.
A DC Motor Model (p. 209) is one of the simplest examples illustrating the ease of constructing multi-domain models in Modelica by simply connecting components from different domains. The point of a Partial DC Motor (p. 210) is to get a structured library component with inside and outside connectors that can be reused. The restrictions on how to connect Input and Output Connectors (p. 212) are also handled. Connection constraints regarding Array, Subscripts and Constants (p. 214) are different from other connected connectors. By Generating Connection Equations (p. 219) we mean the conversion of connect equations to the two different forms of equations to be used for non-flow and flow variables respectively. The process of converting connect-equations can be divided into two steps, the first is building connections sets from connect-equations and the second is generating connection equations for the complete model. In certain cases there is a need to let the behavior of a model be dependent on the number of connections to certain connectors of the model. This can be achieved by using a built-in function cardinality (p. 223) that returns the number of connections that have been made to a connector.
So far in we have focused on explicit connections between connectors where each connection is explicitly represented by a connect-equation and a corresponding line in a connection diagram. However, when modeling certain kinds of large models with many interacting components this approach becomes rather clumsy because of the large number of potential connections, a connection might be needed between each pair of components. These language constructs force lookup for implicit connections through the instance hierarchy instead of the usual nested lookup in the class hierarchy, as described briefly in the next section and more formally in Section 3.17.5, page 115. Another difference compared to explicit connections is that the inner/outer mechanism can be applied to any declared element in a class, not only to connectors. Now let us see an example of accessing shared inner (p.225) environment variable. As mentioned above, the inner/outer mechanism can be applied to any kind of element, not only to connectors. However, this mechanism is especially useful when applied to connectors to establish implicit connections between a single environment object and their components. Now let us see an example of Implicit versus Explicit Connection (p.226) Structures. The next example shows how to model a nested Hierarchical Subsytems with simulataneous inner outer (p. 228) keyword.
The Order of Evaluation (p. 274) (e.g. regarding variable references and function calls in expressions) is not specified, since a Modelica tool is free to solve equations, to reorder expressions, and to avoid evaluating expressions if their values do not influence the result. The rules for Subtyping and Variability (p. 283) for declaration equations and normal equations are illustrated. All declared variables are functions of the independent variable time, which is a built-in variable (p. 269) available in all kinds of classes. The variable time is treated as an input variable.
An Array Variable can be Declared (p. 311) by appending dimensions within square brackets after a type name or after a variable name. An Unspecified Dimension Size (p. 313) is stated by using a colon (:) instead of the usual integer expression for dimension size. For the purpose of Type Checking (p. 313) and selecting the right version of overloaded array operators and functions it is important to determine the expanded type of a variable.
An Array Constructor provides a convenient way of constructing array values, giving concise and readable code (p. 315).
General Array concatenation can be done through the array concatenation operator cat(k,A,B,C,...) that concatenates the arrays A,B,C,... along the k:th dimension (p. 318).
The Array Indexing operator (p. 321) is used to access array elements for retrieval of their values or for updating these values. When at least one of the index expressions in an array indexing operation is a vector expression, a slice or subsection of the array is accessed rather than a single element.
The Modelica Array Concatenation and Slice Operations (p. 325) have been designed for multidimensional arrays and can therefore produce arrays of various dimensions, from one-dimensional vectors to matrices and multidimensional arrays.
Arithmetic Array Operators (p. 329) on arrays and certain combinations of arrays and scalars are available through the standard arithmetic operators.
A number of Built-in Functions (p. 335) for array expressions are provided in Modelica. These functions are directly available and need not be imported from some package in the standard library before being used.
In certain situations it is useful to be able to apply a function to array values even if it has not been defined for such arguments. Modelica functions with one scalar return value can be Applied to Arrays element-wise (p. 340).
Empty Arrays are sometimes used as a kind of null element (p. 341).
That are two kinds of Equations that occur as Parts of Declarations: (p. 349) declaration equations and modifier equations.
The following kinds of equations can be present in equation sections: Simple Equality Equations (p. 351), Repetitive Equation Structures with for-Equations (p. 352), connect equations (p. 355), Conditional Equations with if-Equations (p. 355), Conditional Equations with when-Equations (p. 357) Assert (p. 361) and Terminate (p. 362). Terminate is described using the Moon Landing Example. Polynomial Equations using for-Equations is shown in XPowers (p. 353) and Polynomial Evaluator (p. 354). The class Step (p. 352) includes a repetitive equation structure in the form of a for-equation. Reinit (p. 359) is described in the Bouncing Ball model.
In Modelica, algorithmic statements can only occur within Algorithm Sections (p. 423), starting with the keyword algorithm. Simple Assignment Statements (p. 425) is the most common kind of statements in algorithm sections. There is a special form of assignment statement that is only used when the right hand side contains a call to a Function with Multiple Results (p. 426).
The for-Statement (also called for-loop) is a convenient way of expressing iteration (p. 427). When using the for-loop for iteration we must be able to express the range of values over which the iteration variable should iterate in a closed form as an iteration expression. For cases where this is not feasible there is also a while-loop iteration construct in Modelica (p. 429). Breaking an iteration when executing for and while loop is done with break statements (p.430). For conditional expressions the if-Statement (p. 431) is used. When-Statements (p. 433) are used to express actions at event instants and are closely related to when-equations. The reinit (p. 359) statement (see also reinit equations) can be used in when-statements to define new values for continuous-time state variables of a model at an event.
The assert (p. 436) statement provides a convenient means for specifying checks on model validity within a model.
The most common usage of terminate (p. 437) is to give more appropriate stopping criteria for terminating a simulation than a fixed point in time.
The body of a Modelica function is a kind of algorithm section that contains procedural algorithmic code to be executed when the function is called (p. 439). Since a function is a restricted and enhanced kind of class, it is possible to inherit an existing function declaration in the declaration of a new function. In this way we can declare the common structure of a set of functions as a Partial Base Function (p. 446) which can be inherited into the functions we want to define. A function with more than one output formal parameter has Multiple Results (p. 441).It is possible to call a function via instancename (p.443). It is possible to return a function from anywhere inside a function body (p.444). It is possible to pass a function as arguments to another function (p.446). A function can also be declared as partial function (p.448).It is possible to define functions as record constructors (p.452). It is possible to call functions defined outside of the Modelica language, so called External Functions (p. 466).
What is a Package?
The notion of a package partly originates from the notion of Abstract Data Type (p. 495).
There are essentially two ways of Accessing (p. 497) the definitions of a package: direct reference by prefixing the package name to definition names or importing definitions from the package.
A well-designed Package Structure (p. 500) is one of the most important aspects that influences the complexity, understandability, and maintainability of a large software systems.
In the following sections we will examine certain variants of packages that can be created through operations such as instantiation of Generic Packages (p. 508), Inheritance of Packages (p. 509), and manual editing. In addition will examine two special types of packages: Local Packages (p. 510) and Nonencapsulated Packages (p. 510). Also Copying or Moving Packages (p. 512) is discussed here.
Annotations (p. 519) are attributes that are not really part of the Modelica core language but still belongs to Modelica in a broad sense, and therefore are part of the Modelica language definition. Since annotations need to have a certain Syntax and Placement (p. 521) in classes, rules about this are discussed here. Graphical Annotations (p. 524) is the most common form of annotation in typical Modelica models. Function Annotations (p. 554).
Units and Quantities (p. 558) are constructs that are also not part of the Modelica language, but are for the same reason as Annotations part of the Modelica definition.
So far we have primarily discussed, and shown examples of, the principles of object-oriented mathematical modeling, a number of Modelica language constructs to support high-level model representations and a high degree of model reuse. But in this chapter we will instead present a systematic method on how to create system models.
To begin with, a tank system will be modeled, and there are different approaches. The Traditional Methodology (p. 571) for physical modeling can be roughly divided into three phases: basic structuring in terms of variables, stating equations and formulas, and converting the model to state space form. When using the Object Oriented Component-based (p. 572) approach to modeling we first try to understand the system structure and decomposition in an hierarchical top-down manner. When the system components and interactions between these components have been roughly identified, we can apply the first two traditional modeling phases of identifying variables and equations on each of these model components.
An event is simply something that happens, using everyday language. This is true in the real world as well as in the mathematical sense. Modelica provides a number of built-in functions and operators related to events and time. One function that can be used for generating repeated events is sample (p. 602).
Events arise naturally external to a simulated system or are generated internally in the simulation model. These events should be handled, i.e. some Behavior (p. 613) should be executed associated with each event. We also describe how to Use Event Priority to Avoid Erroneous Multiple Definitions (p. 617). Events often need to be Synchronized (p. 619) and propagated, though Modelica gives no guarantee of exact synchronization. Also discussed are Multiple Events at the Same Point in Time and Event Internation (p. 623).
This section provides you with a number of model examples of different kinds of discrete systems, for example Sampled Systems (p. 625), Finite State Automata (p. 635). The WatchDog System. (p. 644). and the Models for Event Based Stochastic Processes (p. 655).
The Discrete Event System Specification, abbreviated DEVS, is a modeling style and mathematical formalism. Examples of how DEVS models can be represented in Modelica is shown here (p. 658).
Petri Nets is a widely used formalism for modeling and analyzing discrete event systems, with an associated intuitive visual representation. The nets can be thought of as a graph containing two kinds of nodes, Places and Transitions (p. 666). This section is completed with an example of a cellular automata, Game of Life (p. 652).
Hybrid Systems, systems that contain both continuous-time and discrete-time subsystems. This section describes an example of a Hybrid System, the Hybrid Tank Model with a Discrete Controller (p. 676). We end with an example of A Mode Switching Model (p.682).
Mechatronic Systems- A DC Motor (p.794)
Chemical Reaction (p.829)
Economic Systems (p.853)
Design Optimization (p.869)
A 3D Double Pendulum (p.891)
Kinematic Loops (p.895)