Skip to content

Function Derivatives

Michael Wetter edited this page Feb 17, 2014 · 4 revisions

# Implementation

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`](http://simulationresearch.lbl.gov/modelica/releases/latest/help/Buildings_Utilities_Math_Functions.html#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`](http://simulationresearch.lbl.gov/modelica/releases/latest/help/Buildings_Utilities_Math_Functions_Examples.html#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;