Towards Qualifiable Code Generation from a Clocked Synchronous Subset of Modelica

So far no qualifiable automatic code generators (ACGs) are available for Modelica. Hence, digital control applications can be modeled and simulated in Modelica, but require tedious additional efforts (e.g., manual reprogramming) to produce qualifiable target system production code. In order to more fully leverage the potential of a model-based development (MBD) process in Modelica, a qualifiable automatic code generator is needed. Typical Modelica code generation is a fairly complex process which imposes a huge development burden to any efforts of tool qualification. This work aims at mapping a Modelica subset for digital control function development to a well-understood synchronous data-flow kernel language. This kernel language allows to resort to established compilation techniques for data-flow languages which are understood enough to be accepted by certification authorities. The mapping is established by providing a translational semantics from the Modelica subset to the synchronous data-flow kernel language. However, this translation turned out to be more intricate than initially expected and has given rise to several interesting issues that require suitable design decisions regarding the mapping and the language subset.


Introduction
Deliberate use of modeling and simulation (M&S) is an effective strategy to cope with increasing product complexity and time to market pressure.A particular challenge is software functions running on distributed, networked computing devices which are in feedback loops with physical processes (cyber-physical systems).For the development and validation of these functions, it is no longer sufficient to solely consider a single, selfcontained component without taking the interaction of this part within the whole system (including the physical parts!) into account.
For example, modern automotive vehicles can have more than 60 ECUs (electronic control units) commu-nicating over a heterogeneous network of automotive buses like CAN, FlexRay, LIN, and MOST, as well as other communication buses used for infotainment purposes.The complexity 1 of the utilized embedded software increased about fiftyfold within 15 years (Ebert and Jones, 2009).Currently the development phase for new vehicles is estimated to be about three years (Schäuffele and Zurawka, 2010).Increased use of virtual prototyping methods has the potential to further curb the required development time span.Nowadays, model-based development (MBD) has become a well established development approach in the domain of em-bedded (control) systems and the original promise of model-based development, to provide a more rapid and economic development process, seems to be confirmed in industrial practice (Broy et al., 2011).
In order to optimize the benefits gained by a modelbased development process as, it is crucial that formally specified high-level applications can be automatically transformed (usually by using generated embedded C-code) into executable binary code for respective embedded platforms, thus eliminating error prone and expensive manual re-programming of the application using a general-purpose programming language.This requires automatic code generators (ACGs).However, if the generated code affects safety related functions the additional effort to safeguard the generated code diminishes the initial benefit of model-based development.A remedy is to rely on (automatic code generation) tools that are qualifiable i.e., tools for which a certain degree of confidence in their correctness can be established for the relevant use cases.Specialized standards (despite conceptual similarities and shared base standards) apply for different industrial domains, e.g., ISO 26262 (Automotive), ISO 13849: (Machinery Control Systems), DO-178 (Aircraft), etc.
There are tools on the market which fulfill (for specific industrial domains) the necessary requirements for safety related developments and that support control system modeling in an adequate manner (e.g., Simulink Coder from MathWorks, ASCET from ETAS, SCADE from Esterel, TargetLink from dSpace).However, they share two drawbacks: (i) they do not offer state-of-theart physical modeling 2 , and (ii) they are based on proprietary model formats.Hence, more integrated modeling approaches (integrated modeling of software and physical aspects, facilitated integration in an existing software eco system) are considerably impeded.
Extensions of the non-proprietary, multi-domain cyber-physical system modeling language Modelica (Fritzson, 2014) aim at closing that gap by integrating language elements that are motivated from the point of view of clocked synchronous data-flow languages 3 for 2 MathWorks reacted to this deficiency by offering several Simulink toolboxes, most notably SimScape, to enable equation-based physical modeling (SimScape made its debut in the R2007A release of Matlab/Simulink).Unfortunately, despite using the same basic concepts like Modelica, Math-Works decided to create its own, proprietary, physical modeling language.In effect, the huge pool of high-quality (free and commercial) physical modeling libraries already available for Modelica cannot be reused in SimScape. 3Synchronous languages (Benveniste et al., 2003) are an established technology for modeling, specifying, validating, and implementing real-time embedded applications.Prominent members of the synchronous family include the Lustre (Caspi et al., 1987), Esterel (Boussinot and De Simone, 1991) and Signal (LeGuernic et al., 1991) language.The greatest industry relevancy can be attributed to the Lustre-based commer-safety-relevant, sampled-data systems (Elmqvist et al., 2012;Otter et al., 2012).However, so far no Modelica tool for high-integrity, embedded code generation has appeared on the market.Typical compilation techniques for Modelica differ significantly from established compilation techniques for data-flow languages.Hence, available knowledge about high-integrity code generation for clocked synchronous data-flow languages are not directly transferable to Modelica, exacerbating any qualification attempts.
This work proposes to link the semantics of a Modelica subset for digital control function modeling to an established clocked synchronous data-flow kernel language (SDFK) by means of a translational semantics 4 .This is achieved by providing transformation equations from the Modelica language to the SDFK language.At the same time this translational semantics is close to a practical implementation of a source-to-source compiler.This opens up a path to a qualifiable Modelica compiler by leveraging established compilation techniques for clocked synchronous data-flow languages which are understood enough to be accepted by certification authorities.

Model-Based Development and
Tool Qualification

Overview
Figure 1 shows a typical model-based development toolchain including an automatic code generator.The specification model (aka physical model ) is designed using a high-level domain-oriented modeling tool.These specification models are typically enriched with implementation details (e.g., a continuous-time controller model is replaced by a discrete-time approximation) resulting in so-called code generation or implementation models.A code generator transforms code generation models into C-code, that the cross compiler translates into object code.The different object codes, including legacy and basic software code are then finally linked to cial Scade tool (Sauvage and Bouali, 2006) that is especially used for the development of safety critical software functions.Synchronous languages have no notion of continuous time and are therefore not suited for physical modeling. 4Attempts to formalize semantic aspects of the Modelica language can be traced back to the very early phases of the language standard where natural semantics based approaches were considered as a help in the language design process (Kågedal and Fritzson, 1998) and also as a base for translator generation (Fritzson et al., 2009).However, these previous studies focused rather on general advantages of formal language specifications and were not particularly concerned with high-integrity, embedded code generation.The development of safety-relevant software typically needs to comply to rules described in functional safety standards.This also affects the used development tools.A development tool may need to fulfil a certain level of qualification depending on the severity of the impact a malfunction in the development tool is expected to have on a safety-related item.For example, in the automotive domain the ISO 26262-8:2011, Section 11 Qualification of software tools, establishes a set of recommendations concerning the needed qualifications of such software tools.
The automatically generated C-code in Figure 1 can also be seen as a low-level intermediate representation of the model, because it is both the output of the code generator as well as input to the cross compiler for the target.If sufficient confidence can be put into the correct functioning of the tool chain, safeguarding measures for intermediate representations can be eliminated.For example, code reviews on automatically generated code can be omitted.

