See §2 for more details.
Lexical Rules
Comments
Single line comments
// until EOL
Multi-Line Comment
/* Can span multiple
   lines */

Identifiers
Normal Identifier Examples
Syntax:
[A-Za-z_][A-Za-z_0-9]*
aVariable Variable names typically start with lower case letters.
another_variable Word breaks are sometimes represented with underscores.
ClassNames By convention, class names start with upper case letter.
Quoted Identifiers
Syntax: '...'

If an identifier is surrounded by single quotes, it can contains spaces, digits and non-digits anywhere in the name. Furthermore, it can contain any of the following characters:

! # $ % & ( ) * + , - . / : ; < > = ? @ [ ] ^ { } | ~

Numbers
Floating Point Numbers
1, 1.0, 0.5, 2.3e-5, 78.2E+2

Leading zeros
.7 (as one example) is not a valid floating point number in Modelica because the lexical rules state that a floating point number must have a digit before the decimal point. However, several tools will accept such numbers anyway.
Complications with signed numbers
Examples of expressions which are not allowed in Modelica because of interactions between binary operators and unary operators (see §3.2):
2*-2, --2, ++2, 2--2

More information on the various kinds of classes can be found in §4.6.
Specialized Classes
model
model ModelName "Descriptive String"
  // parameters, connectors and sub-compoennts
  parameter TypeName varName "Parameter declaration";
  ConnectorType conName "Connector declaration";
  ModelType subcompName "Sub-component declaration";
  SomeType condComp if ... "Conditions component (see §4.4.5)";
protected
  TypeName varName "Protected declaration";
initial equation
  // Place any equations that apply only at the
  // start of a simulation here

equation
  // Equations go here
  annotation(...);
end ModelName;

record
record RecordName
  Real x;
  Real y;
end RecordName;

Note: record definitions cannot contain protected sections, equation sections or
algorithm sections. See §4.6 for additional restrictions.


connector
// Typical Phyical Connector
connector ConName
  Real acrossVar;
  flow Real throughVar;
end ConName;

// Causal Connector
connector ConName = input Real;

// Expandable Connector
expandable connector ConName
  // Minimum connector elements
  input Real alwaysPresent;
end ConName;

Note: A complete list of restrictions for the connector class can be find in §4.6. More information about expandable connectors can be found in §9.1.3.


block
block BlockName "Descriptive String"
  // parameters, connectors and sub-compoennts
  parameter TypeName varName "Parameter declaration";
  input ConnectorType conName "Connector declaration";
  ModelType subcompName "Sub-component declaration";
protected
  TypeName varName "Protected declaration";
initial equation
  // Place any equations that apply only at the
  // start of a simulation here

equation
  // Equations go here
  annotation(...);
end BlockName;

Note: a block is just like a model except that all connector instances (or their constituents) must have either input or output qualifiers.


type
// Extending built-in types
type Pressure = Real(unit="Pa");

// Creating enumerated types
type AssertionLevel = enumeration(warning, error);

// Named type for arrays
type Point = Real[3];

package
within ParentPackage; // within; for top-level packages
package PackageName "Package description"
  // The fully qualified name for this package
  // will be PackageName.NestedPackage
  package NestedPackage
    // Package contents
  end NestedPackage;
  
  // The fully qualified name for this model
  // will be PackageName.SomeModel
  model SomeModel
    ...
  end SomeModel;

  annotation(version="1.0", // This package's version number,
                            // if it is a top-level package
             // Set of packages this package depends on
             uses(AnotherPackageName(version="2.0"),
                  YetAnother(version="1.2")));
end PackageName;

For more details about packages, see §13


function
function FunctionName "Function description"
  input Real a;
  input Integer b;
  output Boolean c;
algorithm
  // Whatever value the output variables have after the
  // algorithm section is completed or when a return statement
  // is encountered will be returned as the output values.
end FunctionName;

For more details about functions, see §12.2


For complete details on all the predefined types, see §4.8.
Class Definitions
extends (inheritance)
extends BaseClass(/* modifications */);

replaceable
Replaceable Component
replaceable D comp;
Replaceable Class
replaceable model M = D

redeclare

