balance_comp.py#

Define the BalanceComp class.

class openmdao.components.balance_comp.BalanceComp(name=None, eq_units=None, lhs_name=None, rhs_name=None, rhs_val=0.0, use_mult=False, mult_name=None, mult_val=1.0, normalize=True, val=None, lhs_kwargs=None, rhs_kwargs=None, mult_kwargs=None, **kwargs)[source]

Bases: ImplicitComponent

A simple equation balance for solving implicit equations.

Parameters:
namestr

The name of the state variable to be created.

eq_unitsstr or None

Units for the left-hand-side and right-hand-side of the equation to be balanced.

lhs_namestr or None

Optional name for the LHS variable associated with the implicit state variable. If None, the default will be used: ‘lhs:{name}’.

rhs_namestr or None

Optional name for the RHS variable associated with the implicit state variable. If None, the default will be used: ‘rhs:{name}’.

rhs_valint, float, or np.array

Default value for the RHS. Must be compatible with the shape (optionally) given by the val or shape option in kwargs.

use_multbool

Specifies whether the LHS multiplier is to be used. If True, then an additional input mult_name is created, with the default value given by mult_val, that multiplies lhs. Default is False.

mult_namestr or None

Optional name for the LHS multiplier variable associated with the implicit state variable. If None, the default will be used: ‘mult:{name}’.

mult_valint, float, or np.array

Default value for the LHS multiplier. Must be compatible with the shape (optionally) given by the val or shape option in kwargs.

normalizebool

Specifies whether or not the resulting residual should be normalized by a quadratic function of the RHS.

valfloat, int, or np.ndarray

Set initial value for the state.

lhs_kwargsdict

Keyword arguments to be passed to the add_input call for the left-hand-side input of the equation (see add_input method).

rhs_kwargsdict

Keyword arguments to be passed to the add_input call for the right-hand-side input of the equation (see add_input method).

mult_kwargsdict

Keyword arguments to be passed to the add_input call for the multiplier input of the equation, if used (see add_input method).

**kwargsdict

Additional arguments to be passed for the creation of the implicit state variable. (see add_output method).

Attributes:
_state_varsdict

Cache the data provided during add_balance so everything can be saved until setup is called.

Methods

abs_meta_iter(iotype[, local, cont, discrete])

Iterate over absolute variable names and their metadata for this System.

add_balance(name[, eq_units, lhs_name, ...])

Add a new state variable and associated equation to be balanced.

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

Add an output variable to the component.

add_recorder(recorder[, recurse])

Add a recorder to the system.

add_residual(name[, shape, units, desc, ref])

Add a residual variable to the component.

add_response(name, type_[, lower, upper, ...])

Add a response variable to this system.

apply_linear(inputs, outputs, d_inputs, ...)

Compute jac-vector product.

apply_nonlinear(inputs, outputs, residuals)

Calculate the residual for each balance.

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_fd_sparsity([method, num_full_jacs, ...])

Use finite difference to compute a sparsity matrix.

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.

guess_nonlinear(inputs, outputs, residuals)

Provide initial guess for states.

has_vectors()

Check if the system vectors have been initialized.

initialize()

Declare options.

is_explicit([is_comp])

Return True if this is an explicit component.

linearize(inputs, outputs, jacobian)

Calculate the partials of the residual for each balance.

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

override_method(name, method)

Dynamically add a method to this component instance.

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 the partials for outputs once all variable shapes are known.

setup_residuals()

User hook for adding named residuals to this component.

solve_linear(d_outputs, d_residuals, mode)

Apply inverse jac product.

solve_nonlinear(inputs, outputs)

Compute outputs given inputs.

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__(name=None, eq_units=None, lhs_name=None, rhs_name=None, rhs_val=0.0, use_mult=False, mult_name=None, mult_val=1.0, normalize=True, val=None, lhs_kwargs=None, rhs_kwargs=None, mult_kwargs=None, **kwargs)[source]

Initialize a BalanceComp, optionally creating a new implicit state variable.

The BalanceComp allows for the creation of one or more implicit state variables, and computes the residuals for those variables based on the following equation.

\[\mathcal{R}_{name} = \frac{f_{mult}(x,...) \times f_{lhs}(x,...) - f_{rhs}(x,...)}{f_{norm}(f_{rhs}(x,...))}\]

Where \(f_{lhs}\) represents the left-hand-side of the equation, \(f_{rhs}\) represents the right-hand-side, and \(f_{mult}\) is an optional multiplier on the left hand side. At least one of these quantities should be a function of the associated state variable. If use_mult is True the default value of the multiplier is 1. The optional normalization function \(f_{norm}(f_{rhs}(x,...))\) is computed as:

