modelicaopenmodelicadymola

Retrieve final value of a time series variable counter in openmodelica


I have a binary activation signal which varies between 0 and 1. Based on that signal I have built a simple counter in modelica language as follows.

model Counter
  discrete Real counter(start=0);
  Modelica.Blocks.Interfaces.RealInput u
    annotation (Placement(transformation(extent={{-130,-18},{-90,22}})));
  Modelica.Blocks.Sources.RealExpression realExpression(y=counter)
    annotation (Placement(transformation(extent={{-70,-28},{-2,32}})));
  Modelica.Blocks.Interfaces.RealOutput y
    annotation (Placement(transformation(extent={{96,-8},{116,12}})));
equation 
  when u>0 then
    counter=pre(counter)+1;
  end when;
  connect(realExpression.y, y)
    annotation (Line(points={{1.4,2},{106,2}}, color={0,0,127}));
  annotation (Diagram(coordinateSystem(extent={{-100,-20},{100,40}})), Icon(
        coordinateSystem(extent={{-100,-20},{100,40}})));
end Counter;

However, it return me value in time series as well. I would prefer to have a final (integer) value at the end of simulation time which allows to calculate another constant value. I.e. if the counter is 0,1,2,...,10; I want to retrieve the output as counter = 10 (single value) and not a time dependant curve as in picture.

enter image description here


Solution

  • In case you would want the value in the model itself, you could use the terminal statement to retrieve that value (using sample() to count some value). Additionally, you could compute the "another constant value" in the termal section:

    model LastValue
      parameter Modelica.Units.SI.Time startTime = 0.1;
      parameter Modelica.Units.SI.Time sampleInterval = 0.1;
    
      Integer counter(start=0, fixed=true);
      Integer counterLast(start=-1, fixed=true);
    
    equation 
      when sample(startTime, sampleInterval) then
        counter =  pre(counter) + 1;
      end when;
    
      when terminal() then
        counterLast = counter;
      end when;
    
      annotation (uses(Modelica(version="4.0.0")));
    end LastValue;