Search code examples
modelica

Trapezoidal numerical integration in Modelica


I have two arrays "x" and "fy". I have to do the trapezoidal integration of array "fy" w.r.t array "x". I could not find a function in Modelica library. I have found a function in Buildings library but it does not help me exactly. Could you please suggest, if there is other function for this type of integration.


Solution

  • I thought it was worth posting an alternative way to get the integral of an input relying on what Modelica does well. I found this nice example here that uses time and der().

    I'm not sure if the trapezoidal rule integration is done in the MSL but below is a simple function that implements the trapezoidal rule. Here is a pdf with a nice summary and example.

    In the future, you will likely have to write many of your own functions/models. There is still a lot of functionality Modelica needs such as a more complete verified and validated set of math functions like SciPy or GNU Standard Library which would have all sorts of integral, interpolation, etc. things that may be useful.

    function integral_TrapezoidalRule "Integral of array y(x) using the trapezoidal rule"
    
      extends Modelica.Icons.Function;
    
      input Integer n(min=2) "length of array";
      input Real[n] x "dependent array";
      input Real[n] y "independent array";
    
      output Real integral "Resulting integral";
    
    protected 
      Real[n-1] dx;
    
    algorithm 
      integral := 0;
    
      for i in 1:n-1 loop
        dx[i] := x[i+1] - x[i];
        integral := integral + 0.5*dx[i]*(y[i+1]+y[i]);
      end for;
    
    end integral_TrapezoidalRule;
    

    Using the example from the pdf, calling the function with:

    n = 6;
    x = {2.1,2.4,2.7,3.0,3.3,3.6};
    y = {3.2,2.7,2.9,3.5,4.1,5.2};
    

    Yields:

    integral = 5.22;