Tool Qualification
Functional safety standards typically classify development tools into categories that depend on the impact a systematic tool failure ("bug") has on a safety related item and on the probability that a bug remains undetected by downstream development steps and tools.
For example, ISO 26262 defines four categories termed Tool Confidence Level (TCL1 -TCL4) where TCL4 denotes the highest level of required confidence.Tools classified higher than TCL1 need to be qualified.Required qualification measures are further tied to the usage context, in particular to the criticality of the software function that is realized with the development tool.ISO 26262 further recommends four principle methods for tool qualification: (i) increased confidence from use, (ii) development process evaluation, (iii) software tool validation, and (iv) development in compliance with a safety standard.While (i) or (ii) are recommended for less critical functions and/or tool confidence levels, (iii) or (iv) are considered an adequate choice for highly critical functions and tool confidence levels.
Note that the output of tools that are not qualified can still be used, but require suitable safeguarding measures, e.g., automatically generated code can be passed into a standard assurance process where it is treated like manually written code.The benefit of qualified development tools is that certain safeguarding measures, like code reviews on generated code (Stürmer et al., 2006), can be omitted.
In order to increase the confidence in the toolchain depicted in Figure 1 it is, in principle, possible to apply a number of techniques that have been proposed for ensuring safety of compilers.The survey by Frank et al. (2008) gives an overview of existing techniques and also comments on the suitability of the presented methods for practical application.In particular Frank et al. conclude that a combination of test-based approaches (as opposed to formal verification-based approaches) is the most promising way to improve the reliability of compilers for safety-related applications within the automotive industry.
Despite plenty reports in the open literature about (in many cases formal) methods that are in principle capable of increasing confidence levels in compilers or code generators, detailed reports of actually successful tool qualification efforts for automatic code generators are rare.Schneider et al. (2009) give a rather comprehensive report on the practical qualification of an industrial-strength development tool (an integrated code generator tool with target compiler) by a validation suite approach (hence, by a software tool validation method) according to automotive requirements.The approach is centered around an automated test environment that allows the automated execution of large numbers of test cases.The number of required test cases is subject to scalability issues so that suitable language restrictions are an important prerequisite before starting qualification efforts for complex real-world languages.
Regardless of whether the tool qualification method of choice is to develop a new tool according to ap-propriate safety standards, or to use a test-based or verification-based approach to qualify an existing tool: keeping the input language of the code generation model (see Figure 1) as simple and well-defined as possible is essential to keep development/qualification efforts under control.This regards the number and complexity of basic constructs in the language and also the number and complexity of performed transformation rules in the code generation process.
Furthermore, it is important to understand that technically tools need to be qualified in the context of a particular system development project and therefore only qualifiable tools are available on the market.Using a qualifiable tool alleviates tool qualification efforts and the project specific tool qualification is usually achieved in close collaboration of the tool user and the tool vendor (Hatcliff et al., 2014).

Typical Modelica Code Generation
Compiling Modelica code usually involves substantial code transformation.The following description is a slightly adapted reproduction of (Thiele et al., 2012, Section 4.2.5). Figure 2 gives an overview of the compilation and simulation process as described by Broman (2010, p. 29).(Broman, 2010, p. 29).
The different phases are: Lexical Analysis and Parsing This is standard compiler technology.
Elaboration Involves type checking, collapsing the instance hierarchy and generation of connection equations from connect-equations.The result is a hybrid differential algebraic equation (DAE) system consisting of variable declarations, equations from equations sections, algorithm sections, and when-clauses for triggering discrete-time behavior.
Equation Transformation This step encompasses transforming and manipulating the equation system into a representation that can be efficiently solved by a numerical solver.Depending on the intended solver the DAE is typically reduced to an index one problem (in case of a DAE solver) or to an ODE form (in case of numerical integration methods like Euler or Runge-Kutta).
Code generation For efficiency reasons tools typically allow (or require) translation of the residual function (for an DAE) or the right-hand side of an equation system (for an ODE) to C-code that is compiled and linked together with a numerical solver into an executable file.
Simulation Execution of the (compiled) model.During execution the simulation results are typically written into a file for later analysis.
In the context of code generation for safety relevant systems the typical processing of Modelica models has two problems: 1.In the Elaboration phase the instance hierarchy of the hierarchically composed model is collapsed and flattened into one (large) system of equations, which is subsequently translated into one (large) chunk of C-code, thus impeding modularization and traceability at the C-code level.
2. In the Equation Transformation phase the equations are extensively manipulated, optimized and transformed at the global model level.The algorithms used in this step are the core elements that differentiate the model compiler tools (quality of implementation).Although the basic algorithms are documented in the literature, the optimized algorithms and heuristics used in commercial implementations are vendor confidential proprietary information.The lack of transparency and simplicity exacerbates tool qualification efforts.
Therefore, the compilation process for simulation (Figure 2) may be significantly different compared to the target code compilation process depicted in Figure 1.Not only because different compilers are used, but also because the target code generator may (need to) be an entirely distinct piece of software that may share only minimal to no amounts of code with the simulation code generator 5 .In particular the target code generator depicted in Figure 1 is only required to understand a Modelica subset that is sufficient for digital control function modeling.

An Approach Towards a Qualifiable Modelica Code Generator
The requirement to keep the input language of the code generation model as simple and well-defined as possible motivated Thiele et al. (2012) in a previous work to propose a subset of Modelica for safety-relevant control applications that would offer a reasonable compromise between language expressiveness and expected effort of tool qualification.The proposed language restrictions were substantiated by providing rationales.However, no evidence was given about the practical feasibility to develop a qualifiable automatic code generator for that language subset.The Modelica subset used in this work is a modified version of the subset proposed in the former paper.In order to allow a clear and brief presentation of the translational semantics the former subset is further reduced to a kernel of representative elements.The resulting language kernel for automated code generation is denoted as mACG-Modelica.
The presented approach towards a qualifiable code generator relies on: 1.A target language which allows the proposition that a qualifiable code generator can be implemented for it.This language is in the following referred to as the Synchronous Data-Flow Kernel language (SDFK).
2. A representative language kernel for digital control function development in Modelica (mACG-Modelica).
3. A set of translation equations from mACG-Modelica to SDFK.The semantics of mACG-Modelica are defined in terms of this translation (translational semantics). 5 The amount of code that can be shared depends on various aspects, particularly on the tool qualification approach.Tool qualification by developing the tool in compliance with a safety standard, needs respective evidence on the development process that is usually not available for existing code.ISO 26262 also lists increased confidence from use as a method that is particularly applicable for more moderate safety requirements and tool validation as method that is also applicable for more safety-critical software -these methods are more amenable to reuse existing code.
The existence of the translation provides: (i) a strong argument for the feasibility to develop a qualifiable code generator for the considered Modelica subset and (ii) a base that can be used to create a gateway from Modelica to a qualifiable code generator that is based on clocked synchronous data-flow language like Scade/KCG (similarly to what has been reported by Caspi et al. (2003) for a translator from Simulink to Scade).

