• Aucun résultat trouvé

Building a Hybrid Systems Modeler on Synchronous Languages Principles

N/A
N/A
Protected

Academic year: 2021

Partager "Building a Hybrid Systems Modeler on Synchronous Languages Principles"

Copied!
24
0
0

Texte intégral

(1)

HAL Id: hal-01879026

https://hal.inria.fr/hal-01879026

Submitted on 21 Sep 2018

HAL is a multi-disciplinary open access archive for the deposit and dissemination of sci- entific research documents, whether they are pub- lished or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.

L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.

Languages Principles

Albert Benveniste, Timothy Bourke, Benoit Caillaud, Jean-Louis Colaço, Cédric Pasteur, Marc Pouzet

To cite this version:

Albert Benveniste, Timothy Bourke, Benoit Caillaud, Jean-Louis Colaço, Cédric Pasteur, et al.. Build-

ing a Hybrid Systems Modeler on Synchronous Languages Principles. Proceedings of the IEEE, In-

stitute of Electrical and Electronics Engineers, 2018, Design Automation for Cyber-Physical Systems,

106 (9), pp.1568 - 1592. �10.1109/JPROC.2018.2858016�. �hal-01879026�

(2)

Building a Hybrid Systems Modeler on Synchronous Languages Principles

Albert Benveniste , Timothy Bourke †§ , Benoît Caillaud , Jean-Louis Colaço , Cédric Pasteur and Marc Pouzet ¶§†

∗ Inria, Campus de Beaulieu, 263 Avenue Général Leclerc, 35042 Rennes. Email: Firstname.Name@inria.fr

† Inria, 2 Rue Simone IFF, 75012 Paris. Email: Timothy.Bourke@inria.fr

‡ ANSYS/Esterel-Technologies, 9 Rue Michel Labrousse, 31100 Toulouse. Email: Firstname.Name@ansys.com

§ École normale supérieure, PSL University, 45 rue d’Ulm, 75230 Paris. Email: Marc.Pouzet@ens.fr

¶ Université Pierre et Marie Curie, Sorbonne Université, 4 Place Jussieu, 75005 Paris

Abstract—Hybrid systems modeling languages that mix dis- crete and continuous time signals and systems are widely used to develop Cyber-Physical systems where control software interacts with physical devices. Compilers play a central role, statically checking source models, generating intermediate representations for testing and verification, and producing sequential code for simulation and execution on target platforms.

This paper presents a novel approach to the design and im- plementation of a hybrid systems language, built on synchronous language principles and their proven compilation techniques.

The result is a hybrid systems modeling language in which syn- chronous programming constructs can be mixed with Ordinary Differential Equations (ODEs) and zero-crossing events, and a runtime that delegates their approximation to an off-the-shelf numerical solver.

We propose an ideal semantics based on non standard analysis, which defines the execution of a hybrid model as an infinite sequence of infinitesimally small time steps. It is used to specify and prove correct three essential compilation steps: (1) a type system that guarantees that a continuous-time signal is never used where a discrete-time one is expected and conversely; (2) a type system that ensures the absence of combinatorial loops; (3) the generation of statically scheduled code for efficient execution.

Our approach has been evaluated in two implementations: the academic language Zélus, which extends a language reminiscent of Lustre with ODEs and zero-crossing events, and the industrial prototype Scade Hybrid, a conservative extension of Scade 6.

I. I NTRODUCTION

Hybrid systems modeling tools [1] like Simulink

1

are widely used in the development of embedded systems. They have evolved progressively from interfaces to numeric solvers aimed solely at simulation to fully fledged languages for programming executable models of dynamical systems that comprise control software and models of its physical envi- ronment [2]. Models are not only simulated; they are tested, debugged, and verified, from the early stages of the design, and right along the development chain, until the automatic gener- ation of embedded target code. In state-of-the-art methodolo- gies, compilers statically check source models, produce inter- mediate representations used by testing and verification tools, and generate sequential code for either efficient simulation or execution on target platforms. The various compilation steps can be tricky to design and implement. How can we ensure

1

https://www.mathworks.com/products/simulink.html

that they are semantics preserving, that there is no need to program and verify things twice [3]?

In this paper, we focus on the design, semantics, and implementation of such languages, following the viewpoint that “hybrid modeling languages are programming languages that happen to have a hybrid systems semantics” [4]. We focus on modeling with Ordinary Differential Equations (ODEs) and do not consider Differential Algebraic Equations (DAEs).

A Programming Language view of Hybrid Systems Modeling Hybrid systems modeling languages present several new dif- ficulties compared to general purpose programming languages.

The first difficulty is that correctness cannot be defined as the perfect match of an implementation with a specification when part of a model represents a physical device or system rather than a software component. Approximations are gener- ally unavoidable. They result from a lack of exact knowledge of the physical system or from the need to consider simpli- fied models. The science of physics and control engineering treats the important question about the fidelity of a model with respect to the real world [5]. We address solely here programming language issues.

While approximations are unavoidable, they should not arise from artifacts of the modeling tool. It is essential that the simulations of a given model be reproducible both within a single tool and across different tools. Modeling should therefore rely on a modeling language equipped with a mathematical semantics, i.e., an unambiguous and preferably simple definition of what a given model means, and when its semantics is defined. It must be possible to check model executions against their semantics.

The second difficulty is the gap between an ideal math- ematical semantics and the numerical behavior of a model.

This gap is due to approximation schemes for differential equations and state events and cannot be avoided in general.

One solution is to incorporate details of the simulation engine, and even particular solvers, into the semantics of models [6].

The integration scheme and simulation machinery can be

hardwired into the hybrid model to give a purely discrete

model [7], possibly through a synchronous encoding [8]. It

is also possible to generate a synchronous program, replacing

differential equations by difference equations and state events

(3)

by edge detection. But these approaches burden the semantics with low-level details and make it more complex. It becomes difficult to distinguish the properties of the model itself, which should be independent of a particular solver or integration scheme. Furthermore, solvers require certain invariants in order to give reliable results. For example, the function to be integrated must be continuous and the function for state event detection must be continuously differentiable—both properties that are easily broken (e.g., by importing a function containing a conditional, modulo operator, or side effect). A concrete semantics complements but does not replace an ideal one, that is independent of a given solver. An ideal semantics is enough for proving that compilation steps are semantics preserving and for statically ensuring certain invariants, e.g., that functions to be integrated are continuous and free of side effects.

One final difficulty of hybrid systems modeling languages is the multiplicity of language constructs. These languages offer the expressiveness, and thus the complexity of a general purpose language to which it adds parallelism and the mix of discrete and continuous-time signals together with a numerical solver for their simulation: models mix stream equations, ODEs, zero-crossing events, hierarchical automata, and also side effects, loops, different forms of modular composition, for instance subsystem blocks, and calls to external functions produced by other tools. Moreover, all of these features can be composed in parallel.

