.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/indicators/plot_b01expressions.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_indicators_plot_b01expressions.py: Examples of mathematical expressions ==================================== Example of manipulating mathematical expressions and calculation of derivatives. Michel Bierlaire, EPFL Sat Jun 28 2025, 15:54:00 .. GENERATED FROM PYTHON SOURCE LINES 12-37 .. code-block:: Python import numpy as np from biogeme.calculator import ( CallableExpression, create_function_simple_expression, get_value_and_derivatives, ) from biogeme.function_output import FunctionOutput, NamedFunctionOutput try: import matplotlib.pyplot as plt can_plot = True except ModuleNotFoundError: can_plot = False from biogeme.expressions import Beta, exp # ## # We create a simple expression: b = Beta('b', 1, None, None, 0) expression = exp(-b * b + 1) .. GENERATED FROM PYTHON SOURCE LINES 38-41 We can calculate its value. Note that, as the expression is calculated out of Biogeme, the IDs must be prepared. So the parameter 'prepare_ids' is set to True .. GENERATED FROM PYTHON SOURCE LINES 41-44 .. code-block:: Python z = expression.get_value() print(f'exp(-b * b + 1) = {z}') .. rst-class:: sphx-glr-script-out .. code-block:: none exp(-b * b + 1) = 1.0 .. GENERATED FROM PYTHON SOURCE LINES 45-48 We can also calculate the value, the first derivative, the second derivative, and the BHHH, which in this case is the square of the first derivatives .. GENERATED FROM PYTHON SOURCE LINES 48-52 .. code-block:: Python the_function_output: FunctionOutput = get_value_and_derivatives( expression, numerically_safe=False, use_jit=True ) .. GENERATED FROM PYTHON SOURCE LINES 53-54 .. code-block:: Python print(f'f = {the_function_output.function}') .. rst-class:: sphx-glr-script-out .. code-block:: none f = 1.0 .. GENERATED FROM PYTHON SOURCE LINES 55-56 .. code-block:: Python print(f'g = {the_function_output.gradient}') .. rst-class:: sphx-glr-script-out .. code-block:: none g = [-2.] .. GENERATED FROM PYTHON SOURCE LINES 57-58 .. code-block:: Python print(f'h = {the_function_output.hessian}') .. rst-class:: sphx-glr-script-out .. code-block:: none h = [[2.]] .. GENERATED FROM PYTHON SOURCE LINES 59-61 .. code-block:: Python print(f'BHHH = {the_function_output.bhhh}') .. rst-class:: sphx-glr-script-out .. code-block:: none BHHH = [[4.]] .. GENERATED FROM PYTHON SOURCE LINES 62-65 From the expression, we can create a Python function that takes as argument the value of the free parameters, and returns the function, the first, the second derivatives, and the BHHH. .. GENERATED FROM PYTHON SOURCE LINES 65-70 .. code-block:: Python fct: CallableExpression = create_function_simple_expression( expression, numerically_safe=False, named_output=True, use_jit=True ) .. GENERATED FROM PYTHON SOURCE LINES 71-72 By default, we want to calculate the gradient and the hessian .. GENERATED FROM PYTHON SOURCE LINES 72-78 .. code-block:: Python def the_function(x: float) -> NamedFunctionOutput: # The generated function takes an array of betas as argument. In this example, there is only one. beta = [x] return fct(beta, gradient=True, hessian=True, bhhh=False) .. GENERATED FROM PYTHON SOURCE LINES 79-80 We can use the function for different values of the parameter. Note that it takes as argument a vector of betas. .. GENERATED FROM PYTHON SOURCE LINES 80-86 .. code-block:: Python beta = 2.0 the_named_function_output: NamedFunctionOutput = the_function(beta) print(f'f({beta}) = {the_named_function_output.function}') print(f'g({beta}) = {the_named_function_output.gradient}') print(f'h({beta}) = {the_named_function_output.hessian}') .. rst-class:: sphx-glr-script-out .. code-block:: none f(2.0) = 0.049787068367863944 g(2.0) = {'b': np.float64(-0.19914827347145578)} h(2.0) = {'b': {'b': np.float64(0.6970189571500952)}} .. GENERATED FROM PYTHON SOURCE LINES 87-92 .. code-block:: Python beta = 3.0 the_named_function_output = the_function(beta) print(f'f({beta}) = {the_named_function_output.function}') print(f'g({beta}) = {the_named_function_output.gradient}') print(f'h({beta}) = {the_named_function_output.hessian}') .. rst-class:: sphx-glr-script-out .. code-block:: none f(3.0) = 0.00033546262790251185 g(3.0) = {'b': np.float64(-0.0020127757674150712)} h(3.0) = {'b': {'b': np.float64(0.011405729348685403)}} .. GENERATED FROM PYTHON SOURCE LINES 93-116 .. code-block:: Python if can_plot: # We can also use it to plot the function and its derivatives x = np.arange(-2, 2, 0.1) # The value of the function. f = [the_function(xx).function for xx in x] # The gradient is element [1]. As it contains only one entry [0], # we convert it into float. g = [float(the_function(xx).gradient['b']) for xx in x] # The hessian is element [2]. As it contains only one entry # [0][0], we convert it into float. h = [float(the_function(xx).hessian['b']['b']) for xx in x] ax = plt.gca() ax.plot(x, f, label="f(x)") ax.plot(x, g, label="f'(x)") ax.plot(x, h, label='f"(x)') ax.legend() plt.show() .. image-sg:: /auto_examples/indicators/images/sphx_glr_plot_b01expressions_001.png :alt: plot b01expressions :srcset: /auto_examples/indicators/images/sphx_glr_plot_b01expressions_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.479 seconds) .. _sphx_glr_download_auto_examples_indicators_plot_b01expressions.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_b01expressions.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_b01expressions.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_b01expressions.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_