gemseo_umdo / formulations

# taylor_polynomial module¶

Taylor polynomials for multidisciplinary design problems under uncertainty.

TaylorPolynomial is an UMDOFormulation estimating the statistics with first- or second-order Taylor polynomials around the expectation of the uncertain variables: $$f(x,U)\approx f(x,\mu) + (U-\mu)f'(x,\mu) \pm 0.5(U-\mu)^2f''(x,\mu)$$.

E.g. $$\mathbb{E}[f(x,U)]\approx \frac{1}{N}\sum_{i=1}^N f\left(x,U^{(i)}\right)$$ or $$\mathbb{V}[f(x,U)]\approx \sigma^2f'(x,\mu)$$ where $$U$$ is normally distributed with mean $$\mu$$ and unit variance $$\sigma$$.

class gemseo_umdo.formulations.taylor_polynomial.HessianFunction(func)[source]

Bases: MDOFunction

Approximation of the Hessian function with finite differences.

Take an original function and approximate its Hessian with finite differences applied to its analytical or approximated Jacobian.

Initialize self. See help(type(self)) for accurate signature.

Parameters:

func (MDOFunction) – The original function.

class ApproximationMode(value)

Bases: StrEnum

The approximation derivation modes.

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)

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)

Check the gradients of the function.

Parameters:
• x_vect (ndarray[Any, dtype[Number]]) – 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)

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:

ndarray[Any, dtype[Number]] | Number

static filt_0(arr, floor_value=1e-06)

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:
static from_pickle(file_path)

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

classmethod generate_input_names(input_dim, input_names=None)

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

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)

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()

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

offset(value)

Add an offset value to the function.

Parameters:

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

Returns:

The offset function.

Return type:

MDOFunction

static rel_err(a_vect, b_vect, error_max)

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)

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()

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