While this expressiveness is unquestionably useful for writing real applications, the undisciplined composition of language constructs leads to fragile and ‘unsafe’ models [9]

that are difficult to understand modularly and debug because the behavior of a block can change dramatically when other unconnected blocks are added in parallel. Problems can arise, for instance, in the intricate interactions between discrete and continuous-time: when a continuous-time signal is used where a discrete-time signal is expected and vice versa [10];

when a block explicitly refers to the internal time steps of the solver—the so-called major steps of Simulink solvers;

when a call is made during integration to a function that unexpectedly performs a side effect or is discontinuous; or when two parallel blocks write to the same shared variable.

Some of these situations are detected statically by tools and trigger errors or warnings, but not all of them. The static detection is not imposed as a type discipline: some unsafe models pass the static check while some safe ones do not.

The bottom line is that the complexity of actual hybrid systems modeling languages makes the definition of a comprehensive formal static and dynamic semantics difficult to achieve.

Far from being abstract philosophical concerns, these dif- ficulties have practical consequences. System design teams in industry do not like being confronted with unsafe mod- els. They often adopt restrictive programming disciplines by which some operators or certain of their combinations are prohibited [11], [12], [13]. Ensuring that such programming disciplines guarantee the absence of problems is not easy.

More importantly, this approach may be more restrictive than a mathematically sound acceptance or rejection discipline.

For the above reasons, we chose the following approach:

1) To identify a minimal language kernel of orthogonal programming constructs that is expressive enough to write realistic hybrid models;

2) to define a detailed static and dynamic semantics of the language and its compilation steps.

A Synchronous Approach to Hybrid Systems Modeling Synchronous languages [14] partly address the preceding questions but focus solely on discrete-time dynamical systems.

The synchronous abstraction is to consider that computations and communication occur instantaneously. This allows the mathematical definition of an ideal and simple semantics:

signals are modeled as stream, that is, infinite sequences of val- ues, that advance synchronously, and systems are modeled as functions over streams. Fidelity with respect to real-time con- straints is checked a posteriori by verifying that the worst case execution time of the generated code is less than the period of execution or the minimum inter-arrival time of triggering inputs. The expressiveness of synchronous languages has been purposefully tuned to ensure important safety properties. Their static semantics — the set of verifications performed by the compiler to characterize correct models — and their dynamic semantics — what is defined by the model — have been mathematically specified. In particular, compilers statically reject programs that are not proven to be deterministic and free of deadlocks, and generate sequential code that executes in bounded time and space. Such features contribute to the fact that S CADE [15],

2

an industrial synchronous language implementation, is now the reference for critical software development in civil avionics.

Nevertheless, synchronous languages do not adequately model or efficiently simulate systems that mix discrete- and continuous-time signals. This causes a break in the develop- ment chain, with one language for initial hybrid modeling and another for modeling control software, with the risk of mismatches and task duplications.

To address some of the above issues, we experimented with a new approach to the design, semantics, and imple- mentation of a hybrid systems modeling language that reuses and extends the principles and compilation techniques devel- oped for synchronous languages. As a basic language, we took a synchronous and purely functional language, in the style of L USTRE , and conservatively extended it with ODEs and zero-crossing events [16], and later adding hierarchical automata [17]. It allows modeling discrete- and continuous- time systems, and expressing their complex interactions. We introduced an ideal semantics based on nonstandard anal- ysis [10] that models executions as infinite sequences of infinitesimally short reactions. Programs must respect a strict typing discipline that forbids using a discrete-time signal where a continuous-time one is expected and vice versa, and also explicitly referring to the major steps of the solver; every side-effect and state change must be aligned with a zero- crossing [18]. Algebraic loops, which may lead to systems with zero or many solutions, are statically rejected [18].

Finally, programs are compiled into statically scheduled code

2

http://www.esterel-technologies.com/products/scade-suite/

(4)

that is paired with an off-the-shelf numerical ODE solver [19], namely S UNDIALS CVODE [20]. These results form the foundation of Z ÉLUS [21]

3

and the industrial prototype S CADE

H YBRID [19] based on S CADE 6 [15]. In the latter, it was possible to reuse all the existing infrastructure like static checking, intermediate languages, and optimisations, with little modification. The extensions for hybrid features require only 5% additional lines of code. Moreover, the proposed language extension is conservative in that classical synchronous features are compiled as before—the same synchronous code is used for both simulation and execution on target platforms.

The resulting language can be used at the specification and implementation stages, both to write a high level hybrid model of the whole system or to focus on a software component only whose embedded code will be automatically generated by the compiler. It can be used as a classical synchronous language, to write only discrete-time programs, without even knowing its hybrid features, and symetrically, as a simple interface language to write ODEs, without even knowing its syn- chronous features. More interestingly, software components can be programmed in a synchronous language and tested with a programmed model of the physical environment.It is also possible to start from an entirely continuous-time model, and to progressively replace some continuous-time systems by discrete-time ones or vice versa, within a single language and programming model. This combination allows for using continuous-time models (or discrete-time ones) where best suited, to write higher-level executable specifications, and to detect design bugs earlier.

The resulting language is not the composition of two distinct languages and compilers nor does it aggregate several models of computations, as Ptolemy [22] does, for instance. The pro- gramming constructs are those of a synchronous dataflow lan- guage, namely function definition and application, hierarchical automata, and data-flow equations. These constructs are ex- tended to support continuous-time systems. Static verifications like typing, causality analysis, and initialization analysis have been adapted and extended to apply to the whole language.

Finally, the generation of executable code is defined as a small extension to an existing synchronous language compiler.

Organization of the Paper

Section II presents fundamental issues in the design of languages that mix discrete and continuous time with a focus on semantic models. Section III treats an extended example:

a Newton’s cradle with two colliding pendulums. Section IV treats causality and scheduling. Section V develops the dis- tinction between discrete- and continuous-time signals and systems through a static type discipline. Section VI describes the run-time system, which delegates the simulation of con- tinuous dynamics to an off-the-shelf numerical ODE solver.

Section VII describes the architecture of the Z ÉLUS language and its compiler and reports on the experimental extension of S CADE 6 called S CADE H YBRID . We conclude with a discussion in Section VIII.

3

http://zelus.di.ens.fr

This paper follows a tutorial style. Technical details are found in the papers [10], [16], [17], [18], [19], [21], [23].

II. D ESIGNING CPS M ODELING L ANGUAGES

In this section we review and discuss some difficulties that arise as consequences of making hybrid systems modeling tools overly flexible and permissive. The main difficulties relate to the coexistence of continuous and discrete time in models. We develop our discussion using a minimal core of a hybrid systems modeling language, which includes data-flow equations over infinite sequences or streams, ODEs, a switch construct, and the possibility to hierarchically compose such elements in parallel to build libraries of predefined subsystems.

Models of this core language are written in the concrete syntax of Z ÉLUS (so the reader can experiment on their own) but they can easily be written in other languages, like, e.g., P TOLEMY