Translation to a Synchronous
Data-Flow Kernel Language 3.1.The Synchronous Data-Flow Kernel Language (SDFK) Synchronous data-flow kernel languages have been used in various publications as suitable representation for languages in certain formal methods based research.Instead of reinventing syntax, this work utilizes the synchronous data-flow kernel language 6 described by Biernacki et al. (2008).The SDFK is close to Lustre/Scade so that it allows to use well-understood and accepted compilation techniques that have been developed for these languages.Biernacki et al. (2008) formally describe modular code generation from that data-flow kernel into imperative code and note that "The principles presented in this article are implemented in the RELUC compiler of SCADE/LUSTRE and experimented on industrial real-size examples".Hence, using that particular SDFK language is attractive since it directly allows to reuse the described code generation techniques for ACG-Modelica as soon as a translational semantics is available.
In order to keep the following discussion more selfcontained, the syntax and intuitive semantics described in (Biernacki et al., 2008, Section 2) are briefly reproduced in the current section: A program is made of a list of global type ("td") and node ("d") declarations.In order to allow a clear 6 Note that the semantics of the synchronous kernel language is given informally in (Biernacki et al., 2008).However, it can be traced back to a formal semantics if necessary.Biernacki et al. (2008) refer to (Colaço et al., 2005) for the formal semantics of the clock calculus.Actually, the extended language presented in (Colaço et al., 2005) is similar to the one used in (Biernacki et al., 2008).In (Colaço et al., 2005) this extended language is formally translated into a more "basic" data-flow kernel language by a source-to-source transformation.For this "basic" data-flow kernel language (Colaço et al., 2005, Section 3.1) refers to (Colaço and Pouzet, 2003) for a (formal) denotational Kahn semantics (except for the semantics of the modular reset operator "every" which is formally defined in (Hamon and Pouzet, 2000)).(a1, . . . , an) Tuples.v fby a Initialized delays.The first argument "v" (the initial value) is expected to be an immediate value, the second argument "a" is the stream that is delayed.op(a1, . . ., an) Point-wise applications.To simplify the presentation, "op(a1, . . ., an)" is a placeholder for any point-wise application of an external function op (e.g., +, not) to its arguments.To improve the readability of examples, the application of classical arithmetic operations will be written in infix form.f (a1, . . ., an) every a Node instantiations with possible reset condition "a".At any instant at which Boolean stream "a" equals "True" the internal state of the node instantiation is reset.To simplify the notation the reset condition "every a" may be omitted which is equal to writing "every False" as reset condition.a when C(x) Sampling operations.Sample a stream "a" at every instant where "x" equals "C".merge x (C → a1) . . .(C → an) Combination operations are symmetric to the sampling operation: They combine complementary streams in order to produce a faster stream."x" is a stream producing values from a finite enumerated type "bt = C1 + . . .+ Cn"."a1, . . ., an" are complementary streams, i.e., at an instant where "x" produces a value at most one stream of "a1, . . ., an" is producing a value.At every instant where "x" equals "Ci" the value of the corresponding stream "ai" is returned.
and brief presentation, only abstract types and enumerated types are considered in the discussion.A global node declaration "d" has the form "node f (p) = p with var p in D".Within this node declaration "p" denotes a list of variables while "D" denotes a list of parallel equations.In an equation "pat = a" the pattern "pat" is either a variable or a tuple of patterns "(pat, . . ., pat)" and "a" denotes an annotated expression "e" with its clock "ct".Table 1 briefly describes various elements that can be part of an expression.The expressions can be extended by the conditional "if then else" which relates to the original kernel by the equivalence relation: (False → e 3 when False(x)) (1) Note that the clock annotations "ct" have no impact on the data-flow semantics of the language.Clocks do not have to be explicitly given in the SDFK language, although they are part of the language semantics.For example, instead of writing "((v fby x ck ) ck +y ck ) ck " it suffices to write "((v fby x) + y)".Clock annotations in the SDFK language are determined automatically by a clock calculus which is defined as a type inference system.This clock calculus precedes the code generation step (see (Biernacki et al., 2008, Section 2.2) for more details).
The syntax of the (clock-annotated) SDFK language is defined by the following grammar: For the translational semantics the expressions "e" are extended by the conditional "if then else" as defined in (1).Some of the traditional operations supported by Lus-tre are related to SDFK through the following equivalences: Lustre SDFK e when x = e when True(x) Lustre's sampling operation, where x is a Boolean stream.e1 − > e2 = if True fby False then e1 else e2 Lustre's initialization operator.pre(e) = nil fby e Lustre's uninitialized delay operator.The shortcut nil stands for any constant value e which has the type of e.It is the task of the initialization analysis to check that no computation result depends on the actual nil value.
In order to illustrate the effect of these operators Table 2 shows example applications of these operators to streams of values.

mACG-Modelica
To allow a clear and brief presentation of the translational semantics the Modelica language is reduced to a small subset of elements that is considered to be representative for data-flow based digital control functions.
The resulting language kernel is denoted as mACG-Modelica.
A program is made of a list of global type ("td"), connector ("cd") and block ("bd") declarations.Only abstract types "t" are considered (nevertheless the provided examples will use concrete Modelica types, e.g., replacing "t" by "Real").Connectors "cd" have either input or output causality.A block declaration "d" has the form "block id p equation D end;", where "id" is the name of the block, "p" contains the local component declarations and "D" the equation declarations.A component declaration "p" can be modified by a modification "mo" (compared to Modelica modifications are more restricted, see Section 5).
Parameters can be declared with modification expression "parameter t x = me;", or without modification binding "parameter t x;" 7 .
The use of component dot accesses for parameters is not supported in the presented translation in order to simplify the presentation.Allowing it would require to additionally introduce component dot access normalization (Figure 21) and "dummy" equation generation (Figure 22) in a slightly adapted form for parameters in the normalization step.For the actual translation step it would be necessary to translate all parameters not only to node input arguments, but also to node outputs arguments.This seems to make the translation harder to understand without adding much additional conceptual value 8 .
Equations "D" are either connect equations "connect(cx, cx)" or equations of the form "cx = e", where "cx" is a single variable (the unknown of the equation, which is either accessed by a simple identifier "x", or by using a component dot access "x.x") and "e" is an expression (hence, equations are more restricted than in Modelica where the unknown of an equation may appear at an arbitrary place).Similar to SDFK an abstract n-ary operator "op(e, . . ., e)" is provided to simplify the presentation (nevertheless the provided examples will be presented using concrete Modelica operators).
The syntax of mACG-Modelica is defined by the following grammar: 7 Modelica semantics require that modification bindings for parameters have parametric or constant variability (Modelica Association, 2012, Section 3.8).This needs to be ensured by a statical check before the translation (for conciseness the description of that check is omitted). 8In addition to transforming parameters to input arguments of a (C-) function, it becomes necessary to make them available as output arguments.E.g., consider "block A parameter Real p1 = 0.1; end A;" which is instantiated in "block B A a(p1=0.2); parameter Real p2 = a.p1; end B;" and note that a.p1 needs to return the value 0.2.If A is translated to a function, there needs to be an input argument to set p1 and an output argument to retrieve its value.
Abstract types "t" encompass predefined primitive types and user-defined structured types (blocks and connectors).The set "B" is introduced to denote the set of all predefined primitive types, particularly Modelica's "Boolean", "Integer", and "Real" types.
From all the clocked synchronous language elements that are listed in (Modelica Association, 2012, Chapter 16) only "previous" appears in the grammar above.The clock conversion operators are omittedfor practical applications this is not as restrictive as it may appear at a first glance.Section 5 briefly comments on that.
Also the operator "interval(u)" is missing in the grammar.This operator is considered to be available as external function call or macro -the time span between a previous and a present tick is typically only known by the environment that triggers the execution of the synchronous data-flow program.Consequently, that value needs to be provided by the runtime environment.In the case of single-rate programs (i.e., if no clock conversion operators are supported) the interval duration is simply the duration between two ticks of the base clock, in case of multi-rate programs it becomes more complicated and the value depends on the specific clock that is associated to the operators argument "u".

