gemseo.core.mdo_functions.mdo_function module#

Base class to describe a function.

class MDOFunction(func, name, f_type=FunctionType.NONE, jac=None, expr='', input_names=(), dim=0, output_names=(), force_real=False, special_repr='', original_name='', with_normalized_inputs=False)[source]#

Bases: object

The standard definition of an array-based function with algebraic operations.

MDOFunction is the key class to define the objective function, the constraints and the observables of an OptimizationProblem.

an MDOFunction is initialized from an optional callable and a name, e.g. func = MDOFunction(lambda x: 2*x, "my_function").

Note

The callable can be set to None when the user does not want to use a callable but a database to browse for the output vector corresponding to an input vector (see MDOFunction.set_pt_from_database()).

The following information can also be provided at initialization:

  • the type of the function, e.g. f_type="obj" if the function will be used as an objective (see MDOFunction.FunctionType),

  • the function computing the Jacobian matrix, e.g. jac=lambda x: array([2.]),

  • the literal expression to be used for the string representation of the object, e.g. expr="2*x",

  • the names of the inputs and outputs of the function, e.g. input_names=["x"] and output_names=["y"].

Warning

For the literal expression, do not use "f(x) = 2*x" nor "f = 2*x" but "2*x". The other elements will be added automatically in the string representation of the function based on the name of the function and the names of its inputs.

After the initialization, all of these arguments can be overloaded with setters, e.g. MDOFunction.input_names.

The original function and Jacobian function can be accessed with the properties MDOFunction.func and MDOFunction.jac.

an MDOFunction is callable: output = func(array([3.])) # expected: array([6.]).

Elementary operations can be performed with MDOFunction instances: addition (func = func1 + func2 or func = func1 + offset), subtraction (func = func1 - func2 or func = func1 - offset), multiplication (func = func1 * func2 or func = func1 * factor) and opposite (func = -func1). It is also possible to build an MDOFunction as a concatenation of MDOFunction objects: func = MDOFunction.concatenate([func1, func2, func3], "my_func_123").

Moreover, an MDOFunction can be approximated with either a first-order or second-order Taylor polynomial at a given input vector, using respectively MDOFunction.linear_approximation() and quadratic_approx(); such an approximation is also an MDOFunction.

Lastly, the user can check the Jacobian function by means of approximation methods (see MDOFunction.check_grad()).

Parameters:
  • func (WrappedFunctionType | None) -- The original function to be actually called. If None, the function will not have an original function.

  • name (str) -- The name of the function.

  • f_type (FunctionType) --

    The type of the function.

    By default it is set to "".

  • jac (WrappedJacobianType | None) -- The original Jacobian function to be actually called. If None, the function will not have an original Jacobian function.

  • expr (str) --

    The expression of the function, e.g. "2*x", if any.

    By default it is set to "".

  • input_names (Iterable[str]) --

    The names of the inputs of the function. If empty, the inputs of the function will have no names.

    By default it is set to ().

  • dim (int) --

    The dimension of the output space of the function. If 0, the dimension of the output space of the function will be deduced from the evaluation of the function.

    By default it is set to 0.

  • output_names (Iterable[str]) --

    The names of the outputs of the function. If empty, the outputs of the function will have no names.

    By default it is set to ().

  • force_real (bool) --

    Whether to cast the output values to real.

    By default it is set to False.

  • special_repr (str) --

    The string representation of the function. If empty, use default_repr().

    By default it is set to "".

  • original_name (str) --

    The original name of the function. If empty, use the same name than the name input.

    By default it is set to "".

  • with_normalized_inputs (bool) --

    Whether the function expects normalized inputs.

    By default it is set to False.

class ApproximationMode(value)#

Bases: StrEnum

The approximation derivation modes.

CENTERED_DIFFERENCES = 'centered_differences'#

The centered differences method used to approximate the Jacobians by perturbing each variable with a small real number.

COMPLEX_STEP = 'complex_step'#

The complex step method used to approximate the Jacobians by perturbing each variable with a small complex number.

FINITE_DIFFERENCES = 'finite_differences'#

The finite differences method used to approximate the Jacobians by perturbing each variable with a small real number.

class ConstraintType(value)[source]#

Bases: StrEnum

The type of constraint.

EQ = 'eq'#

The type of function for equality constraint.

INEQ = 'ineq'#

The type of function for inequality constraint.

class FunctionType(value)#

Bases: StrEnum

An enumeration.

EQ = 'eq'#
INEQ = 'ineq'#
NONE = ''#
OBJ = 'obj'#
OBS = 'obs'#
check_grad(x_vect, approximation_mode=ApproximationMode.FINITE_DIFFERENCES, step=1e-06, error_max=1e-08)[source]#

Check the gradients of the function.

Parameters:
  • x_vect (ndarray[Any, dtype[number[Any]]]) -- The vector at which the function is checked.

  • approximation_mode (ApproximationMode) --

    The approximation mode.

    By default it is set to "finite_differences".

  • step (float) --

    The step for the approximation of the gradients.

    By default it is set to 1e-06.

  • error_max (float) --

    The maximum value of the error.

    By default it is set to 1e-08.

Raises:

ValueError -- Either if the approximation method is unknown, if the shapes of the analytical and approximated Jacobian matrices are inconsistent or if the analytical gradients are wrong.

Return type:

None

evaluate(x_vect)[source]#

Evaluate the function and store the output value in last_eval.