or Simulink. We illustrate issues using several small examples, but the goal is to accurately identify problems in larger, more complicated models.

Details related to the material of this section are found in [16], [18].

A. Mixing Discrete and Continuous Time

Let us begin with purely discrete-time or purely continuous- time systems. Following the tagged-signal model [24], a signal x is a function from a time domain T —a totally ordered set—

to a set of values. A deterministic system is a function from a set of input signals to a set of output signals. In a block diagram language, such functions can be defined by writing equations on signals: an equation (x = e), where x is a variable name and e is an expression, is an invariant (x = e)(t) that must hold at every time t ∈ T , that is, ∀t ∈ T , x(t) = e(t), where x(t) is the value of signal x at time t and e(t) is the value of expression e at time t. In expressions, external n-ary operations (e.g., arithmetic or boolean operations that apply pointwise), that is, (op(e

1

, . . . , e

n

))(t) = op(e

1

(t), . . . , e

n

(t)).

When E

1

and E

2

are two homogeneous equations, i.e., when they are defined on the same time domain T , the parallel composition E

1

and E

2

means

∀t ∈ T , (E

1

and E

2

)(t) = E

1

(t) ∧ E

2

(t). (1) The above definitions hold for any time domain T , like, for instance, the integers N = {0, 1, 2, . . . } or the non-negative reals R

≥0

. We illustrate it with two examples.

Discrete-time: Consider a linear filter defined as the com- position of two equations over signals:

let node filter(x) = y where rec y = 0.2 *. x +. s and s = 0.8 *. (0.0 fby y)

The keyword node declares that filter is a discrete-time

function. This node takes an input stream x and produces

an output stream y—by stream, we mean a discrete time

signal defined over time index N . The output is defined by a

recurrence equation; the keyword rec, for ‘recursive’, means

that the y on the left and right sides of the equations refers

to the same stream. The expression 0.0 fby y denotes the

(5)

unit delay applied to the stream y. If x = (x

n

)

n∈N

and y = (y

n

)

n∈N

are two streams:

∀n ∈ N

>0

, (x fby y)

n

= y

n−1

and (x fby y)

0

= x

0

. (2) The +. and ∗. stand for addition and multiplication of floating- point numbers. They apply pointwise to all stream elements.

The meaning of the two equations that define y and s is simply:

∀n ∈ N , y

n

= (0.2 ∗ x + s)

n

= 0.2 ∗ x

n

+ s

n

s

n

= (0.8 ∗ (0.0 fby y))

n

= 0.8 ∗ (0.0 fby y)

n

= 0.8 ∗ y

n−1

if n > 0

= 0.8 ∗ 0.0 = 0.0 if n = 0

Up to syntactic details, the linear filter can be written the very same way in L USTRE [25], [26] or S CADE 6 [15].

4

Continuous-time: The second example models a ball falling with initial height y0 and velocity v0 as two continuous-time equations composed in parallel.

let hybrid falling(y0, v0) = y where rec der v = -9.81 init v0

and der y = v init y0

This declaration defines the function falling with two inputs y0 and v0, and an output y. The keyword hybrid indicates that the function relates continuous-time signals. This function is readily expressed in any hybrid systems modeling language, e.g., Simulink

5

or P TOLEMY [27].

6

Its semantics, taking R

≥0

as the time domain, is:

∀t ∈ R

≥0

, v(t) = v0(0) + R

t

0

−9.81 dt = −9.81 t

∀t ∈ R

≥0

, y(t) = y0(0) + R

t

0

v(t) dt = y0(0) − 9.81 R

t 0

t dt Even though a numerical solver would compute a discrete approximation, i.e., two sequences (y

n

)

n≤max

and (v

n

)

n≤max

on increasing instants t

n

∈ R , with t

n

< t

n+1

up to some horizon t

max

, its exact solution is defined by an ideal solver semantics [28]. Besides the problem of relating the ideal se- mantics to a numerical approximation, these two homogeneous models, whether in discrete- or continuous-time, do not pose any particular difficulties.

Mixing discrete- and continuous-time: In contrast, consider now the two following hybrid models that blend discrete- and continuous-time domains:

der time = 1.0 init 0.0

and cpt = 0.0 fby (cpt +. time) (3) and;

cpt = 0.0 fby (cpt +. 1.0)

and der y = cpt init 0.0 (4)

The definition (1) for parallel composition and the application of n-ary operators no longer apply: in the first example, time is a continuous-time signal (its domain is R

≥0

) but cpt is expected to be a stream (its domain is N ) because the unit

4

The fby is a primitive operator of S

CADE

. In L

USTRE

, it can be replaced by the initialization operator -> and uninitialized delay pre with the property that x fby y =

def

x -> pre y.

5

der y = e init v

0

stands for y =

1s

(e) inititialized to v

0

in Simulink.

6

http://ptolemy.eecs.berkeley.edu/ptolemyII/

delay fby expects two streams. In the second, cpt is a stream but y is a continuous-time signal and cpt should also be continuous-time. Nothing in the model indicates how to relate the (logical) discrete-time domain of cpt with the (metric) continuous-time domain of time and y. It is wrongly typed:

it combines signals defined on incomparable time domains.

There is, however, a situation where the composition of a stream and a continuous-time signal makes perfect sense.

Consider a continuous-time signal z that is true on a sequence of increasing instants t

n

∈ R , n ∈ N with 0 ≤ t

0

and t

n

< t

n+1

and false everywhere else. Call such a z a discrete clock.

7

Call zero-crossing a clock that is true at t

i

if and only if some continuous signal x crosses zero from below: x(t

i

− h) < 0 for all h such that −ε < h < 0 and x(t

i

+ h) > 0 for all h such that 0 < h < ε, where ε is a small enough positive number.

(5)

A signal is deemed discrete if its changes are activated on a discrete clock, defined as follows [16, §2]:

A clock is termed discrete if it has been declared so, or if it is a sub-sampling of a discrete clock, or if it is a zero-crossing. Otherwise, it is termed continuous.

(6) A periodic timer, e.g., that ticks every 0.1 seconds, is an example of a discrete clock. It can be defined, albeit sub- optimally, by a sawtooth signal with slope one, initialized to

−0.1, and reset every time it crosses zero. We are now ready to write a corrected version of model (3) where the signal cpt is piecewise constant and changes only when z is true.

let hybrid continuous_with_discrete(z) = cpt where

rec der time = 1.0 init 0.0 and cpt =

present z -> 1.0 fby (cpt +. time) init 0.0

The function continuous_with_discrete takes as input a discrete clock z and returns the signal cpt. The parallel composition of the two equations is perfectly valid: the stream 1.0 fby (cpt + .time) is aligned with the sequence of instants where z is true. The construct present...init returns a piece- wise constant signal, initialized with 0.0 which changes at every occurrence of z.

cpt(t) = 0 0 ≤ t < t

0