The redeclare keyword is used to override the value of a replaceable component. This is typically done either through inheritance or through modifications applied to components. To demonstrate, consider the following model:

model Circuit
  ...
  replaceable Resistor R(R=100.0);
  ...
end Circuit;

Redeclaration in extends clauses
When inheriting from a definition, it is possible to redeclare replaceable components as follows:

model ThermalCircuit
  extends Circuit(redeclare ThermalResistor R(R=100.0));
end ThermalCircuit;
Redeclaration in component modifications
When instantiating a component, it is possible to redeclare replaceable sub-components as follows:

model UsesCircuit
  Circuit circuit(redeclare ThermalResistor R(R=100.0));
end UsesCircuit;

More details about modifications and redeclarations can be found in §7.2 and §7.3, respectively.


constrainedby
Replaceable Component
replaceable D comp constrainedby C;
Replaceable Class
replaceable model M = D constrainedby C;

import
Import a named definition
import Modelica.SIunits.Velocity;

Adds the definition Modelica.SIunits.Velocity to the local scope under the name Velocity.

Import definition under an alias
import SI=Modelica.SIunits;

Adds a given definition to the local scope under an alias name (e.g., Modelica.SIunits.Velocity could be referenced as SI.Velocity in this case).

Import contents of a package
import Modelica.SIunits.*;

Adds all the definitions defined in Modelica.SIunits to the local scope (under their normal names).

Use of the so-called "wildcard import" feature is strongly discouraged. It makes it unclear which definitions are actually used and can easily result in duplicate conflicting local names.

Note: Imports always uses fully qualified names. This means the name used must start from the top-level namespace.

encapsulated

The encapsulated keyword forces all types not belonging to a definition to be imported. More details can be found in §5.3.1.


final

The final keyword is used to indicate that no more modifications will be permitted to a variable. See §7.2.6 for more details.


partial

The partial keyword is used to indicate that a given definition is incomplete. This makes it clear to both users and the tools that the definition, as it stands, cannot be instantiated. Normally, a partial definition is extended from to create a complete (instantiable) definition. See §4.7 for more details.


expandable

The expandable keyword can be applied to a connector to indicate that additional signals can be added (through connections) beyond those declared explicitly in the connector definition. More information about expandable connectors can be found in §9.1.3.

If a variable in a connector lacks any qualifier, the default
connection behavior is to generate an equality equation
with its counterpart on all other connectors in the connection
set. More information on connections and connectors can be found in §9.1.

Connector Qualifiers
input

The input qualifier in a connector indicates that exactly one of that elements counterparts in a resulting connection set (§9.1.1) must have the output qualifier. More discussion of input and output qualifiers can be found in §9.3.


output

The output qualifier in a connector indicates that all other matching elements in a connection set must have the input qualifier. More discussion of input and output qualifiers can be found in §9.3.


flow

The flow qualifier in a connector indicates that all other matching elements in a connection set must also have the flow qualifier. When the connection set is resolved, an equation is generated that sums these matching elements to zero. More details on how equations are generated for flow elements can be found in §9.2.


stream

The stream qualifier is used to indicate when a given element in a connector is an intensive property of flowing through the connector. More details about "stream connectors" can be found in §15.

Default variability is continuous. So if a variable
doesn't have a variability qualifier, it is assumed to be
continuous. See §3.8 for more details.

Variability
constant

The constant qualifier is used for variables whose value will be the same across all potential simulations. (§3.8.1)


parameter

The parameter qualifier is used for variables whose value may change from one simulation to another but won't change during a given simulation. (§3.8.2)


discrete

The discrete qualifier is used for variables whose value changes during a simulation but only in response to discrete events. (§3.8.3)


For complete details on all the predefined types, see §4.8.
Builtin Types
Real
Attribute Type   Default
unit: String  ""
displayUnit: String ""
nominal: Real
stateSelect:   StateSelect  default
min: Real  -infinity
max: Real  -infinity
fixed: Boolean  false*
quantity:   String  ""
start: Real  0.0
Units Examples:  N.m J/(kg.K) m/s mm2 m.s-2 (see §19.1)

