Skip to content

Function Derivatives

mwetter edited this page Mar 17, 2013 · 2 revisions

Implementation of Function Derivatives

For some functions, a Modelica translator may not be able to differentiate the function symbolically. In this situation, a user can implement the derivative of the function to avoid the need for numerical differentiation. How to implement the derivative of a function is described in the Modelica Language Specification. An example implementation can be found in Buildings.Utilities.Math.Functions.polynomial.

When providing a function derivative, a unit test must be provided that ensures that the implementation of the derivative is correct. A unit test need to fail if the provided derivative is incorrect. An example of such a unit test is Buildings.Utilities.Math.Functions.Examples.PolynomialDerivativeCheck, which is as follows

model PolynomialDerivativeCheck
  Real x;
  Real y;
initial equation 
   y=x;
equation 
  x=Buildings.Utilities.Math.Functions.polynomial(x=time-2, a={2, 4, -4, 5});
  der(y)=der(x);
  // Trigger an error if the derivative implementation is incorrect.
  assert(abs(x-y) < 1E-2, "Model has an error.");
  
 annotation(Diagram(coordinateSystem(preserveAspectRatio=false, extent={{-100,
            -100},{100,100}}),
                    graphics),
                     Commands(file="PolynomialDerivativeCheck.mos" "run"),
    Documentation(info="<html>
<p>
This example checks whether the function derivative
is implemented correctly. If the derivative implementation
is incorrect, the model will stop with an assert statement.
</p>
</html>", revisions="<html>
<ul>
<li>
October 29, 2008, by Michael Wetter:<br>
First implementation.
</li>
</ul>
</html>"));
end PolynomialDerivativeCheck;