cpt(t

0

+ h) = 1 0 ≤ h < t

1

− t

0

and, for 0 ≤ h < t

n+1

− t

n

,

cpt(t

n

+ h) = (cpt + time)(t

n−1

)

= cpt(t

n−1

) + time(t

n−1

)

The above function illustrates the typical situation of a soft- ware controller activated periodically on a discrete clock z and composed in parallel with a continuous-time model of a plant, as in the following.

let hybrid model(z) = o where

7

Models may be Zeno, i.e., t

n

may not tend to infinity with n. This problem

cannot, in general, be detected at compile time and it leads to problems at

run-time, e.g., simulations that run very slowly or that go beyond the Zeno

point due to floating-point errors. This is a known and unavoidable problem.

(6)

rec der x = plant(x, u) init x0 and y = f(x, u)

and o = present z -> command(y) init u0 where command is a synchronous stream function whose logical steps are aligned on z.

A discrete clock like z can be used to specify different mode changes, e.g., to reset the value of an integrator. For example, a sawtooth signal with slope 1.0 and reset to 0.0 every time z is true, is written:

der time = 1.0 init 0.0 reset z -> 0.0

The signal z can be defined with a zero-crossing function. In Z ÉLUS , the expression up(x) defines a discrete clock that is true when the signal x crosses zero from a strictly negative value to a strictly positive one.

Yet, using R as a time domain means that we cannot describe a zero-crossing which would be the instantaneous consequence of a previous one (also called a cascade where events appear in sequence but in zero time). We will see later that the previous example can still be justified in this more general setting.

Up to syntactic details, the two preceding models can be written almost as is, in any hybrid systems modeling language, e.g., Simulink

8

or P TOLEMY .

Unsafe mixing of discrete- and continuous time: What if an ill-defined combination of discrete- and continuous- time signals is written as in (3) and (4)? It is tempting to perform implicit conversions between streams and continuous- time signals. But taking cpt(t) = cpt

btc

, where btc is the integer fraction of t, would not make any more sense than cpt(t) = cpt

i(t)

, with i : R 7→ N being any monotone surjective function. The following example, in Simulink this time, illustrates the consequences of such a liberal approach.

✁ s✂ ✄✁ ✂

s

■✁✂t☎ r✄ ✂r

❆✆✆

❯✁ ✝ ✂✥ t❧ ✄✞

❙ ✟♣ t

✠✡☛❡

❝☞ ✠

(a) Basic model

0 50 100 150 200 250

0 1 2 3 4 5 6 7 8 9 10

time cpt

(b) Simulation of basic model

Figure 1. Composition of models that mix discrete- and continuous-time blocks in Simulink (R2016b).

8

For Simulink, replace present/init by a sub-system block triggered on z and fby by the unit delay of the discrete-time library. The ODE with reset can be implemented directly using the integrator block of Simulink.

We consider example (3) again, reprogramming it as in Figure 1a, where the fby is replaced by Simulink’s delay operator which “holds and delays its input by one iteration”.

9

This operator is applied here to a continuous-time signal, though nothing explicitly specifies its discrete-time steps, that is, when “iterations” occur. The constant 1 is connected to the input port of an integrator that is fed directly into a feedback loop involving a unit delay with inherited sampling time. Simulation results are shown in Figure 1b. While the value of time is adequately approximated, it is not at all clear what the output signal cpt should be. In Simulink, cpt is an interpolation of the cumulative “time” computed at so called major steps which depend on when the solver decides to stop.

10

For this model, the compiler infers the discrete steps of the unit delay to be the major steps of the simulation algorithm.

The model’s meaning thus depends critically on the mechanics of the simulation engine. Consequently, if solver parameters, for instance, the minimum step size or the error tolerance, are changed, the value computed for cpt may change significantly.

Furthermore, the solver chooses major step sizes for the entire model and not just for individual fragments, which works contrary to the ideal of a component-based approach. In particular, adding an unrelated component in parallel changes the behavior of the original component significantly.

In the above example, we could have equivalently used the

“memory block” mem(x)

11

instead of the unit delay. If x is a signal, mem(x) is a piecewise constant signal which holds the value of x from the previous major step. If those steps are taken at increasing instants t

i

∈ R , mem(x)(t

0

) = x

0

where t

0

= 0 and x

0

an initial value and mem(x)(t

i

+ h) = x(t

i−1

) for i > 0, 0 ≤ h < t

i+1

− t

i

. Formally, a memory block takes a discrete clock z and an input value x such that:

let hybrid memory(z, x) =

present z -> (0.0 fby x) init 0.0

Thus, if major_step is a discrete clock that denotes the instants where major steps occur, mem(x) is an abbreviation for memory(major_step, x), exhibiting the fact that its value does not depend solely on z. Moreover, major_step is not just the disjunction of all explicit zero-crossings in a model; it is also true at some intermediate instants where the numerical solver stops for other reasons. With variable step numerical solvers, it is difficult to predict the actual value of major_step.

Thus, having a block in a model that explicitly refers to the major step make the whole model sensitive to low-level solver choices. Several other operators in the Simulink standard library explicitly refer to major steps, including the memory,

12

9

See https://www.mathworks.com/help/simulink/slref/unitdelay.html.

10

A Simulink simulation is structured as a pair of nested loops [29, p. 1-10].

The outer loop calculates the values of a model’s signals and states at a single instant of simulation time. Its successive iterations generate the successive instants of a simulation. They are termed major steps. The inner loop both integrates continuous states for use in the next iteration of the outer loop and locates zero-crossings. Its successive iterations are termed minor steps. The values they calculate are provisional; the solver may require multiple iterations to determine an appropriate approximation.

11

See https://www.mathworks.com/help/simulink/slref/memory.html.

12

See https://www.mathworks.com/help/simulink/slref/memory.html.

(7)

derivative,

13

time/transport delay,

14

rate limiter,

15

and backlash blocks.

16

There are understandable reasons to allow operators that implicitly refer to major steps, as Simulink does. Programmers can explicitly exploit the low-level cycles of the simulation algorithm and features like function-call subsystems; even to the point of implementing solvers within a model [30].

This approach can also reduce the number of zero-crossing events and thus give faster simulations. Blocks that explicitly rely on the major steps are definitely useful. However, their use is constrained by rules and guidelines. For instance, the documentation for the memory block advises to “avoid using the Memory block when both these conditions are true: Your model uses the variable-step solver ode15s or ode113. The input to the block changes during simulation”.

Conclusions: The preceding analysis leads first to a ques- tion. Is it possible to replace some of “unsafe” blocks de- scribed above with safer constructs that have a similar—

if not necessarily identical—meaning? And second, to the requirement for a compile-time analysis to reject unsafe com- binations of discrete- and continuous-time equations and, in turn, the possibility to guarantee certain properties of accepted programs. This may seem easy for small models, but it is far from trivial for real-size system models. It requires a careful consideration of the mathematical semantics of hybrid models, which we develop in the following sections.