Integer
Attribute Type   Default
min: Integer  -infinity
max: Integer  -infinity
fixed: Boolean  false*
quantity:   String  ""
start: Integer  0

Boolean
Attribute Type   Default
fixed: Boolean  false*
quantity:   String  ""
start: Boolean  false

String
Attribute Type   Default
quantity:   String  ""
start: String  ""

enumeration
Syntax
type E = enumeration(e1, ..., en);
Attributes Conversions
E.e1, ..., E.en
E.start=e1
E.min=e1,
E.max=en
Integer(E.e1)=1
Integer(E.en)=n
String(E.e1)="e1"
Examples
type AssertionLevel = enumeration(warning, error);
type StateSelect = enumeration(never, avoid, default, prefer, always);
Complete details on enumerations can be found in §4.8.5

ExternalObject

External objects are used to refer (opaquely) to data or information outside the scope of the Modelica language. That are initialized through external functions and can be passed back to external functions.

More information about the ExternalObject type can be found in §12.9.7.

Standard Enumerations
AssertionLevel
// From §8.3.7
type AssertionLevel = enumeration(warning, error);

StateSelect
// From §4.8.8.1
type StateSelect = enumeration(never, avoid, default, prefer, always);

Arithmetic Operators
Name Description
+ Addition Can be used on both scalars and arrays of the same size
- Subtraction Can be used on both scalars and arrays of the same size
* Multiplication Can be used to multiply arrays by scalars or to take the inner product between two arrays.
/ Division Can be used on scalars. Can also be used with arrays as long as the denominator is a scalar.
.+ .- .* ./ Element-wise
Versions
When applied to arrays (of the same size), these operators perform their operation between scalars at matching positions in each array.
+ - * / .+ .- .* ./
Logical and Relational Operators

These role of these operators is self-explanatory. However, it is worth pointing out that the relational operators <, >, <= and >= will generate events when used in conjunction with continuous time variables. More discussion of such events and how to avoid them can be found in §3.7.3.

and or not <> < > <= >=
Mathematical Functions
Function Details
asin(x) -1 <= x <= 1
acos(x) -1 <= x <= 1
atan2(y, x) tangent of y/x
log(x) x>0
log10(x) x>0
tan(x) "x shall not be ..., -π/2, π/2, 3π/2, ..."
See §3.7.1.2 for further details about these functions.
acos asin atan atan2 cos cosh exp log log10 sin sinh tan tanh
Array Functions
Functions Documentation
scalar(A)
vector(A)
matrix(A)
§10.3.2
identity(n)
diagonal(v)
zeros(n1,n2,n3,...)
ones(n1,n2,n3,...)
fill(s,n1,n2,n3,...)
linspace(x1,x2,n)
§10.3.3
transpose(A)
outerProduct(v1,v2)
symmetric(A)
cross(x,y)
skew(x)
§10.3.5
scalar vector matrix identity diagonal zeros ones fill linspace transpose outerProduct symmetric cross skew
Event Generating Functions

The functions shown here generate events. More information about these functions can be found in §3.7.1.1 along with information about how to use the noEvent operator to suppress event generation.

ceil div fill floor integer max min mod rem
Numeric and Conversion Functions

Explanations for these functions can be found in §3.7.1.

abs sign sqrt Integer String
Special Operators
connect
connect(a, b); (see §9.1)

der
der(x) - Take the derivative of a variables or expression (see §3.7.2 )

inStream
Usage Description
inStream(v) v must be a stream variable (i.e., be preceded by the stream qualifier on a connector). This operator provides the value of the stream variable close to the connection point assuming inward flow. For more details, see §15.2.

actualStream
Usage Description
actualStream(v) Returns the actual value of the stream variable v for any flow direction. For more details, see §15.3.
semiLinear
Usage Description
semiLinear(x, postivieSlope, negativeSlope) Equivalent to: if x>=0 then positiveSlope*x else negativeSlope*x;
See §3.7.2 for more details.

spatialDistribution
Usage Description
spatialDistribution(...) See §3.7.2.2

getInstanceName
Usage Description
getInstanceName() Returns a string with model/block and instance names from which it is called. See §3.7.2.6 for further details.