to_pickle(file_path)

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

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: list[str] = ['name', 'f_type', 'expr', 'input_names', '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.

activate_counters: ClassVar[bool] = True

Whether to count the number of function evaluations.

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

force_real: bool

Whether to cast the results to real value.

property func: Callable[[ndarray[Any, dtype[Number]]], 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 has_jac: bool

Check if the function has an implemented Jacobian function.

Returns:

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

class gemseo_umdo.formulations.taylor_polynomial.TaylorPolynomial(disciplines, objective_name, design_space, mdo_formulation, uncertain_space, objective_statistic_name, objective_statistic_parameters=None, maximize_objective=False, grammar_type=GrammarType.JSON, differentiation_method=DifferentiationMethod.USER_GRAD, second_order=False, **options)[source]

Robust MDO formulation based on Taylor polynomials.

Parameters:
• disciplines (Sequence[MDODiscipline]) – The disciplines.

• objective_name (str) – The name(s) of the discipline output(s) used as objective. If multiple names are passed, the objective will be a vector.

• design_space (DesignSpace) – The design space.

• mdo_formulation (MDOFormulation) – The class name of the MDO formulation, e.g. “MDF”.

• uncertain_space (ParameterSpace) – The uncertain variables with their probability distributions.

• objective_statistic_name (str) – The name of the statistic to be applied to the objective.

• objective_statistic_parameters (Mapping[str, Any] | None) – The values of the parameters of the statistic to be applied to the objective, if any.

• maximize_objective (bool) –

Whether to maximize the objective.

By default it is set to False.

• grammar_type (MDODiscipline.GrammarType) –

The type of the input and output grammars.

By default it is set to “JSONGrammar”.

• differentiation_method (OptimizationProblem.DifferentiationMethod) –

The description is missing.

By default it is set to “user”.

• second_order (bool) –

The description is missing.

By default it is set to False.

• **options (Any) – The options of the formulation.

add_constraint(output_name, statistic_name, constraint_type=ConstraintType.INEQ, constraint_name=None, value=None, positive=False, **statistic_parameters)[source]

Add a user constraint.

A user constraint is a design constraint in addition to the formulation specific constraints such as the targets (a.k.a. consistency constraints) in IDF.

The strategy of repartition of constraints is defined in the formulation class.

Parameters:
• output_name (str | Sequence[str]) – The name of the output to be used as a constraint. For instance, if g_1 is given and constraint_type=”eq”, g_1=0 will be added as a constraint to the optimizer.

• statistic_name (str) – The name of the statistic to be applied to the constraint.

• constraint_type (str) –

The type of constraint, either “eq” for equality constraint or “ineq” for inequality constraint.

By default it is set to “ineq”.

• constraint_name (str | None) – The name of the constraint to be stored, If None, the name is generated from the output name.

• value (float | None) – The value of activation of the constraint. If None, the value is equal to 0.

• positive (bool) –

Whether to consider an inequality constraint as positive.

By default it is set to False.

• **statistic_parameters (Any) – The description is missing.

Return type:

None

add_observable(output_names, statistic_name, observable_name=None, discipline=None, **statistic_parameters)[source]

Add an observable to the optimization problem.

The repartition strategy of the observable is defined in the formulation class.

Parameters:
• output_names (Sequence[str]) – The name(s) of the output(s) to observe.

• statistic_name (str) – The name of the statistic to be applied to the observable.

• observable_name (Sequence[str] | None) – The name of the observable.

• discipline (MDODiscipline | None) – The discipline computing the observed outputs. If None, the discipline is detected from inner disciplines.

• **statistic_parameters (Any) – The description is missing.

Return type:

None

evaluate_with_mean(problem, eval_jac)[source]

Evaluate the functions of a problem at the mean of the uncertain variables.

Parameters:
Return type:

None

classmethod get_default_sub_option_values(**options)

Return the default values of the sub-options of the formulation.

When some options of the formulation depend on higher level options, the default values of these sub-options may be obtained here, mainly for use in the API.

Parameters:

**options (str) – The options required to deduce the sub-options grammar.

Returns:

Either None or the sub-options default values.

Return type:

dict

get_expected_dataflow()

Get the expected data exchange sequence.

This method is used for the XDSM representation and can be overloaded by subclasses.

Returns:

The expected sequence of data exchange where the i-th item is described by the starting discipline, the ending discipline and the coupling variables.

Return type:
get_expected_workflow()

Get the expected sequence of execution of the disciplines.

This method is used for the XDSM representation and can be overloaded by subclasses.

For instance:

• [A, B] denotes the execution of A, then the execution of B

• (A, B) denotes the concurrent execution of A and B

• [A, (B, C), D] denotes the execution of A, then the concurrent execution of B and C, then the execution of D.

Returns:

A sequence of elements which are either an ExecutionSequence or a tuple of ExecutionSequence for concurrent execution.

Return type:
get_optim_variable_names()

Get the optimization unknown names to be provided to the optimizer.

This is different from the design variable names provided by the user, since it depends on the formulation, and can include target values for coupling for instance in IDF.

Returns:

The optimization variable names.

Return type:

list[str]

get_sub_disciplines(recursive=False)

Accessor to the sub-disciplines.

This method lists the sub scenarios’ disciplines. It will list up to one level of disciplines contained inside another one unless the recursive argument is set to True.

Parameters:

recursive (bool) –

If True, the method will look inside any discipline that has other disciplines inside until it reaches a discipline without sub-disciplines, in this case the return value will not include any discipline that has sub-disciplines. If False, the method will list up to one level of disciplines contained inside another one, in this case the return value may include disciplines that contain sub-disciplines.

By default it is set to False.

Returns:

The sub-disciplines.

Return type:
classmethod get_sub_options_grammar(**options)

Get the sub-options grammar.

When some options of the formulation depend on higher level options, the schema of the sub-options may be obtained here, mainly for use in the API.

Parameters:

**options (str) – The options required to deduce the sub-options grammar.

Returns:

Either None or the sub-options grammar.

Return type:

JSONGrammar

get_sub_scenarios()

List the disciplines that are actually scenarios.

Returns:

The scenarios.

Return type:
get_top_level_disc()

Return the disciplines which inputs are required to run the scenario.

A formulation seeks to compute the objective and constraints from the input variables. It structures the optimization problem into multiple levels of disciplines. The disciplines directly depending on these inputs are called top level disciplines.

By default, this method returns all disciplines. This method can be overloaded by subclasses.

Returns:

The top level disciplines.

Return type:

Mask a vector from a subset of names, with respect to a set of names.

This method eventually swaps the order of the values if the order of the data names is inconsistent between these sets.

Parameters:
• masking_data_names (Iterable[str]) – The names of the kept data.

• all_data_names (Iterable[str] | None) – The set of all names. If None, use the design variables stored in the design space.

Returns:

The masked version of the input vector.

Raises:
• IndexError – when the sizes of variables are inconsistent.

• ValueError – when the names of variables are inconsistent.

Return type:

ndarray

get_x_names_of_disc(discipline)

Get the design variables names of a given discipline.

Parameters:

discipline (MDODiscipline) – The discipline.

Returns:

The names of the design variables.

Return type:

list[str]

Mask a vector from a subset of names, with respect to a set of names.

This method eventually swaps the order of the values if the order of the data names is inconsistent between these sets.

Parameters:
• masking_data_names (Iterable[str]) – The names of the kept data.

• x_vect (ndarray) – The vector to mask.

• all_data_names (Iterable[str] | None) – The set of all names. If None, use the design variables stored in the design space.

Returns:

The masked version of the input vector.

Raises:

IndexError – when the sizes of variables are inconsistent.

Return type:

ndarray

Unmask a vector from a subset of names, with respect to a set of names.

This method eventually swaps the order of the values if the order of the data names is inconsistent between these sets.

Parameters:
• masking_data_names (Iterable[str]) – The names of the kept data.

• x_masked (ndarray) – The boolean vector to unmask.

• all_data_names (Iterable[str] | None) – The set of all names. If None, use the design variables stored in the design space.

• x_full (ndarray) – The default values for the full vector. If None, use the zero vector.

Returns:

The vector related to the input mask.

Raises:

IndexError – when the sizes of variables are inconsistent.

Return type:

ndarray

update_top_level_disciplines(design_values)

Update the default input values of the top-level disciplines.

Parameters:

design_values (Mapping[str, Any]) – The values of the design variables to update the default input values of the top-level disciplines.

Return type:

None

NAME: ClassVar[str] = 'MDOFormulation'

The name of the MDO formulation.

property available_statistics: list[str]

The names of the statistics to quantify the output uncertainties.

property design_space: DesignSpace

The design space on which the formulation is applied.

property disciplines: list[gemseo.core.discipline.MDODiscipline]

The disciplines of the MDO process.

property hessian_fd_problem: OptimizationProblem

The problem related to the approximation of the Hessian.

property mdo_formulation: MDOFormulation

The MDO formulation.

opt_problem: OptimizationProblem

The optimization problem generated by the formulation from the disciplines.

property second_order: bool

Whether to use a second order approximation.

property uncertain_space: ParameterSpace

The uncertain variable space.