mda module¶
Base class for all Multi-disciplinary Design Analyses (MDA).
- class gemseo.mda.mda.MDA(disciplines, max_mda_iter=10, name=None, grammar_type=GrammarType.JSON, tolerance=1e-06, linear_solver_tolerance=1e-12, warm_start=False, use_lu_fact=False, coupling_structure=None, log_convergence=False, linear_solver='DEFAULT', linear_solver_options=None)[source]
Bases:
MDODiscipline
An MDA analysis.
Initialize self. See help(type(self)) for accurate signature.
- Parameters:
disciplines (list[MDODiscipline]) – The disciplines from which to compute the MDA.
max_mda_iter (int) –
The maximum iterations number for the MDA algorithm.
By default it is set to 10.
name (str | None) – The name to be given to the MDA. If None, use the name of the class.
grammar_type (MDODiscipline.GrammarType) –
The type of the input and output grammars.
By default it is set to “JSONGrammar”.
tolerance (float) –
The tolerance of the iterative direct coupling solver; the norm of the current residuals divided by initial residuals norm shall be lower than the tolerance to stop iterating.
By default it is set to 1e-06.
linear_solver_tolerance (float) –
The tolerance of the linear solver in the adjoint equation.
By default it is set to 1e-12.
warm_start (bool) –
Whether the second iteration and ongoing start from the previous coupling solution.
By default it is set to False.
use_lu_fact (bool) –
Whether to store a LU factorization of the matrix when using adjoint/forward differentiation. to solve faster multiple RHS problem.
By default it is set to False.
coupling_structure (MDOCouplingStructure | None) – The coupling structure to be used by the MDA. If None, it is created from disciplines.
log_convergence (bool) –
Whether to log the MDA convergence, expressed in terms of normed residuals.
By default it is set to False.
linear_solver (str) –
The name of the linear solver.
By default it is set to “DEFAULT”.
linear_solver_options (Mapping[str, Any]) – The options passed to the linear solver factory.
- class ResidualScaling(value)[source]
Bases:
LowercaseStrEnum
The scaling method applied to MDA residuals for convergence monitoring.
- INITIAL_RESIDUAL_COMPONENT = 'initial_residual_component'
The residual is scaled component-wise with the initial residual if not null, and not scaled otherwise. The MDA is considered converged when,
\[\max_i \left| \frac{(R_k)_i}{(R_0)_i} \right| \leq \text{tol}.\]
- INITIAL_RESIDUAL_NORM = 'initial_residual_norm'
The residual is scaled by the norm of the initial residual if it is not null, and not scaled otherwise. The MDA is considered converged when,
\[\frac{ \|R_k\|_2 }{ \|R_0\|_2 } \leq \text{tol}.\]
- INITIAL_SUBRESIDUAL_NORM = 'initial_subresidual_norm'
The residual is scaled by considering the convergence of each sub-residual individually. The MDA is considered converged when,
\[\max_i \left| \frac{\|r^i_k\|_2}{\|r^i_0\|_2} \right| \leq \text{tol}.\]
- NO_SCALING = 'no_scaling'
The residual is not scaled and the MDA is considered converged when,
\[\|R_k\|_2 \leq \text{tol}.\]
- N_COUPLING_VARIABLES = 'n_coupling_variables'
The residual is scaled by the number of coupling variables. The MDA is considered converged when,
\[\frac{ \|R_k\|_2 }{ \sqrt{n_\text{coupl.}} } \leq \text{tol}.\]
- SCALED_INITIAL_RESIDUAL_COMPONENT = 'scaled_initial_residual_component'
The residual is not scaled and the MDA is considered converged when.
\[\frac{1}{\sqrt{n_\text{coupl.}}} \| R_k \div R_0 \|_2 \leq \text{tol}.\]
- check_jacobian(input_data=None, derr_approx=ApproximationMode.FINITE_DIFFERENCES, step=1e-07, threshold=1e-08, linearization_mode='auto', inputs=None, outputs=None, parallel=False, n_processes=2, use_threading=False, wait_time_between_fork=0, auto_set_step=False, plot_result=False, file_path='jacobian_errors.pdf', show=False, fig_size_x=10, fig_size_y=10, reference_jacobian_path=None, save_reference_jacobian=False, indices=None)[source]
Check if the analytical Jacobian is correct with respect to a reference one.
If reference_jacobian_path is not None and save_reference_jacobian is True, compute the reference Jacobian with the approximation method and save it in reference_jacobian_path.
If reference_jacobian_path is not None and save_reference_jacobian is False, do not compute the reference Jacobian but read it from reference_jacobian_path.
If reference_jacobian_path is None, compute the reference Jacobian without saving it.
- Parameters:
input_data (Mapping[str, ndarray] | None) – The input values. If None, use the default input values.
derr_approx (MDODiscipline.ApproximationMode) –
The derivative approximation method.
By default it is set to “finite_differences”.
step (float) –
The step for finite differences or complex step differentiation methods.
By default it is set to 1e-07.
threshold (float) –
The acceptance threshold for the Jacobian error.
By default it is set to 1e-08.
linearization_mode (str) –
The mode of linearization, either “direct”, “adjoint” or “auto” switch depending on dimensions of inputs and outputs.
By default it is set to “auto”.
inputs (Iterable[str] | None) – The names of the inputs with respect to which to differentiate. If None, use the inputs of the MDA.
outputs (Iterable[str] | None) – The outputs to differentiate. If None, use all the outputs of the MDA.
parallel (bool) –
Whether to execute the MDA in parallel.
By default it is set to False.
n_processes (int) –
The maximum simultaneous number of threads, if
use_threading
is True, or processes otherwise, used to parallelize the execution.By default it is set to 2.
use_threading (bool) –
Whether to use threads instead of processes to parallelize the execution; multiprocessing will copy (serialize) all the disciplines, while threading will share all the memory. This is important to note if you want to execute the same discipline multiple times, you shall use multiprocessing.
By default it is set to False.
wait_time_between_fork (int) –
The time waited between two forks of the process / thread.
By default it is set to 0.
auto_set_step (bool) –
Whether to compute the optimal step for a forward first order finite differences gradient approximation.
By default it is set to False.
plot_result (bool) –
Whether to plot the result of the validation comparing the exact and approximated Jacobians.
By default it is set to False.
file_path (str | Path) –
The path to the output file if plot_result is True.
By default it is set to “jacobian_errors.pdf”.
show (bool) –
Whether to open the figure.
By default it is set to False.
fig_size_x (float) –
The x size of the figure in inches.
By default it is set to 10.
fig_size_y (float) –
The y size of the figure in inches.
By default it is set to 10.
reference_jacobian_path (None | Path | str) – The path of the reference Jacobian file.
save_reference_jacobian (bool) –
Whether to save the reference Jacobian.
By default it is set to False.
indices (Iterable[int] | None) – The indices of the inputs and outputs for the different sub-Jacobian matrices, formatted as
{variable_name: variable_components}
wherevariable_components
can be either an integer, e.g. 2 a sequence of integers, e.g. [0, 3], a slice, e.g. slice(0,3), the ellipsis symbol (…) or None, which is the same as ellipsis. If a variable name is missing, consider all its components. If None, consider all the components of all theinputs
andoutputs
.
- Returns:
Whether the passed Jacobian is correct.
- Return type:
- execute(input_data=None)[source]
Execute the discipline.
This method executes the discipline:
Adds the default inputs to the
input_data
if some inputs are not defined in input_data but exist inMDODiscipline.default_inputs
.Checks whether the last execution of the discipline was called with identical inputs, i.e. cached in
MDODiscipline.cache
; if so, directly returnsself.cache.get_output_cache(inputs)
.Caches the inputs.
Checks the input data against
MDODiscipline.input_grammar
.If
MDODiscipline.data_processor
is not None, runs the preprocessor.Updates the status to
MDODiscipline.ExecutionStatus.RUNNING
.Calls the
MDODiscipline._run()
method, that shall be defined.If
MDODiscipline.data_processor
is not None, runs the postprocessor.Checks the output data.
Caches the outputs.
Updates the status to
MDODiscipline.ExecutionStatus.DONE
orMDODiscipline.ExecutionStatus.FAILED
.Updates summed execution time.
- Parameters:
input_data (Mapping[str, Any] | None) – The input data needed to execute the discipline according to the discipline input grammar. If None, use the
MDODiscipline.default_inputs
.- Returns:
The discipline local data after execution.
- Raises:
RuntimeError – When residual_variables are declared but self.run_solves_residuals is False. This is not supported yet.
- Return type:
- get_expected_dataflow()[source]
Return the expected data exchange sequence.
This method is used for the XDSM representation.
The default expected data exchange sequence is an empty list.
See also
MDOFormulation.get_expected_dataflow
- Returns:
The data exchange arcs.
- Return type:
list[tuple[gemseo.core.discipline.MDODiscipline, gemseo.core.discipline.MDODiscipline, list[str]]]
- get_expected_workflow()[source]
Return the expected execution sequence.
This method is used for the XDSM representation.
The default expected execution sequence is the execution of the discipline itself.
See also
MDOFormulation.get_expected_workflow
- Returns:
The expected execution sequence.
- Return type:
- plot_residual_history(show=False, save=True, n_iterations=None, logscale=None, filename=None, fig_size=None)[source]
Generate a plot of the residual history.
The first iteration of each new execution is marked with a red dot.
- Parameters:
show (bool) –
Whether to display the plot on screen.
By default it is set to False.
save (bool) –
Whether to save the plot as a PDF file.
By default it is set to True.
n_iterations (int | None) – The number of iterations on the x axis. If None, use all the iterations.
logscale (tuple[int, int] | None) – The limits of the y axis. If None, do not change the limits of the y axis.
filename (str | None) – The name of the file to save the figure. If None, use “{mda.name}_residual_history.pdf”.
fig_size (FigSizeType | None) – The width and height of the figure in inches, e.g. (w, h).
- Returns:
The figure, to be customized if not closed.
- Return type:
Figure
- reset_disciplines_statuses()[source]
Reset all the statuses of the disciplines.
- Return type:
None
- reset_statuses_for_run()[source]
Set all the statuses to
MDODiscipline.ExecutionStatus.PENDING
.- Raises:
ValueError – When the discipline cannot be run because of its status.
- Return type:
None
- N_CPUS = 2
- RESIDUALS_NORM: ClassVar[str] = 'MDA residuals norm'
- activate_cache: bool = True
Whether to cache the discipline evaluations by default.
- assembly: JacobianAssembly
- cache: AbstractCache | None
The cache containing one or several executions of the discipline according to the cache policy.
- coupling_structure: MDOCouplingStructure
The coupling structure to be used by the MDA.
- data_processor: DataProcessor
A tool to pre- and post-process discipline data.
- exec_for_lin: bool
Whether the last execution was due to a linearization.
- input_grammar: BaseGrammar
The input grammar.
- jac: dict[str, dict[str, ndarray]]
The Jacobians of the outputs wrt inputs.
The structure is
{output: {input: matrix}}
.
- lin_cache_tol_fact: float
The tolerance factor to cache the Jacobian.
- linear_solver: str
The name of the linear solver.
- linear_solver_tolerance: float
The tolerance of the linear solver in the adjoint equation.
- property log_convergence: bool
Whether to log the MDA convergence.
- matrix_type: JacobianAssembly.JacobianType
The type of the matrix.
- max_mda_iter: int
The maximum iterations number for the MDA algorithm.
- name: str
The name of the discipline.
- normed_residual: float
The normed residual.
- output_grammar: BaseGrammar
The output grammar.
- re_exec_policy: ReExecutionPolicy
The policy to re-execute the same discipline.
- reset_history_each_run: bool
Whether to reset the history of MDA residuals before each run.
- residual_variables: Mapping[str, str]
The output variables mapping to their inputs, to be considered as residuals; they shall be equal to zero.
- run_solves_residuals: bool
Whether the run method shall solve the residuals.
- scaling: ResidualScaling
The scaling method applied to MDA residuals for convergence monitoring.
- tolerance: float
The tolerance of the iterative direct coupling solver.
- use_lu_fact: bool
Whether to store a LU factorization of the matrix.
- warm_start: bool
Whether the second iteration and ongoing start from the previous solution.
Examples using MDA¶
MDAChain with independent parallel MDAs