When the output dimension dim is not defined, it is inferred on the first evaluation.

Parameters:

x_vect (ndarray[Any, dtype[number[Any]]]) -- The input value of the function.

Returns:

Either the raw output value or its real part when force_real is True.

Return type:

ndarray[Any, dtype[number[Any]]] | Complex

static filt_0(arr, floor_value=1e-06)[source]#

Set the non-significant components of a vector to zero.

The component of a vector is non-significant if its absolute value is lower than a threshold.

Parameters:
Returns:

The original vector whose non-significant components have been set at zero.

Return type:

ndarray[Any, dtype[number[Any]]]

classmethod generate_input_names(input_dim, input_names=())[source]#

Generate the names of the inputs of the function.

Parameters:
  • input_dim (int) -- The dimension of the input space of the function.

  • input_names (Sequence[str]) --

    The initial names of the inputs of the function. If the number of names matches the dimension of the input space, use these names as is. Otherwise, if there is only one name, e.g. ["var"], and if the dimension of the input space is equal to 3, use this name as a base name and generate the names of the inputs, e.g. ["var[0]", "var[1]", "var[2]"]. If empty, use "x" as a base name and generate the names of the inputs, i.e. ["x[0]", "x[1]", "x[2]"].

    By default it is set to ().

Returns:

The names of the inputs of the function.

Return type:

Sequence[str]

get_indexed_name(index)[source]#

Return the name of function component.

Parameters:

index (int) -- The index of the function component.

Returns:

The name of the function component.

Return type:

str

static init_from_dict_repr(**attributes)[source]#

Initialize a new function.

This is typically used for deserialization.

Parameters:

**attributes (Any) -- The values of the serializable attributes listed in MDOFunction.DICT_REPR_ATTR.

Returns:

A function initialized from the provided data.

Raises:

ValueError -- If the name of an argument is not in MDOFunction.DICT_REPR_ATTR.

Return type:

MDOFunction

is_constraint()[source]#

Check if the function is a constraint.

The constraint type is either "eq" or "ineq".

Returns:

Whether the function is a constraint.

Return type:

bool

offset(value)[source]#

Add an offset value to the function.

Parameters:

value (ndarray[Any, dtype[number[Any]]] | Complex) -- The offset value.

Returns:

The offset function.

Return type:

MDOFunction

static rel_err(a_vect, b_vect, error_max)[source]#

Compute the 2-norm of the difference between two vectors.

Normalize it with the 2-norm of the reference vector if the latter is greater than the maximal error.

Parameters:
Returns:

The difference between two vectors, normalized if required.

Return type:

float

set_pt_from_database(database, design_space, normalize=False, jac=True, x_tolerance=1e-10)[source]#

Set the original function and Jacobian function from a database.

For a given input vector, the method MDOFunction.func() will return either the output vector stored in the database if the input vector is present or None. The same for the method MDOFunction.jac().

Parameters:
  • database (Database) -- The database to read.

  • design_space (DesignSpace) -- The design space used for normalization.

  • normalize (bool) --

    If True, the values of the inputs are unnormalized before call.

    By default it is set to False.

  • jac (bool) --

    If True, a Jacobian pointer is also generated.

    By default it is set to True.

  • x_tolerance (float) --

    The tolerance on the distance between inputs.

    By default it is set to 1e-10.

Return type:

None

to_dict()[source]#

Create a dictionary representation of the function.

This is used for serialization. The pointers to the functions are removed.

Returns:

Some attributes of the function indexed by their names. See MDOFunction.DICT_REPR_ATTR.

Return type:

dict[str, str | int | list[str]]

COEFF_FORMAT_1D: str = '{:.2e}'#

The format to be applied to a number when represented in a vector.

COEFF_FORMAT_ND: str = '{: .2e}'#

The format to be applied to a number when represented in a matrix.

DEFAULT_BASE_INPUT_NAME: str = 'x'#

The default base name for the inputs.

DICT_REPR_ATTR: ClassVar[list[str]] = ['name', 'f_type', 'expr', 'input_names', 'dim', 'special_repr', 'output_names']#

The names of the attributes to be serialized.

property default_repr: str#

The default string representation of the function.

property expects_normalized_inputs: bool#

Whether the function expects normalized inputs.

expr: str#

The expression of the function, e.g. "2*x".

f_type: FunctionType#

The type of the function.

force_real: bool#

Whether to cast the results to real value.

property func: Callable[[ndarray[Any, dtype[number[Any]]]], ndarray[Any, dtype[number[Any]]] | Complex]#

The wrapped function.

has_default_name: bool#

Whether the name has been set with a default value.

property has_jac: bool#

Whether the function has an implemented Jacobian function.

property input_names: list[str]#

The names of the inputs of the function.

Use a copy of the original names.

property jac: Callable[[ndarray[Any, dtype[number[Any]]]], ndarray[Any, dtype[number[Any]]]]#

The Jacobian function to be evaluated from a given input vector.

last_eval: OutputType | None#

The value of the function output at the last evaluation.

None if it has not yet been evaluated.

name: str#

The name of the function.

original: MDOFunction#

`.OptimizationProblem.

Type:

The function before preprocessing by the

Type:

class

property original_name: str#

The original name of the function.

property output_names: list[str]#

The names of the outputs of the function.

Use a copy of the original names.

special_repr: str#

The string representation of the function overloading its default string ones.