homotopy
Usage Description
homotopy(actual=...,simplified=...) The homotopy operator can be used to ease the solving of non-linear systems. Further discussion of its use can be found in §3.7.2.

delay
Usage Description
delay(expr, delayTime)
delay(expr, delayTime, delayMax) 
Give the value of expr delayed by (the potentially variable) delayTime. See §3.7.2 and §3.7.2.1 for more details.

assert
Usage Description
assert(cond, message, level=AssertionLevel.error) Assertions are used to enforce limitations in a model through the conditional expression, cond. Normally, the level argument defaults to AssertionLevel.error. However, if a false value for cond isn't strictly an error, the level argument can be set to AssertionLevel.warning. See §8.3.7 for more details about assert.

ndims
Usage Description
ndims(A) Returns the number of dimensions of A. See §10.3.1 for more details.

size
Usage Description
size(A,i) Returns the size of dimension i in A where 0 < i <= ndims(A).
size(A) Returns a vector containing the size of each dimension of A.
See §10.3.1 for more discussion about the size function.

cardinality
This operator is deprecated. It should no longer be used (see §3.7.2).

isPresent
This operator was removed from the language as of version 3.0.
Reduction operators are discussed in §10.3.4.
Reduction Operators
max
Usage Description
max(A) When applied to an array, the max function returns the element of the array with the greatest value. For example,
max([1, 5; 7, 3]) returns 7
max({3, 8, 1}) returns 8
max(x, y) When used with two scalar arguments, max returns the greater of the two arguments.
max(e, for i in u, j in v, ...)   Returns the greatest value among all possible values of e over the range of all possible index combinations.

min
Usage Description
min(A) When applied to an array, the min function returns the element of the array with the least value. For example,
min([1, 5; 7, 3]) returns 1
min({3, 8, 1}) returns 1
min(x, y) When used with two scalar arguments, min returns the lesser of the two arguments.
min(e, for i in u, j in v, ...)   Returns the least value among all possible values of e over the range of all possible index combinations.

product
Usage Description
product(A) When applied to an array, the product function returns the product of all elements in the array. For example,
product([1, 5; 7, 3]) returns 105
product({3, 8, 1}) returns 24
product(e, for i in u, j in v, ...)   Returns the product of all values of e over all possible index combinations.

sum
Usage Description
sum(A) When applied to an array, the sum function returns the sum of all elements in the array. For example,
sum([1, 5; 7, 3]) returns 16
sum({3, 8, 1}) returns 12
sum(e, for i in u, j in v, ...) Returns the sum of all values of e over all possible index combinations.
These event related operators are discussed in §3.7.3.
Event Operators
pre
Usage Description
pre(y) At an event, the pre operator is used to refer to the value of a variable prior to that event. There are several caveats related to the use of pre. These can be found in §3.7.3.

noEvent
Usage Description
noEvent(expr) The noEvent operator suppresses the generation of events by any event generating operators or functions in the expression expr. Further information about the noEvent operator can be found in §3.7.3.2 and §8.5.

change
Usage Description
change(v) The expression change(v) because true only for the instant that the value of the variable v changes (i.e., v<>pre(v)). See the pre operator and/or §3.7.3.1 for more details and restrictions.

edge
Usage Description
edge(b) The edge operator becomes true only at the instant when the expression b goes from false to true (i.e., b and not pre(b)). See the pre operator and/or §3.7.3.1 for more details and restrictions.

initial
Usage Description
initial() The initial operator is true during the initialization phase of the simulation.

terminal
Usage Description
terminal() The terminal operator becomes true at the end of a successful simulation.

reinit
Usage Description
reinit(x, expr) The reinit operator sets the value of the variable x to be equal to the of expr. Note, reinit can only be used within a when clause. For more details on the usage and restrictions of reinit, see §8.3.6.

sample
Usage Description
sample(start, interval) The sample operator because true when time>=start and again every interval seconds after that. Further details can be found in §3.7.3.

smooth
Usage Description
smooth(p, expr) When evaluated, the smooth operator simply returns the value of the expression expr. But it also acts as a guarantee that expr is p times continuously differentiable. For further details, see §3.7.3.2.

