Build a discipline from a simple Python function#
Let's consider a simple Python function, e.g.:
def f(x=0., y=0.):
"""A simple Python function"""
z = x + 2*y
return z
Then, we can consider the AutoPyDiscipline
to convert it into an Discipline
.
Create and instantiate the discipline#
For that, we can use the create_discipline()
API function with AutoPyDiscipline
as first argument:
from gemseo import create_discipline
from numpy import array
disc = create_discipline('AutoPyDiscipline', py_func=f)
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, even considering default inputs:
print(disc.execute())
which results in:
{'y': array([ 0.]), 'x': array([ 0.]), 'z': array([ 0.])}
or using new inputs:
print(disc.execute({'x': array([1.]), 'y':array([-3.2])}))
which results in:
{'y': array([-3.2]), 'x': array([ 1.]), 'z': array([-5.4])}
Optional arguments#
Optional arguments are:
py_jac=None
: The Python function to compute the Jacobian which must return a 2D numpy array,use_arrays=False
: ifTrue
, the function is expected to take arrays as inputs and give outputs as arrays,grammar_type=Discipline.GrammarType.JSON
: The type of grammar to be used.
Here is an example of Jacobian function, returning a 2D matrix. The rows of the matrix correspond to the derivatives of the outputs, the columns correspond to the variables with respect to the outputs are derived.
def dzdxy(x=0., y=0.):
"""Jacobian function of z=f(x,y)"""
jac = array((1,2))
jac[0, 0] = 1.
jac[0, 1] = 2.
return jac