modelicaopenmodelica

How to define a constant from a function in initial algorithm. Modelica


I want to define a constant value at the start of a Modelica simulation using an external function. The function is defined with an algorithm section.

Here’s a minimal example:

within Test;

model MinimalExample
  import MyFunctions.*;

  parameter Real x = 2.0;
  Real y;

initial algorithm
  // Calculate y using an external function
  y := myFunction(x);

equation
  // No dynamic equations
end MinimalExample;

Problem:

If I declare y as constant or parameter, I get errors like:

Trying to assign to constant component

Component of higher variability parameter

Question:

What is the correct way in Modelica to compute a value from a function at initialization and then use it as a fixed value in the simulation?


Solution

  • You should be able to assign a value for the parameter directly by calling the function (=a binding equation). At least that works in Dymola, and it should be valid Modelica and therefore work in Open Modelica as well. See Demo.MinimalExample in the package below.

    As an alternative (which isn't the preferable way to do it), you can assign parameter values in an initial equation. See Demo.MinimalExampleInit below.

    package Demo
      model MinimalExample
        parameter Real x = 2.0;
        parameter Real y = myFunction(x);
    
      equation 
        // No dynamic equations
      end MinimalExample;
    
      model MinimalExampleInit
        parameter Real x = 3.0;
        parameter Real y(fixed=false);
    
      initial equation 
        y = myFunction(x);
    
      equation 
        // No dynamic equations
      end MinimalExampleInit;
    
      function myFunction
        input Real x;
        output Real y;
      algorithm 
        y := 1.2345 * x;
      end myFunction;
    end Demo;