Search code examples
modelicaopenmodelica

Variable automatically resets to zero in the "when sample()" statement


The following Modelica code resets variable 'bb' to 0 after it sets to 123. Can anyone explain why? I am using OpenModelica v1.13.2.

model test2
import Modelica.Utilities.Streams.print;

Real b(start=0, fixed=true);
Real bb(start=0, fixed=true);

Integer c(start=0,fixed=true);
algorithm
  when sample(0,0.1) then
    c := pre(c) + 1;
    if c == 1 then
      b := 12.3;
    elseif c == 2 then 
      bb := 123;
    end if;
    print(String(time)+", "+String(b)+", "+String(bb));
  end when;
end test2;

Simulation prints:

0, 12.3, 0
0, 12.3, 123
0, 12.3, 0
...(repeats)

Also screenshot of the plot:

enter image description here


Solution

  • The result is incorrect according to the Modelica 3.4 specification, and bb should not be set to zero:

    At the start of the algorithm bb should be set to pre(bb) which is 123; according to "11.1.2 Execution of an algorithm in a model" https://specification.modelica.org/master/Ch11.html#execution-of-an-algorithm-in-a-model

    Note that the semantics for when in equations give similar results but in a different way, in that case the specific when-clause is instead implicitly mapped to an if-then-else where the else-branch would set bb=pre(bb) according to section "8.3.5.1" - https://specification.modelica.org/master/Ch8.html#defining-when-equations-by-if-expressions-in-equality-equations