Create a discipline from a python function

from __future__ import absolute_import, division, print_function, unicode_literals

from future import standard_library

Import

from numpy import array, empty

from gemseo.api import configure_logger, create_discipline

configure_logger()

standard_library.install_aliases()

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 a MDODiscipline. For that, we can use the create_discipline() API function with 'AutoPyDiscipline' as first argument:

disc = create_discipline("AutoPyDiscipline", py_func=f)

Execute the discipline

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

print(disc.execute())

Out:

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

or using new inputs:

print(disc.execute({"x": array([1.0]), "y": array([-3.2])}))

Out:

{'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:

print(dfdxy())

Out:

[[1.]
 [2.]]

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

Gallery generated by Sphinx-Gallery