A Multilevel Translation Approach
The translation to the SDFK language is rather complex.In order to keep the translation manageable and understandable the translation is subdivided into several steps.The two major steps are: 1. Normalization of mACG-Modelica (formulated as source-to-source transformation).This step is again subdivided in: a) Generation of connection equations.
b) Stripping of parameter modifications, normalizing instance modifications and extracting instance dot accesses appearing in expressions.
c) Creating a fresh block that instantiates the top-level block as a component with normalized component modifications.
2. Translation to the SDFK language.
Normalization and translation are defined as a system of mutually recursive functions.The normalization is needed in order to transform mACG-Modelica into a (simplified) normalized form which is the basis for the translation to the SDFK language.The syntax for the normalized mACG-Modelica language can be found in Section 3.5.
Using a multilevel translation approach facilitates including further language elements, as long as a sourceto-source transformation into a smaller language kernel can be given.The generation of connection equations is a good example for this: it eliminates the connector declarations and connect equations by replacing them with simple variable declarations (using the proper input/output causalities) and simple equations of the form "x = e".Hence, the multilevel translation approach provides a path to incrementally extend the mACG-Modelica subset to more comprehensive subsets for control function development (see also the discussion in Section 5).

The Normalization
The normalization is presented by using example code snippets that illustrate the required source-to-source transformation.The formal translation equations are rather heavy and are therefore provided as a supplementary part of the appendix, Section B.
The line numbers of the code snippets are consecutively incremented, so that descriptive text can refer to them.Once a class/type is declared, it may reappear in subsequent code snippets.

Generation of Connection Equations
Connector Declarations Connector declarations (line 1-2) are replaced by their corresponding short class definition (e.g., In ↦ input Real, compare line 4 ↦ 10 and Out ↦ output Real, compare line 5 ↦ 11).Connect Equations The connect equations are replaced by simple equations of the form "x = e".Note that the causality is not directly encoded in the connect equations, so it has to be inferred from the variable declarations.Parameter Modifications at Instantiated Blocks All parameters of an instantiated block are extracted, merged with applicable instance modifications and introduced as fresh parameters with a modification expression.
Note that the parameter modification from line 28 is extracted and reintroduced in line 43, while the modification from line 29 is overridden by the instance modification in line 28 before being assigned to the fresh parameter _pi_Td in line 44.

Generation of Top-Level Instantiation Blocks
If a block is the top-level block for code generation, it needs a special treatment: parameter modifications in that block should not be lost by stripping them away.To achieve that without requiring a special case treatment in the preceding translation step, a fresh block that instantiates the top-level block with normalized instance modifications is inserted for every block.Hence, block C (line 35-39) would introduce the fresh block:

Normalized mACG-Modelica
After the normalization all component dot accesses are extracted from nested expressions.All "connectequations" are resolved.At instance declarations all available parameters are set as modifications.In a block that instantiates another block, any output of the instantiated block is at least accessed once.The syntax of normalized mACG-Modelica is defined by the following grammar:

The Translation
After normalization (Section 3.4), the model is available in the normalized mACG-Modelica language (Section 3.5).This form allows a more straightforward translation to the SDFK language (Section 3.1) which will be described in the following sections.Any normalized mACG-block is directly mapped to an SDFK node -no context information from surrounding blocks is needed.

Intuitive Translation
Inputs, Outputs, Parameters without Modification, and Initialized Delays Inputs and parameters without modification bindings are mapped to node input arguments.Outputs are mapped to node return values.A lexicographic order relation on node input and output arguments ensures an unambiguous mapping.

Formal Translation Semantics
This section defines the translational semantics for the normalized mACG-Modelica language.Hence, semantics of modeling constructs in normalized mACG-Modelica are expressed in terms of constructs from the SDFK language.
Frequently, elements e i are tuples (e.g., e i = (x i , t i )).Especially if tuples encode variable names and their associated types an alternative notation is preferred in which "," is replaced by "∶" and the parentheses are dropped (e.g., e i = x i ∶ t i ).The underscore " " is used as a placeholder for entries which are irrelevant in the specific context.

