.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_functional_modeling/vectorial_functions/plot_quick_start_functions.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_functional_modeling_vectorial_functions_plot_quick_start_functions.py: Defining Python and symbolic functions: a quick start introduction to functions =============================================================================== .. GENERATED FROM PYTHON SOURCE LINES 6-10 Abstract -------- In this example, we show how to define Python and symbolic functions. Such functions can be evaluated by the library and used, for example, to propagate uncertainties. We focus on functions which have a vector input and a vector output. .. GENERATED FROM PYTHON SOURCE LINES 12-44 Introduction ------------ We consider the following example: * three input variables, * two outputs. Moreover, we assume that the input distribution has independent Gaussian marginals. The function is defined by the equations: .. math:: Y_1 = X_1 + X_2 + X_3 and .. math:: Y_2 = X_1 - X_2 X_3 for any :math:`X_1,X_2,X_3 \in \mathbb{R}`. The exact expectation and standard deviation of the output random variable are presented in the following table. ============= =========== ================== Variable Expectation Standard deviation ============= =========== ================== :math:`Y_1` 0 1.732 :math:`Y_2` 0 1.415 ============= =========== ================== .. GENERATED FROM PYTHON SOURCE LINES 46-51 .. code-block:: default import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) .. GENERATED FROM PYTHON SOURCE LINES 52-53 We first define the input random vector of the function. .. GENERATED FROM PYTHON SOURCE LINES 55-62 .. code-block:: default X0 = ot.Normal(0.,1.) X1 = ot.Normal(0.,1.) X2 = ot.Normal(0.,1.) inputDistribution = ot.ComposedDistribution((X0,X1,X2)) inputRandomVector = ot.RandomVector(inputDistribution) .. GENERATED FROM PYTHON SOURCE LINES 63-82 The Python function ------------------- Based on a Python function defined with the `def` keyword, the `PythonFunction` class creates a function. The simplest constructor of the `PythonFunction` class is: `PythonFunction ( nbInputs , nbOutputs , myPythonFunc )` where * `nbInputs`: the number of inputs, * `nbOutputs`: the number of outputs, * `myPythonFunc`: a Python function. The goal of the `PythonFunction` class are: * to easily create a function in Python, * use all the power of the Python libraries in order to evaluate the function. .. GENERATED FROM PYTHON SOURCE LINES 84-88 The function `mySimulator` has the calling sequence `y=mySimulator(x)` where: * `x`: the input of the function, a vector with `nbInputs` dimensions, * `y`: the output of the function, a vector with `nbOutputs` dimensions. .. GENERATED FROM PYTHON SOURCE LINES 90-97 .. code-block:: default def mySimulator(x): y0=x[0]+x[1]+x[2] y1=x[0]-x[1]*x[2] y=[y0,y1] return y .. GENERATED FROM PYTHON SOURCE LINES 98-99 We now define the `PythonFunction` object. .. GENERATED FROM PYTHON SOURCE LINES 101-103 .. code-block:: default myfunction = ot.PythonFunction (3 ,2 , mySimulator ) .. GENERATED FROM PYTHON SOURCE LINES 104-105 This function can be evaluated using parentheses. It produces the same outputs as the `mySimulator` function. .. GENERATED FROM PYTHON SOURCE LINES 107-109 .. code-block:: default myfunction([1.,2.,3.]) .. raw:: html

[6,-5]



