Conditional Equations with when-Equations

1 WhenEquation

When-equations are used to express instantaneous equations that are only valid at events, e.g. at discontinuities or when certain conditions become true. The conditional equations automatically contain only discrete-time expressions since they become active only at event instants. The two equations in the whenEquation below become active at the event instant when the Boolean expression x > 2 becomes true.

2 Simulation of WhenEquation

Here WhenEquation is simulated. Then as below the variables can be plotted.

3 WhenSet

If we instead use a Boolean vector expression containing three elements as the conditions, then the two equations will be activated at event instants when either of the three conditions: x > 2, sample(0,2), or x becomes true. Sample is more explained here.

4 Simulation of WhenSet

Here WhenSet is simulated.

5 Activate

Special behavior can be specified by when-equations when a simulation starts and finishes by testing the built-in predicates initial() and terminal(). The predicate initial() returns true at the beginning of the simulation when time is equal to time.start and the predicate terminal() returns true at the end of the simulation.

6 Simulation of Activate

Here Activate is simulated.

7 Restrictions on Equations within when-Equations

To make it possible both for a Modelica tool and a person to determine which variables are "results" from a when-equation, Modelica restricts the allowed equations within a when-equation to a form where the result variable is on the left-hand side.

7.1 WhenNotValid

7.2 Simulation of WhenNotValid

Here WhenNotValid is simulated. Since the code 2*x + y = 7; is not valid Modelica code the error message Illegal left hand equation in when equation is shown in the failed simulation message below.

7.3 WhenValidResult

7.4 Simulation of WhenValidResult

Here WhenValidResult is simulated.

7.5 Nested When

When-clauses are not allowed to be nested.

7.6 Simulation of ErrorNestedWhen

Here ErrorNestedWhen is simulated. Since it is not allowed to have nested when-clauses. there will be an error.

8 Application of the Single-Assignment Rule on when-Clauses

Two when-caluses may not define the same variable. Without this rule that may actually happen for the erroneous model DoubleConflict below a conflict between the equations will occur if both conditions become true at the same time instant.

8.1 DoubleWhenConflict

8.2 Simulation of DoubleWhenConflict

Since the variable close cannot be defined by two equations the model could not be translated.

"Simulate failed to translate model."