Mutually
recursive functions "Function (context) (element)" are used for defining a transformation of an element within a context.To keep the notation concise the definition of a function is often overloaded -its actual interpretation should be clear from the context.
Additionally, the transformation relies on a suitable lexicographical order relation "< L " to allow an unambiguous ordering of node input and output arguments (see Figure 13 on page 43).
Translation Equations The function T (.) in Figure 3 defines the translation of a block from the normalized mACG-Modelica language to the SDFK language.Note that the translation is performed block-by-block, without requiring a context of global block declarations as it was required during normalization.
The function CEq creates an auxiliary representation structure d, i, o, l, s, j, q by traversing equations D and using an accumulator initialized by the function CId.The function CId is similar to CEq, but it traverses the block's instance declarations P and starts with all elements of the accumulator being set to the empty list [].The auxiliary structure is then directly used in the translation T or further processed by translation functions TEqList and TCList and their supporting functions TE and TC (all described later).
stands for an environment of variables with start values (e.g., state variables).
is an environment to collect information of non primitive class instances (i.e., block components).c i denotes the component name, t i its type (i.e., the block declaration's name).ci i = [u 1 ↦ e 1 ; . . .; u n ↦ e n ] contains the input variables of c i .Each u i denotes the name of an input variable and e i is the expression bound to that variable.Similarly, co i = [y 1 ↦ x 1 ; . . .; y n ↦ x n ] contains the output variables of c i .Each y i denotes the name of an output variable and x i is a local variable bound to that output variable.
q = [x 1 = e 1 ; . . .; x n = e n ] stands for a list of equations, where x i is a variable or parameter name and e i is an expression.
Most of the function CId (defined in Figure 4) is rather straightforward.It seems worth mentioning that a parameter with a bound expression is added as equation to q while a parameter without a bound expression is added as input to i.The parameter modifications (m 1 = e 1 , . . ., m n = e n ) in component declarations are mapped to input variables with their respective bound expression in the block components environment j ([m 1 ↦ e 1 ; . . .; m n ↦ e n ]).
Function CEq (defined in Figure 5) adds equations from a block to q, unless the equation includes a component dot access.In that case the block components environment j is modified and the equation is either mapped to the inputs ci or outputs co bindings of that component.
Once CEq returns the auxiliary representation struc-Translate list of equations into SDFK equations: ) (e 1 ) and . . .and Translate list of block instance contexts into SDFK equations with node instantiations: and TCList (d,s) (j) Figure 3: Translation from the normalized mACG-Modelica language into the SDFK language.The translation function T(.) utilizes functions CId (defined in Figure 4) and CEq (defined in Figure 5) to create auxiliary structures d, i, o, l, s, j, q which are further used in the translation functions TEqList and TCList and their supporting functions TE (defined in Figure 6) and TC (defined in Figure 7).
ture d, i, o, l, s, j, q, the elements i, o, and l translate (after applying SortList to i and o) directly to an SDFK node signature and its local variable declarations.Equations gathered in q are translated to SDFK equations by function TEqList, which in turn applies TE to each RHS expression in q.Function TE (defined in Figure 6) translates mACG-Modelica expressions into SDFK expressions.

Translator Implementation
A concrete translator was implemented using the Scala programming language Odersky et al. (2010) and the Kiama language processing library Sloane (2011).
The translator is structured in three main components: Parser Lightweight parser implementation using Scala's parser combinator library (extended by additional functionality provided by the Kiama library).
Transformation Implementation of the presented multilevel translation approach.Taking advantage of where and os = (x 1 , . . ., x n ) where the functional nature of Scala allows a rather direct and lean implementation.
Emitter Emitters to the SDFK language defined in Section 3.1 and to Lustre code.The emitter component utilizes the functional pretty printing combinators provided by the Kiama library.
The SDFK output is not executable and needs to be checked statically (currently by manual inspection).The Lustre output allows taking advantage of the software infrastructure that is available around Lustre.Particularly, using Lustre as intermediate presentation, allows to generate executable C-code utilizing Verimag's Lustre V4 Toolbox9 .This C-code can be used for dynamic testing.The translator supports that by allowing to generate appropriate Modelica code adapters ("C code wrapper blocks") that provide an interface from Modelica to the generated C code (using Modelica's external function interface).These wrappers can be directly loaded into Modelica simulation environments, enabling convenient back-to-back testing.
Note that the presented translation differs significantly from typical Modelica code generation as described in Section 2.3.Hence, a completely new translator implementation was needed to allow experimenting with the new approach.

Example
This section aims to present a short, yet still illustrative, example of how ACG-Modelica can be used for modeling practical relevant control functions.The example is presented in the context of a control design for an electric drive system.However, it is focused on one particular aspect: The digital realization of a practical proportional-integral-derivative controller (PID controller).

PID Controller Realization
PID controllers constitute the most widespread control loop feedback mechanism used within industrial practice.Hence, they can be considered the "bread and butter" of control engineering.The "textbook" equation for a PID controller is where y(t) is the controller output signal (≡ actuator input signal), e(t) = u s (t) − u m (t) is the error between set-point signal u s (t) and measurement signal u m (t), k is the proportional gain of the controller, and T i and T d are the integral-and the derivative time constants.However, practical implementations are more elaborate than this.For example, the Modelica Standard Library contains a continuous-time model of a PID controller (library path of the model: Modelica.Blocks.Continuous.LimPID) which incorporates several aspects of practical PID controller design which are described in ( Åström and Hägglund, 1995, Chapter 3), namely limited controller output, anti-windup compensation and set-point weighting.
The following PID controller equation incorporates set-point weighting and accounts for the fact that practical implementations use a modified derivative ("D") term which is more robust against high-frequency content in the controller input signal (a typical source of high-frequency content is measurement noise).The controller equation is given in its Laplace transformed form using s as Laplace variable: The "D" part of the controller is approximated by , where N d limits the gain at high frequencies (typically: 3 ≤ N d ≤ 20).Set-point weighting is provided by parameters w p and w d and allows to weight the set-point in the proportional and derivative part independently from the measurement.
A digital implementation requires a discrete-time representation.Following the example in ( Åström and Wittenmark, 1997, Listing 8.1) the discretization is performed by using forward differences10 for the integral term and backward differences11 for the derivative term.A valid Z-domain representation for the integral term is therefore where z is the Z-transform variable and h is the sampling period.The Z-domain representation is commonly used in the area of digital control systems or digital signal processing.Such a representation can be conveniently mapped to ACG-Modelica code by the substitution rule xz −1 → previous(x).Hence, a corresponding Modelica equation for Equation ( 4) is: The implementation of the derivative part follows in an analogous way.
Figure 8 shows the complete digital PID-controller model.Its structure (Figure 8a) is similar to the continuous-time version provided in the Modelica Standard Library, the parameters (except for sampling period "h") are the same as in the continuous-time version so that parameters found for the continuous-time PIDcontroller can be directly reused in the digital version (Figure 8b).
Anti-windup compensation is provided by an internal feedback loop which uses an error signal formed from the difference between the output of an actuator model (here the actor is modeled by a simple output limiter "limiter") and the output of the controller (i.e., the output of gain "gainPID") in order to drive the integrator to a value which makes the error signal equal to zero.This mechanism is identical to the one implemented in the continuous-time MSL version.Note that setting parameter Td = 0 will give a controller with PI controller characteristics.