B. Background: Ideal Solver Semantics and Superdense Time The semantic model of a programming language is supposed to be faithfully implemented by interpreters and compilers, but numerical approximations are unavoidable for simulating models with non-trivial continuous-time dynamics. Must we give up on precision altogether? Must we incorporate the details of numerical solvers into the language semantics as in [31]? An alternative approach, the Ideal Solver Semantics, was advocated by Liu and Lee [28], and later further developed by Lee [32]. We briefly present it next.

ODE solvers such as S UNDIALS CVODE [20] compute approximate solutions to the problem of finding a solution to an ODE until some specified stopping event less than a given t

max

∈ R . Formally, for t

0

, t

1

∈ R , t

0

< t

1

≤ t

max

, a signal x(t) is defined over [t

0

, t

1

] and beyond if there exists s

1

> t

1

such that x(t) is defined over [t

0

, s

1

). For I a non-empty open interval of R and h : I 7→ R , h possesses a zero-crossing at t ∈ I if there exists an open interval J ⊆ I containing t and such that, inside J , h(s) < 0 before t and h(s) > 0 after t.

ODE solvers address the following problem:

Problem 1. Given t

0

∈ R , f : R

m

× R 7→ R

m

, x

0

∈ R

m

, and g

i

: R

m

× R 7→ R for i = 1, . . . , k, find an instant t

1

> t

0

and an R

m

-valued signal x(t) defined over [t

0

, t

1

] such that:

1) x satisfies the ODE x

0

(t) = f (x(t), t) with initial condition x(t

0

) = x

0

; and

13

See https://www.mathworks.com/help/simulink/slref/derivative.html

14

See https://www.mathworks.com/help/simulink/slref/transportdelay.html

15

See https://www.mathworks.com/help/simulink/slref/ratelimiter.html

16

See https://www.mathworks.com/help/simulink/slref/backlash.html

2) t

1

is the smallest instant at which at least one of the functions t 7→ g

i

(x(t), t) possesses a zero-crossing.

If found, the instant t

1

is called the event of zero-crossing.

Variable step solvers adapt their time steps to varying stiffness of f and the detection of the zero-crossings of g.

For the solver to work properly, it is therefore advisable that both f and g be smooth enough, at least f continuous and g continuously differentiable.

So far Problem 1 specifies exit conditions from continuous modes. In addition, we must describe how the system state x is reset after time t

1

for the next phase of the dynamics.

It has been identified by previous authors [33], [28], [32], [4] that the transition from one continuous mode to the next one may require several steps of a discrete time automaton. A simple example illustrating this need is the Newton’s Cradle with three balls or more. The transfer of inertia from the first to the last ball occurs via a cascade of successive transfers, from each ball to the next one.

With reference to the above discussion, the Ideal Solver Semantics of a model consists of:

1) an oracle returning an exact solution to Problem 1, completed by

2) the specification, for each event, of the discrete time automaton specifying the reset conditions for the state, together with its exit conditions.

Resetting may take several successive computation steps, for which extra instants are required. To unambiguously represent this, Lee and Zheng [4] use superdense time [33]:

T

sd

=

def

R

≥0

× N

with the lexicographic order defined by (s, m) < (t, n) if s < t, or s = t and m < n. A signal is a function T

sd

→ D, where D is the value domain. At each real time t, a signal takes a totally ordered sequence of values indexed by N .

This time base is used to represent signals whose dynamics alternate between smooth trajectories of positive duration and sequences of events where the signal takes a finite but arbitrary number of successive values in zero time, the last of which gives an initial value for the next continuous phase. The representation of a signal in superdense time is defined [32]:

17

x : T

sd

→ D is a partial function with domain {(t, n) | 0 ≤ n ≤ N

x

(t)}, where N

x

: R

≥0

→ N is the timeline of signal x.

(7) For all t ∈ R

≥0

, x(t, n) is defined for all 0 ≤ n ≤ N

x

(t) and undefined otherwise. If N

x

(t) is the constant zero, then (7) defines a signal indexed by R

≥0

× {0}, which is isomorphic to R

≥0

. This defines an embedding of ordinary continuous time signals in superdense time signals.

We say that x has an event at t ∈ R

≥0

if N

x

(t) > 0, and that x is chattering free if the set of t such that x has an event at t is a finite or diverging sequence [32]. We are mainly interested in chattering-free systems here, as they capture the

17

[32] defines signals as total functions x : T

sd

→ D ∪ {} whose value

is frozen beyond the timeline and possibly absent at some instant. Here, we

only consider non-absent signals for which the two definitions are equivalent.

(8)

situations where successive modes, in which the continuous- time dynamics are smooth, are traversed in a non-Zeno way.

This is illustrated in Figure 2. In particular, an event occurs

t

1

t

2

(t

1

, 0) (t

1

,1)

(t

2

, 0)

(t

1

,2)

(t

2

, 1)

Figure 2. A chattering-free signal x(t, n) in superdense time. The vertical axis is the domain R of values for x and the horizontal axis is the set of instants R

≥0

. The trajectory is the solid curve augmented with black bullets at events t

1

and t

2

. The ordering of discrete instants at the two events is indicated by dashed arrows. The self-loops indicate “freezing” when the height is reached.

at t

2

where x has a jump typical of the resetting of an ODE.

At this event, the bullet x(t

2

, 0) represents the left-limit of x at t

2

, whereas x(t

2

, 1) represents the actual value of x at t

2

, after which x remains constant. An event also occurs at time t

1

, followed by two others.

C. Synchronous Models in Nonstandard Time

The ideal solver semantics is adequate to describe the execution of a hybrid system model. In our development, we had a different objective, however, expecting from the semantics:

to support the study of the parallel composition of pro- grams, and to be modular — meaning that the semantics of complex programs is derived by simple constructions from the semantics of the primitives of the language;

to provide a mathematical justification of all the compi- lation steps, from the model to the sequential code paired with the numerical solver, and to make sure those steps can be defined modularly;

to define a set of static constraints that ensure certain safety invariants for programs that are accepted by the compiler.

The semantic developments of synchronous languages had the same objectives. Hence, not surprisingly, our answer borrows ideas from synchronous languages. It relies on the notion of nonstandard semantics, a technique that essentially treats continuous time as if it were discrete. Let us first recall the essence of synchronous models.

1) Synchronous Models: In this model, input, output and local signals are sequences of values or streams that advance synchronously; systems are synchronous stream functions de- fined by a set of mutually recursive equations over streams. It is very clear here that time is logical [3]: there is no hypothesis on the physical duration between two successive values nor a way to express it internally by composing stream functions.

an equation x = a, where a is an expression, means that x

n

= a

n

, for all n ∈ N . The parallel composition of two equations is synchronous, that is, x = a and y = b, where a and b are expressions, means (x

n

= a

n

) ∧ (y

n

= b

n

) for all n ∈ N . Operations are implicitly lifted to stream. E.g., if x = (x

n

)

