BalanceComp

BalanceComp is a specialized implementation of ImplicitComponent that is intended to provide a simple way to implement most implicit equations without the need to define your own residuals.

BalanceComp Options

Option Default Acceptable Values Acceptable Types Description Deprecation
assembled_jac_typecsc ['csc', 'dense'] N/A Linear solver(s) in this group or implicit component, if using an assembled jacobian, will use this type. N/A
distributed False [True, False] ['bool'] True if ALL variables in this component are distributed across multiple processes. The 'distributed' option has been deprecated. Individual inputs and outputs should be set as distributed instead, using calls to add_input() or add_output().
guess_func N/A N/A ['function'] A callable function in the form f(inputs, outputs, residuals) that can provide an initial "guess" value of the state variable(s) based on the inputs, outputs and residuals.N/A
run_root_only False [True, False] ['bool'] If True, call compute/compute_partials/linearize/apply_linear/apply_nonlinear/compute_jacvec_product only on rank 0 and broadcast the results to the other ranks. N/A

BalanceComp Constructor

The call signature for the BalanceComp constructor is:

BalanceComp.__init__()[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()

Using the BalanceComp

BalanceComp allows you to add one or more state variables and its associated implicit equations. For each balance added to the component it solves the following equation:

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

The optional normalization function \(f_{norm}(f_{rhs})\) is computed as:

\[\begin{split} \begin{align} 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{align} \end{split}\]

The following inputs and outputs are associated with each implicit state.

Name

I/O

Description

{name}

output

implicit state variable

lhs:{name}

input

left-hand side of equation to be balanced

rhs:{name}

input

right-hand side of equation to be balanced

mult:{name}

input

left-hand side multiplier of equation to be balanced

The default value for the rhs:{name} input can be set to via the rhs_val argument (see arguments below). If the rhs value is fixed (e.g. 0), then the input can be left unconnected. The lhs:{name} input must always have something connected to it and should be dependent upon the value of the implicit state variable.

The multiplier is optional and will default to 1.0 if not connected.

BalanceComp supports vectorized implicit states. Simply provide a default value or shape when adding the balance that reflects the correct shape.

You can provide the arguments to create a balance when instantiating a BalanceComp or you can use the add_balance method to create one or more state variables after instantiation. The constructor accepts all the same arguments as the add_balance method:

BalanceComp.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, **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.

**kwargsdict

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

Note that the kwargs arguments can include any of the keyword arguments normally available when creating an output variable with the add_output method of a Component.

Example: Scalar Root Finding

The following example uses a BalanceComp to implicitly solve the equation:

\[ 2 \cdot x^2 = 4 \]

Here, our LHS is connected to a computed value for \(x^2\), the multiplier is 2, and the RHS is 4. The expected solution is \(x=\sqrt{2}\). We initialize \(x\) with a value of 1 so that it finds the positive root.

import openmdao.api as om

prob = om.Problem()

bal = om.BalanceComp()
bal.add_balance('x', use_mult=True)

exec_comp = om.ExecComp('y=x**2', x={'val': 1}, y={'val': 1})

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 = om.DirectSolver(assemble_jac=True)
prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False, maxiter=100, iprint=0)

prob.setup()

prob.set_val('balance.rhs:x', 4)
prob.set_val('balance.mult:x', 2.)

# A reasonable initial guess to find the positive root.
prob['balance.x'] = 1.0

prob.run_model()

print(prob.get_val('balance.x'))
[1.41421356]

Alternatively, we could simplify the code by using the mult_val argument.

prob = om.Problem()

bal = om.BalanceComp()
bal.add_balance('x', use_mult=True, mult_val=2.0)

exec_comp = om.ExecComp('y=x**2', x={'val': 1}, y={'val': 1})

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 = om.DirectSolver(assemble_jac=True)
prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False, maxiter=100, iprint=0)

prob.setup()

prob.set_val('balance.rhs:x', 4)

# A reasonable initial guess to find the positive root.
prob.set_val('balance.x', 1.0)

prob.run_model()
print(prob.get_val('balance.x'))
[1.41421356]

Example: Vectorized Root Finding

The following example uses a BalanceComp to implicitly solve the equation:

