I would like to determine the parts of a model that are consuming the most CPU. To do this I have tried putting a counter into parts of the Modelica code, as shown in the example below:
model counter
discrete Integer[3] counter(each start = 0, each fixed = true);
Real y;
equation
if (time >= 0 and time < 5) then
counter[1] = pre(counter[1]) + 1;
counter[2] = pre(counter[2]);
counter[3] = pre(counter[3]);
y = 2 * time + 10;
elseif (time >= 5 and time < 10) then
counter[1] = pre(counter[1]);
counter[2] = pre(counter[2]) + 1;
counter[3] = pre(counter[3]);
y = 3 * time + 20;
else
counter[1] = pre(counter[1]);
counter[2] = pre(counter[2]);
counter[3] = pre(counter[3]) + 1;
y = 5 * time;
end if;
end counter;
As you can see in the ‘Simulation Log’ screenshot, Simulation Center generates an error after initialization (and presumably during integration) at time = 0. Can someone explain what it is happening and why? For example, why was counter1=pre(counter1)+1 evaluated 7 times before the Error was generated?
And, if the approach above won’t work, is there another way of counting how many times a branch of a conditional statement is executed during a simulation.
The exhausted event iteration error is given when the event iteration hasn’t converged after an ad-hoc selected maximum number of iterations. A more stringent approach would have been to keep a record of all visited states during the event iteration, and only give the error when a true cycle has been detected by reaching an already visited state. However, the more stringent approach would probably only have made things worse in your case, as the event iteration would go on essentially endlessly, possibly only ending when running into overflow in the counter (which takes a while when using 64 bit integers).
I am afraid that there is no reliable and fully conformant way of counting number of executions using Modelica syntax. One might be tempted to use impure functions to do it, but I would expect that there is no way of avoiding that the side-effect semantics that one is trying use become undefined, see Chapter 12 Functions ‣ Modelica® Language Specification version 3.8-dev.
Instead of trying to express the counting in Modelica, I would recommend introducing the counting in the generated C++ code. It is should be easy to find the correct place in the generated code using links from the Equation Browser.