Search code examples
modelicadymolaopenmodelica

Syntax for while loop in equation in Modelica?


I am trying to implement a simple iterative guessing scheme within the equation section in a model, however, I am getting the following error: No viable alternative near token: while in OpenModelica. Is there a simple explanation to why this while-loop does not work?

while hf>=dh loop
   v_guess = v_guess*0.95;  
   f_guess = Functions.f_Haaland(v=v_guess, D=d, rho=rho, mu=mu, eps=roughness);
   hf = Functions.H_f(f=_guess, L=length, D=d, v=v_guess, g=system.g);
end while;

Say,

  • hf=11
  • dh=10
  • v_guess=1

What I want is v_guess to become smaller and smaller until hf is approximately equal to dh. Then I'll use v_guess in the next step of my model because it is close to the real v occurring at dh. I also tried the same with for-loops and break, to no avail.

I'm looking at the syntax for while-loops and it looks exactly similar. Is there any fundamental thing that is wrong with my scheme, which I cannot see?


Solution

  • Modelica has equations and algorithms. Algorithms work similarly as in most languages and allow while-loops.

    Equations are always valid and unordered so if you write v_guess = v_guess*0.95; it means that v_guess should always have this value - which only has the solution v_guess=0 - which is likely not what you want.

    You can have for-loops in equations, but that is for handling an array where each element in the array have a separate equation - written compactly.

    So, if you want to write a while-loop either write it directly in an algorithm section or hide it in a function.

    algorithm
     while hf>=dh loop
       v_guess := v_guess*0.95;  
       f_guess := Functions.f_Haaland(v=v_guess, D=d, rho=rho, mu=mu, eps=roughness);
       hf := Functions.H_f(f=_guess, L=length, D=d, v=v_guess, g=system.g);
    end while;
    

    (Note that it should be := in algorithms and = in equations to emphasize this difference, most tools handle both.)

    Added: Note that you can have multiple algorithm-sections in a model, so you can have a few equations, an algorithm section, another algorithm section, and then a few more equations. The benefit of having multiple algorithm sections is that each section is executed in order, but they can be rearranged freely.