Code Generation and SIL Validation
Figure 9 shows a Software-in-the-Loop (SIL) configuration in which the PID controller from Figure 8 was translated to C code (using the tool chain described in Section 3.7) and imported back into Modelica by using Modelica's external C function interface.The generated C code is encapsulated in the "wrapper" block "sILPI".The digital PID block from Figure 8   The generated code is interfaced to the model by using a "wrapper" block ("sILPI").For direct comparison, the original digital PID model (see Figure 8) is included as component "digitalPI".
direct comparison of "model" vs "software".The PID block regulates the speed of the DC permanent magnet machine "dcpmMotor".The block is configured as a PI controller (Td = 0), and the time constant of the integral part is set to a value that compensates the largest time constant of the motor model.The controller gain "k = k C " is provided as an input to the "software wrapper" block (the translation in Section 3.1 maps Modelica parameters to SDFK node inputs).Besides the top-level parameters "k_C" (controller gain) and "h" (sampling period for "periodicClock") the model has a parameter record component "p" which contains parameters for the motor model.The block "saturation" limits the actuator output to ±24 V.The sample element "sample1"has an additional input for a clock signal.Its origin is block "periodicClock" that defines a sampling period of h = 0.001 seconds.The hold element "hold1" implements a zero-order hold element.Hence, the digital control parts of the model will be executed with a sampling period of h = 0.001 seconds, while the physical parts are simulated as continuous-time systems.The blocks stem from the Modelica Synchronous library12 which is described in (Otter et al., 2012).
Figure 9  the control performance cannot be improved arbitrarily by increasing the controller gain k C .
Figure 11 shows a plot of the relative error between the output of the "controller software" encapsulated in the "wrapper" block "sILPI.y"and the output of the digital PID model "digitalPI.y".The difference 0 0.01 0.02 0.03 0.04 Figure 11: Relative error between the output of the "controller software" (i.e., code using the tool chain described in Section 3.7) and the "controller model".
between the "software" and the "model" stays within reasonable bounds.For k C = 0.3 the actuator output is at its limits at the start and the anti-windup compensation with its associated equations is active.At t = 0.005 s the actuator output is close to zero and changes its sign for one tick, hence the sign change in the relative error.

Summary
The example demonstrates that the ACG-Modelica language subset is expressive enough in order to model a practically relevant digital control function.It furthermore indicates how Modelica allows to integrate such discrete-time control models seamlessly with physical models from the continuous-time domain.Modelica tools' support for hybrid models is based on solid mathematical foundations as well as long-term practical experiences in hybrid systems simulation.Hence, a model-based development process leveraging Modelica technology extended with high-integrity production code generation can be an attractive and powerful approach for the development of cyber-physical systems.

Discussion
The foregoing discussion is based on a rather restricted subset of the Modelica language.This allows to keep the scope of the translation within manageable bounds and keeps the language simple and well-defined.The considered subset is neither arbitrarily chosen nor without alternatives -this section comments design decisions and possible extensions.

Design Decisions
Languages restrictions and extensions for safetyrelated control applications in Modelica have been discussed in (Thiele et al., 2012).The mACG-Modelica subset is guided by the same considerations, but at the same time, the translation effort has also given additional insight.This section will briefly highlight important points that motivated the subset.

Clocked Variables
In the mACG-Modelica subset all variables are considered to be clocked variables.Clocked variables were introduced in Modelica 3.3 to improve the support for sampled-data systems.They provide improved modeling safety since the clock calculus ensures that only variables that are on the same clock (are active at the same time instant) can be combined in expressions (otherwise explicit clock conversion operators are needed).Previous Modelica support for sampled-data systems had an automatic sample and hold semantics for discrete-time variables so that this temporal correctness property could not be checked automatically by a compiler.

Causal Data-Flow without Algebraic Loops
Modelica is based on (acausal) equations.Hence, "a*b = c" is a valid gather and symbolic processing of the equation system (see Section 2.3) will transform the equation as needed.If symbolic processing identifies "b" as the unknown variable the equation will be transformed into the assignment "b := c/a".This is very convenient and powerful when modeling the physical part of a system, since physical "textbook" equations can be mapped naturally and directly to Modelica code.However, it can be problematic for (safetyrelevant) digital control function modeling since symbolic transformations interfere with the ability of the developer to tightly control the evaluation of expressions.The transformation above is potentially harmful if "a = 0" cannot be excluded.It is conceivable to safeguard performed symbolic transformations, however, a simple solution is to only allow causal data-flow equations for the digital control part.This is the design decision used for the mACG-Modelica subset in which the left-hand side of an equation must be the unknown variable of that equation.Additionally, these data-flow equations may not contain algebraic loops.Solving algebraic loops needs (potentially unbounded) numerical iteration, which is not compatible with the hard realtime constraints of control applications.

Modular Code Generation
Modular code generation is understood identical to Biernacki et al. (2008) that define it as "producing a transition function for each block definition and composing them together to produce the main transition function".Support of modular code generation has considerable advantages: it facilitates to generate code that can be treated just like handcrafted code (e.g., in order to pass generated code into a standard assurance process if the level of tool qualification is not sufficient for the development project at hand), it helps to establish a good traceability between model and generated code, it may decrease the size of the generated code, since a transition function that corresponds to a block can be reused for all instances of the block, it allows separate compilation of blocks which, on one hand has positive effects on the scalability of the development process and on the other hand allows to distribute modules without source code in order to protect intellectual property.
Modular code generation is known to impose stronger causality constraints when sorting the equations (see (Biernacki et al., 2008)).Hence, design trade-offs become necessary, e.g., one might want to use modular code generation for high-level, highlycohesive blocks, but not for basic arithmetic blocks.There are also approaches to modular code generation which impose less (or none) additional causality constraints.Lublinerman et al. (2009) provide a good discussion of the involved trade-offs and also present an alternative approach to modular code generation.
It is important to understand that the translation to the synchronous data-flow kernel language enables a straightforward path to modular code generation for Modelica, but it does not enforce a particular code generation approach.It is highly likely that an industryrelevant code generator would support modular code generation as a "per block" option and delegate necessary trade-off decisions to the developer.

Simplified Modifications
Modifications handling in Modelica is rather complex ( Åkesson et al. (2010) provide a good exposition of the challenges).Modifications allow to change aspects of a block/class (e.g., parameter values) at instance declarations of that block/class.The difficulty lies in the possibility to nest modifications over several instance levels, e.g., "a(b(c=2))".In mACG-Modelica modifications must not be nested, e.g., "b(c=2)" is allowed, but not "a(b(c=2))".
This reduces the language complexity and is also advantageous with respect to modular code generation.The presented translation maps parameters to SDFK node inputs which means that a node that instantiates another node has to be aware of all the applicable parameters.Using this approach, supporting several levels of modifications would require to collect all applicable parameters of instantiated nodes and propagate them through by introducing them as additional inputs to the enclosing node.As a result node signatures (and consequently also function signatures of generated modular code) would grow significantly.Having simplified modifiers in the language keeps the size of node signatures within acceptable bounds.
Furthermore, restrictions on nesting modifications can be considered as beneficial in terms of code readability on the Modelica level -hence, restricting it (arguable) enforces a better modeling style.

Applicability to Extended Language Subsets
The multilevel translation approach presented in Section 3.3 allows adding new language elements in a way that keeps the lower level language representation untouched.This is thus an attractive way to further extend the considered language scope as long as a sourceto-source transformation into a smaller kernel language can be given.Essentially, a design trade-off needs to be made.On one hand the language should be as simple and well defined as possible to keep qualification efforts under control, but on the other hand control function developers need a sufficiently expressive modeling language in order to work efficiently.

Data typing and Hierarchical Scoping
Data typing and hierarchical scoping using package declarations has been left out of the discussion.Data typing is rather similar to typical general purpose languages and its discussion is considered to be out of scope of this work.The extension of the language with packages should be feasible by introducing an additional step to the aforementioned multilevel translation approach.