n∈N

and y = (y

n

)

n∈N

, then x + y = (x

n

+ y

n

)

n∈N

and a constant like 1 stands for an infinite constant stream.

As an example, consider the forward Euler integration function for the ODE y

0

= u with y(0) = i

0

parameterized by a step size h:

let node forward_euler(h)(i, u) = y where rec y = i fby (y +. (h *. u)) (8) In this example, h is a static parameter, which can only be instantiated by an expression whose value is computable at compile time (otherwise the program does not type check).

The function forward_euler(h) takes two input streams, i and u, and returns an output stream y such that:

∀n ∈ N , y

n

= (i fby (y + (h ∗ u)))

n

= i

0

if n = 0

= y

n−1

+ (h ∗ u

n−1

) otherwise The following function is the forward Euler with reset.

let node forward_euler_r(h)(i0, i, r, u)

= (sy, y)

where rec sy = i0 fby (y +. (h *. u))

and y = if r then i else sy (9) It returns a pair of streams (sy, y), where sy is y except at instants when r is true, where it takes the value of i.

For a given stream function, the compiler generates a statically scheduled, loop-free function, which computes a step of the system—we call it the step function. Given the current inputs i

n

, u

n

and a current internal state, this step function returns the current output y

n

and a new state (in practice, the state is modified in place). This compilation is possible when the function have no instantaneous feedback, i.e., the value of y

n

does not depend on itself. In contrast, writing the following function leads to a compile-time error:

let node forward_euler(h)(i, u) = y where rec y = y +. (h *. u)

^^^^^^^^^^^^^^^^^

Causality error: this expression depends instantaneously on itself.

Here, y(n) depends instantaneously on itself. Rejecting in- stantaneous feedback loops is a sufficient condition to ensure that fix-point equations have a unique solution. Moreover, it ensures that statically scheduled code can be generated. For every function definition, the causality analysis of Z ÉLUS

computes a type signature that expresses the dependencies between inputs and outputs. This signature is then used everywhere the function is called. If the causality analysis fails, the compilation stops.

2) Synchronous Models in Continuous-Time: Let us attempt to directly extend our previous reasoning to a model defining continuous-time signals, e.g., made of ODEs and equations.

For example, consider the model of the temperature in a tank that is heated or not.

let hybrid heater(i, heat) = tp where

(9)

rec der tp = v init i

and v = if heat then k1 *. (k2 -. temp) else k3 *. (k4 -. temp)

The function heater takes two inputs i, heat and returns one output tp. Suppose that k1, k2, k3 and k4 are constants.

The body defines the signals tp and v such that:

tp

0

= k

1

(k

2

− tp)+ if heat is true tp

0

= k

3

(k

4

− tp) if heat is false t(0) = i

0

(10) Forgetting the derivative definition gives a causality error:

let hybrid heater(i, heat) = tp where rec tp = v

and v = if heat then k1 *. (k2 -. temp) else k3 *. (k4 -. temp)

Causality error: here is an example of a cycle v < tp, tp < v

There is an intuitive justification for this: because the defined set of mutually recursive equations is cyclic, it is not possible to compute a statically scheduled function that returns the current value of the derivative of tp as a function of tp. For the first version, the compiler produces a statically scheduled function which computes the current derivative, from the current value of i, heat and tp. When given to a numerical solver [34], this solver returns a sequence of approximations tp(t

n

) for increasing values of time t

n

∈ R

+

and n ∈ N . Thus, for continuous-time signals, an integrator breaks causality loops just as unit delays do for discrete-time signals. Yet, this intuitive justification is not satisfactory as it builds on details about how an ODE solver functions, and it says nothing bout the more general situation when discrete and continuous-time computations depend on each other. In particular, are we sure that the signal heat is constant during integration? Solver- agnostic reasoning would be preferable.

We would like to justify that the above function is causal and compute a causality signature prior to code generation in the same way we do when writting synchronous stream functions.

Could we not simply reuse the straightforward justification we had for data-flow equations in discrete-time? It turns out that nonstandard analysis makes this possible.

3) Nonstandard Analysis: Nonstandard analysis [35], [36]

extends the set R of real numbers into a superset

?

R of hy- perreals (also called nonstandard reals) with an infinite set of infinitely large numbers and infinitely small numbers. The key properties of hyperreals that we need are the following [36]:

There exist infinitesimals, which are hyperreals that are smaller in absolute value than any real number: An infinitesimal ∂ ∈

?

R is such that |∂| < a for any positive a ∈ R . For x and y, two hyperreals, write x ≈ y if x − y is an infinitesimal.

All relations, operators, and propositional formulas valid over R are also valid over

?

R . For example,

?

R is a totally ordered set. The arithmetic operations +, ×, etc. can be lifted to

?

R ; and so on. A hyperreal x is finite if there is a standard finite positive real number a such that |x| < a.

Every finite hyperreal x ∈

?

R possesses a unique standard real number st (x) ∈ R such that st (x) ≈ x; we call st(x) the standard part of x.

Let t 7→ x(t), t ∈ R be an R -valued (standard) signal.

Then:

18

x is continuous at instant t ∈ R if and only if,

for any infinitesimal ∂ ∈

?

R , x(t +∂) ≈ x(t); (11) x is differentiable at instant t ∈ R if and

only if there exists a ∈ R such that, for any infinitesimal ∂ ∈

?

R ,

x(t+∂)−x(t)

≈ a. In this case, a = x

0

(t).

(12)

We can consider the following set of instants:

T ⊆

?

R T = 0, ∂, 2∂, 3∂, · · · = {n∂ | n ∈

?

N } (13) where

?

N denotes the set of hyperintegers, consisting of all integers augmented with additional infinite numbers called nonstandard. The important point here is that, on one hand, any finite real time t ∈ R has an element of T that is infinitesi- mally close to it (informally, T covers R ), and, on the other, T is discrete in that every instant n∂ has a predecessor (n−1)∂

and a successor (n+1)∂.

4) Nonstandard Semantics: Using T as a time base amounts to indexing signals with the discrete index n ∈

?

N defined in (13). Following Suenaga, Sekine, and Hasuo [37], we call the signals indexed by T hyperstreams—the mention of “stream”

emphasizes their discrete-time nature. Whenever needed for clarity, we will indicate hyperstreams with the star-prefix notation “

?

x ”.

Consider, for example, the forward Euler scheme, imple- mented by the function forward_euler defined in Z ÉLUS

in (8). Interpret the stream equation for y with time base T defined in (13) and an infinitesimal time step h = ∂, as the hyperstream satisfying the recurrence equation:

?

y

n+1

=

?

y

n

+ ∂ ×

?

u

n

,

?

y

0

=

?

i

0

(14) Since ∂ is infinitesimal, it turns out by (12) that,

for any t ∈ R and any n∂ ∈ T such that n∂ ≈ t,

1

