-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMSL.tex
3506 lines (2998 loc) · 139 KB
/
MSL.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[10pt,a4paper]{report}
\usepackage[utf8]{inputenc}
\NeedsTeXFormat{LaTeX2e}
% Uses some packages:
\usepackage{amsmath}
\allowdisplaybreaks
%
\usepackage{t1enc}
\usepackage[dvips]{graphicx}
\usepackage{verbatim}
%
% Allow lot of figures on page:
\renewcommand{\textfraction}{0}
\renewcommand{\topfraction}{1}
\renewcommand{\bottomfraction}{1}
\setcounter{totalnumber}{1000}
\raggedbottom
\usepackage{hyperref}
\hypersetup{colorlinks=true}
\usepackage{longtable}
\usepackage{listings}
\usepackage{color}
% For myref below:
\usepackage{ifpdf,ifxetex,ifluatex}
% Special commands for comments:
% They format the actual text as "emph" enclosed in []
% due to embedded listings there are 4 commands, and not just one
\def\Mcomment#1{{[}\emph{#1}{]}}
\def\Mcommentbegin#1{{[}\emph{#1}}
\def\Mcommentend#1{\emph{#1}{]}}
\def\Mcommentmid#1{\emph{#1}}
% It will be cleaner after resolving https://github.com/brucemiller/LaTeXML/issues/874
% Label handling:
% Define something to both be a label in latex and in html:
\def\doublelabel#1{\label{#1}\hypertarget{#1}{}}
% If we want items to be both numbered and named that seems different for LaTeXML:
% We could also have it differently depending on environment:
\ifpdf
\def\myref#1{\ref{#1}~\nameref{#1}}
\else
\def\myref#1{\nameref{#1}}
\fi
%
% Set up listing:
\definecolor{darkgreen}{rgb}{0,0.4,0}
\lstset{
basicstyle=\color{blue}\ttfamily,
keywordstyle=\color{red}\rmfamily\bfseries,
commentstyle=\color{darkgreen}\sffamily,
}
\setcounter{secnumdepth}{5}
\definecolor{keywordcolor1}{rgb}{0,0,.4}
\definecolor{keywordcolor2}{rgb}{.90,0,0}
% See https://github.com/modelica-tools/listings-modelica/blob/master/listings-modelica.cfg
\lstdefinelanguage{modelica}{%
alsoletter={...},%
%otherkeywords={-, =, +, [, ], (, ), \{, \}, :, *, !},%
morekeywords=[1]{},% blue Keywords
morekeywords=[2]{% blue + bold keywords
annotation,assert,block,class,connector,constant,discrete,%
encapsulated,else,elseif,elsewhen,end,exit,extends,external,final,flow,for,%
function,if,in,inner,initial,input,import,loop,model,nondiscrete,outer,%
output,package,parameter,partial,record,redeclare,replaceable,return,%
size,terminate,then,type,when,while,algorithm,equation,%
protected,public,and,false,not,or,true},%
% Note: initial is in both variants - depending on context, use first variant
morekeywords=[3]{% red keywords
abs,acos,asin,atan,atan2,connect,cos,cosh,cross,der,edge,exp,%
noEvent,pre,reinit,sample,sign,sin,sinh,tan,tanh,terminal,%
start,Real,Integer,Boolean,String,homotopy,spatialDistribution,cardinality},%
comment=[l]{//}, % comment lines
morecomment=[s]{/*}{*/}, % comment blocs
morestring=[b]{'}, %
morestring=[b]{"},
}[keywords,comments,strings]
\lstdefinelanguage{grammar}{
alsoletter={...},
breaklines=true,
breakatwhitespace=true,
morekeywords=[2]{letters}
morekeywords=[1]{|}
}[keywords,comments,strings]
\lstset{ %
backgroundcolor=\color{white}, % choose the background color
basicstyle=\footnotesize, % size of fonts used for the code
breaklines=true, % automatic line breaking only at whitespace
captionpos=b, % sets the caption-position to bottom
commentstyle=\color{darkgreen}, % comment style
keywordstyle=\color{blue}, % keyword style
keywordstyle=[1]\color{keywordcolor1},
keywordstyle=[2]\color{keywordcolor1}\bfseries,
keywordstyle=[3]\color{keywordcolor2},
stringstyle=\color{black}, % string literal style
language=modelica, % Set your language (you can change the language for each code-block optionally)
showstringspaces=false,
frame=lrtb, %
xleftmargin=\fboxsep, %
xrightmargin=-\fboxsep, %
}
% ------------------------------------------------------------------------------------------------
% End preamble
% The title page is slightly different than before.
\begin{document}
\title{Modelica® - A Unified Object-Oriented Language for Systems Modeling\\[2\baselineskip]Language Specification\\[2\baselineskip]Version 3.4}
\date{\today}
\author{\includegraphics[width=0.7\textwidth,height=0.35\textwidth]{media/image1}\\Modelica Association}
\maketitle
\begin{abstract}
This document defines the Modelica\footnote{Modelica is a registered
trademark of the Modelica Association} language, version 3.4, which is
developed by the Modelica Association, a non-profit organization with
seat in Linköping, Sweden. Modelica is a freely available,
object-oriented language for modeling of large, complex, and
heterogeneous systems. It is suited for multi-domain modeling, for
example, mechatronic models in robotics, automotive and aerospace
applications involving mechanical, electrical, hydraulic control and
state machine subsystems, process oriented applications and generation
and distribution of electric power. Models in Modelica are
mathematically described by differential, algebraic and discrete
equations. No particular variable needs to be solved for manually. A
Modelica tool will have enough information to decide that automatically.
Modelica is designed such that available, specialized algorithms can be
utilized to enable efficient handling of large models having more than
one hundred thousand equations. Modelica is suited and used for
hardware-in-the-loop simulations and for embedded control systems. More
information is available at
\href{http://www.modelica.org/}{http://www.Modelica.org/}
\end{abstract}
Copyright © 1998-2015, Modelica Association (https://www.modelica.org)
All rights reserved. Reproduction or use of editorial or pictorial
content is permitted, i.e., this document can be freely distributed
especially electronically, provided the copyright notice and these
conditions are retained. No patent liability is assumed with respect to
the use of information contained herein. While every precaution has been
taken in the preparation of this document no responsibility for errors
or omissions is assumed.
The contributors to this and to previous versions of this document are
listed in Appendix E. All contributors worked voluntarily and without
compensation.
\tableofcontents
\chapter*{Preface}
Modelica is a freely available, object-oriented language for modeling of
large, complex, and heterogeneous physical systems. From a user's point
of view, models are described by schematics, also called object
diagrams. Examples are shown in the next figure:
\begin{center}
\includegraphics[width=0.9\textwidth]{media/image2}
\end{center}
A schematic consists of connected components, like a resistor, or a
hydraulic cylinder. A component has ``connectors'' (often also called
``ports'') that describe the interaction possibilities, e.g., an
electrical pin, a mechanical flange, or an input signal. By drawing
connection lines between connectors a physical system or block diagram
model is constructed. Internally a component is defined by another
schematic or on ``bottom'' level, by an equation based description of
the model in Modelica syntax.
The Modelica language is a textual description to define all parts of a
model and to structure model components in libraries, called packages.
An appropriate Modelica simulation environment is needed to graphically
edit and browse a Modelica model (by interpreting the information
defining a Modelica model) and to perform model simulations and other
analysis. Information about such environments is available at
\href{http://www.modelica.org/tools}{www.modelica.org/tools}. Basically,
all Modelica language elements are mapped to differential, algebraic and
discrete equations. There are no language elements to describe directly
partial differential equations, although some types of discretized
partial differential equations can be reasonably defined, e.g., based on
the finite volume method and there are Modelica libraries to import
results of finite-element programs.
This document defines the details of the Modelica language. It is not
intended to learn the Modelica language with this text. There are better
alternatives, such as the Modelica books referenced at
\href{http://www.modelica.org/publications}{www.modelica.org/publications}.
This specification is used by computer scientist to implement a Modelica
translator and by modelers who want to understand the exact details of a
particular language element.
The Modelica language has been developed since 1996. This document
describes version 3.4 of the Modelica language. A complete summary is
available in Appendix E.1.
2015, The Modelica Association
\chapter{Introduction}
\section{Overview of Modelica}
Modelica is a language for modeling of physical systems, designed to
support effective library development and model exchange. It is a modern
language built on acausal modeling with mathematical equations and
object-oriented constructs to facilitate reuse of modeling knowledge.
\section{Scope of the Specification}
The semantics of the Modelica language is specified by means of a set of
rules for translating any class described in the Modelica language to a
flat Modelica structure. A class must have additional properties in
order that its flat Modelica structure can be further transformed into a
set of differential, algebraic and discrete equations (= flat hybrid
DAE). Such classes are called simulation models.
The flat Modelica structure is also defined for other cases than
simulation models; including functions (can be used to provide
algorithmic contents), packages (used as a structuring mechanism), and
partial models (used as base-models). This allows correctness to be
verified before building the simulation model.
Modelica was designed to facilitate symbolic transformations of models,
especially by mapping basically every Modelica language construct to
continuous or instantaneous equations in the flat Modelica structure.
Many Modelica models, especially in the associated Modelica Standard
Library, are higher index systems, and can only be reasonably simulated
if symbolic index reduction is performed, i.e., equations are
differentiated and appropriate variables are selected as states, so that
the resulting system of equations can be transformed to state space form
(at least locally numerically), i.e., a hybrid DAE of index zero. The
Modelica specification does not define how to simulate a model. However,
it defines a set of equations that the simulation result should satisfy
as well as possible.
The key issues of the translation (or flattening) are:
\begin{itemize}
\item
Expansion of inherited base classes
\item
Parameterization of base classes, local classes and components
\item
Generation of connection equations from connect-equations
\end{itemize}
The flat hybrid DAE form consists of:
\begin{itemize}
\item
Declarations of variables with the appropriate basic types, prefixes
and attributes, such as "parameter Real v=5".
\item
Equations from equation sections.
\item
Function invocations where an invocation is treated as a set of
equations which involves all input and all result variables (number of
equations = number of basic result variables).
\item
Algorithm sections where every section is treated as a set of
equations which involves the variables occurring in the algorithm
section (number of equations = number of different assigned
variables).
\item
When-clauses where every when-clause is treated as a set of
conditionally evaluated equations, also called instantaneous
equations, which are functions of the variables occurring in the
clause (number of equations = number of different assigned variables).
\end{itemize}
Therefore, a flat hybrid DAE is seen as a set of equations where some of
the equations are only conditionally evaluated (e.g. instantaneous
equations are only evaluated when the corresponding when-condition
becomes true). Initial setup of the model is specified using
start-values and instantaneous equations that hold at the initial time
only.
A Modelica class may also contain annotations, i.e. formal comments,
which specify graphical representations of the class (icon and diagram),
documentation text for the class, and version information.
\section{Some Definitions}
The semantic specification should be read together with the Modelica
grammar. Non-normative text, i.e., examples and comments, are enclosed
in {[} {]}; comments are set in italics. Additional terms are explained
in the glossary in Appendix A. Some important terms are:
\begin{tabular}{|l|p{8.5cm}|}
\hline
\emph{Term} & \emph{Definition} \\
\hline
Component & An element defined by the production
component\_clause in the Modelica grammar (basically a
variable or an instance of a class)\\
\hline
Element & Class definitions, extends-clauses and
component-clauses declared in a class (basically a class
reference or a component in a declaration). \\
\hline
Flattening & The translation of a model described in Modelica to the
corresponding model described as a hybrid DAE, involving expansion of
inherited base classes, parameterization of base classes, local classes
and components, and generation of connection equations from
connect-equations (basically, mapping the hierarchical structure of a
model into a set of differential, algebraic and discrete equations
together with the corresponding variable declarations and function
definitions from the model).\\
\hline
\end{tabular}
\section{Notation and Grammar}
The following syntactic meta symbols are used (extended BNF):
{[} {]} optional
\{ \} repeat zero or more times
Boldface denotes keywords of the Modelica language. Keywords are
reserved words and may not be used as identifiers, with the exception of
initial which is a keyword in section headings, and der which is a
keyword for declaration functions, but it is also possible to call the
functions initial() and der(\ldots{}).
See Appendix B for a full lexical specification and grammar.
\chapter{Lexical Structure}
This chapter describes several of the basic building blocks of Modelica
such as characters and lexical units including identifiers and literals.
Without question, the smallest building blocks in Modelica are single
characters belonging to a character set. Characters are combined to form
lexical units, also called tokens. These tokens are detected by the
lexical analysis part of the Modelica translator. Examples of tokens are
literal constants, identifiers, and operators. Comments are not really
lexical units since they are eventually discarded. On the other hand,
comments are detected by the lexical analyzer before being thrown away.
The information presented here is derived from the more formal
specification in Appendix B.
\section{Character Set}
The character set of the Modelica language is Unicode, but restricted to
the Unicode characters corresponding to 7-bit ASCII characters in
several places; for details see Appendix B.1.
\section{Comments}
There are two kinds of comments in Modelica which are not lexical units
in the language and therefore are treated as whitespace by a Modelica
translator. The whitespace characters are space, tabulator, and line
separators (carriage return and line feed); and whitespace cannot occur
inside tokens, e.g., \textless{}= must be written as two characters
without space or comments between them. \Mcomment{The comment syntax is
identical to that of C++}. The following comment variants are
available:
\begin{lstlisting}[language=modelica]
// comment Characters from // to the end of the line are ignored.
/* comment */ Characters between /* and */ are ignored, including line terminators.
\end{lstlisting}
Modelica comments do not nest, i.e., /* */ cannot be embedded within /* */. The following is \emph{invalid}:
\begin{lstlisting}[language=modelica]
/* Commented out - erroneous comment, invalid nesting of comments!
/* This is a interesting model */
model interesting
...
end interesting;
*/
\end{lstlisting}
There is also a kind of ``documentation comment,'' really a
\emph{documentation string} that is part of the Modelica language and
therefore not ignored by the Modelica translator. Such ``comments'' may
occur at the ends of declarations, equations, or statements or at the
beginning of class definitions. For example:
\begin{lstlisting}[language=modelica]
model TempResistor "Temperature dependent resistor"
...
parameter Real R "Resistance for reference temp.";
...
end TempResistor;
\end{lstlisting}
\section{Identifiers, Names, and Keywords}
\emph{Identifiers} are sequences of letters, digits, and other
characters such as underscore, which are used for \emph{naming} various
items in the language. Certain combinations of letters are
\emph{keywords} represented as \emph{reserved} words in the Modelica
grammar and are therefore not available as identifiers.
\subsection{Identifiers}
Modelica \emph{identifiers}, used for naming classes, variables,
constants, and other items, are of two forms. The first form always
start with a letter or underscore (\_), followed by any number of
letters, digits, or underscores. Case is significant, i.e., the names
Inductor and inductor are different. The second form (Q-IDENT) starts
with a single quote, followed by a sequence of any printable ASCII
character, where single-quote must be preceded by backslash, and
terminated by a single quote, e.g. '12H', '13\textbackslash{}'H',
'+foo'. Control characters in quoted identifiers have to use string
escapes. The single quotes are part of the identifier, i.e., 'x' and x
are distinct identifiers, but the redundant escapes ('\textbackslash{}?'
and '\textbackslash{}"') are the same as the corresponding non-escaped
variants ('?' and '"'). The following BNF-like rules define Modelica
identifiers, where curly brackets \{\} indicate repetition zero or more
times, and vertical bar \textbar{} indicates alternatives. A full BNF
definition of the Modelica syntax and lexical units is available in
Appendix B.
%\begin{verbatim}
%IDENT = NONDIGIT { DIGIT | NONDIGIT } | Q-IDENT
%Q-IDENT = "’" { Q-CHAR | S-ESCAPE | """ } "’"
%NONDIGIT = "_" | letters "a" to "z" | letters "A" to "Z"
%DIGIT = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
%Q-CHAR = NONDIGIT | DIGIT | "!" | "#" | "$" | "%" | "&" | "(" | ")"
%| "*" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | ">" | "=" | "?"
%| "@" | "[" | "]" | "^" | "{" | "}" | "|" | "~" | " "_
%S-ESCAPE = "\’" | "\"" | "\?" | "\\" | "\a" | "\b" | "\f" | "\n" | "\r" | "\t" | "\v"
%\end{verbatim}
\begin{lstlisting}[language=grammar]
IDENT = NONDIGIT { DIGIT | NONDIGIT } | Q-IDENT
Q-IDENT = "'" { Q-CHAR | S-ESCAPE | """ } "'"
NONDIGIT = "_" | letters "a" ... "z" | letters "A" ... "Z"
DIGIT = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Q-CHAR = NONDIGIT | DIGIT | "!" | "#" | "$" | "%" | "&" | "(" | ")" | "*" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | ">" | "=" | "?" | "@" | "[" | "]" | "^" | "{" | "}" | "|" | "~" | " "_
S-ESCAPE = "\'" | "\"" | "\?" | "\\" | "\a" | "\b" | "\f" | "\n" | "\r" | "\t" | "\v"
\end{lstlisting}
\subsection{Names}
A \emph{name} is an identifier with a certain interpretation or meaning.
For example, a name may denote an Integer variable, a Real variable, a
function, a type, etc. A name may have different meanings in different
parts of the code, i.e., different scopes. The interpretation of
identifiers as names is described in more detail in Chapter 5. The
meaning of package names is described in more detail in Chapter 13.
\subsection{Modelica Keywords}
The following Modelica \emph{keywords} are reserved words and may not be
used as identifiers, except as listed in Appendix B.1:
\begin{longtable}[c]{@{}lllll@{}}
algorithm & discrete & false & loop & pure\tabularnewline
and & each & final & model & record\tabularnewline
annotation & else & flow & not & redeclare\tabularnewline
& elseif & for & operator & replaceable\tabularnewline
block & elsewhen & function & or & return\tabularnewline
break & encapsulated & if & outer & stream\tabularnewline
class & end & import & output & then\tabularnewline
connect & enumeration & impure & package & true\tabularnewline
connector & equation & in & parameter & type\tabularnewline
constant & expandable & initial & partial & when\tabularnewline
constrainedby & extends & inner & protected & while\tabularnewline
der & external & input & public & within\tabularnewline
\end{longtable}
\section{Literal Constants}
Literal constants are unnamed constants that have different forms
depending on their type. Each of the predefined types in Modelica has a
way of expressing unnamed constants of the corresponding type, which is
presented in the ensuing subsections. Additionally, array literals and
record literals can be expressed.
\subsection{Floating Point Numbers}
A floating point number is expressed as a decimal number in the form of
a sequence of decimal digits optionally followed by a decimal point,
optionally followed by an exponent. At least one digit must be present.
The exponent is indicated by an E or e, followed by an optional sign (+
or -) and one or more decimal digits. The minimal recommended range is
that of IEEE double precision floating point numbers, for which the
largest representable positive number is 1.7976931348623157E+308 and the
smallest positive number is 2.2250738585072014E-308. For example, the
following are floating point number literal constants:
22.5, 3.141592653589793, 1.2E-35
The same floating point number can be represented by different literals.
For example, all of the following literals denote the same number:
13., 13E0, 1.3e1, 0.13E2
\subsection{Integer Literals}
Literals of type Integer are sequences of decimal digits, e.g. as in the
integer numbers 33, 0, 100, 30030044. \Mcomment{Negative numbers are
formed by unary minus followed by an integer literal}. The minimal
recommended number range is from -2147483648 to +2147483647 for a
two's-complement 32-bit integer implementation.
\subsection{Boolean Literals}
The two Boolean literal values are true and false.
\subsection{Strings}
String literals appear between double quotes as in "between". Any
character in the Modelica language character set (see appendix B.1 for
allowed characters) apart from double quote (") and backslash
(\textbackslash{}), including new-line, can be \emph{directly} included
in a string without using an escape code. Certain characters in string
literals can be represented using escape codes, i.e., the character is
preceded by a backslash (\textbackslash{}) within the string. Those
characters are:
\begin{longtable}[c]{@{}ll@{}}
\textbackslash{}' & single quote may also appear without backslash in
string constants.\tabularnewline
\textbackslash{}" & double quote\tabularnewline
\textbackslash{}? & question-mark may also appear without backslash in
string constants.\tabularnewline
\textbackslash{}\textbackslash{} & backslash itself\tabularnewline
\textbackslash{}a & alert (bell, code 7, ctrl-G)\tabularnewline
\textbackslash{}b & backspace (code 8, ctrl-H)\tabularnewline
\textbackslash{}f & form feed (code 12, ctrl-L)\tabularnewline
\textbackslash{}n & new-line (code 10, ctrl-J)\tabularnewline
\textbackslash{}r & return (code 13, ctrl-M)\tabularnewline
\textbackslash{}t & horizontal tab (code 9, ctrl-I)\tabularnewline
\textbackslash{}v & vertical tab (code 11, ctrl-K)\tabularnewline
\end{longtable}
For example, a string literal containing a tab, the words: This is,
double quote, space, the word: between, double quote, space, the word:
us, and new-line, would appear as follows:
"\textbackslash{}tThis is\textbackslash{}" between\textbackslash{}"
us\textbackslash{}n"
Concatenation of string literals in certain situations (see the Modelica
grammar) is denoted by the + operator in Modelica, e.g. "a" + "b"
becomes "ab". This is useful for expressing long string literals that
need to be written on several lines.
\Mcomment{Note, if the contents of a file is read into a Modelica string,
it is assumed that the reading function is responsible to handle the
different line ending symbols on file (e.g. on Linux systems to have a
``newline'' character at the end of a line and on Windows systems to
have a ``newline'' and a ``carriage return'' character. As usual in
programming languages, the content of a file in a Modelica string only
contains the ``newline'' character. }
\Mcommentbegin{For long string comments, e.g., the ``info'' annotation to store
the documentation of a model, it would be very inconvenient, if the
string concatenation operator would have to be used for every line of
documentation. It is assumed that a Modelica tool supports the
non-printable ``newline'' character when browsing or editing a string
literal. For example, the following statement defines one string that
contains (non-printable) newline characters:}
\begin{lstlisting}[language=modelica]
assert(noEvent(length > s_small), "
The distance between the origin of frame_a and the origin
of frame_b of a LineForceWithMass component became smaller
than parameter s_small (= a small number, defined in the
\"Advanced\" menu). The distance is set to s_small, although
it is smaller, to avoid a division by zero when computing the
direction of the line force.",
level = AssertionLevel.warning);
\end{lstlisting}
\Mcommentend{}
\section{Operator Symbols}
The predefined operator symbols are formally defined on page 255 and
summarized in the table of operators in Section \ref{operator-precedence}.
\chapter{Operators and Expressions}\doublelabel{operators-and-expressions}
The lexical units are combined to form even larger building blocks such
as expressions according to the rules given by the expression part of
the Modelica grammar in Appendix B.
This chapter describes the evaluation rules for expressions, the concept
of expression variability, built-in mathematical operators and
functions, and the built-in special Modelica operators with function
syntax.
Expressions can contain variables and constants, which have types,
predefined or user defined. The predefined built-in types of Modelica
are Real, Integer, Boolean, String, and enumeration types which are
presented in more detail in Section \ref{predefined-types}. \Mcomment{The abbreviated
predefined type information below is given as background information for
the rest of the presentation.}
\section{Expressions}
Modelica equations, assignments and declaration equations contain
expressions.
Expressions can contain basic operations, +, -, *, /, \^{}, etc. with
normal precedence as defined in the Table in Section \ref{operator-precedence} and the
grammar in Appendix B. The semantics of the operations is defined for
both scalar and array arguments in Section 10.6.
It is also possible to define functions and call them in a normal
fashion. The function call syntax for both positional and named
arguments is described in Section 12.4.1 and for vectorized calls in
Section 12.4.4. The built-in array functions are given in Section
10.1.1 and other built-in operators in Section \myref{built-in-intrinsic-operators-with-function-syntax}.
\section{Operator Precedence and Associativity}\doublelabel{operator-precedence}
Operator precedence determines the order of evaluation of operators in
an expression. An operator with higher precedence is evaluated before an
operator with lower precedence in the same expression.
The following table presents all the expression operators in order of
precedence from highest to lowest, as derived from the Modelica grammar
in Appendix B. All operators are binary except the postfix operators
and those shown as unary together with \emph{expr}, the conditional
operator, the array construction operator \{\} and concatenation
operator {[} {]}, and the array range constructor which is either binary
or ternary. Operators with the same precedence occur at the same line of
the table:
\begin{table}
\caption{Operators}
\begin{tabular}{|p{3cm}|p{4cm}|p{3.5cm}|}
\hline
\emph{Operator Group} & \emph{Operator Syntax} & \emph{Examples} \\ \hline
postfix array index operator & {[}{]} & arr{[}index{]} \\ \hline
postfix access operator & . & a.b \\ \hline
postfix function call & \emph{funcName}(\emph{function-arguments}) & sin(4.36)\\ \hline
array construct/concat & \{\emph{expressions}\}\linebreak {[}\emph{expressions}{]} \linebreak{[}\emph{expressions};\linebreak \emph{expressions}...{]} &
\{2,3\} \linebreak{[}5,6{]}\linebreak{[}2,3; 7,8{]}\\ \hline
exponentiation & \^{} & 2\^{}3\\ \hline
multiplicative and array elementwise multiplicative & * / .* ./ & 2*3 2/3 {[}1,2;3,4{]}.*{[}2,3;5,6{]} \\ \hline
additive and array elementwise additive & + - +\emph{expr} -\emph{expr} .+ .- & {[}1,2;3,4{]}.+{[}2,3;5,6{]}\\ \hline
relational & \textless{} \textless{}= \textgreater{} \textgreater{}= == \textless{}\textgreater{} &
a\textless{}b, a\textless{}=b, a\textgreater{}b, ...\\ \hline
unary negation & not \emph{expr} & not b1\\ \hline
logical and & and & b1 and b2\\ \hline
logical or & or & b1 or b2\\ \hline
array range & \emph{expr} : \emph{expr}
\emph{expr} : \emph{expr} : \emph{expr} & 1:5
start:step:stop\\ \hline
conditional & if \emph{expr} then \emph{expr} else \emph{expr} & if b
then 3 else x\\ \hline
named argument & \emph{ident} = \emph{expr} & x = 2.26\\ \hline
\end{tabular}
\end{table}
The conditional operator may also include elseif-clauses. Equality = and
assignment := are not expression operators since they are allowed only
in equations and in assignment statements respectively. All binary
expression operators are left associative, except exponentiation which
is non-associative. The array range operator is non-associative.
\Mcommentbegin{The unary minus and plus in Modelica is slightly different than
in Mathematica and in MATLAB}\footnote{MATLAB is a registered trademark
of MathWorks Inc.}\Mcommentmid{, since the following expressions are illegal
(whereas in Mathematica}\footnote{Mathematica is a registered trademark
of Wolfram Research Inc.} \Mcommentmid{and in MATLAB these are valid
expressions):}
\begin{lstlisting}[language=modelica]
2*-2 // = -4 in Mathematica/MATLAB; is illegal in Modelica
--2 // = 2 in Mathematica/MATLAB; is illegal in Modelica
++2 // = 2 in Mathematica/MATLAB; is illegal in Modelica
2--2 // = 4 in Mathematica/MATLAB; is illegal in Modelica
\end{lstlisting}
\emph{Non-associative exponentation and array range operator:}
\begin{lstlisting}[language=modelica]
x^y^z // Not legal, use parenthesis to make it clear
a:b:c:d:e:f:g // Not legal, and scalar arguments gives no legal
interpretation.
\end{lstlisting}
\Mcommentend{}
\section{Evaluation Order}
\doublelabel{evaluation-order}
A tool is free to solve equations, reorder expressions and to not
evaluate expressions if their values do not influence the result (e.g.
short-circuit evaluation of Boolean expressions). If-statements and
if-expressions guarantee that their clauses are only evaluated if the
appropriate condition is true, but relational operators generating state
or time events will during continuous integration have the value from
the most recent event.
If a numeric operation overflows the result is undefined. For literals
it is recommended to automatically convert the number to another type
with greater precision.
\subsection{Example: Guarding Expressions Against Incorrect Evaluation}
{[}\emph{Example. If one wants to guard an expression against incorrect
evaluation, it should be guarded by an if:}
\begin{lstlisting}[language=modelica]
Boolean v[n];
Boolean b;
Integer I;
equation
x=v[I] and (I>=1 and I<=n); // Invalid
x=if (I>=1 and I<=n) then v[I] else false; // Correct
\end{lstlisting}
\emph{To guard square against square root of negative number use}
noEvent\emph{:}
\begin{lstlisting}[language=modelica]
der(h)=if h>0 then -c*sqrt(h) else 0; // Incorrect
der(h)=if noEvent(h>0) then -c*sqrt(h) else 0; // Correct
\end{lstlisting}
{]}
\section{Arithmetic Operators}
Modelica supports five binary arithmetic operators that operate on any
numerical type:
\begin{longtable}[c]{@{}ll@{}}
\^{} & Exponentiation\tabularnewline
* & Multiplication\tabularnewline
/ & Division\tabularnewline
+ & Addition\tabularnewline
- & Subtraction\tabularnewline
\end{longtable}
Some of these operators can also be applied to a combination of a scalar
type and an array type, see Section 10.6.
The syntax of these operators is defined by the following rules from the
Modelica grammar:
\begin{lstlisting}[language=grammar]
arithmetic_expression :
[ add_op ] term { add_op term }
add_op :
"+" | "-"
term :
factor { mul_op factor }
mul_op :
"*" | "/"
factor :
primary [ "^" primary ]
\end{lstlisting}
\section{Equality, Relational, and Logical Operators}\doublelabel{equality-relational-and-logical-operators}
Modelica supports the standard set of relational and logical operators,
all of which produce the standard boolean values true or false.
\begin{longtable}[c]{@{}ll@{}}
\textgreater{} & greater than\tabularnewline
\textgreater{}= & greater than or equal\tabularnewline
\textless{} & less than\tabularnewline
\textless{}= & less than or equal to\tabularnewline
== & equality within expressions\tabularnewline
\textless{}\textgreater{} & Inequality\tabularnewline
\end{longtable}
A single equals sign = is never used in relational expressions, only in
equations (Chapter 8, Section 10.6.1) and in function calls using
named parameter passing (Section 12.4.1).
The following logical operators are defined:
\begin{longtable}[c]{@{}ll@{}}
\textbf{not} & negation, unary operator\tabularnewline
\textbf{and} & logical and\tabularnewline
\textbf{or} & logical or\tabularnewline
\end{longtable}
The grammar rules define the syntax of the relational and logical
operators.
\begin{lstlisting}[language=grammar]
logical_expression :
logical_term { or logical_term }
logical_term :
logical_factor { and logical_factor }
logical_factor :
[ not ] relation
relation :
arithmetic_expression [ rel_op arithmetic_expression ]
rel_op :
"<" | "<=" | ">" | ">=" | "==" | "<>"
\end{lstlisting}
The following holds for relational operators:
\begin{itemize}
\item
Relational operators \textless{}, \textless{}=, \textgreater{},
\textgreater{}=, ==, \textless{}\textgreater{}, are only defined for
scalar operands of simple types. The result is Boolean and is true or
false if the relation is fulfilled or not, respectively.
\item
For operands of type String, str1 op str2 is for each relational
operator, op, defined in terms of the C-function strcmp as
strcmp(str1,str2) op 0.
\item
For operands of type Boolean, false\textless{}true.
\item
For operands of enumeration types, the order is given by the order of
declaration of the enumeration literals.
\item
In relations of the form v1 == v2 or v1 \textless{}\textgreater{} v2,
v1 or v2 shall, unless used in a function, not be a subtype of Real.
{[}\emph{The reason for this rule is that relations with Real
arguments are transformed to state events (see Events, Section}
8.5\emph{) and this transformation becomes unnecessarily complicated
for the == and \textless{}\textgreater{} relational operators (e.g.
two crossing functions instead of one crossing function needed,
epsilon strategy needed even at event instants). Furthermore, testing
on equality of Real variables is questionable on machines where the
number length in registers is different to number length in main
memory}{]}.
\item
Relations of the form ``v1 rel\_op v2'', with v1 and v2 variables and
rel\_op a relational operator are called elementary relations. If
either v1 or v2 or both variables are a subtype of Real, the relation
is called a Real elementary relation.
\end{itemize}
\section{Miscellaneous Operators and Variables}
Modelica also contains a few built-in operators which are not standard
arithmetic, relational, or logical operators. These are described below,
including time, which is a built-in variable, not an operator.
\subsection{String Concatenation}
Concatenation of strings (see the Modelica grammar) is denoted by the +
operator in Modelica {[}\emph{e.g.} "a" + "b" \emph{becomes} "ab"{]}.
\subsection{Array Constructor Operator}
The array constructor operator \{ ... \} is described in Section 10.4.
\subsection{Array Concatenation Operator}
The array concatenation operator {[} ... {]} is described in Section
10.4.2.
\subsection{Array Range Operator}
The array range constructor operator : is described in Section 10.4.3.
\subsection{If-Expressions}
An expression
\begin{lstlisting}[language=modelica]
if expression1 then expression2 else expression3
\end{lstlisting}
is one example of if-expression. First expression1, which must be
boolean expression, is evaluated. If expression1 is true expression2 is
evaluated and is the value of the if-expression, else expression3 is
evaluated and is the value of the if-expression. The two expressions,
expression2 and expression3, must be type compatible expressions
(Section 6.6) giving the type of the if-expression. If-expressions with
elseif are defined by replacing elseif by else if. {[}\emph{Note:}
elseif \emph{has been added for symmetry with if-clauses.}{]} For
short-circuit evaluation see Section \ref{evaluation-order}.
{[}\emph{Example}:
\begin{lstlisting}[language=modelica]
Integer i;
Integer sign_of_i1=if i<0 then -1 elseif i==0 then 0 else 1;
Integer sign_of_i2=if i<0 then -1 else if i==0 then 0 else 1;
\end{lstlisting}
\subsection{Member Access Operator}
It is possible to access members of a class instance using dot notation,
i.e., the . operator.
{[}\emph{Example:} R1.R \emph{for accessing the resistance component} R
\emph{of resistor} R1\emph{. Another use of dot notation: local classes
which are members of a class can of course also be accessed using dot
notation on the name of the class, not on instances of the class.}{]}
\subsection{Built-in Variable time}
All declared variables are functions of the independent variable time.
The variable time is a built-in variable available in all models and
blocks, which is treated as an input variable. It is implicitly defined
as:
\begin{lstlisting}[language=modelica]
input Real time (final quantity = "Time",
final unit = "s");
\end{lstlisting}
The value of the start attribute of time is set to the time instant at
which the simulation is started.
{[}\emph{Example}:
\begin{lstlisting}[language=modelica]
encapsulated model SineSource
import Modelica.Math.sin;
connector OutPort=output Real;
OutPort y=sin(time); // Uses the built-in variable time.
end SineSource;
\end{lstlisting}
{]}
\section{Built-in Intrinsic Operators with Function Syntax}\doublelabel{built-in-intrinsic-operators-with-function-syntax}
Certain built-in operators of Modelica have the same syntax as a
function call. However, they do not behave as a mathematical function,
because the result depends not only on the input arguments but also on
the status of the simulation.
There are also built-in functions that depend only on the input
argument, but also may trigger events in addition to returning a value.
Intrinsic means that they are defined at the Modelica language level,
not in the Modelica library. The following built-in intrinsic
operators/functions are available:
\begin{itemize}
\item
Mathematical functions and conversion functions, see Section \ref{numeric-functions-and-conversion-functions}.
below.
\end{itemize}
\begin{itemize}
\item
Derivative and special purpose operators with function syntax, see
Section \ref{derivative-and-special-purpose-operators-with-function-syntax} below.
\item
Event-related operators with function syntax, see Section \ref{event-related}
below.
\item
Array operators/functions, see Section 10.1.1.
\end{itemize}
With exception of built-in operator String(..), all operators in this
section can only be called with positional arguments.
\subsection{Numeric Functions and Conversion Functions}\doublelabel{numeric-functions-and-conversion-functions}
The following mathematical operators and functions, also including some
conversion functions, are predefined in Modelica, and are vectorizable
according to Section 12.4.6, except for the String function. The
functions which do not trigger events are described in the table below,
whereas the event-triggering mathematical functions are described in
Section \ref{event-triggering-mathematical-functions}.
\begin{longtable}{|p{3.5cm}|p{8cm}|}
\hline
abs(v) & Is expanded into ``noEvent(\textbf{if} v \textgreater{}= 0
\textbf{then} v \textbf{else} --v)''. Argument v needs to be an Integer
or Real expression.\\ \hline
sign(v) & Is expanded into ``noEvent(\textbf{if} v\textgreater{}0
\textbf{then} 1 \textbf{else if} v\textless{}0 \textbf{then} --1
\textbf{else} 0)''. Argument v needs to be an Integer or Real
expression.\\ \hline
sqrt(v) & Returns the square root of v if v\textgreater{}=0, otherwise
an error occurs. Argument v needs to be an Integer or Real
expression.\\ \hline
Integer(e) & Returns the ordinal number of the expression e of
enumeration type that evaluates to the enumeration value E.enumvalue,
where Integer(E.e1)=1, Integer(E.en)= n, for an enumeration type
E=enumeration(e1, ..., en). See also Section \ref{attributes-of-enumeration-types}.\\ \hline
String(b,\textless{}options\textgreater{})\linebreak
String(i,\textless{}options\textgreater{})\linebreak
String(r,\linebreak \hspace*{2mm} significantDigits=d,\linebreak \hspace*{2mm} options)\linebreak
String(r, format=s)\linebreak
String(e, \textless{}options\textgreater{})\linebreak &
Convert a scalar non-String expression to a String representation. The
first argument may be a Boolean b, an Integer i, a Real r or an
Enumeration e (Section \ref{attributes-of-enumeration-types}). The other arguments must use named arguments. The optional
\textless{}options\textgreater{} are:
Integer minimumLength=0: minimum length of the resulting string. If
necessary, the blank character is used to fill up unused space.
Boolean leftJustified = true: if true, the converted result is left
justified in the string; if false it is right justified in the string.
For Real expressions the output shall be according to the Modelica
grammar. Integer significantDigits=6: defines the number of significant
digits in the result string. {[}\emph{Examples: "}12.3456\emph{",
"}0.0123456\emph{", "}12345600\emph{", "}1.23456E-10\emph{"}{]}\emph{.}
The format string corresponding to options is:
for Reals:~(if leftJustified then "-" else
"")+String(minimumLength)+"."+ String(signficantDigits)+"g",
for Integers:~(if leftJustified then "-" else