component.py#
Define the Component class.
- class openmdao.core.component.Component(**kwargs)[source]
Bases:
SystemBase Component class; not to be directly instantiated.
- Parameters:
- **kwargsdict of keyword arguments
Available here and in all descendants of this system.
- Attributes:
- _var_rel2metadict
Dictionary mapping relative names to metadata. This is only needed while adding inputs and outputs. During setup, these are used to build the dictionaries of metadata. This contains both continuous and discrete variables.
- _static_var_rel2metadict
Static version of above - stores data for variables added outside of setup.
- _var_rel_names{‘input’: [str, …], ‘output’: [str, …]}
List of relative names of owned variables existing on current proc. This is only needed while adding inputs and outputs. During setup, these are used to determine the list of absolute names. This includes only continuous variables.
- _static_var_rel_namesdict
Static version of above - stores names of variables added outside of setup.
- _declared_partials_patternsdict
Dictionary of declared partials patterns. Each key is a tuple of the form (of, wrt) where of and wrt may be glob patterns.
- _declared_partial_checkslist
Cached storage of user-declared check partial options.
- _no_check_partialsbool
If True, the check_partials function will ignore this component.
- _has_distrib_outputsbool
If True, this component has at least one distributed output.
- _compute_primals_out_shapetuple or None
Cached (shape, istuple) of the output from compute_primal function. If istuple is True, then shape is a tuple of shapes, otherwise it is a single shape.
- _valid_name_mapdict
Mapping of declared input/output names to valid Python names.
- _orig_compute_primalfunction
The original compute_primal method.
Methods
abs_meta_iter(iotype[, local, cont, discrete])Iterate over absolute variable names and their metadata for this System.
add_constraint(name[, lower, upper, equals, ...])Add a constraint variable to this system.
add_design_var(name[, lower, upper, ref, ...])Add a design variable to this system.
add_discrete_input(name, val[, desc, tags, ...])Add a discrete input variable to the component.
add_discrete_output(name, val[, desc, tags, ...])Add an output variable to the component.
add_input(name[, val, shape, units, desc, ...])Add an input variable to the component.
add_objective(name[, ref, ref0, index, ...])Add a response variable to this system.
add_output(name[, val, shape, units, ...])Add an output variable to the component.
add_recorder(recorder[, recurse])Add a recorder to the system.
add_response(name, type_[, lower, upper, ...])Add a response variable to this system.
best_partial_deriv_direction()Return the best direction for partial deriv calculations based on input and output sizes.
check_config(logger)Perform optional error checks.
check_partials([out_stream, compact_print, ...])Check partial derivatives comprehensively for this component.
check_sparsity([method, max_nz, out_stream])Check the sparsity of the computed jacobian against the declared sparsity.
cleanup()Clean up resources prior to exit.
comm_info_iter()Yield comm size for this system and all subsystems.
compute_fd_jac(jac[, method])Force the use of finite difference to compute a jacobian.
compute_sparsity([direction, num_iters, ...])Compute the sparsity of the partial jacobian.
convert2units(name, val, units)Convert the given value to the specified units.
convert_from_units(name, val, units)Convert the given value from the specified units to those of the named variable.
convert_units(name, val, units_from, units_to)Wrap the utility convert_units and give a good error message.
declare_coloring([wrt, method, form, step, ...])Set options for deriv coloring of a set of wrt vars matching the given pattern(s).
declare_partials(of, wrt[, dependent, rows, ...])Declare information about this component's subjacobians.
dist_size_iter(io, top_comm)Yield names and distributed ranges of all local and remote variables in this system.
get_coloring_fname(mode)Return the full pathname to a coloring file.
get_conn_graph()Return the model connection graph.
get_constraints([recurse, get_sizes, ...])Get the Constraint settings from this system.
get_declare_partials_calls([sparsity])Return a string containing declare_partials() calls based on the subjac sparsity.
get_design_vars([recurse, get_sizes, ...])Get the DesignVariable settings from this system.
get_io_metadata([iotypes, metadata_keys, ...])Retrieve metadata for a filtered list of variables.
get_linear_vectors()Return the linear inputs, outputs, and residuals vectors.
get_nonlinear_vectors()Return the inputs, outputs, and residuals vectors.
get_objectives([recurse, get_sizes, ...])Get the Objective settings from this system.
get_outputs_dir(*subdirs[, mkdir])Get the path under which all output files of this system are to be placed.
get_promotions([inprom, outprom])Return all promotions for the given promoted variable(s).
get_reports_dir()Get the path to the directory where the report files should go.
get_responses([recurse, get_sizes, use_prom_ivc])Get the response variable settings from this system.
get_self_statics()Override this in derived classes if compute_primal references static values.
get_source(name)Return the source variable connected to the given named variable.
get_val(name[, units, indices, get_remote, ...])Get an output/input/residual variable.
get_var_dup_info(name, io)Return information about how the given variable is duplicated across MPI processes.
get_var_sizes(name, io)Return the sizes of the given variable on all procs.
has_vectors()Check if the system vectors have been initialized.
initialize()Perform any one-time initialization run at instantiation.
is_explicit([is_comp])Return True if this is an explicit component.
list_inputs([val, prom_name, units, shape, ...])Write a list of input names and other optional information to a specified stream.
list_options([include_default, ...])Write a list of output names and other optional information to a specified stream.
list_outputs([explicit, implicit, val, ...])Write a list of output names and other optional information to a specified stream.
list_vars([val, prom_name, residuals, ...])Write a list of inputs and outputs sorted by component in execution order.
load_case(case)Pull all input and output variables from a Case into this System.
load_model_options()Load the relevant model options from Problem._metadata['model_options'].
record_iteration()Record an iteration of the current System.
run_apply_linear(mode[, scope_out, scope_in])Compute jac-vec product.
run_apply_nonlinear()Compute residuals.
run_linearize([sub_do_ln])Compute jacobian / factorization.
run_solve_linear(mode)Apply inverse jac product.
run_solve_nonlinear()Compute outputs.
run_validation()Run validate method on all systems below this system.
set_check_partial_options(wrt[, method, ...])Set options that will be used for checking partial derivatives.
set_constraint_options(name[, ref, ref0, ...])Set options for constraints in the model.
set_design_var_options(name[, lower, upper, ...])Set options for design vars in the model.
set_objective_options(name[, ref, ref0, ...])Set options for objectives in the model.
set_output_solver_options(name[, lower, ...])Set solver output options.
set_solver_print([level, depth, type_, ...])Control printing for solvers and subsolvers in the model.
set_val(name, val[, units, indices])Set an input or output variable.
setup()Declare inputs and outputs.
setup_partials()Declare partials.
sparsity_matches_fd([direction, outstream])Compare the sparsity computed by this system vs.
subjac_sparsity_iter(sparsity[, wrt_matches])Iterate over sparsity for each subjac in the jacobian.
system_iter([include_self, recurse, typ, ...])Yield a generator of local subsystems of this system.
total_local_size(io)Return the total local size of the given variable.
use_fixed_coloring([coloring, recurse])Use a precomputed coloring for this System.
uses_approx()Return True if the system uses approximations to compute derivatives.
validate(inputs, outputs[, discrete_inputs, ...])Check any final input / output values after a run.
- __init__(**kwargs)[source]
Initialize all attributes.
- add_discrete_input(name, val, desc='', tags=None, primal_name=None)[source]
Add a discrete input variable to the component.
- Parameters:
- namestr
Name of the variable in this component’s namespace.
- vala picklable object
The initial value of the variable being added.
- descstr
Description of the variable.
- tagsstr or list of strs
User defined tags that can be used to filter what gets listed when calling list_inputs and list_outputs.
- primal_namestr or None
Valid python name to represent the variable in compute_primal if ‘name’ is not a valid python name.
- Returns:
- dict
Metadata for added variable.
- add_discrete_output(name, val, desc='', tags=None, primal_name=None)[source]
Add an output variable to the component.
- Parameters:
- namestr
Name of the variable in this component’s namespace.
- vala picklable object
The initial value of the variable being added.
- descstr
Description of the variable.
- tagsstr or list of strs or set of strs
User defined tags that can be used to filter what gets listed when calling list_inputs and list_outputs.
- primal_namestr or None
Valid python name to represent the variable in compute_primal if ‘name’ is not a valid python name.
- Returns:
- dict
Metadata for added variable.
- add_input(name, val=1.0, shape=None, units=None, desc='', tags=None, shape_by_conn=False, copy_shape=None, compute_shape=None, units_by_conn=False, copy_units=None, compute_units=None, require_connection=False, distributed=None, primal_name=None)[source]
Add an input variable to the component.
- Parameters:
- namestr
Name of the variable in this component’s namespace.
- valfloat or list or tuple or ndarray or Iterable
The initial value of the variable being added in user-defined units. Default is 1.0.
- shapeint or tuple or list or None
Shape of this variable, only required if val is not an array. Default is None.
- unitsstr or None
Units in which this input variable will be provided to the component during execution. Default is None, which means it is unitless.
- descstr
Description of the variable.
- tagsstr or list of strs
User defined tags that can be used to filter what gets listed when calling list_inputs and list_outputs.
- shape_by_connbool
If True, shape this input to match its connected output.
- copy_shapestr or None
If a str, that str is the name of a variable. Shape this input to match that of the named variable.
- compute_shapefunction
A function taking a dict arg containing names and shapes of this component’s outputs and returning the shape of this input.
- units_by_connbool
If True, set units of this input to match its connected output.
- copy_unitsstr or None
If a str, that str is the name of a variable. Set the units of this input to match those of the named variable.
- compute_unitsfunction
A function taking a dict arg containing names and PhysicalUnits of this component’s outputs and returning the PhysicalUnits of this input.
- require_connectionbool
If True and this input is not a design variable, it must be connected to an output.
- distributedbool
If True, this variable is a distributed variable, so it can have different sizes/values across MPI processes.
- primal_namestr or None
Valid python name to represent the variable in compute_primal if ‘name’ is not a valid python name.
- Returns:
- dict
Metadata for added variable.
- add_output(name, val=1.0, shape=None, units=None, res_units=None, desc='', lower=None, upper=None, ref=1.0, ref0=0.0, res_ref=None, tags=None, shape_by_conn=False, copy_shape=None, compute_shape=None, units_by_conn=False, copy_units=None, compute_units=None, distributed=None, primal_name=None)[source]
Add an output variable to the component.
- Parameters:
- namestr
Name of the variable in this component’s namespace.
- valfloat or list or tuple or ndarray
The initial value of the variable being added in user-defined units. Default is 1.0.
- shapeint or tuple or list or None
Shape of this variable, only required if val is not an array. Default is None.
- unitsstr or None
Units in which the output variables will be provided to the component during execution. Default is None, which means it has no units.
- res_unitsstr or None
Units in which the residuals of this output will be given to the user when requested. Default is None, which means it has no units.
- descstr
Description of the variable.
- lowerfloat or list or tuple or ndarray or Iterable or None
Lower bound(s) in user-defined units. It can be (1) a float, (2) an array_like consistent with the shape arg (if given), or (3) an array_like matching the shape of val, if val is array_like. A value of None means this output has no lower bound. Default is None.
- upperfloat or list or tuple or ndarray or or Iterable None
Upper bound(s) in user-defined units. It can be (1) a float, (2) an array_like consistent with the shape arg (if given), or (3) an array_like matching the shape of val, if val is array_like. A value of None means this output has no upper bound. Default is None.
- reffloat or ndarray
Scaling parameter. The value in the user-defined units of this output variable when the scaled value is 1. Default is 1.
- ref0float or ndarray
Scaling parameter. The value in the user-defined units of this output variable when the scaled value is 0. Default is 0.
- res_reffloat or ndarray
Scaling parameter. The value in the user-defined res_units of this output’s residual when the scaled value is 1. Default is 1.
- tagsstr or list of strs or set of strs
User defined tags that can be used to filter what gets listed when calling list_inputs and list_outputs.
- shape_by_connbool
If True, shape this output to match its connected input(s).
- copy_shapestr or None
If a str, that str is the name of a variable. Shape this output to match that of the named variable.
- compute_shapefunction
A function taking a dict arg containing names and shapes of this component’s inputs and returning the shape of this output.
- units_by_connbool
If True, set the units of this output to match its connected input(s).
- copy_unitsstr or None
If a str, that str is the name of a variable. Set the units of this output to match those of the named variable.
- compute_unitsfunction
A function taking a dict arg containing names and PhysicalUnits of this component’s inputs and returning the PhysicalUnits of this output.
- distributedbool
If True, this variable is a distributed variable, so it can have different sizes/values across MPI processes.
- primal_namestr or None
Valid python name to represent the variable in compute_primal if ‘name’ is not a valid python name.
- Returns:
- dict
Metadata for added variable.
- check_partials(out_stream=DEFAULT_OUT_STREAM, compact_print=False, abs_err_tol=0.0, rel_err_tol=1e-06, method='fd', step=None, form='forward', step_calc='abs', minimum_step=1e-12, force_dense=True, show_only_incorrect=False, show_worst=True, rich_print=True)[source]
Check partial derivatives comprehensively for this component.
- Parameters:
- out_streamfile-like object
Where to send human readable output. By default it goes to stdout. Set to None to suppress.
- compact_printbool
Set to True to just print the essentials, one line per input-output pair.
- abs_err_tolfloat
Threshold value for absolute error. Errors about this value will have a ‘*’ displayed next to them in output, making them easy to search for. Default is 1.0E-6.
- rel_err_tolfloat
Threshold value for relative error. Errors about this value will have a ‘*’ displayed next to them in output, making them easy to search for. Note at times there may be a significant relative error due to a minor absolute error. Default is 1.0E-6.
- methodstr
Method, ‘fd’ for finite difference or ‘cs’ for complex step. Default is ‘fd’.
- stepNone, float, or list/tuple of float
Step size(s) for approximation. Default is None, which means 1e-6 for ‘fd’ and 1e-40 for ‘cs’.
- formstr
Form for finite difference, can be ‘forward’, ‘backward’, or ‘central’. Default ‘forward’.
- step_calcstr
Step type for computing the size of the finite difference step. It can be ‘abs’ for absolute, ‘rel_avg’ for a size relative to the absolute value of the vector input, or ‘rel_element’ for a size relative to each value in the vector input. In addition, it can be ‘rel_legacy’ for a size relative to the norm of the vector. For backwards compatibilty, it can be ‘rel’, which is now equivalent to ‘rel_avg’. Defaults to None, in which case the approximation method provides its default value.
- minimum_stepfloat
Minimum step size allowed when using one of the relative step_calc options.
- force_densebool
If True, analytic derivatives will be coerced into arrays. Default is True.
- show_only_incorrectbool, optional
Set to True if output should print only the subjacs found to be incorrect.
- show_worstbool, optional
Set to False to suppress the display of the worst subjac.
- rich_printbool, optional
If True, print using rich if available.
- Returns:
- tuple of the form (derivs_dict, worst)
Where derivs_dict is a dict, where the top key is the component pathname. Under the top key, the subkeys are the (of, wrt) keys of the subjacs. Within the (of, wrt) entries are the following keys: ‘tol violation’, ‘magnitude’, ‘J_fd’, ‘J_fwd’, ‘J_rev’, ‘vals_at_max_error’, and ‘rank_inconsistent’. For ‘J_fd’, ‘J_fwd’, ‘J_rev’ the value is a numpy array representing the computed Jacobian for the three different methods of computation. For ‘tol violation’ and ‘vals_at_max_error’ the value is a tuple containing values for forward - fd, reverse - fd, forward - reverse. For ‘magnitude’ the value is a tuple indicating the maximum magnitude of values found in Jfwd, Jrev, and Jfd. The boolean ‘rank_inconsistent’ indicates if the derivative wrt a serial variable is inconsistent across MPI ranks.
worst is either None or a tuple of the form (error, table_row, header) where error is the max error found, table_row is the formatted table row containing the max error, and header is the formatted table header. ‘worst’ is not None only if compact_print is True.
- check_sparsity(method='fd', max_nz=90.0, out_stream=DEFAULT_OUT_STREAM)[source]
Check the sparsity of the computed jacobian against the declared sparsity.
Check is skipped if one of the dimensions of the jacobian is 1 or if the percentage of nonzeros in the computed jacobian is greater than max_nz%.
- Parameters:
- methodstr
The type of finite difference to perform. Valid options are ‘fd’ for forward difference, or ‘cs’ for complex step.
- max_nzfloat
If the percentage of nonzeros in a sub-jacobian exceeds this, no warning is issued if the computed sparsity does not match the declared sparsity.
- out_streamfile-like object
Where to send the output. If None, output will be suppressed.
- Returns:
- list
A list of tuples, one for each subjacobian that has a mismatch between the computed sparsity and the declared sparsity. Each tuple has the form (of, wrt, computed_rows, computed_cols, declared_rows, declared_cols, shape, pct_nonzero).
- property checking
Return True if check_partials or check_totals is executing.
- Returns:
- bool
True if we’re running within check_partials or check_totals.
- compute_fd_jac(jac, method='fd')[source]
Force the use of finite difference to compute a jacobian.
This can be used to compute sparsity for a component that computes derivatives analytically in order to check the accuracy of the declared sparsity.
- Parameters:
- jacJacobian
The Jacobian object that will contain the computed jacobian.
- methodstr
The type of finite difference to perform. Valid options are ‘fd’ for forward difference, or ‘cs’ for complex step.
- declare_coloring(wrt=('*',), method='fd', form=None, step=None, per_instance=True, num_full_jacs=3, tol=1e-25, orders=None, perturb_size=1e-09, min_improve_pct=5.0, show_summary=True, show_sparsity=False)[source]
Set options for deriv coloring of a set of wrt vars matching the given pattern(s).
- Parameters:
- wrtstr or list of str
The name or names of the variables that derivatives are taken with respect to. This can contain input names, output names, or glob patterns.
- methodstr
Method used to compute derivative: “fd” for finite difference, “cs” for complex step.
- formstr
Finite difference form, can be “forward”, “central”, or “backward”. Leave undeclared to keep unchanged from previous or default value.
- stepfloat
Step size for finite difference. Leave undeclared to keep unchanged from previous or default value.
- per_instancebool
If True, a separate coloring will be generated for each instance of a given class. Otherwise, only one coloring for a given class will be generated and all instances of that class will use it.
- num_full_jacsint
Number of times to repeat partial jacobian computation when computing sparsity.
- tolfloat
Tolerance used to determine if an array entry is nonzero during sparsity determination.
- ordersint
Number of orders above and below the tolerance to check during the tolerance sweep.
- perturb_sizefloat
Size of input/output perturbation during generation of sparsity.
- min_improve_pctfloat
If coloring does not improve (decrease) the number of solves more than the given percentage, coloring will not be used.
- show_summarybool
If True, display summary information after generating coloring.
- show_sparsitybool
If True, display sparsity with coloring info after generating coloring.
- declare_partials(of, wrt, dependent=True, rows=None, cols=None, val=None, method='exact', step=None, form=None, step_calc=None, minimum_step=None, diagonal=None)[source]
Declare information about this component’s subjacobians.
- Parameters:
- ofstr or iter of str
The name of the residual(s) that derivatives are being computed for. May also contain a glob pattern.
- wrtstr or iter of str
The name of the variables that derivatives are taken with respect to. This can contain the name of any input or output variable. May also contain a glob pattern.
- dependentbool(True)
If False, specifies no dependence between the output(s) and the input(s). This is only necessary in the case of a sparse global jacobian, because if ‘dependent=False’ is not specified and declare_partials is not called for a given pair, then a dense matrix of zeros will be allocated in the sparse global jacobian for that pair. In the case of a dense global jacobian it doesn’t matter because the space for a dense subjac will always be allocated for every pair.
- rowsndarray of int or None
Row indices for each nonzero entry. For sparse subjacobians only.
- colsndarray of int or None
Column indices for each nonzero entry. For sparse subjacobians only.
- valfloat or ndarray of float or scipy.sparse
Value of subjacobian. If rows and cols are not None, this will contain the values found at each (row, col) location in the subjac.
- methodstr
The type of approximation that should be used. Valid options include: ‘fd’: Finite Difference, ‘cs’: Complex Step, ‘exact’: use the component defined analytic derivatives. Default is ‘exact’.
- stepfloat
Step size for approximation. Defaults to None, in which case the approximation method provides its default value.
- formstr
Form for finite difference, can be ‘forward’, ‘backward’, or ‘central’. Defaults to None, in which case the approximation method provides its default value.
- step_calcstr
Step type for computing the size of the finite difference step. It can be ‘abs’ for absolute, ‘rel_avg’ for a size relative to the absolute value of the vector input, or ‘rel_element’ for a size relative to each value in the vector input. In addition, it can be ‘rel_legacy’ for a size relative to the norm of the vector. For backwards compatibilty, it can be ‘rel’, which is now equivalent to ‘rel_avg’. Defaults to None, in which case the approximation method provides its default value.
- minimum_stepfloat
Minimum step size allowed when using one of the relative step_calc options.
- diagonalbool
If True, the subjacobian is a diagonal matrix.
- Returns:
- dict
Metadata dict for the specified partial(s).
- get_declare_partials_calls(sparsity=None)[source]
Return a string containing declare_partials() calls based on the subjac sparsity.
- Parameters:
- sparsitycoo_matrix or None
Sparsity matrix to use. If None, compute_sparsity will be called to compute it.
- Returns:
- str
A string containing a declare_partials() call for each nonzero subjac. This string may be cut and pasted into a component’s setup() method.
- set_check_partial_options(wrt, method='fd', form=None, step=None, step_calc=None, minimum_step=None, directional=False)[source]
Set options that will be used for checking partial derivatives.
- Parameters:
- wrtstr or list of str
The name or names of the variables that derivatives are taken with respect to. This can contain the name of any input or output variable. May also contain a glob pattern.
- methodstr
Method for check: “fd” for finite difference, “cs” for complex step.
- formstr
Finite difference form for check, can be “forward”, “central”, or “backward”. Leave undeclared to keep unchanged from previous or default value.
- stepfloat
Step size for finite difference check. Leave undeclared to keep unchanged from previous or default value.
- step_calcstr
Step type for computing the size of the finite difference step. It can be ‘abs’ for absolute, ‘rel_avg’ for a size relative to the absolute value of the vector input, or ‘rel_element’ for a size relative to each value in the vector input. In addition, it can be ‘rel_legacy’ for a size relative to the norm of the vector. For backwards compatibilty, it can be ‘rel’, which is now equivalent to ‘rel_avg’. Defaults to None, in which case the approximation method provides its default value..
- minimum_stepfloat
Minimum step size allowed when using one of the relative step_calc options.
- directionalbool
Set to True to perform a single directional derivative for each vector variable in the pattern named in wrt.
- setup()[source]
Declare inputs and outputs.
- Available attributes:
name pathname comm options
- setup_partials()[source]
Declare partials.
This is meant to be overridden by component classes. All partials should be declared here since this is called after all size/shape information is known for all variables.