Create a discipline from a Python function

Import

from __future__ import annotations

from numpy import array
from numpy import empty

from gemseo import configure_logger
from gemseo import create_discipline

configure_logger()
<RootLogger root (INFO)>

Build a discipline from a simple Python function

Let’s consider a simple Python function, e.g.:

def f(x=0.0, y=0.0):
    """A simple Python function."""
    z = x + 2 * y
    return z

Create and instantiate the discipline

Then, we can consider the AutoPyDiscipline class to convert it into an MDODiscipline. For that, we can use the create_discipline() API function with 'AutoPyDiscipline' as first argument:

disc = create_discipline("AutoPyDiscipline", py_func=f)
WARNING - 01:06:17: Discipline f: py_func has inconsistent type hints: either both the signature arguments and the return values shall have type hints or none. The grammars will not use the type hints at all.

The original Python function may or may not include default values for input arguments, however, if the resulting AutoPyDiscipline is going to be placed inside an MDF, a BiLevel formulation or a BaseMDA with strong couplings, then the Python function must assign default values for its input arguments.

Execute the discipline

Then, we can execute it easily, either considering default inputs:

disc.execute()
{'x': array([0.]), 'y': array([0.]), 'z': array([0.])}

or using new inputs:

disc.execute({"x": array([1.0]), "y": array([-3.2])})
{'x': array([1.]), 'y': array([-3.2]), 'z': array([-5.4])}

Optional arguments

The optional arguments passed to the constructor are:

  • py_jac=None: pointer to the jacobian function which must returned a 2D numpy array (see below),

  • use_arrays=False: if True, the function is expected to take arrays as inputs and give outputs as arrays,

  • write_schema=False: if True, write the json schema on the disk.

Define the jacobian function

Here is an example of jacobian function:

def dfdxy(x=0.0, y=0.0):
    """Jacobian function of f."""
    jac = empty((2, 1))
    jac[0, 0] = 1
    jac[1, 0] = 2
    return jac

that we can execute with default inputs for example:

dfdxy()
array([[1.],
       [2.]])

Total running time of the script: (0 minutes 0.007 seconds)

Gallery generated by Sphinx-Gallery