Multirate Control Systems
A more distinctive omission is the absence of clock conversion operators -hence, the considered language subset does not allow to model multirate systems.This is not as restrictive in practice as it may seem at first sight.Typically, generated code from behavioural models is integrated into an existing software architecture that handles non-functional aspects like communication and scheduling (see Figure 1).Linking the timely start of generated code sequences to activation events (e.g., hardware timer interrupts) becomes therefore a responsibility of the software integration phase.In effect, this allows assigning different activation events to different code generation models during software integration and thus enables multirate systems.
Figure 12 illustrates this aspect on the basis of a multirate cascade control system for a very simple drive system.The objective is that the load inertia "load" follows the reference angle given by block "reference".The discrete-time controllers are connected to the Note, that the rate-conversion elements ("subSample1", "super") and the clock are considered to be part of the Plant Model.Hence, it is not essential that the qualified code generator supports that elements.continuous-time model parts by sample and hold elements.Sampling elements "sample1" and "sample2" have an additional input for a clock signal.The clock signal defines the activation instants of the controller blocks.Its origin is block "periodicClock" that defines a sampling period of 0.02 seconds.The rate transition element "subSample1" converts that sampling rate to 0.1 seconds.Hence, the inner speed control loop is faster than the outer position control loop.Element "super" provides slow-to-fast rate transition between the two controller blocks.The utilized rate transition and clock blocks stem from the Modelica Synchronous library.Otter et al. (2012) describe that library in detail.
While the complete multirate system can be modeled and simulated in Modelica, a qualified code generator would not need to support the rate-conversion elements: block "slowController" and "fastController" can be translated separately into sequential code and activation and rate-conversion can be offloaded to the software integration phase.Also note that clock "periodicClock" is not part of the code generation model, it is also considered to be part of the plant model.Hence, the omission of clock conversion operators in the behavioral model for code generation does not prohibit multirate models on the global system level.

Inheritance
Inheritance is not supported in the language subset.A full support of Modelica's multiple inheritance (including its related modification and redeclaration) features would increase the language complexity considerably and therefore complicate tool qualification efforts.However, extending the subset with a restricted support of inheritance seems quite feasible.

State Machines
Control application often consists of both: data-flow parts that are naturally described with block diagrams and system logic parts which are described more naturally using state machine formalisms.Modelica 3.3 introduced state machines with a comparable modeling power as Statecharts (Harel, 1987) as built-in language elements (Modelica Association, 2012, Chapter 17).Extending the presented translation with support for state machines is desirable, but is a challenge on its own.

Conclusions
Despite its suitability for integrated modeling and simulation of multi-domain physical systems and sampleddata systems, the use of Modelica for embedded systems development was so far limited.A model-driven development process for embedded systems is so far impeded by the lack of tools for qualifiable automatic code generation from Modelica.
To mitigate that deficiency this article presented a translational semantics of a Modelica subset for control applications to a synchronous data-flow kernel language.The synchronous data-flow kernel allows to resort to published and well-established compilation techniques which are accepted by certification authorities.
In addition to the formal translation a concrete prototype translator was implemented.The translator additionally supports emitting Lustre code for which the software infrastructure around Lustre can be leveraged.This demonstrates that the translation equations can also serve as a base to create a gateway from Modelica to established tools based on synchronous data-flow.
Enabling the proposed approach requires suitable design decisions regarding the supported Modelica subset.The necessary trade-offs that resulted in the considered data-flow based language subset for control application have been exposed and possible extensions have been discussed.Particularly, extending the subset with a state machine formalism seems a desirable task for the future.
The presented translation to a synchronous dataflow kernel language opens up new paths towards a qualifiable automatic code generator for Modelica that can directly utilize well-accepted methodology and technology for high-integrity software development.

B.2. Modification and Dot Access Normalization
This normalization step includes the stripping of parameter modifications, the normalizing of component modifications and the extraction of component dot accesses appearing in expressions.As previously, it is defined as a source-to-source transformation through a set of mutually recursive functions.The translation makes use of a couple of auxiliary functions defined in Figure 16.A notable complication of the name decoration function dn (D,p) (x) in Figure 16 is that it may be used at places there it is required that the decorated name introduces a fresh variable -i.e., a variable of the same name must not already exist in its scope.To ensure that a fresh name is introduced one may provide a set of names D which are forbidden as a result of name decoration.The second equation in Figure 16 handles cases in which the resulting name would be in D by prefixing an additional " " to the name until the resulting name is not any longer in D.
Function N(D) at the bottom of Figure 17 defines the translation from the mACG-Modelica language into the normalized mACG-Modelica language.This is achieved in three steps: 1. Creation of an auxiliary representation structure C = NCenv [] (D) (defined in Figure 18) which encodes the mACG-Modelica block declarations "D" in a structure that facilitates the normalization transformation in the subsequent step, end id; x -internal input, y -internal output: GTd Extract names from lists of parameters, variables or (non-primitive) instance declarations: Join a list of declarations using ";" as separator: Figure 16: Auxiliary functions for the normalization.
2. application of the normalization transformation to the auxiliary structure, C N = NormC(C) (defined in Figure 19 and discussed in more detail later), and finally 3. output of the auxiliary structure as normalized mACG-Modelica using function NdeclList(C N ).
The auxiliary representation structure C = [(b 1 , p 1 , m 1 , r 1 , q 1 ); . . .; (b n , p n , m n , r n , q n )] is a list of block class declarations within the (global) environment.b i is a class declaration name.
is the list of parameter declarations of block b i with their respective type t i and an optionally bound expression e i .The case that no expressions is bound to a parameter e i is denoted by the symbol (e.g., x ∶ t ∶ ).
is the list of (non-primitive) class instances appearing in block b i , where c i denotes the instance name, t i denotes the respective type, and cm i = [x 1 = e 1 ; . . .; x n = e n ] is the list of respective class modifications.
r i is partitioned into the tuple is the list of outputs from block b i with their respective primitive types, and l = [l 1 ; . . .; l n ]) is the list of all local class declarations of primitive type in block b i , except for parameter declarations (i.e., the list includes input, output and local variable declarations).
q i = [x 1 = e 1 ; . . .; x n = e n ] is the list of equations declared in block b i .Function NormC in Figure 19 performs the actual normalization transformation on the auxiliary block representation structure C constructed in function NCenv (see Figure 18).It applies functions NB and NbInst to each block.The translation differs depending on whether a block is used as instance in another block, or whether a block is used as the top-level instance.Although the final program will have only one top-level instance, function NormC always creates two versions of a block: One version that is used if the block is used as instance in another block (using function NB) and one version that is used if the block is used as top-level instance (using function NbInst which is described in more detail in Section B.3).
Function NB first strips all parameter modifications from a block using the auxiliary function NBstrip.This is necessary, because the parameters of a block will later be transformed to node inputs in the SDFK language Na (b,p,m,r,q) (x = e) = (b, p, m, r, q + [x = e]) where t ∈ B Na (b,p,m,(i,o,l),q) (t x) = (b, p, m, (i, o, l + [t x]), q) where t ∈ B Na (b,p,m,(i,o,l),q) (t x(start = v)) = (b, p, m, (i, o, l + [t x(start = v)]), q) where t ∈ B NCdec (b,p,m,r,q) (d; ) = Na (b,p,m,r,q) (d) 3) to each block.Function NB uses NBstrip to remove parameter modifications, NBm (defined in Figure 20) to normalize component modifications, NBq (defined in Figure 21) to extract and normalize dot accesses appearing in RHS expressions and NBo (defined in Figure 22) to add "dummy" equations for component outputs that are not accessed.
which resemble function arguments.Therefore, the parameters of a block need to be set at the place there the block/node is instantiated and not within the block itself.
After that, function NB uses function NBm (defined in Figure 20) to normalize component modifications for every component instantiated in the current block.NBm first extracts all parameters from the component's block definition and introduces them as new (decorated) parameters in the block enclosing the component declaration.During that process it needs to be ensured that component modifications applied in the enclosing block replace parameter modifications in the component's block definition.In order to ensure that any component dot access c.a is uniquely associated to exactly one equation x ca = c.a it is checked whether an equation association x ca = c.a already exists -if so, the variable x ca is reused and no fresh variable is introduced.
And finally function NB applies function NBo (defined in Figure 22) to add "dummy" equations for component outputs that are not accessed in in the instantiating block.This is necessary, since after normalization it is required that all outputs of a component actually have a binding equation in a block that instantiates the component.Hence, function NBo first extracts all RHS component dot access variables that appear in the block equations for the respective component.