.. GENERATED FROM PYTHON SOURCE LINES 110-111 However, the newly created `myfunction` has services that the basic Python function did not have. For example, we can create a `CompositeRandomVector` on top of it, by associating it to the input random vector. .. GENERATED FROM PYTHON SOURCE LINES 113-115 .. code-block:: default outputVect = ot.CompositeRandomVector(myfunction, inputRandomVector) .. GENERATED FROM PYTHON SOURCE LINES 116-117 In the following example, we estimate the output mean based on a simple Monte-Carlo experiment using 10000 function evaluations. .. GENERATED FROM PYTHON SOURCE LINES 119-122 .. code-block:: default montecarlosize = 10000 outputSample = outputVect.getSample(montecarlosize) .. GENERATED FROM PYTHON SOURCE LINES 123-128 .. code-block:: default empiricalMean = outputSample.computeMean() print(empiricalMean) empiricalSd = outputSample.computeStandardDeviation() print(empiricalSd) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [0.00539467,0.0025914] [1.7437,1.42212] .. GENERATED FROM PYTHON SOURCE LINES 129-143 What types for x and for y ? ---------------------------- Not all types are possible for the inputs and outputs of the `mySimulator` function. The following table present some of the available types. All in all, any type which can be converted to or from a "vector" can be managed by the `PythonFunction` class. ==================== ======= ======== Type Input X Output Y ==================== ======= ======== `list` (Python) NO YES `tuple` (Python) NO YES `array` (NumPy) NO YES `Point` (OpenTURNS) YES YES ==================== ======= ======== .. GENERATED FROM PYTHON SOURCE LINES 145-150 The vectorized Python function ------------------------------ The `PythonFunction` class has a `func_sample` option which vectorizes the computation so that all the output values in the sample are computed from a single function call, without any `for` loop. To make this possible, the input and output is then a `Sample` instead of a `Point`. This often boosts performance (but not always). .. GENERATED FROM PYTHON SOURCE LINES 152-167 The calling sequence of a vectorized Python function is: def mySimulator (x): [...] return y myfunction = PythonFunction(nbInputs, nbOutputs, func_sample = mySimulator) where * x: the input of the function, a `Sample` with size `nbExperiments` (`getSize`) and dimension `nbInputs` (`getDimension`), * y: the output of the function * a numpy `array` with `nbExperiments` rows and `nbOutputs` columns * or a `Sample` with size `nbExperiments` and dimension `nbOutputs` .. GENERATED FROM PYTHON SOURCE LINES 169-170 In the following, we present an vectorization example based on the `numpy` module. .. GENERATED FROM PYTHON SOURCE LINES 172-175 .. code-block:: default import numpy as np .. GENERATED FROM PYTHON SOURCE LINES 176-190 .. code-block:: default def mySimulatorVect (x): # Convert NumericalSample > Array Numpy x = np.array (x) x0 = x[: ,0] # Extract column 0 x1 = x[: ,1] x2 = x[: ,2] y0 = x0 + x1 + x2 y1 = x0 - x1 * x2 # Stack the two rows y = np.vstack ((y0 ,y1 )) y = y.transpose () return y .. GENERATED FROM PYTHON SOURCE LINES 191-193 .. code-block:: default myfunctionVect = ot.PythonFunction (3, 2, func_sample = mySimulatorVect ) .. GENERATED FROM PYTHON SOURCE LINES 194-196 .. code-block:: default outputVect = ot.CompositeRandomVector(myfunctionVect, inputRandomVector) .. GENERATED FROM PYTHON SOURCE LINES 197-205 .. code-block:: default montecarlosize = 10000 outputSample = outputVect.getSample(montecarlosize) empiricalMean = outputSample.computeMean() print(empiricalMean) empiricalSd = outputSample.computeStandardDeviation() print(empiricalSd) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [0.000783921,0.0295123] [1.69871,1.40625] .. GENERATED FROM PYTHON SOURCE LINES 206-220 How to manage the history ------------------------- The `MemoizeFunction` class defines a history system to store the calls to the function. ==================== =============================================== Methods Description ==================== =============================================== `enableHistory()` enables the history (it is enabled by default) `disableHistory()` disables the history `clearHistory()` deletes the content of the history `getHistoryInput()` a `Sample`, the history of inputs X `getHistoryOutput()` a `Sample`, the history of outputs Y ==================== =============================================== .. GENERATED FROM PYTHON SOURCE LINES 222-225 .. code-block:: default myfunction = ot.PythonFunction (3 ,2 , mySimulator ) myfunction = ot.MemoizeFunction(myfunction) .. GENERATED FROM PYTHON SOURCE LINES 226-230 .. code-block:: default outputVariableOfInterest = ot.CompositeRandomVector(myfunction, inputRandomVector) montecarlosize = 10 outputSample = outputVariableOfInterest.getSample(montecarlosize) .. GENERATED FROM PYTHON SOURCE LINES 231-232 Get the history of input points. .. GENERATED FROM PYTHON SOURCE LINES 234-237 .. code-block:: default inputs = myfunction.getInputHistory() inputs .. raw:: html
v0v1v2
01.239932-0.99098631.534201
11.8120981.200897-0.4582733
21.405359-0.9086479-1.26565
3-0.1699915-1.88662-0.4467178
41.5075990.4815180.01914742
50.1360075-0.8089527-2.306429
60.3516106-0.8275894-1.258126
70.06710225-0.88967190.2026469
80.6187073.195236-0.8220204
90.18429920.398224-0.02921958


.. GENERATED FROM PYTHON SOURCE LINES 238-249 Symbolic functions ------------------ The `SymbolicFunction` class can create symbolic functions whenever the function is simple enough to be expressed as a string. This has at least two significant advantages. * It generally improves the performance. * This allows to automatically evaluate the exact gradient and Hessian matrix. In practice, some functions cannot be expressed as a symbolic function: in this case, the Python function cannot be avoided. .. GENERATED FROM PYTHON SOURCE LINES 251-261 The calling sequence is the following: ` myfunction = SymbolicFunction( list_of_inputs, list_of_formulas) ` where * list_of_inputs: a `list` of `nbInputs` strings, the names of the input variables, * list_of_formulas: a `list` of `nbOutputs` strings, the equations. .. GENERATED FROM PYTHON SOURCE LINES 263-265 .. code-block:: default myfunction = ot.SymbolicFunction(("x0","x1","x2"),("x0 + x1 + x2","x0 - x1 * x2")) .. GENERATED FROM PYTHON SOURCE LINES 266-267 A `SymbolicFunction`, like any other function, can also have a history. .. GENERATED FROM PYTHON SOURCE LINES 269-271 .. code-block:: default myfunction = ot.MemoizeFunction(myfunction) .. GENERATED FROM PYTHON SOURCE LINES 272-274 .. code-block:: default outputVect = ot.CompositeRandomVector(myfunction, inputRandomVector) .. GENERATED FROM PYTHON SOURCE LINES 275-280 .. code-block:: default montecarlosize = 10000 outputSample = outputVect.getSample(montecarlosize) empiricalMean = outputSample.computeMean() print(empiricalMean) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [-0.00344238,0.00346235] .. GENERATED FROM PYTHON SOURCE LINES 281-282 Since the history is enabled, we can get the history of outputs of the function. .. GENERATED FROM PYTHON SOURCE LINES 284-286 .. code-block:: default outputs = myfunction.getOutputHistory() outputs[1:10,:] .. raw:: html
v0v1
0-4.624662-3.34754
1-0.36133560.6389562
20.67351850.2003821
3-0.20415821.429427
4-2.128861-2.153778
5-1.407545-0.2374226
6-0.93925671.41314
70.82174151.719395
82.7624722.69433


.. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.083 seconds) .. _sphx_glr_download_auto_functional_modeling_vectorial_functions_plot_quick_start_functions.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_quick_start_functions.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_quick_start_functions.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_