\[ b \cdot x + c = 0 \]

for various values of \(b\), and \(c\). Here, our LHS is connected to a computed value of the linear equation. The multiplier is one and the RHS is zero (the defaults), and thus they need not be connected.

n = 100

prob = om.Problem()

exec_comp = om.ExecComp('y=b*x+c',
                        b={'val': np.random.uniform(0.01, 100, size=n)},
                        c={'val': np.random.rand(n)},
                        x={'val': np.zeros(n)},
                        y={'val': np.ones(n)})

prob.model.add_subsystem(name='exec', subsys=exec_comp)
prob.model.add_subsystem(name='balance', subsys=om.BalanceComp('x', val=np.ones(n)))

prob.model.connect('balance.x', 'exec.x')
prob.model.connect('exec.y', 'balance.lhs:x')

prob.model.linear_solver = om.DirectSolver(assemble_jac=True)
prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False, maxiter=100, iprint=0)

prob.setup()

prob.set_val('balance.x', np.random.rand(n))

prob.run_model()

b = prob.get_val('exec.b')
c = prob.get_val('exec.c')

print(prob.get_val('balance.x'))
[-1.80485934e-02 -1.62288352e-03 -6.00072485e-03 -1.30622644e-02
 -6.13158077e-03 -1.37001274e-02 -1.68702613e-02 -1.55225122e-02
 -4.49113319e-04 -1.18876298e-02 -9.71646436e-03 -5.36649785e-03
 -2.90187743e-02 -3.17783828e-02 -1.03805785e-02 -1.44380610e-02
 -9.98816237e-03 -1.32919265e-02 -1.42122497e-02 -1.21983710e-02
 -2.03528832e-04 -6.41522612e-04 -1.26276141e-02 -1.13639334e-02
 -4.41448723e-02 -5.81675634e-03 -2.07628132e-02 -1.36203243e-02
 -9.86109529e-03 -2.47575182e-03 -5.90777386e-03 -6.13140063e-04
 -3.24224364e-03 -4.30205191e-03 -1.89796362e-03 -8.85320977e-03
 -3.61137346e-03 -2.17226839e-03 -3.51001809e-03 -1.72107356e-01
 -4.30460726e-03 -3.86767627e-05 -1.19304118e-02 -7.28060447e-03
 -2.02952884e-03 -3.18154149e-03 -1.31306688e-01 -6.04892706e-02
 -1.45826913e-02 -3.80850525e-02 -1.12858727e-03 -9.77647348e-03
 -1.88766695e-02 -6.33619808e-02 -7.76393914e-04 -2.68425296e-02
 -3.57819100e-03 -3.15085252e-03 -4.57947637e-03 -2.79007020e-02
 -5.40849273e-03 -1.18458558e-01 -5.77154904e-03 -4.29700021e-01
 -1.44327995e-02 -5.31394925e-03 -9.56094816e-03 -9.48631626e-03
 -1.05188300e-02 -1.30095434e-01 -2.11937810e-02 -1.17917767e-02
 -9.18674909e-03 -3.82890812e-03 -3.40731141e-02 -1.04805990e-02
 -2.59072415e-03 -8.76613342e-03 -8.54486002e-04 -6.77170960e-02
 -1.65868193e-02 -4.64729182e-02 -6.31505791e-03 -2.30384839e-03
 -1.88770908e-02 -1.99107083e-02 -1.39012006e-02 -1.19805047e-02
 -1.54417950e-02 -1.94250679e-01 -1.45262255e-02 -1.01332796e-01
 -8.55840002e-03 -7.91691078e-03 -2.68783530e-02 -1.15279809e-02
 -1.56136241e-03 -2.26656849e-02 -8.67249431e-03 -7.84366266e-03]
