problem.py

Define the Problem class and a FakeComm class for non-MPI users.

class openmdao.core.problem.ErrorTuple(forward, reverse, forward_reverse)

Bases: tuple

__contains__(self, key, /)

Return key in self.

__getitem__(self, key, /)

Return self[key].

__init__(self, /, *args, **kwargs)

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

__iter__(self, /)

Implement iter(self).

count()
forward

Alias for field number 0

forward_reverse

Alias for field number 2

index()

Raises ValueError if the value is not present.

reverse

Alias for field number 1

class openmdao.core.problem.MagnitudeTuple(forward, reverse, fd)

Bases: tuple

__contains__(self, key, /)

Return key in self.

__getitem__(self, key, /)

Return self[key].

__init__(self, /, *args, **kwargs)

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

__iter__(self, /)

Implement iter(self).

count()
fd

Alias for field number 2

forward

Alias for field number 0

index()

Raises ValueError if the value is not present.

reverse

Alias for field number 1

class openmdao.core.problem.Problem(model=None, driver=None, comm=None, root=None)[source]

Bases: object

Top-level container for the systems and drivers.

Attributes

model

(<System>) Pointer to the top-level <System> object (root node in the tree).

comm

(MPI.Comm or <FakeComm>) The global communicator.

driver

(<Driver>) Slot for the driver. The default driver is Driver, which just runs the model once.

cite

(str) Listing of relevant citations that should be referenced when publishing work that uses this class.

recording_options

(<OptionsDictionary>) Dictionary with problem recording options.

__getitem__(self, name)[source]

Get an output/input variable.

Parameters
namestr

Promoted or relative variable name in the root system’s namespace.

Returns
float or ndarray or any python object

the requested output/input variable.

__init__(self, model=None, driver=None, comm=None, root=None)[source]

Initialize attributes.

Parameters
model<System> or None

The top-level <System>. If not specified, an empty <Group> will be created.

driver<Driver> or None

The driver for the problem. If not specified, a simple “Run Once” driver will be used.

commMPI.Comm or <FakeComm> or None

The global communicator.

root<System> or None

Deprecated kwarg for model.

__setitem__(self, name, value)[source]

Set an output/input variable.

Parameters
namestr

Promoted or relative variable name in the root system’s namespace.

valuefloat or ndarray or any python object

value to set this variable to.

add_recorder(self, recorder)[source]

Add a recorder to the problem.

Parameters
recorderCaseRecorder

A recorder instance.

check_partials(self, out_stream=<object object at 0x7facf3edc230>, includes=None, excludes=None, compact_print=False, abs_err_tol=1e-06, rel_err_tol=1e-06, method='fd', step=None, form='forward', step_calc='abs', force_dense=True, show_only_incorrect=False)[source]

Check partial derivatives comprehensively for all components in your model.

Parameters
out_streamfile-like object

Where to send human readable output. By default it goes to stdout. Set to None to suppress.

includesNone or list_like

List of glob patterns for pathnames to include in the check. Default is None, which includes all components in the model.

excludesNone or list_like

List of glob patterns for pathnames to exclude from the check. Default is None, which excludes nothing.

compact_printbool

Set to True to just print the essentials, one line per unknown-param 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’.

stepfloat

Step size for approximation. Default is None, which means 1e-6 for ‘fd’ and 1e-40 for ‘cs’.

formstring

Form for finite difference, can be ‘forward’, ‘backward’, or ‘central’. Default ‘forward’.

step_calcstring

Step type for finite difference, can be ‘abs’ for absolute’, or ‘rel’ for relative. Default is ‘abs’.

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.

Returns
dict of dicts of dicts
First key:

is the component name;

Second key:

is the (output, input) tuple of strings;

Third key:

is one of [‘rel error’, ‘abs error’, ‘magnitude’, ‘J_fd’, ‘J_fwd’, ‘J_rev’];

For ‘rel error’, ‘abs error’, ‘magnitude’ the value is: A tuple containing norms for

forward - fd, adjoint - fd, forward - adjoint.

For ‘J_fd’, ‘J_fwd’, ‘J_rev’ the value is: A numpy array representing the computed

Jacobian for the three different methods of computation.