B.3. Top-Level Block Instantiation
For any block declaration with name m in mACG-Modelica, function NbInst, defined in Figure 23, creates a fresh block with its name decorated by the string "Inst".The fresh block duplicates inputs and outputs of the instantiated block m and adds equations to connect its inputs and outputs to the inputs and outputs of m.
As a last step it calls function NBm (see Figure 20) on the freshly constructed block.That call ensures that parameter modifications in the block definition of m are applied at the created instance of m and that parameters in m that have no binding modification are introduced as parameters (likewise with no binding modifications) in the fresh block.Note that parameters that have no binding modification will be turned to additional node inputs in the subsequent translation to the SDFK language (see Section 3.6).

Figure 1 :
Figure 1: The generic build process for a modelbased development toolchain with an automatic code generator (adapted from Schneider et al. (2009)).

Figure 2 :
Figure2: Outline of a typical compilation and simulation process for a Modelica language tool(Broman, 2010, p. 29).

td
∶∶= type t; bd ∶∶= block id p equation D end; cd ∶∶= connector id = c t; c ∶∶= input output p ∶∶= p p t x; t x mo; c t x; c t x mo; parameter t x; parameter t x = me; mo ∶∶= (ar , . . ., ar) ar ∶∶= id = me D ∶∶= D D eq; 2. Parameters, Instance Modifications, and Dot Accesses Parameter Stripping Parameter modifications in a class are stripped away.block PI parameter Real kd = Td *2; parameter Real Td = 0.1; end PI; source ↧ normal block PI parameter Real kd; parameter Real Td; end PI; _pi_kd = _pi_Td *2; 44 parameter Real _pi_Td =Td; 45 PI pi(kd=_pi_kd , Td= _pi_Td ); 46 end C; Extraction of dot accesses Instance dot accesses in RHS equations are extracted and replaced by fresh substitute variables.
Inputs and outputs of a block are simply propagated through, e.g., block D (line 47-53) would introduce the fresh block: td ∶∶= type t; d ∶∶= block id p equation D end id; c ∶∶= input output p ∶∶= p p t x; t x mo; c t x; c t x mo; parameter t x parameter t x = e; mo ∶∶= (ar , . . ., ar) ar ∶∶= id = e D ∶∶= D D eq; e ∶∶= v x op(e, . . ., e) previous(x) if e then e else e eq ∶∶= x = e x .x = e x = x .x x ∶∶= id v = value id = identifier previous (x) + u/Td; 9 y = kd*(x + u) 10 end PI; normal ↧ sdf k 11 node PI (Td:real , 12 kd:real , 13 u:real) = 14 y:real with 15 var x:real in 16 x = 0 fby x + u/Td 17 and y = kd*(x+u) Parameters with Modification Parameters with modification bindings are mapped to local variables and equations.Instance Modifications and Dot Access Instance modifications and instance dot accesses are mapped to function application like node instance calls.

Figure 7 :
Figure 7: Function TC-Translate component dot accesses to an SDFK equation with an RHS SDFK node instance.
Figure9shows a Software-in-the-Loop (SIL) configuration in which the PID controller from Figure8was translated to C code (using the tool chain described in Section 3.7) and imported back into Modelica by using Modelica's external C function interface.The generated C code is encapsulated in the "wrapper" block "sILPI".The digital PID block from Figure8is shown on the right side.It is fed with the same inputs as the "sILPI" block and is included in the model to allow a

Figure 8 :Figure 9 :
Figure 8: Digital PID controller with limited output, anti-windup compensation and set-point weighting.

Figure 10 :
Figure 10: Step response of SIL model (with DCPM engine model and actuator saturation) for different controller gain values k C .

Figure 12 :
Figure 12: Multirate cascaded control loop with Code Generation Models.Note, that the rate-conversion elements ("subSample1", "super") and the clock are considered to be part of the Plant Model.Hence, it is not essential that the qualified code generator supports that elements.

Figure 13 :
Figure 13: Lexicographical order relation and function SortList-Auxiliary relation and function for arranging node input or output arguments in alphabetical order.The elements of the list xs have the structure name ∶ type.They are sorted by a suitable lexicographical order relation on name.

Figure 15 :
Figure 15: Function GTd-Replace connect-equations by equations of the form "x = e".

NBm
Figure 20: Function NBm-Normalize component modifications.All parameters from the modified component are extracted from the component's block definition and are introduced as fresh (decorated) parameters in the block enclosing the component declaration.During that introduction it is ensured that the components modification replace the parameter modifications from the component's block definition.
Figure22: Function NBo-Add "dummy" equations for component outputs that are not accessed in the instantiating block.Normalization requires that all outputs of a component have bindings to equations in the block that instantiates the component.

Table 1 :
Expressions in SDFK t 1 ; . . .; x n ∶ t n ] stands for a list of declarations within the scope, i = [x 1 ∶ t 1 ; . . .; x n ∶ t n ] stands for a list of input argument declarations, o = [x 1 ∶ t 1 ; . . .; x n ∶ t n ] for a list of node output argument declarations, and n = [x 1 ∶ t 1 ; . . .; x n ∶ t n ] for a list of local declarations (note that d