(

?

y

n+1

?

y

n

) ≈ y

0

(t) holds, (15) which means that (14) approximates the solution of the ODE:

y

0

= u y(0) = i(0) (16)

up to an infinitesimal error. Since such an error is smaller than any positive error, it can be ignored and the stream equation (14) can be seen as a perfect semantics for the ODE.

By (11) and (12), the above analysis holds regardless of the particular choice for ∂ provided that it is infinitesimal. All of this legitimates that we call (14) the nonstandard semantics of the ODE (16):

let hybrid int(i, u) = y where rec der y = u init i

As another example, consider the integration with possible reset, written:

18

In (11) and (12), we abuse the notation slightly by invoking the value of

signal x at nonstandard instants; see [36] for a formalization.

(10)

let hybrid int_with_reset(r, i, u) = y where rec der y = u init i reset r -> i

Its nonstandard semantics is:

?

y

0

= i

0

?

y

n+1

=

i

n+1

if

?

r

n+1

occurs

?

y

n

+∂×

?

u

n

otherwise

(17) We can express this nonstandard semantics using (9), that is, forward_euler

r

(h)(i, i, r, u) with h = ∂, the infinitesimal basic time step.

To summarize, for a hybrid function, we have replayed the simple semantics for expressions, equations and parallel com- position that we gave for a stream function in Section II-C1, replacing N by

?

N and considering that every step is of infinitesimal length ∂.

The different constructions proposed for the extension

?

R amount to invoking the axiom of choice [36], [10]. Hence, not surprisingly, nonstandard analysis is not effective. No computer exists that can compute with hyperreals. So what do we gain by considering nonstandard semantics? As we have turned differential equations into difference equations, some symbolic reasoning and transformations or static analyses like the detection of instantaneous loops can be easily justified and extended to the whole language. This discrete-time interpre- tation of a hybrid model is also helpful to prove important properties of hybrid system models, see Section V-B and the properties (1) and (2) therein.

5) From Nonstandard Semantics to Superdense Time Se- mantics: Once the required program analyses and transforma- tions have been performed, it remains to establish a bridge between:

the nonstandard semantics of the program that supported our analyses and compilation steps, and

a standard semantics that formally specifies what should be executed in practice; we chose the Ideal Solver Se- mantics for this.

This bridge is formalized as the standardization of the non- standard semantics. Its justification is provided in [10], [23], we describe the intuition below.

Consider first the case of the ODE with reset (17). Stan- dardizing the tuple of signals (

?

y,

?

u,

?

r) consists in finding a standard domain and a tuple (y, u, r) over it such that

?

y ≈ y,

?

u ≈ u,

?

r ≈ r.

Outside the occurrences of the event

?

r,

?

x satisfies the forward-Euler scheme which we know standardizes to the ODE x

0

= u—so much for continuous-time dynamical systems of timebase R

≥0

.

How should we standardize the dynamics (17) at an occurrence of event

?

r? Simply by mapping them to the two successive values

?

y

n

,

?

y

n+1

occurring in sequence within an infinitesimal amount of time, which itself standardizes as zero time. We thus eventually recover the handling of events performed by the superdense time approach [4], [32].

The standardization of the nonstandard semantics of (17) is illustrated in Figure 3. If several events occur consecutively, the standardization of of a nonstandard signal is a signal in

i

0

?

r

?

r + ∂

i

0

r

Figure 3. Nonstandard semantics (top) of (17) and the superdense time semantics (bottom) resulting from the standardization of the former. The nonstandard semantics is dashed to indicate that it is discrete time.

superdense time,and it is defined as follows [18], [23]. For t ∈ R and T ⊆ T , define the halo of t as

T

t

=

def

{t

0

∈ T | t

0

≈ t}

i.e., the set of nonstandard instants belonging to T and infinitely close to t. For

?

x a nonstandard signal, its standard- ization x is defined as follows:

1) For t ∈ R

≥0

, define the standard signal st(

?

x) by st(

?

x)(t) =

def

{st (

?

x(t

0

) | t

0

∈ T

t

}. That is, for every real standard time t, we take the set of all standard parts of

?

x(t

0

) when t

0

ranges over the halo of t.

2) The standardization of

?

x is the superdense time signal x defined as follows:

If st (

?

x)(t) = {v} is a singleton; then N

x

(t) = 0 and x(t, 0) = v;

If st(

?

x)(t) is not a singleton, let T

t0

⊆ T

t

be the set of nonstandard instants t

0

∈ T

t

at which

?

x has a non infinitesimal change, that is,

?

x(t

0

) 6≈

?

x(t

0

− ∂). In the considered case, T

t0

is not empty and two cases occur:

– Either T

t0

= {t

01

, . . . , t

0m

} is finite; we then define the timeline of x as N

x

(t) = m and set

x(t, n) =

 

 

st (

?

x(t

01

− ∂)) for n = 0

st (

?

x(t

0n

)) for n = 1, . . . , N

x

(t) undefined for n > N

x

(t) – Or T

t0

= {t

01

, . . . } is infinite, which corresponds to

a Zeno behavior; then N

x

(t) is undefined and so is x(t, n), n ∈ N and x(t

0

, n) for any t

0

> t.

In [10], [18], [23], any chattering free hybrid system has a nonstandard semantics that can be standardized to a model defined everywhere in superdense time, i.e., the last case does not occur. This final model corresponds to the definition given by the ideal solver semantics.

The important point about standardization is that it is

performed as a final step on the global program. In particular,

(11)

neither the causality analysis nor the discrete/continuous typ- ing that we develop in Section V rely on superdense semantics for their soundness.

The two semantic domains — nonstandard time and super- dense time — complement each other: the former is useful to design and justify modular compile time checking and symbolic transformations, while the latter justifies the final simulation loop in which the resolution of ODEs is delegated to a solver.

III. T HE N EWTON ’ S C RADLE EXAMPLE

Our subsequent developments are illustrated by a running example, sketched in Figures 4 and 5.

θ

ω l

g

Figure 4. Pendulum in polar coordinates.

θ

1

l

l ω

2

ω

1

θ

2

g g

Figure 5. Newton’s Cradle with two colliding pendulums.

Consider a pendulum of length l as shown in Figure 4.

It is defined in polar coordinates, where θ is the angle of the pendulum relative to the vertical axis, ω is the angular velocity, and g is an acceleration parallel to the vertical axis.

The dynamics of the pendulum are defined by the following system of ODEs:

θ

0

= ω

ω

0

= a sin θ where a = g/l (18) We consider next a Newton’s Cradle consisting of two pen- dulums of equal mass, depicted in Figure 5. Outside collision events, each pendulum is governed by an instance of model (18) and we index the two instances with the subscripts 1 and 2. When the pendulums collide, it is assumed that the interaction between the two balls is elastic, meaning that the energy of the system is invariant. A collision occurs whenever the pendulums are in contact (θ

1

≥ θ

2

) and their relative

