gemseo / core / mdofunctions

# mdo_function module¶

Base class to describe a function.

class gemseo.core.mdofunctions.mdo_function.MDOFunction(func, name, f_type='', jac=None, expr='', args=None, dim=0, outvars=None, force_real=False, special_repr='')[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.

A 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.AVAILABLE_TYPES for the available types),

• 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. args=["x"] and outvars=["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.args.

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

A 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 a MDOFunction as a concatenation of MDOFunction objects: func = MDOFunction.concatenate([func1, func2, func3], "my_func_123").

Moreover, a 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 a 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 (str) –

The type of the function among MDOFunction.AVAILABLE_TYPES if any.

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 “”.

• args (Iterable[str] | None) – The names of the inputs of the function. If None, the inputs of the function will have no names.

• 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.

• outvars (Iterable[str] | None) – The names of the outputs of the function. If None, the outputs of the function will have no names.

• 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 “”.

Check the gradients of the function.

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

• method (str) –

The method used to approximate the gradients, either “FirstOrderFD” or “ComplexStep”.

By default it is set to “FirstOrderFD”.

• 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

static concatenate(functions, name, f_type=None)[source]

Concatenate functions.

Parameters:
• functions (Iterable[MDOFunction]) – The functions to be concatenated.

• name (str) – The name of the concatenation function.

• f_type (str | None) – The type of the concatenation function. If None, the function will have no type.

Returns:

The concatenation of the functions.

Return type:

Concatenate

convex_linear_approx(x_vect, approx_indexes=None, sign_threshold=1e-09)[source]

Compute a convex linearization of the function.


$\begin{split}\newcommand{\partialder}{\frac{\partial f}{\partial x_i}(\xref)} f(x) \approx f(\xref) + \sum_{\substack{i = 1 \\ \partialder > 0}}^{\dim} \partialder \, (x_i - \xref_i) - \sum_{\substack{i = 1 \\ \partialder < 0}}^{\dim} \partialder \, \xref_i^2 \, \left(\frac{1}{x_i} - \frac{1}{\xref_i}\right).\end{split}$

$$\newcommand{\approxinds}{I}$$ Optionally, one may require the convex linearization of $$f$$ with respect to a subset of its variables $$x_{i \in \approxinds}$$, $$I \subset \{1, \dots, \dim\}$$, rather than all of them:

$\begin{split}f(x) = f(x_{i \in \approxinds}, x_{i \not\in \approxinds}) \approx f(\xref_{i \in \approxinds}, x_{i \not\in \approxinds}) + \sum_{\substack{i \in \approxinds \\ \partialder > 0}} \partialder \, (x_i - \xref_i) - \sum_{\substack{i \in \approxinds \\ \partialder < 0}} \partialder \, \xref_i^2 \, \left(\frac{1}{x_i} - \frac{1}{\xref_i}\right).\end{split}$
Parameters:
• x_vect (ArrayType) – The input vector at which to build the convex linearization.

• approx_indexes (ndarray[bool] | None) – A boolean mask specifying w.r.t. which inputs the function should be approximated. If None, consider all the inputs.

• sign_threshold (float) –

The threshold for the sign of the derivatives.

By default it is set to 1e-09.

Returns:

The convex linearization of the function at the given input vector.

Return type:

ConvexLinearApprox

static deserialize(file_path)[source]

Deserialize a function from a file.

Parameters:

file_path (str | Path) – The path to the file containing the function.

Returns:

The function instance.

Return type:

MDOFunction

evaluate(x_vect)[source]

Evaluate the function and store the dimension of the output space.

Parameters:

x_vect (ndarray[Any, dtype[Number]]) – The value of the inputs of the function.

Returns:

The value of the output of the function.

Return type:

Union[ndarray[Any, dtype[Number]], Number]

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:
• arr (ndarray[Any, dtype[Number]]) – The original vector.

• floor_value (float) –

The threshold.

By default it is set to 1e-06.

Returns:

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

Return type:
classmethod generate_args(input_dim, args=None)[source]

Generate the names of the inputs of the function.

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

• args (Sequence[str] | None) – The initial names of the inputs of the function. If there is only one name, e.g. ["var"], use this name as a base name and generate the names of the inputs, e.g. ["var!0", "var!1", "var!2"] if the dimension of the input space is equal to 3. If None, use "x" as a base name and generate the names of the inputs, i.e. ["x!0", "x!1", "x!2"].

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

has_args()[source]

Check if the inputs of the function have names.

Returns:

Whether the inputs of the function have names.

Return type:

bool

has_dim()[source]

Check if the dimension of the output space of the function is defined.

Returns:

Whether the dimension of the output space of the function is defined.

Return type:

bool

has_expr()[source]

Check if the function has an expression.

Returns:

Whether the function has an expression.

Return type:

bool

has_f_type()[source]

Check if the function has a type.

Returns:

Whether the function has a type.

Return type:

bool

has_jac()[source]

Check if the function has an implemented Jacobian function.

Returns:

Whether the function has an implemented Jacobian function.

Return type:

bool

has_outvars()[source]

Check if the outputs of the function have names.

Returns:

Whether the outputs of the function have names.

Return type:

bool

static init_from_dict_repr(**attributes)[source]

Initialize a new function.

This is typically used for deserialization.

Parameters:

**attributes – 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 type of a constraint function is either ‘eq’ or ‘ineq’.

Returns:

Whether the function is a constraint.

Return type:

bool

linear_approximation(x_vect, name=None, f_type=None, args=None)[source]

Compute a first-order Taylor polynomial of the function.


$\newcommand{\partialder}{\frac{\partial f}{\partial x_i}(\xref)} f(x) \approx f(\xref) + \sum_{i = 1}^{\dim} \partialder \, (x_i - \xref_i).$
Parameters:
• x_vect (ArrayType) – The input vector at which to build the Taylor polynomial.

• name (str | None) – The name of the linear approximation function. If None, create a name from the name of the function.

• f_type (str | None) – The type of the linear approximation function. If None, the function will have no type.

• args (Sequence[str] | None) – The names of the inputs of the linear approximation function, or a name base. If None, use the names of the inputs of the function.

Returns:

The first-order Taylor polynomial of the function at the input vector.

Return type:

MDOLinearFunction

offset(value)[source]

Add an offset value to the function.

Parameters:

value (Union[ndarray[Any, dtype[Number]], Number]) – The offset value.

Returns:

The offset function.

Return type:

MDOFunction

Build a quadratic approximation of the function at a given point.

The function must be scalar-valued.


$\newcommand{\partialder}{\frac{\partial f}{\partial x_i}(\xref)} f(x) \approx f(\xref) + \sum_{i = 1}^{\dim} \partialder \, (x_i - \xref_i) + \frac{1}{2} \sum_{i = 1}^{\dim} \sum_{j = 1}^{\dim} \hessapprox_{ij} (x_i - \xref_i) (x_j - \xref_j).$
Parameters:
• x_vect (ArrayType) – The input vector at which to build the quadratic approximation.

• hessian_approx (ArrayType) – The approximation of the Hessian matrix at this input vector.

• args (Sequence[str] | None) – The names of the inputs of the quadratic approximation function, or a name base. If None, use the ones of the current function.

Returns:

The second-order Taylor polynomial of the function at the given point.

Raises:
• ValueError – Either if the approximated Hessian matrix is not square, or if it is not consistent with the dimension of the given point.

• AttributeError – If the function does not have an implemented Jacobian function.

Return type:

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

restrict(frozen_indexes, frozen_values, input_dim, name=None, f_type=None, expr=None, args=None)[source]

Return a restriction of the function.


$\frestr: x_{i \not\in \approxinds} \longmapsto f(\xref_{i \in \approxinds}, x_{i \not\in \approxinds}).$
Parameters:
• frozen_indexes (ndarray[int]) – The indexes of the inputs that will be frozen

• frozen_values (ArrayType) – The values of the inputs that will be frozen.

• input_dim (int) – The dimension of input space of the function before restriction.

• name (str | None) – The name of the function after restriction. If None, create a default name based on the name of the current function and on the argument args.

• f_type (str | None) – The type of the function after restriction. If None, the function will have no type.

• expr (str | None) – The expression of the function after restriction. If None, the function will have no expression.

• args (Sequence[str] | None) – The names of the inputs of the function after restriction. If None, the inputs of the function will have no names.

Returns:

The restriction of the function.

Return type:

FunctionRestriction

serialize(file_path)[source]

Serialize the function and store it in a file.

Parameters:

file_path (str | Path) – The path to the file to store the function.

Return type:

None

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]]

