-
Notifications
You must be signed in to change notification settings - Fork 41
/
operatorsandexpressions.tex
1437 lines (1252 loc) · 62.1 KB
/
operatorsandexpressions.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
\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 \autoref{modelica-concrete-syntax}.
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 \lstinline!Real!, \lstinline!Integer!, \lstinline!Boolean!, \lstinline!String!, and enumeration types which are
presented in more detail in \autoref{predefined-types-and-classes}.
\begin{nonnormative}
The abbreviated predefined type information below is given as background information for the rest of the presentation.
\end{nonnormative}
\section{Expressions}\doublelabel{expressions}
Modelica equations, assignments and declaration equations contain
expressions.
Expressions can contain basic operations, \lstinline!+!, \lstinline!-!, \lstinline!*!, \lstinline!/!, \lstinline!^!, etc.\ with
normal precedence as defined in the Table in \autoref{operator-precedence-and-associativity} and the grammar
in \autoref{modelica-concrete-syntax}. The semantics of the operations is defined for both
scalar and array arguments in \autoref{scalar-vector-matrix-and-array-operator-functions}.
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 \autoref{positional-or-named-input-arguments-of-functions} and for vectorized calls in
\autoref{initialization-and-binding-equations-of-components-in-functions}. The built-in array functions are given in \autoref{array-dimension-lower-and-upper-index-bounds}
and other built-in operators in \autoref{built-in-intrinsic-operators-with-function-syntax}.
\section{Operator Precedence and Associativity}\doublelabel{operator-precedence-and-associativity}
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 \autoref{modelica-concrete-syntax}. All operators are binary except the postfix operators and
those shown as unary together with \emph{expr}, the conditional
operator, the array construction operator \lstinline!{ }! and concatenation
operator \lstinline![ ]!, 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}[H]
\caption{Operators}
\begin{tabular}{|p{5cm}|p{5cm}|p{4cm}|}
\hline
\tablehead{Operator Group} & \tablehead{Operator Syntax} & \tablehead{Examples}\\ \hline
postfix array index operator & \lstinline![]! & \lstinline!arr[index]! \\ \hline
postfix access operator & \lstinline!.! & \lstinline!a.b! \\ \hline
postfix function call & \lstinline!$\mathit{funcName}$($\mathit{functionArguments}$)! & \lstinline!sin(4.36)! \\ \hline
array construct/concat & \begin{tabular}{@{}p{5cm}@{}}
\lstinline!{$\mathit{expressions}$}!\\
\lstinline![$\mathit{expressions}$]!\\
\lstinline![$\mathit{expressions}$; $\mathit{expressions}\ldots$]!
\end{tabular} & \begin{tabular}{@{}p{5cm}@{}}
\lstinline!{2,3}! \\
\lstinline![5,6]! \\
\lstinline![2,3; 7,8]!
\end{tabular} \\ \hline
exponentiation & \ \lstinline!^! & \lstinline!2^3! \\ \hline
multiplicative and array elementwise multiplicative & \lstinline!* / .* ./! & \begin{tabular}{@{}p{5cm}@{}}
\lstinline!2*3!, \lstinline!2/3! \\
\lstinline![1,2;3,4].*[2,3;5,6]!
\end{tabular} \\ \hline
additive and array elementwise additive & \lstinline!+ - +$\mathit{expr}$ -$\mathit{expr}$ .+ .-! & \lstinline![1,2;3,4].+[2,3;5,6]!\\ \hline
relational & \lstinline!< <= > >= == <>! &
\lstinline!a<b!, \lstinline!a<=b!, \lstinline!a>b!, \ldots\\ \hline
unary negation & \lstinline!not $\mathit{expr}$! & \lstinline!not b1! \\ \hline
logical and & \lstinline!and! & \lstinline!b1 and b2! \\ \hline
logical or & \lstinline!or! & \lstinline!b1 or b2!\\ \hline
array range & \begin{tabular}{@{}p{5cm}@{}}
\lstinline!$\mathit{expr}$ : $\mathit{expr}$! \\
\lstinline!$\mathit{expr}$ : $\mathit{expr}$ : $\mathit{expr}$!
\end{tabular} & \begin{tabular}{@{}p{5cm}@{}}
\lstinline!1:5! \\
\lstinline!start:step:stop!
\end{tabular} \\ \hline
conditional & \lstinline!if $\mathit{expr}$ then $\mathit{expr}$ else $\mathit{expr}$! & \lstinline!if b then 3 else x!\\ \hline
named argument & \lstinline!$\mathit{ident}$ = $\mathit{expr}$! & \lstinline!x = 2.26!\\ \hline
\end{tabular}
\end{table}
The conditional operator may also include elseif-clauses. Equality \lstinline!=! and
assignment \lstinline!:=! 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.
\begin{nonnormative}
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.}, since the following expressions are illegal
(whereas in Mathematica\footnote{Mathematica is a registered trademark
of Wolfram Research Inc.} 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}
Non-associative exponentiation 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}
\end{nonnormative}
\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}\doublelabel{example-guarding-expressions-against-incorrect-evaluation}
\begin{example}
If one wants to guard an expression against incorrect evaluation, it should be guarded by an \lstinline!if!:
\begin{lstlisting}[language=modelica]
Boolean v[n];
Boolean b;
Integer I;
equation
b=(I>=1 and I<=n) and v[I]; // Invalid
b=if (I>=1 and I<=n) then v[I] else false; // Correct
\end{lstlisting}
To guard square against square root of negative number use \lstinline!noEvent!:
\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}
\end{example}
\section{Arithmetic Operators}\doublelabel{arithmetic-operators}
Modelica supports five binary arithmetic operators that operate on any
numerical type:
\begin{longtable}[c]{ll}
\lstinline!^! & Exponentiation\\
\lstinline!*! & Multiplication\\
\lstinline!/! & Division\\
\lstinline!+! & Addition\\
\lstinline!-! & Subtraction\\
\end{longtable}
Some of these operators can also be applied to a combination of a scalar
type and an array type, see \autoref{scalar-vector-matrix-and-array-operator-functions}.
The syntax of these operators is defined by the following rules from the
Modelica grammar:
\begin{lstlisting}[language=grammar]
arithmetic-expression :
[ add-operator ] term { add-operator term }
add-operator :
"+" | "-"
term :
factor { mul-operator factor }
mul-operator :
"*" | "/"
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 \lstinline!true! or \lstinline!false!.
\begin{longtable}[]{ll}
\lstinline!>! & greater than\\
\lstinline!>=! & greater than or equal\\
\lstinline!<! & less than\\
\lstinline!<=! & less than or equal to\\
\lstinline!==! & equality within expressions\\
\lstinline!<>! & Inequality\\
\end{longtable}
A single equals sign \lstinline!=! is never used in relational expressions, only in
equations (\autoref{equations}, \autoref{equality-and-assignment}) and in function calls using named
parameter passing (\autoref{positional-or-named-input-arguments-of-functions}).
The following logical operators are defined:
\begin{longtable}[]{ll}
\lstinline!not! & negation, unary operator\\
\lstinline!and! & logical and\\
\lstinline!or! & logical or\\
\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 [ relational-operator arithmetic-expression ]
relational-operator :
"<" | "<=" | ">" | ">=" | "==" | "<>"
\end{lstlisting}
The following holds for relational operators:
\begin{itemize}
\item
Relational operators \lstinline!<!, \lstinline!<=!,\lstinline!>!,
\lstinline!>=!, \lstinline!==!, \lstinline!<>!, are only defined for
scalar operands of simple types. The result is \lstinline!Boolean! and is true or
false if the relation is fulfilled or not, respectively.
\item
For operands of type \lstinline!String!, \lstinline!str1 op str2! is for each relational
operator, \lstinline!op!, defined in terms of the C-function \lstinline!strcmp! as
\lstinline!strcmp(str1,str2) op 0!.
\item
For operands of type \lstinline!Boolean!, \lstinline!false < 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 \lstinline!v1 == v2 or v1 <> v2!,
\lstinline!v1! or \lstinline!v2! shall, unless used in a function, not be a subtype of \lstinline!Real!.
\begin{nonnormative}
The reason for this rule is that relations with \lstinline!Real! arguments are transformed to state events (see Events, \autoref{events-and-synchronization})
and this transformation becomes unnecessarily complicated for the \lstinline!==! and \lstinline!<>! 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.
\end{nonnormative}
\item
Relational operators can generate events, see \autoref{discrete-time-expressions}.
\end{itemize}
\section{Miscellaneous Operators and Variables}\doublelabel{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 \lstinline!time!, which is a built-in variable, not an operator.
\subsection{String Concatenation}\doublelabel{string-concatenation}
Concatenation of strings (see the Modelica grammar) is denoted by the \lstinline!+!
operator in Modelica.
\begin{example}
\lstinline!"a" + "b"! becomes \lstinline!"ab"!.
\end{example}
\subsection{Array Constructor Operator}\doublelabel{array-constructor-operator}
The array constructor operator \lstinline!{ $\ldots$ }! is described in \autoref{vector-matrix-and-array-constructors}.
\subsection{Array Concatenation Operator}\doublelabel{array-concatenation-operator}
The array concatenation operator \lstinline![ $\ldots$ ]! is described in \autoref{array-concatenation}.
\subsection{Array Range Operator}\doublelabel{array-range-operator}
The array range constructor operator \lstinline!:! is described in \autoref{vector-construction}.
\subsection{If-Expressions}\doublelabel{if-expressions}
An expression
\begin{lstlisting}[language=modelica]
if expression1 then expression2 else expression3
\end{lstlisting}
is one example of if-expression. First \lstinline!expression1!, which must be
\lstinline!Boolean! expression, is evaluated. If \lstinline!expression1! is true \lstinline!expression2! is
evaluated and is the value of the if-expression, else \lstinline!expression3! is
evaluated and is the value of the if-expression. The two expressions,
\lstinline!expression2! and \lstinline!expression3!, must be type compatible expressions
(\autoref{type-compatible-expressions}) giving the type of the if-expression. If-expressions with
\lstinline!elseif! are defined by replacing \lstinline!elseif! by \lstinline!else if!. For
short-circuit evaluation see \autoref{evaluation-order}.
\begin{nonnormative}
\lstinline!elseif! in expressions has been added to the Modelica language for symmetry with if-clauses.
\end{nonnormative}
\begin{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}
\end{example}
\subsection{Member Access Operator}\doublelabel{member-access-operator}
It is possible to access members of a class instance using dot notation,
i.e., the \lstinline!.! operator.
\begin{example}
\lstinline!R1.R! for accessing the resistance component \lstinline!R!
of resistor \lstinline!R1!. 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.
\end{example}
\subsection{Built-in Variable time}\doublelabel{built-in-variable-time}
All declared variables are functions of the independent variable \lstinline!time!.
The variable \lstinline!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.
\begin{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}
\end{example}
\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 \autoref{numeric-functions-and-conversion-functions}
below.
\item
Derivative and special purpose operators with function syntax, see
\autoref{derivative-and-special-purpose-operators-with-function-syntax} below.
\item
Event-related operators with function syntax, see \autoref{event-related-operators-with-function-syntax} below.
\item
Array operators/functions, see \autoref{array-dimension-lower-and-upper-index-bounds}.
\end{itemize}
Note that when the specification references a function having the name
of a built-in function it references the built-in function, not a
user-defined function having the same name, see also \autoref{built-in-functions}. With
exception of the built-in \lstinline!String! operator, 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 \autoref{scalar-functions-applied-to-array-arguments}, except for the \lstinline!String! function. The
functions which do not trigger events are described in the table below,
whereas the event-triggering mathematical functions are described in
\autoref{event-triggering-mathematical-functions}.
\begin{longtable}{|p{4.5cm}|p{10cm}|} \hline
\endhead
\lstinline!abs(v)! & Is expanded into \lstinline!noEvent(if v >= 0 then v else -v)!. Argument v needs to be an Integer or Real expression.\\ \hline
\lstinline!sign(v)! & Is expanded into \lstinline!noEvent(if v>0 then 1 else if v<0 then -1 else 0)!. Argument v needs to be an Integer or Real
expression.\\ \hline
\lstinline!sqrt(v)! & Returns the square root of \lstinline!v if v>=0!, otherwise
an error occurs. Argument v needs to be an Integer or Real
expression.\\ \hline
\lstinline!Integer(e)! & Returns the ordinal number of the expression \lstinline!e! of
enumeration type that evaluates to the enumeration value \lstinline!E.enumvalue!,
where \lstinline!Integer(E.e1)=1!, \lstinline!Integer(E.en)=n!, for an enumeration type
\lstinline!E=enumeration(e1, ..., en)!. See also \autoref{type-conversion-of-enumeration-values-to-string-or-integer}.\\ \hline
\lstinline!EnumTypeName(i)! &
For any enumeration type \lstinline!EnumTypeName!, returns the enumeration
value \lstinline!EnumTypeName!.e such that \lstinline!Integer(EnumTypeName.e) = i!. Refer to the definition of
\lstinline!Integer! above.
It is an error to attempt to convert values of i that do not correspond
to values of the enumeration type. See also \autoref{type-conversion-of-integer-to-enumeration-values}.
\\ \hline
\begin{tabular}{@{}p{4.5cm}@{}}
\lstinline!String(b, <options>)!\\
\lstinline!String(i, <options>)!\\
\lstinline!String(r,!
\hspace*{1ex}\lstinline!significantDigits=d,!
\hspace*{1ex}\lstinline!<options>)!\\
\lstinline!String(r, format=s)!\\
\lstinline!String(e, <options>)!
\end{tabular}
&
Convert a scalar non-\lstinline!String! expression to a \lstinline!String! representation. The
first argument may be a \lstinline!Boolean b!, an \lstinline!Integer i!, a \lstinline!Real r! or an
\lstinline!Enumeration e! (\autoref{type-conversion-of-enumeration-values-to-string-or-integer}). The other arguments must use named
arguments. The optional \textless{}options\textgreater{} are:
\lstinline!Integer minimumLength=0!: minimum length of the resulting string. If
necessary, the blank character is used to fill up unused space.
\lstinline!Boolean leftJustified = true!: if true, the converted result is left
justified in the string; if false it is right justified in the string.
For \lstinline!Real! expressions the output shall be according to the Modelica
grammar. \lstinline!Integer significantDigits!=6: defines the number of significant
digits in the result string.
\begin{nonnormative}
Examples of \lstinline!Real! values formatted with 6 significant digits: \emph{12.3456}, \emph{0.0123456}, \emph{12345600}, \emph{1.23456E-10}.
\end{nonnormative}
The format string corresponding to options is:
\begin{itemize}
\item
for Reals: %\newline
\lstinline!(if leftJustified then "-" else "") + String(minimumLength)+"."+ String(signficantDigits)+"g"!,
\item
for Integers: %\newline
\lstinline!(if leftJustified then "-" else "")+ String(minimumLength)+"d"!.
\end{itemize}
Format string: According to ANSI-C the format string specifies one
conversion specifier (excluding the leading \%), may not contain length
modifiers, and may not use `\lstinline!*!' for width and/or precision. For all
numeric values the format specifiers `\lstinline!f!', `\lstinline!e!', `\lstinline!E!', `\lstinline!g!', `\lstinline!G!' are allowed. For
integral values it is also allowed to use the `\lstinline!d!', `\lstinline!i!', `\lstinline!o!', `\lstinline!x!', `\lstinline!X!', `\lstinline!u!', and
`\lstinline!c!' format specifiers (for non-integral values a tool may~round, truncate
or use a different format if the integer conversion characters are
used).
The x,X-formats (hexa-decimal)~and c (character) for Integers does not
lead to input~that agrees with the Modelica-grammar.\\ \hline
\end{longtable}
\subsubsection{Event Triggering Mathematical Functions}\doublelabel{event-triggering-mathematical-functions}
The built-in operators in this section trigger events if used outside of
a when-clause and outside of a clocked discrete-time partition (see
\autoref{clocked-discrete-time-and-clocked-discretized-continuous-time-partition}).
These expression for \lstinline!div!, \lstinline!ceil!, \lstinline!floor!, and \lstinline!integer! are
event generating expression. The event generating expression for
\lstinline!mod(x,y)! is \lstinline!floor(x/y)!, and for \lstinline!rem(x,y)! it is \lstinline!div(x,y)! --- i.e.\ events
are not generated when \lstinline!mod! or \lstinline!rem! changes continuously in an interval,
but when they change discontinuously from one interval to the next.
\begin{nonnormative}
If this is not desired, the \lstinline!noEvent! function can be applied to them. E.g.\ \lstinline!noEvent(integer(v))!.
\end{nonnormative}
\begin{longtable}{|p{2cm}|p{12cm}|} \hline
\endhead
\lstinline!div(x,y)! & Returns the algebraic quotient \lstinline!x/y! with any fractional part
discarded (also known as truncation toward zero).
\begin{nonnormative}
This is defined for \lstinline!/! in C99; in C89 the result for negative numbers is implementation-defined, so the standard function \lstinline[language=C]!div! must be used.
\end{nonnormative}
Result and arguments shall have type \lstinline!Real! or \lstinline!Integer!. If
either of the arguments is \lstinline!Real! the result is \lstinline!Real! otherwise
\lstinline!Integer!.\\ \hline
\lstinline!mod(x,y)! & Returns the integer modulus of \lstinline!x/y!, i.e.
\lstinline!mod(x,y)=x-floor(x/y)*y!. Result and arguments shall have type \lstinline!Real! or
\lstinline!Integer!. If either of the arguments is \lstinline!Real! the result is \lstinline!Real! otherwise
\lstinline!Integer!.
\par
\begin{nonnormative*}
Note, outside of a when-clause state events are triggered when the return value changes discontinuously. Examples:
\lstinline!mod(3,1.4)=0.2!, \lstinline!mod(-3,1.4)=1.2!, \lstinline!mod(3,-1.4)=-1.2!.
\end{nonnormative*}
\\ \hline
\lstinline!rem(x,y)! & Returns the integer remainder of \lstinline!x/y!, such that \lstinline!div(x,y)*y + rem(x, y) = x!. Result and arguments shall have type \lstinline!Real! or \lstinline!Integer!. If
either of the arguments is \lstinline!Real! the result is \lstinline!Real! otherwise \lstinline!Integer!.
\par
\begin{nonnormative*}
Note, outside of a when-clause state events are triggered when the return value changes discontinuously. Examples:
\lstinline!rem(3,1.4)=0.2!, \lstinline!rem(-3,1.4)=-0.2!
\end{nonnormative*}
\\ \hline
\lstinline!ceil(x)! & Returns the smallest integer not less than \lstinline!x!. Result and
argument shall have type \lstinline!Real!.
\par
\begin{nonnormative*}
Note, outside of a when-clause state events are triggered when the return value changes discontinuously.
\end{nonnormative*}
\\ \hline
\lstinline!floor(x)! & Returns the largest integer not greater than \lstinline!x!. Result and
argument shall have type \lstinline!Real!.
\par
\begin{nonnormative*}
Note, outside of a when-clause state events are triggered when the return value changes discontinuously.
\end{nonnormative*}
\\ \hline
\lstinline!integer(x)! & Returns the largest integer not greater
than \lstinline!x!. The argument shall have type \lstinline!Real!. The result has type
\lstinline!Integer!.
\par
\begin{nonnormative*}
Note, outside of a when-clause state events are triggered when the return value changes discontinuously.
\end{nonnormative*}
\\ \hline
\end{longtable}
\subsubsection{Built-in Mathematical Functions and External Built-in Functions}\doublelabel{built-in-mathematical-functions-and-external-built-in-functions}
The following built-in mathematical functions are available in Modelica
and can be called directly without any package prefix added to the
function name. They are also available as external built-in functions in
the \lstinline!Modelica.Math! library.
\begin{longtable}{|l|p{8cm}|}
\hline \endhead
\lstinline!sin(x)! & sine\\ \hline
\lstinline!cos(x)! & cosine\\ \hline
\lstinline!tan(x)! & tangent ($x$ shall not be: ..., -$\pi$/2, $\pi$/2, 3$\pi$/2, ...)\\ \hline
\lstinline!asin(x)! & inverse sine (-1 $\le x \le$ 1)\\ \hline
\lstinline!acos(x)! & inverse cosine (-1 $\le x \le$ 1)\\ \hline
\lstinline!atan(x)! & inverse tangent\\ \hline
\lstinline!atan2(y, x)! & the \lstinline!atan2(y, x)! function calculates the principal value of the arc tangent of $y/x$, using the signs of the two arguments to determine the quadrant of the result\\ \hline
\lstinline!sinh(x)! & hyperbolic sine\\ \hline
\lstinline!cosh(x)! & hyperbolic cosine\\ \hline
\lstinline!tanh(x)! & hyperbolic tangent\\ \hline
\lstinline!exp(x)! & exponential, base $e$\\ \hline
\lstinline!log(x)! & natural (base $e$) logarithm ($x > 0$)\\ \hline
\lstinline!log10(x)! & base 10 logarithm ($x > 0$)\\ \hline
\end{longtable}
\subsection{Derivative and Special Purpose Operators with Function Syntax}\doublelabel{derivative-and-special-purpose-operators-with-function-syntax}
The following derivative operator and special purpose operators with
function syntax are predefined. The special purpose operators with
function syntax where the call below uses named arguments can be called
with named arguments (with the specified names), or with positional
arguments (the inputs of the functions are in the order given in the
calls below).
\begin{longtable}{|p{5.1cm}|p{8cm}|}
\hline \endhead
\lstinline!der!(expr) &
The time derivative of \lstinline!expr!. If the expression \lstinline!expr! is a
scalar it needs to be a subtype of Real. The expression and all its
time-varying subexpressions must be continuous and semi-differentiable.
If \lstinline!expr! is an array, the operator
is applied to all elements of the array. For non-scalar arguments the
function is vectorized according to \autoref{vectorized-calls-of-functions}.
\par
\begin{nonnormative*}
For Real parameters and constants the result is a zero scalar or array of the same size as the variable.
\end{nonnormative*}
\\
\hline
\begin{tabular}{@{}p{5.1cm}@{}}
% delay
\lstinline!delay(expr,delayTime,delayMax)!\\
\lstinline!delay(expr,delayTime)!
\end{tabular} &
Returns: \lstinline!expr(time-delayTime)! for \lstinline!time>time.start + delayTime! and \lstinline!expr(time.start)! for \lstinline!time <= time.start + delayTime!. The arguments, i.e., \lstinline!expr!, \lstinline!delayTime! and \lstinline!delayMax!, need to be
subtypes of Real. \lstinline!delayMax! needs to be additionally a parameter
expression. The following relation shall hold: \lstinline!0 <= delayTime <= delayMax!, otherwise an error occurs. If \lstinline!delayMax! is not
supplied in the argument list, \lstinline!delayTime! needs to be a parameter
expression. See also \autoref{delay}. For non-scalar arguments the
function is vectorized according to \autoref{vectorized-calls-of-functions}.\\
\hline
% cardinality
\lstinline!cardinality(c)! &
\begin{nonnormative*}
This is a deprecated operator. It should no longer be used, since it will be removed in one of the next Modelica releases.
\end{nonnormative*}
Returns the number of (inside and outside) occurrences of connector
instance \lstinline!c! in a connect-equation as an \lstinline!Integer! number. See also \autoref{cardinality-deprecated}.\\
\hline
% homotopy
\lstinline!homotopy(actual=actual,!\\
\lstinline! simplified=simplified)! & The scalar expressions \lstinline!actual! and \lstinline!simplified! are subtypes of
\lstinline!Real!. A Modelica translator should map this operator into either of the two forms:
\begin{enumerate}
\item
Returns \lstinline!actual! (trivial implementation).
\item
In order to solve algebraic systems of equations, the operator might
during the solution process return a combination of the two arguments,
ending at actual.
\begin{example}
\lstinline!actual*lambda + simplified*(1-lambda)!, where \lstinline!lambda! is a homotopy parameter going from 0 to 1.
\end{example}
The solution must fulfill the equations for homotopy returning \lstinline!actual!.
\end{enumerate}
See also \autoref{homotopy}. For non-scalar arguments the function is
vectorized according to \autoref{scalar-functions-applied-to-array-arguments}.\\
\hline
% semiLinear
\begin{tabular}{@{}p{5.1cm}@{}}
\lstinline!semiLinear(x,!\\
\lstinline! positiveSlope,!\\
\lstinline! negativeSlope)!\\
\end{tabular}&
Returns:
\lstinline!smooth(0, if x>=0 then positiveSlope*x else negativeSlope*x)!.
The result is of type \lstinline!Real!. See \autoref{semilinear} (especially in
the case when $x = 0$). For non-scalar arguments the function is
vectorized according to \autoref{vectorized-calls-of-functions}.\\
\hline
% inStream
\lstinline!inStream(v)! & \lstinline!inStream(v)! is only allowed for stream
variables \lstinline!v! defined in stream connectors, and is the value of the stream
variable \lstinline!v! close to the connection point assuming that the flow is from
the connection point into the component. This value is computed from the
stream connection equations of the flow variables and of the stream
variables. The operator is vectorizable. For more details see \autoref{stream-operator-instream-and-connection-equations}.\\
\hline
% actualStream
\lstinline!actualStream(v)! & \lstinline!actualStream(v)! returns the actual value
of the stream variable \lstinline!v! for any flow direction. The operator is
vectorizable. For more details, see \autoref{stream-operator-actualstream}.\\
\hline
% spatialDistribution
\begin{tabular}{@{}p{5.1cm}@{}}
\lstinline!spatialDistribution(!\\
\lstinline! in0=in0, in1=in1, x=x,!\\
\lstinline! positiveVelocity=...,!\\
\lstinline! initialPoints=...,!\\
\lstinline! initialValues=...)!
\end{tabular} &
\lstinline!spatialDistribution! allows approximation of variable-speed transport of properties, see \autoref{spatialdistribution}.\\
\hline
% getInstanceName
\lstinline!getInstanceName()! & Returns a string with the name of the model/block
that is simulated, appended with the fully qualified name of the
instance in which this function is called, see \autoref{getinstancename}.\\
\hline
\end{longtable}
A few of these operators are described in more detail in the following.
\subsubsection{delay}\doublelabel{delay}
\begin{nonnormative}
\lstinline!delay! allows a numerical sound
implementation by interpolating in the (internal) integrator
polynomials, as well as a more simple realization by interpolating
linearly in a buffer containing past values of expression expr. Without
further information, the complete time history of the delayed signals
needs to be stored, because the delay time may change during simulation.
To avoid excessive storage requirements and to enhance efficiency, the
maximum allowed delay time has to be given via \lstinline!delayMax!.
This gives an upper bound on the values of the delayed signals
which have to be stored. For real-time simulation where fixed step size
integrators are used, this information is sufficient to allocate the
necessary storage for the internal buffer before the simulation starts.
For variable step size integrators, the buffer size is dynamic during
integration. In principle, \lstinline!delay! could break algebraic
loops. For simplicity, this is not supported because the minimum delay
time has to be give as additional argument to be fixed at compile time.
Furthermore, the maximum step size of the integrator is limited by this
minimum delay time in order to avoid extrapolation in the delay
buffer.
\end{nonnormative}
\subsubsection{spatialDistribution}\doublelabel{spatialdistribution}
\begin{nonnormative}
Many applications involve the modelling of variable-speed
transport of properties. One option to model this infinite-dimensional
system is to approximate it by an ODE, but this requires a large number
of state variables and might introduce either numerical diffusion or
numerical oscillations. Another option is to use a built-in operator
that keeps track of the spatial distribution of $z(x, t)$, by suitable
sampling, interpolation, and shifting of the stored distribution. In
this case, the internal state of the operator is hidden from the ODE
solver.
\end{nonnormative}
\lstinline!spatialDistribution! allows to approximate efficiently the solution of the infinite-dimensional problem
\begin{align*}
\frac{\partial z(y,t)}{\partial t}+v(t)\frac{\partial z(y,t)}{\partial y} &= 0.0\\
z(0.0, t) &= \mathrm{in}_0(t) \text{ if $v\ge 0$}\\
z(1.0, t) &= \mathrm{in}_1(t) \text{ if $v<0$}
\end{align*}
where $z(y, t)$ is the transported quantity, $y$ is the
normalized spatial coordinate ($0.0 \le y \le 1.0$), $t$ is the
time, $v(t)=\mathrm{der}(x)$ is the normalized
transport velocity and the boundary conditions are set at either
$y=0.0$ or $y=1.0$, depending on the sign of the velocity.
The calling syntax is:
\begin{lstlisting}[language=modelica]
(out0, out1) = spatialDistribution(in0, in1, x, positiveVelocity,
initialPoints = {0.0, 1.0},
initialValues = {0.0, 0.0});
\end{lstlisting}
where \lstinline!in0!, \lstinline!in1!, \lstinline!out0!, \lstinline!out1!, \lstinline!x!, \lstinline!v! are all subtypes of Real,
\lstinline!positiveVelocity! is a Boolean, \lstinline!initialPoints! and \lstinline!initialValues! are
arrays of subtypes of Real of equal size, containing the y coordinates
and the $z$ values of a finite set of points describing the initial
distribution of $z(y, \mathit{t0})$. The \lstinline!out0! and \lstinline!out1! are given by
the solutions at $z(0.0, t)$ and $z(1.0, t)$; and \lstinline!in0! and \lstinline!in1!
are the boundary conditions at $z(0.0, t)$ and $z(1.0, t)$ (at
each point in time only one of in0 and in1 is used). Elements in the
initialPoints array must be sorted in non-descending order. The operator
can not be vectorized according to the vectorization rules described in
\autoref{scalar-functions-applied-to-array-arguments}. The operator can be vectorized only with respect to the
arguments in0 and in1 (which must have the same size), returning
vectorized outputs out0 and out1 of the same size; the arguments
initialPoints and initialValues are vectorized accordingly.
The solution, $z$, can be described in terms of characteristics:
\begin{equation*}
z(y+\int_{t}^{t+\beta} v(\alpha) \mathrm{d}\alpha, t+\beta) = z(y, t),\quad\text{for all $\beta$ as long as staying inside the domain}
\end{equation*}
This allows to directly compute the solution based on interpolating the
boundary conditions.
\lstinline!spatialDistribution! can be described in terms of the pseudo-code given as a block:
\begin{lstlisting}[language=modelica]
block spatialDistribution
input Real in0;
input Real in1;
input Real x;
input Boolean positiveVelocity;
parameter Real initialPoints(each min=0, each max=1)[:] = {0.0, 1.0};
parameter Real initialValues[:] = {0.0, 0.0};
output Real out0;
output Real out1;
protected
Real points[:];
Real values[:];
Real x0;
Integer m;
algorithm
if positiveVelocity then
out1:=interpolate(points, values, 1-(x-x0));
out0:=values[1]; // similar to in0 but avoiding algebraic loop
else
out0:=interpolate(points, values, 0-(x-x0));
out1:=values[end]; // similar to in1 but avoiding algebraic loop
end if;
when <acceptedStep> then
if x>x0 then
m:=size(points,1);
while (if m>0 then points[m]+(x-x0)>=1 else false) then
m:=m-1;
end while;
values:=cat(1, {in0}, values[1:m], {interpolate(points, values,1-(x-x0))} );
points:=cat(1, {0}, points[1:m] .+ (x-x0), {1} );
elseif x<x0 then
m:=1;
while (if m<size(points,1) then points[m]+(x-x0)<=0 else false) then
m:=m+1;
end while;
values:=cat(1, {interpolate(points, values, 0-(x-x0))},values[m:end],{in1});
points:=cat(1, {0}, points[m:end] .+ (x-x0), {1});
end if;
x0:=x;
end when;
initial algorithm
x0:=x;
points:=initialPoints;
values:=initialValues;
end spatialDistribution;
\end{lstlisting}
\begin{nonnormative}
Note that the implementation has an internal state and thus
cannot be described as a function in Modelica; initialPoints and
initialValues are declared as parameters to indicate that they are only
used during initialization.
The infinite-dimensional problem stated above can then be formulated in the following way:
\begin{lstlisting}[language=modelica]
der(x) = v;
(out0, out1) = spatialDistribution(in0, in1, x,v >=0, initialPoints, initialValues);
\end{lstlisting}
Events are generated at the exact instants when the velocity
changes sign --- if this is not needed, \lstinline!noEvent! can be used to
suppress event generation.
If the velocity is known to be always positive, then \lstinline!out0! can be omitted, e.g.:
\begin{lstlisting}[language=modelica]
der(x) = v;
(,out1) = spatialDistribution(in0, 0, x, true, initialPoints, initialValues);
\end{lstlisting}
Technically relevant use cases for the use of
\lstinline!spatialDistribution! are modeling of electrical
transmission lines, pipelines and pipeline networks for gas, water and
district heating, sprinkler systems, impulse propagation in elongated
bodies, conveyor belts, and hydraulic systems. Vectorization is needed
for pipelines where more than one quantity is transported with velocity
v in the example above.
\end{nonnormative}
\subsubsection{cardinality (deprecated)}\doublelabel{cardinality-deprecated}
\begin{nonnormative}
\lstinline!cardinality! is deprecated for the following reasons and will be removed in a future release:
\begin{itemize}
\item
Reflective operator may make early type checking more difficult.
\item
Almost always abused in strange ways
\item
Not used for Bond graphs even though it was originally introduced for that purpose.
\end{itemize}
\end{nonnormative}
\begin{nonnormative}
\lstinline!cardinality! allows the definition of connection dependent equations in a model, for example:
\begin{lstlisting}[language=modelica]
connector Pin
Real v;
flow Real i;
end Pin;
model Resistor
Pin p, n;
equation
assert(cardinality(p) > 0 and cardinality(n) > 0, "Connectors p and n of Resistor must be connected");
// Equations of resistor
...
end Resistor;
\end{lstlisting}
\end{nonnormative}
The cardinality is counted after removing conditional components, and
may not be applied to expandable connectors, elements in expandable
connectors, or to arrays of connectors (but can be applied to the scalar
elements of array of connectors). \lstinline!cardinality! should only
be used in the condition of assert and if-statements -- that do not
contain connect (and similar operators -- see \autoref{clocked-discrete-time-and-clocked-discretized-continuous-time-partition}).
\subsubsection{homotopy}\doublelabel{homotopy}
\begin{nonnormative}
During the initialization phase of a dynamic simulation
problem, it often happens that large nonlinear systems of equations must
be solved by means of an iterative solver. The convergence of such
solvers critically depends on the choice of initial guesses for the
unknown variables. The process can be made more robust by providing an
alternative, simplified version of the model, such that convergence is
possible even without accurate initial guess values, and then by
continuously transforming the simplified model into the actual model.
This transformation can be formulated using expressions of this kind:
$$\lambda\cdot\text{actual} + (1-\lambda)\cdot\text{simplified}$$
in the formulation of the system equations, and is usually called
a homotopy transformation. If the simplified expression is chosen
carefully, the solution of the problem changes continuously with $\lambda$,
so by taking small enough steps it is possible to eventually obtain the
solution of the actual problem.
The operator can be called with ordered arguments or preferably
with named arguments for improved readability.
It is recommended to perform (conceptually) one homotopy iteration
over the whole model, and not several homotopy iterations over the
respective non-linear algebraic equation systems. The reason is that the
following structure can be present:
\begin{lstlisting}[language=modelica]
w = $f_1$(x) // has homotopy
0 = $f_2$(der(x), x, z, w)
\end{lstlisting}
Here, a non-linear equation system $f_2$
is present. \lstinline!homotopy! is, however used on a variable
that is an ``input'' to the non-linear algebraic equation system, and
modifies the characteristics of the non-linear algebraic equation
system. The only useful way is to perform the homotopy iteration over
$f_1$ and $f_2$ together.
The suggested approach is ``conceptual'', because more efficient
implementations are possible, e.g.\ by determining the smallest iteration
loop, that contains the equations of the first BLT block in which
\lstinline!homotopy! is present and all equations up to the last BLT block
that describes a non-linear algebraic equation system.
A trivial implementation of \lstinline!homotopy! is obtained by
defining the following function in the global scope:
\begin{lstlisting}[language=modelica]
function homotopy
input Real actual;
input Real simplified;
output Real y;
algorithm
y := actual;
annotation(Inline = true);
end homotopy;
\end{lstlisting}
\end{nonnormative}
\begin{example}[1] In electrical systems it is often difficult to solve non-linear
algebraic equations if switches are part of the algebraic loop. An
idealized diode model might be implemented in the following way, by
starting with a ``flat'' diode characteristic and then move with
\lstinline!homotopy! to the desired ``steep'' characteristic:
\begin{lstlisting}[language=modelica]
model IdealDiode
...
parameter Real Goff = 1e-5;
protected
Real Goff_flat = max(0.01, Goff);
Real Goff2;
equation
off = s < 0;
Goff2 = homotopy(actual=Goff, simplified=Goff_flat);
u = s*(if off then 1 else Ron2) + Vknee;
i = s*(if off then Goff2 else 1 ) + Goff2*Vknee;
...
end IdealDiode;
\end{lstlisting}
\end{example}
\begin{example}[2] In electrical systems it is often useful that all voltage sources
start with zero voltage and all current sources with zero current, since
steady state initialization with zero sources can be easily obtained. A
typical voltage source would then be defined as:
\begin{lstlisting}[language=modelica]
model ConstantVoltageSource
extends Modelica.Electrical.Analog.Interfaces.OnePort;
parameter Modelica.Units.SI.Voltage V;
equation
v = homotopy(actual=V, simplified=0.0);
end ConstantVoltageSource;
\end{lstlisting}
\end{example}
\begin{example}[3] In fluid system modelling, the pressure/flowrate relationships are
highly nonlinear due to the quadratic terms and due to the dependency on
fluid properties. A simplified linear model, tuned on the nominal
operating point, can be used to make the overall model less nonlinear
and thus easier to solve without accurate start values. Named arguments
are used here in order to further improve the readability.
\begin{lstlisting}[language=modelica]
model PressureLoss
import Modelica.Units.SI;
...
parameter SI.MassFlowRate m_flow_nominal "Nominal mass flow rate";
parameter SI.Pressure dp_nominal "Nominal pressure drop";
SI.Density rho "Upstream density";
SI.DynamicViscosity lambda "Upstream viscosity";
equation
...
m_flow = homotopy(actual = turbulentFlow_dp(dp, rho, lambda),
simplified = dp/dp_nominal*m_flow_nominal);
...
end PressureLoss;
\end{lstlisting}
\end{example}
\begin{example}[4] Note that \lstinline!homotopy! \emph{shall not} be used to
combine unrelated expressions, since this can generate singular systems
from combining two well-defined systems.
\begin{lstlisting}[language=modelica]
model DoNotUse
Real x;
parameter Real x0 = 0;
equation
der(x) = 1-x;
initial equation
0 = homotopy(der(x), x - x0);
end DoNotUse;
\end{lstlisting}
The initial equation is expanded into
$$ 0 = \lambda*\mathrm{der}(x)+(1-\lambda)(x-x_0)$$