print(-c/b)  # expected
[-1.80485934e-02 -1.62288352e-03 -6.00072485e-03 -1.30622644e-02
 -6.13158077e-03 -1.37001274e-02 -1.68702613e-02 -1.55225122e-02
 -4.49113319e-04 -1.18876298e-02 -9.71646436e-03 -5.36649785e-03
 -2.90187743e-02 -3.17783828e-02 -1.03805785e-02 -1.44380610e-02
 -9.98816237e-03 -1.32919265e-02 -1.42122497e-02 -1.21983710e-02
 -2.03528832e-04 -6.41522612e-04 -1.26276141e-02 -1.13639334e-02
 -4.41448723e-02 -5.81675634e-03 -2.07628132e-02 -1.36203243e-02
 -9.86109529e-03 -2.47575182e-03 -5.90777386e-03 -6.13140063e-04
 -3.24224364e-03 -4.30205191e-03 -1.89796362e-03 -8.85320977e-03
 -3.61137346e-03 -2.17226839e-03 -3.51001809e-03 -1.72107356e-01
 -4.30460726e-03 -3.86767627e-05 -1.19304118e-02 -7.28060447e-03
 -2.02952884e-03 -3.18154149e-03 -1.31306688e-01 -6.04892706e-02
 -1.45826913e-02 -3.80850525e-02 -1.12858727e-03 -9.77647348e-03
 -1.88766695e-02 -6.33619808e-02 -7.76393914e-04 -2.68425296e-02
 -3.57819100e-03 -3.15085252e-03 -4.57947637e-03 -2.79007020e-02
 -5.40849273e-03 -1.18458558e-01 -5.77154904e-03 -4.29700021e-01
 -1.44327995e-02 -5.31394925e-03 -9.56094816e-03 -9.48631626e-03
 -1.05188300e-02 -1.30095434e-01 -2.11937810e-02 -1.17917767e-02
 -9.18674909e-03 -3.82890812e-03 -3.40731141e-02 -1.04805990e-02
 -2.59072415e-03 -8.76613342e-03 -8.54486002e-04 -6.77170960e-02
 -1.65868193e-02 -4.64729182e-02 -6.31505791e-03 -2.30384839e-03
 -1.88770908e-02 -1.99107083e-02 -1.39012006e-02 -1.19805047e-02
 -1.54417950e-02 -1.94250679e-01 -1.45262255e-02 -1.01332796e-01
 -8.55840002e-03 -7.91691078e-03 -2.68783530e-02 -1.15279809e-02
 -1.56136241e-03 -2.26656849e-02 -8.67249431e-03 -7.84366266e-03]

Example: Providing an Initial Guess for a State Variable

BalanceComp has a guess_func option that can be used to supply an initial guess value for the state variables. This option provides the same functionality as the guess_nonlinear method of ImplicitComponent.

The Kepler example script shows how guess_func can be used.

prob = om.Problem()

bal = om.BalanceComp()

bal.add_balance(name='E', val=0.0, units='rad', eq_units='rad', rhs_name='M')

# Use M (mean anomaly) as the initial guess for E (eccentric anomaly)
def guess_function(inputs, outputs, residuals):
    if np.abs(residuals['E']) > 1.0E-2:
        outputs['E'] = inputs['M']

bal.options['guess_func'] = guess_function

# ExecComp used to compute the LHS of Kepler's equation.
lhs_comp = om.ExecComp('lhs=E - ecc * sin(E)',
                       lhs={'val': 0.0, 'units': 'rad'},
                       E={'val': 0.0, 'units': 'rad'},
                       ecc={'val': 0.0})

prob.model.add_subsystem(name='balance', subsys=bal,
                         promotes_inputs=['M'],
                         promotes_outputs=['E'])

prob.model.set_input_defaults('M', 85.0, units='deg')

prob.model.add_subsystem(name='lhs_comp', subsys=lhs_comp,
                         promotes_inputs=['E', 'ecc'])

# Explicit connections
prob.model.connect('lhs_comp.lhs', 'balance.lhs:E')

# Set up solvers
prob.model.linear_solver = om.DirectSolver()
prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False, maxiter=100, iprint=2)

prob.setup()

prob.set_val('ecc', 0.6)

prob.run_model()

print(np.degrees(prob.get_val('E')))
NL: Newton 0 ; 1.30402513 1
NL: Newton 1 ; 0.117134648 0.0898254536
NL: Newton 2 ; 0.00208780933 0.00160104992
NL: Newton 3 ; 7.36738647e-07 5.64972738e-07
NL: Newton 4 ; 9.19264664e-14 7.04943981e-14
NL: Newton Converged
[115.91942563]