velocity is negative (ω

1

> ω

2

). Since the balls have equal masses, a collision results in an exchange of angular velocities:

ω

+1

= ω

2

ω

+2

= ω

1

(19)

This is a physically meaningful illustrative example of small scale. It does not blend plant and control but it combines continuous dynamics and mode changes with event handling, the central difficulty. It does not exhibit the complexity issues of large CPS systems but it is sufficient to illustrate in detail some semantic issues. Prior to presenting our approach, we first review some difficulties in modeling this system using the reference tool Simulink. This will illustrate that, despite its small size, this example already exhibits some interesting and representative difficulties.

!

"#$"%

!

%

&

'($)%

!

* +'

*,$$-

! +'*

,'*.".'/

01'-23"

*./

41.)'/'($"1.3 52/3".'/

&

'($)%6

7

"#$"%6 8

1$*$"

Figure 6. Simulink model of the pendulum

1 z 1

theta1 2 theta2

3 omega1

4 omega2

>=

Relational Operator1

>

Relational Operator2

AND Logical Operator

Figure 7. Simulink model of the collision detector

a omega0 theta0 reset

theta omega Pendulum1

a omega0 theta0 reset

theta omega Pendulum2 -9.81

a -1.5 theta01

1.1 theta02

theta1 theta2 omega1 omega2

z

CollisionDetector

Figure 8. Simulink model of the Newton’s Cradle with two pendulums

!

"#$"%

!

%

&

'($)%

!

* +'

*,$$-

! +'*

,'*.".'/

01'-23"

*./

41.)'/'($"1.3 52/3".'/

&

'($)%6

7

"#$"%6 8

1$*$"

Figure 9. Simulink model of the pendulum with state port

(12)

-9.81 a -1.5 theta01

1.1 theta02

a omega0 theta0 reset

theta omega omega_sp Pendulum1

a omega0 theta0 reset

theta omega omega_sp Pendulum2

theta1 theta2 omega1 omega2

z

CollisionDetector

Figure 10. Simulink model of the Newton’s Cradle with state ports

����

��

����

��

����

��

����

�� �� �� �� �� �� �� �� �� �� ���

Figure 11. Incorrect behavior of the model with state ports. Trajectory of variable θ

1

(resp. θ

2

) is shown in red (resp. blue).

A. Difficulties and Pitfalls

The Simulink model of the single pendulum of Figure 4 and model (18) is given in Figure 6. Modeling the Newton’s Cradle seems to be an easy task in Simulink by interconnecting two instances of the pendulum model with the collision detector corresponding to formulas (19) and specified in Simulink as shown in Figure 7. The whole model is shown in Figure 8.

However, the simulation of this Simulink model fails at the in- stant of the first collision, with a “Block diagram ‘pendulums’

-9.81 a -1.5 theta01

0.75 theta02

Memory1

Memory2

theta1 theta2 omega1 omega2

z

CollisionDetector a

omega0 theta0 reset

theta omega Pendulum1

a omega0 theta0 reset

theta omega Pendulum2 omega_2b

omega_1b

z omega_1

omega_2

Figure 12. Simulink model of the Newton’s Cradle with memory blocks

t z omega_1 omega_1b

0.080212582126707 0 0.7842526 0.1569379 0.306505169555583 0 2.9055798 0.7842526 0.560709471482921 0 4.2594777 2.9055798 0.560709471482928 1 -2.2754531 4.2594777 0.560709471482935 0 -2.2754531 -2.2754531 0.839389940219895 0 -1.2708350 -2.2754531 Figure 13. Data logged from the Newton’s Cradle with memory blocks

����

��

����

��

����

��

����

�� �� �� �� �� �� �� �� �� �� ���

Figure 14. Behavior of the model with memory blocks. Red (resp. blue) pendulum 1 (resp. 2).

contains 1 algebraic loop(s)” error message. The reason is that at the instant of reinitialization of the ω

1

and ω

2

integrators, the reset values of the integrators depend on one another. The error message even contains a hint of how this issue can be solved : “Use integrator state port to avoid algebraic loops”.

Indeed, the help pages give the following definition of the state port : “The output of the state port is the same as the output of the block’s standard output port except for the following case. If the block is reset in the current time step, the output of the state port is the value that would have appeared at the block’s standard output if the block had not been reset.”. In other words the value of the state port is the left-limit of the integrator’s output.

The corrected model, using state ports, is shown Figures 9 and 10. This model simulates without reporting an error.

However, the trajectory of the system is incorrect, as shown in Figure 11. This is the consequence of a miscompilation, explained in detail in [18]. In a nutshell, the reinitialization of the integrators are scheduled sequentially, without temporarily storing the state of the first integrator to be reinitialized so that it can be used later to reinitialize the second one. The consequence is that the new velocity of one of the pendulums is not set to be the left limit of the velocity of the other pendulum, but rather, its new velocity. This explains why the pendulums have identical trajectories after the first collision.

This problem can be avoided in Simulink by using two memory blocks mem(x) that introduce a small delay in the angular velocity variables ω

1

and ω

2

; see Figure 12. When a collision occurs, the memory blocks break the algebraic loop and the values of the output ports of the memory blocks are numerically close (but not exactly equal) to the left-limits of the angular velocities. Figure 13 shows the values of ω

1

and ω

1b

= mem(ω

1

) at every major step. z is true at the instant of the contact (line with z = 1 in Figure 13). Note that right after this instant (line below), Simulink takes an extra step that is very close in time to the previous one.

19

It is at this instant that the speeds ω

1

and ω

2

are exchanged, not at the instant where the contact is detected. This extra delay makes the simulation imprecise from a numerical point of view and possibly unpredictable. Yet, for this simple example, the

19

This extra step can serve to detect that a zero-crossing signal goes from

zero to a strictly positive (or negative) value.

Références

Documents relatifs

GEMOC 2014 is supported by the GEMOC initiative that promotes research seeking to develop the necessary breakthroughs in software languages to support global software engineering,

copies active states to the reach phase (during a flush in the sub-round (R0)), and selects boldfaced edges (in all the sub-rounds). We want to extract from the strategy tree σ ∃ ∃ ∃

The result of copying and relabelling is that the strong degree of nondeterminism for the grammar is reduced to the weak degree because the number of auxiliary trees labelled by

In this paper we analyze the worst case complexity of regular operations on cofinite languages (i.e., languages whose complement is finite) and provide algo- rithms to

The structure of the code we generate is reminiscent of the so-called dummy derivatives method [37]: for both the continuous dynamics and the handling of transient modes or mode

The framework consists of an abstract core language that serves as a common basis for the integration of DSLs for a comprehensive specification and for matching.. The core

The next reason why the new modeling languages are textual is that it is quite easy to create a new language and integrate it into a development environment such as Eclipse or

The clutch example is informally developed in Section 2; we show how to map this model to the nonstandard domain, how the structural analysis works (in particular, the handling of