check_totals(self, of=None, wrt=None, out_stream=<object object at 0x7facf3edc230>, compact_print=False, driver_scaling=False, abs_err_tol=1e-06, rel_err_tol=1e-06, method='fd', step=None, form='forward', step_calc='abs')[source]

Check total derivatives for the model vs. finite difference.

Parameters
oflist of variable name strings or None

Variables whose derivatives will be computed. Default is None, which uses the driver’s objectives and constraints.

wrtlist of variable name strings or None

Variables with respect to which the derivatives will be computed. Default is None, which uses the driver’s desvars.

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 unknown-param pair.

driver_scalingbool

Set to True to scale derivative values by the quantities specified when the desvars and responses were added. Default if False, which is unscaled.

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’

stepfloat

Step size for approximation. Default is None, which means 1e-6 for ‘fd’ and 1e-40 for ‘cs’.

formstring

Form for finite difference, can be ‘forward’, ‘backward’, or ‘central’. Default ‘forward’.

step_calcstring

Step type for finite difference, can be ‘abs’ for absolute’, or ‘rel’ for relative. Default is ‘abs’.

Returns
Dict of Dicts of Tuples of Floats
First key:

is the (output, input) tuple of strings;

Second key:

is one of [‘rel error’, ‘abs error’, ‘magnitude’, ‘fdstep’];

For ‘rel error’, ‘abs error’, ‘magnitude’ the value is: A tuple containing norms for

forward - fd, adjoint - fd, forward - adjoint.

cleanup(self)[source]

Clean up resources prior to exit.

compute_totals(self, of=None, wrt=None, return_format='flat_dict', debug_print=False, driver_scaling=False)[source]

Compute derivatives of desired quantities with respect to desired inputs.

Parameters
oflist of variable name strings or None

Variables whose derivatives will be computed. Default is None, which uses the driver’s objectives and constraints.

wrtlist of variable name strings or None

Variables with respect to which the derivatives will be computed. Default is None, which uses the driver’s desvars.

return_formatstring

Format to return the derivatives. Can be either ‘dict’ or ‘flat_dict’. Default is a ‘flat_dict’, which returns them in a dictionary whose keys are tuples of form (of, wrt).

debug_printbool

Set to True to print out some debug information during linear solve.

driver_scalingbool

Set to True to scale derivative values by the quantities specified when the desvars and responses were added. Default if False, which is unscaled.

Returns
derivsobject

Derivatives in form requested by ‘return_format’.

final_setup(self)[source]

Perform final setup phase on problem in preparation for run.

This is the second phase of setup, and is done automatically at the start of run_driver and run_model. At the beginning of final_setup, we have a model hierarchy with defined variables, solvers, case_recorders, and derivative settings. During this phase, the vectors are created and populated, the drivers and solvers are initialized, and the recorders are started, and the rest of the framework is prepared for execution.

get_val(self, name, units=None, indices=None)[source]

Get an output/input variable.

Function is used if you want to specify display units.

Parameters
namestr

Promoted or relative variable name in the root system’s namespace.

unitsstr, optional

Units to convert to before upon return.

indicesint or list of ints or tuple of ints or int ndarray or Iterable or None, optional

Indices or slice to return.

Returns
float or ndarray

The requested output/input variable.

list_problem_vars(self, show_promoted_name=True, print_arrays=False, desvar_opts=[], cons_opts=[], objs_opts=[])[source]

Print all design variables and responses (objectives and constraints).

Parameters
show_promoted_namebool

If True, then show the promoted names of the variables.

print_arraysbool, optional

When False, in the columnar display, just display norm of any ndarrays with size > 1. The norm is surrounded by vertical bars to indicate that it is a norm. When True, also display full values of the ndarray below the row. Format is affected by the values set with numpy.set_printoptions Default is False.

desvar_optslist of str

List of optional columns to be displayed in the desvars table. Allowed values are: [‘lower’, ‘upper’, ‘ref’, ‘ref0’, ‘indices’, ‘adder’, ‘scaler’, ‘parallel_deriv_color’, ‘vectorize_derivs’, ‘cache_linear_solution’]

cons_optslist of str

List of optional columns to be displayed in the cons table. Allowed values are: [‘lower’, ‘upper’, ‘equals’, ‘ref’, ‘ref0’, ‘indices’, ‘index’, ‘adder’, ‘scaler’, ‘linear’, ‘parallel_deriv_color’, ‘vectorize_derivs’, ‘cache_linear_solution’]