\[\begin{split}f_{norm}(f_{rhs}(x,...)) = \begin{cases} \left| f_{rhs} \right|, & \text{if normalize and } \left| f_{rhs} \right| \geq 2 \\ 0.25 f_{rhs}^2 + 1, & \text{if normalize and } \left| f_{rhs} \right| < 2 \\ 1, & \text{if not normalize} \end{cases}\end{split}\]

New state variables, and their associated residuals are created by calling add_balance. As an example, solving the equation \(x**2 = 2\) implicitly can be be accomplished as follows:

prob = Problem()
bal = BalanceComp()
bal.add_balance('x', val=1.0)
exec_comp = ExecComp('y=x**2')
prob.model.add_subsystem(name='exec', subsys=exec_comp)
prob.model.add_subsystem(name='balance', subsys=bal)
prob.model.connect('balance.x', 'exec.x')
prob.model.connect('exec.y', 'balance.lhs:x')
prob.model.linear_solver = DirectSolver()
prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
prob.setup()
prob.set_val('exec.x', 2)
prob.run_model()

The arguments to add_balance can be provided on initialization to provide a balance with a one state/residual without the need to call add_balance:

prob = Problem()
bal = BalanceComp('x', val=1.0)
exec_comp = ExecComp('y=x**2')
prob.model.add_subsystem(name='exec', subsys=exec_comp)
prob.model.add_subsystem(name='balance', subsys=bal)
prob.model.connect('balance.x', 'exec.x')
prob.model.connect('exec.y', 'balance.lhs:x')
prob.model.linear_solver = DirectSolver()
prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
prob.setup()
prob.set_val('exec.x', 2)
prob.run_model()
add_balance(name, eq_units=None, lhs_name=None, rhs_name=None, rhs_val=0.0, use_mult=False, mult_name=None, mult_val=1.0, normalize=True, val=None, lhs_kwargs=None, rhs_kwargs=None, mult_kwargs=None, **kwargs)[source]

Add a new state variable and associated equation to be balanced.

This will create new inputs lhs:name, rhs:name, and mult:name that will define the left and right sides of the equation to be balanced, and a multiplier for the left-hand-side.

Parameters:
namestr

The name of the state variable to be created.

eq_unitsstr or None

Units for the left-hand-side and right-hand-side of the equation to be balanced.

lhs_namestr or None

Optional name for the LHS variable associated with the implicit state variable. If None, the default will be used: ‘lhs:{name}’.

rhs_namestr or None

Optional name for the RHS variable associated with the implicit state variable. If None, the default will be used: ‘rhs:{name}’.

rhs_valint, float, or np.array

Default value for the RHS. Must be compatible with the shape (optionally) given by the val or shape option in kwargs.

use_multbool

Specifies whether the LHS multiplier is to be used. If True, then an additional input mult_name is created, with the default value given by mult_val, that multiplies lhs. Default is False.

mult_namestr or None

Optional name for the LHS multiplier variable associated with the implicit state variable. If None, the default will be used: ‘mult:{name}’.

mult_valint, float, or np.array

Default value for the LHS multiplier. Must be compatible with the shape (optionally) given by the val or shape option in kwargs.

normalizebool

Specifies whether or not the resulting residual should be normalized by a quadratic function of the RHS.

valfloat, int, or np.ndarray

Set initial value for the state.

lhs_kwargsdict

Keyword arguments to be passed to the add_input call for the left-hand-side input of the equation (see add_input method).

rhs_kwargsdict

Keyword arguments to be passed to the add_input call for the right-hand-side input of the equation (see add_input method).

mult_kwargsdict

Keyword arguments to be passed to the add_input call for the multiplier input of the equation, if used (see add_input method).

**kwargsdict

Additional arguments to be passed for the creation of the implicit state variable. (see add_output method).

apply_nonlinear(inputs, outputs, residuals)[source]

Calculate the residual for each balance.

Parameters:
inputsVector

Unscaled, dimensional input variables read via inputs[key].

outputsVector

Unscaled, dimensional output variables read via outputs[key].

residualsVector

Unscaled, dimensional residuals written to via residuals[key].

guess_nonlinear(inputs, outputs, residuals)[source]

Provide initial guess for states.

Override this method to set the initial guess for states.

Parameters:
inputsVector

Unscaled, dimensional input variables read via inputs[key].

outputsVector

Unscaled, dimensional output variables read via outputs[key].

residualsVector

Unscaled, dimensional residuals written to via residuals[key].

initialize()[source]

Declare options.

linearize(inputs, outputs, jacobian)[source]

Calculate the partials of the residual for each balance.

Parameters:
inputsVector

Unscaled, dimensional input variables read via inputs[key].

outputsVector

Unscaled, dimensional output variables read via outputs[key].

jacobianJacobian

Sub-jac components written to jacobian[output_name, input_name].

setup_partials()[source]

Declare the partials for outputs once all variable shapes are known.