AVAILABLE_TYPES: list[str] = ['obj', 'eq', 'ineq', 'obs']

The available types of function.

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_ARGS_BASE: str = 'x'

The default name base for the inputs.

DICT_REPR_ATTR: list[str] = ['name', 'f_type', 'expr', 'args', 'dim', 'special_repr']

The names of the attributes to be serialized.

INDEX_PREFIX: str = '!'

The character used to separate a name base and a prefix, e.g. "x!1.

TYPE_EQ: str = 'eq'

The type of function for equality constraint.

TYPE_INEQ: str = 'ineq'

The type of function for inequality constraint.

TYPE_OBJ: str = 'obj'

The type of function for objective.

TYPE_OBS: str = 'obs'

The type of function for observable.

activate_counters: ClassVar[bool] = True

Whether to count the number of function evaluations.

property args: list[str]

The names of the inputs of the function.

Use a copy of the original names.

property default_repr: str

The default string representation of the function.

property dim: int

The dimension of the output space of the function.

property expects_normalized_inputs: bool

Whether the functions expect normalized inputs or not.

property expr: str

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

property f_type: str

The type of the function, among MDOFunction.AVAILABLE_TYPES.

force_real: bool

Whether to cast the results to real value.

property func: Callable[[ndarray[Any, dtype[Number]]], Union[ndarray[Any, dtype[Number]], Number]]

The function to be evaluated from a given input vector.

has_default_name: bool

Whether the name has been set with a default value.

property jac: Callable[[ndarray[Any, dtype[Number]]], ndarray[Any, dtype[Number]]]

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.

property n_calls: int

The number of times the function has been evaluated.

This count is both multiprocess- and multithread-safe, thanks to the locking process used by MDOFunction.evaluate().

property name: str

The name of the function.

property outvars: list[str]

The names of the outputs of the function.

Use a copy of the original names.

special_repr: str

## Examples using MDOFunction¶

Analytical test case # 1

Analytical test case # 1

Analytical test case # 2

Analytical test case # 2

Analytical test case # 3

Analytical test case # 3

Change the seed of a DOE

Change the seed of a DOE