Modelica Language Specification Version 3.6-dev

Transcription

Modelica A Uni ed Object-Oriented Languagefor Systems ModelingLanguage Speci cationVersion 3.6-devJuly 13, 2022Modelica AssociationAbstractThis document de nes the Modelica1 language, version 3.6-dev, which is developed by the ModelicaAssociation, a non-pro t 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 formulti-domain modeling, for example, mechatronic models in robotics, automotive and aerospace applications involving mechanical, electrical, hydraulic control and state machine subsystems, process orientedapplications and generation and distribution of electric power. Models in Modelica are mathematicallydescribed by di erential, algebraic and discrete equations. No particular variable needs to be solvedfor 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 e cient handlingof large models having more than one hundred thousand equations. Modelica is suited and used forhardware-in-the-loop simulations and for embedded control systems. More information is available athttps://modelica.org.1Modelica is a registered trademark of the Modelica Association.

Modelica Language Speci cation 3.6-devCopyright 1998-2021, Modelica Association (https://modelica.org)All rights reserved. Reproduction or use of editorial or pictorial content is permitted, i.e., this documentcan be freely distributed especially electronically, provided the copyright notice and these conditionsare 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 errorsor omissions is assumed.The contributors to this and to previous versions of this document are listed in appendix D.1

ContentsPreface51 Introduction1.11.21.31.4Overview of Modelica . .Scope of the Speci cationSome De nitions . . . . .Notation . . . . . . . . . . . . . . . . . . . .Keywords. . . . . . . . . . .Expressions . . . . . . . . . . . . . . . . . . . . .Operator Precedence and Associativity . . . . . .Evaluation Order . . . . . . . . . . . . . . . . . .Arithmetic Operators . . . . . . . . . . . . . . . .Equality, Relational, and Logical Operators . . .Miscellaneous Operators and Variables . . . . . .Built-in Intrinsic Operators with Function SyntaxVariability of Expressions . . . . . . . . . . . . . . . . . . . . . . . . .Lookup. . . . . . . . .2 Lexical Structure2.12.22.32.42.5Character Set . . . . .Comments . . . . . . .Identi ers, Names, andLiteral Constants . . .Operator Symbols . .3 Operators and Expressions3.13.23.33.43.53.63.73.84 Classes, Prede ned Types, and Declarations4.14.24.34.44.54.64.74.8Access Control Public and Protected ElementsDouble Declaration not Allowed . . . . . . . . . .Declaration Order . . . . . . . . . . . . . . . . . .Component Declarations . . . . . . . . . . . . . .Class Declarations . . . . . . . . . . . . . . . . .Specialized Classes . . . . . . . . . . . . . . . . .Balanced Models . . . . . . . . . . . . . . . . . .Prede ned Types and Classes . . . . . . . . . . .5 Scoping, Name Lookup, and Flattening5.15.25.35.45.55.6Flattening Context . . . . . . . . . . . . . . .Enclosing Classes . . . . . . . . . . . . . . . .Static Name Lookup . . . . . . . . . . . . . .Inner Declarations - Instance Hierarchy NameSimultaneous Inner/Outer Declarations . . .Flattening Process . . . . . . . . . . . . . . .6 Interface or Type Relationships6.16.26.36.4Interface Terminology . . . . . . . . . . . . .The Concepts of Type, Interface and SubtypeInterface or Type . . . . . . . . . . . . . . . .Interface Compatibility or Subtyping . . . . 495057636363636567687474757678

Modelica Language Speci cation 3.6-devContents6.56.66.7Plug-Compatibility or Restricted Subtyping . . . . . . . . . . . . . . . . . . . . . . . . . 79Function-Compatibility or Function-Subtyping for Functions . . . . . . . . . . . . . . . . 80Type Compatible Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827 Inheritance, Modi cation, and Redeclaration7.17.27.383Inheritance Extends Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Modi cations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86Redeclaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918 Equations8.18.28.38.48.58.6Equation Categories . . . . . . . . . . . . . . . . . . . .Flattening and Lookup in Equations . . . . . . . . . . .Equations in Equation Sections . . . . . . . . . . . . . .Synchronous Data-Flow Principle and Single AssignmentEvents and Synchronization . . . . . . . . . . . . . . . .Initialization, initial equation, and initial algorithm . . .9 Connectors and Connections9.19.29.39.4Connect-Equations and Connectors . . . . .Generation of Connection Equations . . . .Restrictions of Connections and ConnectorsOverconstrained Connections . . . . . . . .Array Declarations . . . . . . . . . . . . . . . . . . . .Flexible Array Sizes . . . . . . . . . . . . . . . . . . .Built-in Array Functions . . . . . . . . . . . . . . . . .Vector, Matrix and Array Constructors . . . . . . . . .Indexing . . . . . . . . . . . . . . . . . . . . . . . . . .Scalar, Vector, Matrix, and Array Operator FunctionsEmpty Arrays . . . . . . . . . . . . . . . . . . . . . . .10 Arrays10.110.210.310.410.510.610.7. . . . . . .Rule. . . . .11 Statements and Algorithm Sections11.111.2Function Declaration . . . . . . . . . . .Function as a Specialized Class . . . . .Pure Modelica Functions . . . . . . . . .Function Call . . . . . . . . . . . . . . .Built-in Functions . . . . . . . . . . . .Record Constructor Functions . . . . . .Derivatives and Inverses of Functions . .Function Inlining and Event GenerationExternal Function Interface . . . . . . .Package as Specialized Class . . . . . . . . . . . .Importing De nitions from a Package . . . . . . .The Modelica Library Path MODELICAPATHFile System Mapping of Package/Class . . . . . .External Resources . . . . . . . . . . . . . . . . .14 Overloaded 35140144145150151.13 hm Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15212 rview of Overloaded OperatorsMatching Function . . . . . . . . .Overloaded Constructors . . . . . .Overloaded String Conversions . 4205205206206207

Modelica Language Speci cation 3.6-devContents14.514.614.7Overloaded Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207Overloaded Unary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208Example of Overloading for Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . 20915 Stream Connectors15.115.215.316 Synchronous Language 6.11213De nition of Stream Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213inStream and Connection Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214actualStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218Rationale for Clocked Semantics .De nitions . . . . . . . . . . . . . .Clock Constructors . . . . . . . . .Clocked State Variables . . . . . .Partitioning Operators . . . . . . .Clocked When-Clause . . . . . . .Clock Partitioning . . . . . . . . .Clocked Discretized Partition . . .Initialization of Clocked PartitionsOther Operators . . . . . . . . . .Semantics . . . . . . . . . . . . . .17 State 240242Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242State Machine Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244State Machine Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24518 1018.11219Vendor-Speci c Annotations . . . . . . . . . . .Documentation . . . . . . . . . . . . . . . . . .Symbolic Processing . . . . . . . . . . . . . . .Simulations . . . . . . . . . . . . . . . . . . . .Usage Restrictions . . . . . . . . . . . . . . . .Graphical Objects . . . . . . . . . . . . . . . .Graphical User Interface . . . . . . . . . . . . .Versions . . . . . . . . . . . . . . . . . . . . . .Access Control to Protect Intellectual PropertyFunctions . . . . . . . . . . . . . . . . . . . . .Choices for Modi cations and Redeclarations .25425425425925926026127127628228628619 Unit Expressions28720 The Modelica Standard Library289A Modelica Concrete Syntax290B Modelica DAE Representation298C Derivation of Stream Equations302D Modelica Revision History307Bibliography342Index34319.1A.1A.2The Syntax of Unit Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287Lexical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2914

PrefaceModelica is a freely available, object-oriented language for modeling of large, complex, and heterogeneousphysical systems. From a user's point of view, models are described by schematics, also called objectdiagrams. Examples are shown below:A schematic consists of connected components, like a resistor, or a hydraulic cylinder. A component hasconnectors (often also called ports ) that describe the interaction possibilities, e.g., an electrical pin, amechanical ange, or an input signal. By drawing connection lines between connectors a physical systemor block diagram model is constructed. Internally a component is de ned 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 de ne all parts of a model and to structure modelcomponents in libraries, called packages. An appropriate Modelica simulation environment is neededto graphically edit and browse a Modelica model (by interpreting the information de ning a Modelicamodel) and to perform model simulations and other analysis. Information about such environments isavailable at https://modelica.org/tools. Basically, all Modelica language elements are mapped todi erential, algebraic and discrete equations. There are no language elements to describe directly partialdi erential equations, although some types of discretized partial di erential equations can be reasonablyde ned, e.g., based on the nite volume method and there are Modelica libraries to import results ofnite-element programs.This document de nes the details of the Modelica language. It is not intended to learn the Modelicalanguage with this text. There are better alternatives, such as the Modelica books referenced at https://modelica.org/publications. This speci cation is used by computer scientist to implement a Modelicatranslator and by modelers who want to understand the exact details of a particular language element.5

Modelica Language Speci cation 3.6-devContentsThe text directly under the chapter headings are non-normative introductions to the chapters.The Modelica language has been developed since 1996. This document describes version 3.6-dev of theModelica language. The revision history is available in appendix D.6

Chapter 1Introduction1.1Overview of ModelicaModelica is a language for modeling of cyber-physical systems, supporting acausal connection of components governed by mathematical equations to facilitate modeling from rst principles. It providesobject-oriented constructs that facilitate reuse of models, and can be used conveniently for modelingcomplex systems containing, e.g., mechanical, electrical, electronic, magnetic, hydraulic, thermal, control, electric power or process-oriented subcomponents.1.2Scope of the Speci cationThe semantics of the Modelica language is speci ed by means of a set of rules for translating any classdescribed in the Modelica language to a at Modelica structure. The semantic speci cation should beread together with the Modelica grammar.A class (of specialized class model or block) intended to be simulated on its own is called amodel .simulationThe at Modelica structure is also de ned for other cases than simulation models; including functions(can be used to provide algorithmic contents), packages (used as a structuring mechanism), and partialmodels (used as base-models). This allows correctness to be veri ed for those classes, before using themto build the simulation model.There are speci c semantic restrictions for a simulation model to ensure that the model is complete; theyallow its at Modelica structure to be further transformed into a set of di erential, algebraic and discreteequations ( at hybrid DAE). Note that satisfying the semantic restrictions does not guarantee thatthe model can be initialized from the initial conditions and simulated.Modelica was designed to facilitate symbolic transformations of models, especially by mapping basicallyevery Modelica language construct to equations in the at Modelica structure. Many Modelica models,especially in the associated Modelica Standard Library, are higher index systems, and can only bereasonably simulated if symbolic index reduction is performed, i.e., equations are di erentiated andappropriate variables are selected as states, so that the resulting system of equations can be transformedto state space form (at least locally numerically), i.e., a hybrid DAE of index zero. In order to allowthis structural analysis, a tool may reject simulating a model if parameters cannot be evaluated duringtranslation due to calls of external functions or initial equations/initial algorithms for fixed falseparameters. Accepting such models is a quality of implementation issue. The Modelica speci cationdoes not de ne how to simulate a model. However, it de nes a set of equations that the simulation resultshould satisfy as well as possible.The key issues of the translation (or attening) are: Expansion of inherited base classes Parameterization of base classes, local classes and components7

Modelica Language Speci cation 3.6-dev1.3. Some De nitions Generation of connection equations from connect-equationsThe at hybrid DAE form consists of: Declarations of variables with the appropriate basic types, pre xes and attributes, such as parameterReal v 5. Equations from equation sections. Function invocations where an invocation is treated as a set of equations which involves all inputand all result variables (number of equations number of basic result variables). Algorithm sections where every section is treated as a set of equations which involves the variablesoccurring in the algorithm section (number of equations number of di erent assigned variables). The when-clauses where every when-clause is treated as a set of conditionally evaluated equations,which are functions of the variables occurring in the clause (number of equations number ofdi erent assigned variables).Therefore, a at hybrid DAE is seen as a set of equations where some of the equations are only conditionally evaluated. Initial setup of the model is speci ed using start-attributes and equations that holdonly during initialization.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.1.3Some De nitionsExplanations of many terms can be found using the document index in appendix D.14.5. Some importantterms are de ned below.De nition 1.1. Component . An element de ned by the production component-clause in the Modelicagrammar (basically a variable or an instance of a class)De nition 1.2. Element . Class de nition, extends-clause, or(basically a class reference or a component in a declaration).component-clause declared in a classDe nition 1.3. Flattening . The translation of a model described in Modelica to the correspond-ing model described as a hybrid DAE (see appendix B), involving expansion of inherited base classes,parameterization of base classes, local classes and components, and generation of connection equationsfrom connect-equations. In other words, mapping the hierarchical structure of a model into a set ofdi erential, algebraic and discrete equations together with the corresponding variable declarations andfunction de nitions from the model.De nition 1.4. Initialization . Simulation starts with solving the initialization problem at the starting time, resulting in values for all variables that are consistent with the result of the attening.De nition 1.5. Transient analysis . Starting from the result of the initialization problem, the modelis simulated forward in time. This uses numerical methods for handling the hybrid DAE, resulting insolution trajectories for the model's variables, i.e., the value of the variables as a function of time.[Inthe numerical literature transient analysis is often called solving theterm is not used here to avoid confusion with the initialization problem.]initial value problem,but thatDe nition 1.6. Simulation . Simulation is the combination of initialization followed by transientanalysis.[Themodel can be analyzed in ways other than simulation, e.g., linearization, and parameter estimation,but they are not described in the speci cation.]De nition 1.7. Translation . Translation is the process of preparing a Modelica simulation modelfor simulation, starting with attening but not including the simulation itself.[Typically,in addition to attening, translation involves symbolic manipulation of the hybrid DAE andtransforming the result into computer code that can simulate the model.]8

Modelica Language Speci cation 3.6-dev1.4. Notation1.4NotationThe remainder of this section shows examples of the presentation used in this document.Syntax highlighting of Modelica code is illustrated by the code listing below. Things to note includekeywords that de ne code structure such as equation, keywords that do not de ne code structure suchas connect, and recognized identi ers with meaning de ned by the speci cation such as semiLinear:model Example " Example used to illustrate syntax highlighting escriptionpresentedString s 1.0; / / E r r o r : No c o n v e r s i o nReal x ;equation2 * x semiLinear ( time - 0.5 , 2 , 3) ;/*Theannotationbelowhasomittedstring ,likeformdetailsthisthis :*/Realtoisacomment .*/String .representedbyanellipsis :*/connect ( resistor .n , conductor . p ) annotation (. . .) ;end Example ;Relying on implicit conversion of Integer literals to Real is common, as seen in the equation above(note use of Modelica code appearing inline in the text).It is common to mix Modelica code with mathematical notation. For example, average(x, y) could bede ned as x y2 .De nition 1.8. Something . Text de ning the meaning of something.In addition to the style of de nition above, new terminology can be introduced in the running text. Forexample, a dummy is something that. . .[Thisis non-normative content that provides some explanation, motivation, and/or additional things tokeep in mind.It has no de ning power and may be skipped by readers strictly interested in just thede nition of the Modelica language.][Example:This is an example, which is a special kind of non-normative content. Examples often containa mix of code listings and explanatory text, and this is no exception:String s 1.0;//Error :NoconversionformRealtoTo x the type mismatch above, the number has to be replaced by aString .Stringexpression, such as"1.0".]Other code listings in the document include speci cation of lexical units and grammatical structure, bothusing metasymbols of the extended BNF-grammar de ned in appendix A.1. Lexical units are namedwith all upper-case letters and introduced with the ' sign:SOME-TOKEN NON-DIGIT { DIGIT NON-DIGIT }Grammatical structure is recognized by production rules being named with lower-case letters and introduced with the :' sign (also note appearance of the Modelica keyword der):d i f f e r e n t i a t e d -e x p r e s s i o n :der " ( " SOME-TOKEN " ) " " ( " d i f f e r e n t i a t e d- e x p r e s s i o n " " d i f f e r e n t i a t e d- e x p r e s s i o n " ) "9

Chapter 2Lexical StructureThis chapter describes several of the basic building blocks of Modelica such as characters and lexicalunits including identi ers and literals. Without question, the smallest building blocks in Modelica aresingle characters belonging to a character set. Characters are combined to form lexical units, also calledtokens. These tokens are detected by the lexical analysis part of the Modelica translator. Examples oftokens are literal constants, identi ers, and operators. Comments are not really lexical units since theyare eventually discarded. On the other hand, comments are detected by the lexical analyzer before beingthrown away.The information presented here is derived from the more formal speci cation in appendix A.2.1Character SetThe character set of the Modelica language is Unicode, but restricted to the Unicode characters corresponding to 7-bit ASCII characters for identi ers; see appendix A.1.2.2CommentsThere are two kinds of comments in Modelica which are not lexical units in the language and thereforeare treated as white-space by a Modelica translator. The white-space characters are space, tabulator,and line separators (carriage return and line feed); and white-space cannot occur inside tokens, e.g., must be written as two characters without space or comments between them. The following commentvariants are available://R e s t o f l i n ecomment :Everythingfrom//totheendofthelineareignored ." Not part of comment "/*Delimitedincluding[Thecomment :lineCharacterstermination .afterThe/*commentareendsignored ,with*/comment syntax is identical to that of C .]Delimited Modelica comments do not nest, i.e., /* */ cannot be embedded within /* . . . */. The following is invalid :/*Invalidmodel/*nestingofcomments ,thecommentendsjustbefore' end 'InterestingTobedone*/end Interesting ;*/Rest-of-line comments can safely be used to comment out blocks of code without risk of con ict withcomments inside.// model///*// endValidTobe//Somedone*/othercommentValid ;10

Modelica Language Speci cation 3.6-dev2.3. Identi ers, Names, and KeywordsThere is also a description-string, that is part of the Modelica language and therefore not ignored bythe Modelica translator. Such a description-string may occur at the end of a declaration, equation, orstatement or at the beginning of a class de nition. For example:model TempResistor " Temperature dependent resistor ".parameter Real R " Resistance for reference temp . " ;.end TempResistor ;2.3Identi ers, Names, and Keywordsare sequences of letters, digits, and other characters such as underscore, which are used forvarious items in the language. Certain combinations of letters are keywords represented asreserved words in the Modelica grammar and are therefore not available as identi ers.Identi ersnaming2.3.1Identi ersModelica identi ers , used for naming classes, variables, constants, and other items, are of two forms.The rst form always starts with a letter or underscore ( '), followed by any number of letters, digits,or underscores. Case is signi cant, i.e., the identi ers Inductor and inductor are di erent. The secondform (Q-IDENT) starts with a single quote, followed by a sequence of any printable ASCII character, wheresingle-quote must be preceded by backslash, and terminated by a single quote, e.g. '12H', '13\'H', ' foo'. Control characters in quoted identi ers have to use string escapes. The single quotes are partof the identi er, i.e., 'x' and x are distinct identi ers. The redundant escapes ('\?' and '\"') are thesame as the corresponding non-escaped variants ('?' and '"'), but are only for use in Modelica sourcecode. A full BNF de nition of the Modelica syntax and lexical units is available in appendix A.IDENT NON-DIGIT { DIGIT NON-DIGIT } Q-IDENTQ-IDENT " '" { Q-CHAR S-ESCAPE } " '"NON-DIGIT " " letters " a " . . . " z " letters " A " . . . " Z "DIGIT " 0 " " 1 " " 2 " " 3 " " 4 " " 5 " " 6 " " 7 " " 8 " " 9 "Q-CHAR NON-DIGIT DIGIT " ! " " # " " " " % " " & " " ( " " ) " " * " " " " ," " - " " . " " / " " : " " ; " " " " " " " "?" "@" "[" "]" " " "{" "}" " " " " " " """S-ESCAPE " \ ' " " \ " " " \? " " \\ " "\a" "\b" "\f" "\n" "\r" "\t" "\v"2.3.2NamesA name is an identi er with a certain interpretation or meaning. For example, a name may denotean Integer variable, a Real variable, a function, a type, etc. A name may have di erent meanings indi erent parts of the code, i.e., di erent scopes. The interpretation of identi ers as names is describedin more detail in chapter 5. The meaning of package names is described in more detail in chapter 13.[Example:A name:Ele.Resistor]A component reference is an expression containing a sequence of identi ers and indices. A componentreference is equivalent to the referenced object, which must be a component. A component reference isresolved (evaluated) in the scope of a class (section 4.4), or expression for the case of a local iteratorvariable (section 10.6.9).[Example:2.3.3A component reference:Ele.Resistor.u[21].r]Modelica KeywordsThe following Modelicakeywordsare reserved words and shall not be used as identi ers:11

Modelica Language Speci cation 3.6-dev2.4. Literal hentruetypewhenwhilewithinLiteral ConstantsLiterals (or literal constants ) are unnamed constants used to build expressions, and have di erent formsdepending on their type. Each of the prede ned types in Modelica has a way of expressing unnamedconstants of the corresponding type, which is presented in the ensuing subsections. Additionally, arrayliterals and record literals can be expressed.2.4.1Floating Point NumbersA oating point number is expressed as a decimal number in the form of a sequence of decimal digitsfollowed by a decimal point, followed by decimal digits, followed by an exponent indicated by E or efollowed by a sign and one or more decimal digits. The various parts can be omitted, see UNSIGNED-REALin appendix A.1 for details and also the examples below. The minimal recommended range is thatof IEEE double precision oating point numbers, for which the largest representable positive numberis 1.7976931348623157 10308 and the smallest positive number is 2.2250738585072014 10 308 . Forexample, the following are oating point number literal constants:22.5 , 3.141592653589793 , 1.2 E -35The same oating point number can be represented by di erent literals. For example, all of the followingli

Modelica A Uni ed Object-Oriented Language for Systems Modeling Language Speci cation Version 3.6-dev July 13, 2022 Modelica Association Abstract This document de nes the Modelica 1 language, version 3.6-dev, which is developed by the Modelica Association, a non-pro t organization with seat in Linköping, Sweden.