terminate
Usage Description
terminate() The terminate operator instructs the underlying simulation environment to terminate the simulation after the completion of the next integration step or event iteration. See §8.3.8 for more details.

Statements
if
If Statement (§11.2.6)
if cond then
  ...
elseif cond then
  ...
else
  ...
end if
If Expression (§3.6.5)
if cond1 then expr1 elseif cond2 then expr2 else expr3;

when
When Statement (§11.2.7)
when cond then
  ...
elsewhen cond then
  ...
end when;

Tip: It is easy to get into trouble with algebraic loops when using when clauses. To avoid problems, assign your conditional expression, cond, to a variable, v, and then state your when condition as when pre(v) then. This is a fancy way of saying "when I know that this condition has happened for sure (and can't be undone by the equations in this when clause), do this...".


Restrictions:

  • Cannot be used in a function
  • Cannot be nested
  • Cannot occur inside while, if or for clauses.

If the conditional expression for the when clause is a vector, the contents of the when clause become active when any of the elements in the vector become true.


while
While Statement (§11.2.3)
while cond loop
  ...
end while;

for
For Statement (§11.2.2)
Syntax for indices loop
  ...
end for;
Indices
for i in 1:10 loop Looping over a range of integers
1,2,3,...,10
for i in 1.0 : 1.5 : 5.5 loop Looping over reals
1.0, 2.5, 4.0, 5.5
for i in {1,3,6,7} loop Looping over a collection of values
1, 3, 6, 7
for i in TwoEnums loop Looping over enum values
TwoEnums.one, TwoEnums.two
where type TwoEnums = enumeration(one, two)

Complex Expression
Vector Literal
{..., ....}

Array Literals
[..., ...; ..., ...]

Array Comprehensions
One index { f(i) for i in 1:ni }
Two indices { f(i,j) for i in 1:ni, j in 1:nj }
Note: The resulting array will have dimensions [nj,ni].

Operator overloading is a complex topic and is covered in detail in §14

Operators
operator record
What's an operator record?

An operator record is like an ordinary record except that it is possible to define custom behavior for operators like +, -, etc. For more details, see §14.

Canonical Syntax
operator record Complex
  Real re;
  Real im;
  ...
  // Definition of operator functions
  // operators
end Complex;

operator function
What's an operator function?

An operator function is a function that implements an operator for an operator record.

Possible Operators
Constructors (see §14.2): constructor, 0
Conversions (see §14.3): String
Binary Operators (see §14.4): + , - , * , / , ^ , == ,
<> , > , < , >= , <= , and , or
Unary Operators (see §14.5): - , not
Examples
encapsulated operator function '+'
  import Complex;
  input Complex c1;
  input Complex c2;
  output Complex result;
algorithm
  result := Complex(c1.re+c2.re, c1.im+c2.im);
  annotation(Inline=true);
end '+';
Note: An operator function should be encapsulated.

operator
What's an operator?

When an operator record requires more than one implementation of a given operator, e.g., '+', a special type of package called an operator is created with the name of the overloaded operator. This operator "package" includes all the various implementations of the operator.

Example
enscapsulated operator '-'
  import Complex;
  function negate
    input Complex c;
    output Complex result;
  algorithm
    result := Complex(-c.re, -c.im);
    annotation(Inline=true);
  end negate;

  function subtract
    input Complex c1;
    input Complex c2;
    output Complex result;
  algorithm
    result := Complex(c1.re-c2.re, c1.im-c2.im);
    annotation(Inline=true);
  end subtract;
end '-';
Note: An operator should be encapsulated.
Annotations
choices
Explicit values for a variable
parameter Integer x
  annotation(choices(choice=3 "Desc", choice=5 "Desc"));

Explicit redeclarations
replaceable model Resistor Load(R=2) constrainedby TwoPin
  annotation(choices(
              choice(redeclare ThermalResistor Load(R=2,T0=273)),
              choice(redeclare Capacitor Load(C=2e-3))));

defaultComponentName

The defaultComponentName annotation allows a default name to be associated with a given definition. When dragging new instances of a given definition into a diagram, the string associated with the defaultComponentName should be used as the basis for the initial instance name.


defaultComponentPrefixes