objs_optslist of str

List of optional columns to be displayed in the objs table. Allowed values are: [‘ref’, ‘ref0’, ‘indices’, ‘adder’, ‘scaler’, ‘parallel_deriv_color’, ‘vectorize_derivs’, ‘cache_linear_solution’]

load_case(self, case)[source]

Pull all input and output variables from a case into the model.

Parameters
caseCase object

A Case from a CaseRecorder file.

record_iteration(self, case_name)[source]

Record the variables at the Problem level.

Parameters
case_namestr

Name used to identify this Problem case.

root

Provide ‘root’ property for backwards compatibility.

Returns
<Group>

reference to the ‘model’ property.

run(self)[source]

Backward compatible call for run_driver.

Returns
boolean

Failure flag; True if failed to converge, False is successful.

run_driver(self, case_prefix=None, reset_iter_counts=True)[source]

Run the driver on the model.

Parameters
case_prefixstr or None

Prefix to prepend to coordinates when recording.

reset_iter_countsbool

If True and model has been run previously, reset all iteration counters.

Returns
boolean

Failure flag; True if failed to converge, False is successful.

run_model(self, case_prefix=None, reset_iter_counts=True)[source]

Run the model by calling the root system’s solve_nonlinear.

Parameters
case_prefixstr or None

Prefix to prepend to coordinates when recording.

reset_iter_countsbool

If True and model has been run previously, reset all iteration counters.

run_once(self)[source]

Backward compatible call for run_model.

set_solver_print(self, level=2, depth=1e+99, type_='all')[source]

Control printing for solvers and subsolvers in the model.

Parameters
levelint

iprint level. Set to 2 to print residuals each iteration; set to 1 to print just the iteration totals; set to 0 to disable all printing except for failures, and set to -1 to disable all printing including failures.

depthint

How deep to recurse. For example, you can set this to 0 if you only want to print the top level linear and nonlinear solver messages. Default prints everything.

type_str

Type of solver to set: ‘LN’ for linear, ‘NL’ for nonlinear, or ‘all’ for all.

set_val(self, name, value, units=None, indices=None)[source]

Set an output/input variable.

Function is used if you want to set a value using a different unit.

Parameters
namestr

Promoted or relative variable name in the root system’s namespace.

valuefloat or ndarray or list

Value to set this variable to.

unitsstr, optional

Units that value is defined in.

indicesint or list of ints or tuple of ints or int ndarray or Iterable or None, optional

Indices or slice to set to specified value.

setup(self, vector_class=None, check=False, logger=None, mode='auto', force_alloc_complex=False, distributed_vector_class=<class 'openmdao.vectors.petsc_vector.PETScVector'>, local_vector_class=<class 'openmdao.vectors.default_vector.DefaultVector'>, derivatives=True)[source]

Set up the model hierarchy.

When setup is called, the model hierarchy is assembled, the processors are allocated (for MPI), and variables and connections are all assigned. This method traverses down the model hierarchy to call setup on each subsystem, and then traverses up the model hierarchy to call configure on each subsystem.

Parameters
vector_classtype

Reference to an actual <Vector> class; not an instance. This is deprecated. Use distributed_vector_class instead.

checkboolean

whether to run config check after setup is complete.

loggerobject

Object for logging config checks if check is True.

modestring

Derivatives calculation mode, ‘fwd’ for forward, and ‘rev’ for reverse (adjoint). Default is ‘auto’, which will pick ‘fwd’ or ‘rev’ based on the direction resulting in the smallest number of linear solves required to compute derivatives.

force_alloc_complexbool

Force allocation of imaginary part in nonlinear vectors. OpenMDAO can generally detect when you need to do this, but in some cases (e.g., complex step is used after a reconfiguration) you may need to set this to True.

distributed_vector_classtype

Reference to the <Vector> class or factory function used to instantiate vectors and associated transfers involved in interprocess communication.

local_vector_classtype

Reference to the <Vector> class or factory function used to instantiate vectors and associated transfers involved in intraprocess communication.

derivativesbool

If True, perform any memory allocations necessary for derivative computation.

Returns
self<Problem>

this enables the user to instantiate and setup in one line.