The defaultComponentPrefixes annotation allows a default set of prefixes to be associated with a given definition. When dragging new instances of a given definition into a diagram, these prefixes should automatically be applied to the new instance.


derivative
A normal single argument function
function f0
  input Real x;
  output Real y;
algorithm
  ...
  annotation(derivative=f1);
end f0;
Definition of the first derivative of f0
function f1
  input Real x;
  input Real der_x;
  output Real der_y;
algorithm
  ...
end f1;
The derivative annotation is discussed in great detail in §12.7.1.

Dialog
Definition
record Dialog
  parameter String  tab = "General";
  parameter String  group = "Parameters";
  parameter Boolean enable = true;
  parameter Boolean showStartAttribute = false;
  parameter String  groupImage = "";
  parameter Boolean connectorSizing = false;
end Dialog;
A detailed description of each field in the Dialog annotation can be found in §18.7.

Documentation
annotation(Documentation(info="<html>...</html>",
                         revisions="..."));

Note: Within the <html> tags, it is possible to use "Modelica URIs" of the form:

  • Modelica://Fully.Qualfied.Name#layer: Where layer can be one of diagram, info, text or icon.
  • Modelica://Fully.Qualfied.Name/dir/path/filename: Where dir/path is a directory structure starting at the point where the package Fully.Qualified.Name is stored and filename is a file in that directory.

Complete documentation for the Documentation annotation can be found in §18.2.


DynamicSelect
Syntax
DynamicSelect(val1, val2)
Explanation

The DynamicSelect annotation can be used as a value in any graphical annotation. The first argument must be a literal expression (no variables) and the second argument can reference variables. Tools can then use the second expression in contexts (e.g., when simulation results are available) to adjust the graphical representation according to the values of the variables.


Evaluate

When applied to a parameter, the Evaluation annotation indicates that the user does not intend to modify the value of the parameter between simulations. As a result, some potentially significant symbolic optimizations can often be made.

See §18.3 for more details.


experiment
Definition
record experiment
  parameter Real StartTime;
  parameter Real StopTime;
  parameter Real Interval;
  parameter Real Tolerance;
end experiment;

StartTime, StopTime and Interval are all assumed to have units of seconds.

See §18.4 for more details.


GenerateEvents

When the GenerateEvents annotation is associated with a function definition and given a value of true, this indicates that expressions in the function should generate events (e.g., as if they appeared in an equation section).

See §18.3 for more details.


HideResult

When applied to a variable declaration, the HideResult annotation indicates that the user does not wish to view this variable among the simulation results.

See §18.3 for more details.


Inline

When the Inline annotation is associated with a function definition and given a value of true, this indicates that the function should be inlined prior to symbolic manipulation.

See §18.3 for more details.


inverse
function f
  input T1 u1;
  input T2 u2;
  output R y;
algorithm
  ...
  annotation(inverse(u1=fi1(u2,y),
                     u2=fi2(u1, y)));
end f;

LateInline

When the LateInline annotation is associated with a function definition and given a value of true, this indicates that the function should be inlined during the code generation process, but not before symbolic manipulation has been performed.

See §18.3 for more details.


missingInnerMessage
annotation(missingInnerMessage="...");

This annotation allows a tool to provide a customized message when an outer declaration cannot find a matching inner. This allows library developers to provide more specific and meaningful diagnostics to users.

See §18.7 for more details.


preferredView

In a definition, the preferredView annotation can be given the values "info", "diagram" or "text" to indicate which particular view makes the most sense as the default view for that definition (see §18.2).


smoothOrder

In a function definition, the smoothOrder annotation indicates how many times the function can be differentiated and still have continuous outputs. See §18.3 for complete details.


unassignedMessage

If the unassignedMessage annotation is associated with a variable, then the value of the annotation (which must be a String) will be used as a diagnostic message to the user if the structural analysis of the problem does not yield an equation to compute that variable. See §18.7 for complete details.


version

Within a top-level package, the version annotation is used to indicate the version number for that package. This is used to distinguish between multiple versions when they are available. See §18.8.2 for more details about version handling.

Legend

  • : Read more
  • : Note of caution
  • : Sample code
(You can hit the Escape key to close all popups)
© 2013 Xogeny