# exec_comp.py¶

Define the ExecComp class, a component that evaluates an expression.

class openmdao.components.exec_comp.ExecComp(exprs=[], **kwargs)[source]

A component defined by an expression string.

Attributes

 complex_stepsize (double) Step size used for complex step which is used for derivatives.
__init__(self, exprs=[], **kwargs)[source]

Create a <Component> using only an expression string.

Given a list of assignment statements, this component creates input and output variables at construction time. All variables appearing on the left-hand side of an assignment are outputs, and the rest are inputs. Each variable is assumed to be of type float unless the initial value for that variable is supplied in **kwargs. Derivatives are calculated using complex step.

The following functions are available for use in expressions:

Function

Description

abs(x)

Absolute value of x

acos(x)

Inverse cosine of x

acosh(x)

Inverse hyperbolic cosine of x

arange(start, stop, step)

Array creation

arccos(x)

Inverse cosine of x

arccosh(x)

Inverse hyperbolic cosine of x

arcsin(x)

Inverse sine of x

arcsinh(x)

Inverse hyperbolic sine of x

arctan(x)

Inverse tangent of x

asin(x)

Inverse sine of x

asinh(x)

Inverse hyperbolic sine of x

atan(x)

Inverse tangent of x

cos(x)

Cosine of x

cosh(x)

Hyperbolic cosine of x

dot(x, y)

Dot product of x and y

e

Euler’s number

erf(x)

Error function

erfc(x)

Complementary error function

exp(x)

Exponential function

expm1(x)

exp(x) - 1

factorial(x)

Factorial of all numbers in x

fmax(x, y)

Element-wise maximum of x and y

fmin(x, y)

Element-wise minimum of x and y

inner(x, y)

Inner product of arrays x and y

isinf(x)

Element-wise detection of np.inf

isnan(x)

Element-wise detection of np.nan

kron(x, y)

Kronecker product of arrays x and y

linspace(x, y, N)

Numpy linear spaced array creation

log(x)

Natural logarithm of x

log10(x)

Base-10 logarithm of x

log1p(x)

log(1+x)

matmul(x, y)

Matrix multiplication of x and y

maximum(x, y)

Element-wise maximum of x and y

minimum(x, y)

Element-wise minimum of x and y

ones(N)

Create an array of ones

outer(x, y)

Outer product of x and y

pi

Pi

power(x, y)

Element-wise x**y

prod(x)

The product of all elements in x

sin(x)

Sine of x

sinh(x)

Hyperbolic sine of x

sum(x)

The sum of all elements in x

tan(x)

Tangent of x

tanh(x)

Hyperbolic tangent of x

tensordot(x, y)

Tensor dot product of x and y

zeros(N)

Create an array of zeros

Parameters
exprsstr, tuple of str or list of str

An assignment statement or iter of them. These express how the outputs are calculated based on the inputs. In addition to standard Python operators, a subset of numpy and scipy functions is supported.

**kwargsdict of named args

Initial values of variables can be set by setting a named arg with the var name. If the value is a dict it is assumed to contain metadata. To set the initial value in addition to other metadata, assign the initial value to the ‘value’ entry of the dict.

Notes

If a variable has an initial value that is anything other than 1.0, either because it has a different type than float or just because its initial value is != 1.0, you must use a keyword arg to set the initial value. For example, let’s say we have an ExecComp that takes an array ‘x’ as input and outputs a float variable ‘y’ which is the sum of the entries in ‘x’.

import numpy
from openmdao.api import ExecComp
excomp = ExecComp('y=sum(x)', x=numpy.ones(10,dtype=float))


In this example, ‘y’ would be assumed to be the default type of float and would be given the default initial value of 1.0, while ‘x’ would be initialized with a size 10 float array of ones.

If you want to assign certain metadata for ‘x’ in addition to its initial value, you can do it as follows:

excomp = ExecComp('y=sum(x)',
x={'value': numpy.ones(10,dtype=float),
'units': 'ft'})

add_constraint(self, name, lower=None, upper=None, equals=None, ref=None, ref0=None, adder=None, scaler=None, indices=None, linear=False, parallel_deriv_color=None, vectorize_derivs=False, cache_linear_solution=False)

Add a constraint variable to this system.

Parameters
namestring

Name of the response variable in the system.

lowerfloat or ndarray, optional

Lower boundary for the variable

upperfloat or ndarray, optional

Upper boundary for the variable

equalsfloat or ndarray, optional

Equality constraint value for the variable

reffloat or ndarray, optional

Value of response variable that scales to 1.0 in the driver.

ref0float or ndarray, optional

Value of response variable that scales to 0.0 in the driver.

Value to add to the model value to get the scaled value. Adder is first in precedence.

scalerfloat or ndarray, optional

value to multiply the model value to get the scaled value. Scaler is second in precedence.

indicessequence of int, optional

If variable is an array, these indicate which entries are of interest for this particular response. These may be positive or negative integers.

linearbool

Set to True if constraint is linear. Default is False.

parallel_deriv_colorstring

If specified, this design var will be grouped for parallel derivative calculations with other variables sharing the same parallel_deriv_color.

vectorize_derivsbool

If True, vectorize derivative calculations.

cache_linear_solutionbool

If True, store the linear solution vectors for this variable so they can be used to start the next linear solution with an initial guess equal to the solution from the previous linear solve.

Notes

The response can be scaled using ref and ref0. The argument ref0 represents the physical value when the scaled value is 0. The argument ref represents the physical value when the scaled value is 1.

add_design_var(self, name, lower=None, upper=None, ref=None, ref0=None, indices=None, adder=None, scaler=None, parallel_deriv_color=None, vectorize_derivs=False, cache_linear_solution=False)

Add a design variable to this system.

Parameters
namestring

Name of the design variable in the system.

lowerfloat or ndarray, optional

Lower boundary for the param

upperupper or ndarray, optional

Upper boundary for the param

reffloat or ndarray, optional

Value of design var that scales to 1.0 in the driver.

ref0float or ndarray, optional

Value of design var that scales to 0.0 in the driver.

indicesiter of int, optional

If a param is an array, these indicate which entries are of interest for this particular design variable. These may be positive or negative integers.

Value to add to the model value to get the scaled value. Adder is first in precedence.

scalerfloat or ndarray, optional

value to multiply the model value to get the scaled value. Scaler is second in precedence.

parallel_deriv_colorstring

If specified, this design var will be grouped for parallel derivative calculations with other variables sharing the same parallel_deriv_color.

vectorize_derivsbool

If True, vectorize derivative calculations.

cache_linear_solutionbool

If True, store the linear solution vectors for this variable so they can be used to start the next linear solution with an initial guess equal to the solution from the previous linear solve.

Notes

The response can be scaled using ref and ref0. The argument ref0 represents the physical value when the scaled value is 0. The argument ref represents the physical value when the scaled value is 1.

add_discrete_input(self, name, val, desc='')

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

Returns
dict

add_discrete_output(self, name, val, desc='')

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.

Returns
dict

add_input(self, name, val=1.0, shape=None, src_indices=None, flat_src_indices=None, units=None, desc='')

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 src_indices not provided and val is not an array. Default is None.

src_indicesint or list of ints or tuple of ints or int ndarray or Iterable or None

The global indices of the source variable to transfer data from. A value of None implies this input depends on all entries of source. Default is None. The shapes of the target and src_indices must match, and form of the entries within is determined by the value of ‘flat_src_indices’.

flat_src_indicesbool

If True, each entry of src_indices is assumed to be an index into the flattened source. Otherwise each entry must be a tuple or list of size equal to the number of dimensions of the source.

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

Returns
dict

add_objective(self, name, ref=None, ref0=None, index=None, adder=None, scaler=None, parallel_deriv_color=None, vectorize_derivs=False, cache_linear_solution=False)

Add a response variable to this system.

Parameters
namestring

Name of the response variable in the system.

reffloat or ndarray, optional

Value of response variable that scales to 1.0 in the driver.

ref0float or ndarray, optional

Value of response variable that scales to 0.0 in the driver.

indexint, optional

If variable is an array, this indicates which entry is of interest for this particular response. This may be a positive or negative integer.

Value to add to the model value to get the scaled value. Adder is first in precedence.

scalerfloat or ndarray, optional

value to multiply the model value to get the scaled value. Scaler is second in precedence.

parallel_deriv_colorstring

If specified, this design var will be grouped for parallel derivative calculations with other variables sharing the same parallel_deriv_color.

vectorize_derivsbool

If True, vectorize derivative calculations.

cache_linear_solutionbool

If True, store the linear solution vectors for this variable so they can be used to start the next linear solution with an initial guess equal to the solution from the previous linear solve.

Notes

The objective can be scaled using scaler and adder, where

$x_{scaled} = scaler(x + adder)$

or through the use of ref/ref0, which map to scaler and adder through the equations:

\begin{align}\begin{aligned}0 = scaler(ref_0 + adder)\\1 = scaler(ref + adder)\end{aligned}\end{align}

which results in:

\begin{align}\begin{aligned}adder = -ref_0\\scaler = \frac{1}{ref + adder}\end{aligned}\end{align}
add_output(self, 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)

Add an output variable to the component.

For ExplicitComponent, res_ref defaults to the value in res unless otherwise specified.

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

Scaling parameter. The value in the user-defined units of this output variable when the scaled value is 1. Default is 1.

ref0float

Scaling parameter. The value in the user-defined units of this output variable when the scaled value is 0. Default is 0.

res_reffloat

Scaling parameter. The value in the user-defined res_units of this output’s residual when the scaled value is 1. Default is None, which means residual scaling matches output scaling.

Returns
dict

add_recorder(self, recorder, recurse=False)

Add a recorder to the driver.

Parameters
recorder<CaseRecorder>

A recorder instance.

recurseboolean

Flag indicating if the recorder should be added to all the subsystems.

add_response(self, name, type_, lower=None, upper=None, equals=None, ref=None, ref0=None, indices=None, index=None, adder=None, scaler=None, linear=False, parallel_deriv_color=None, vectorize_derivs=False, cache_linear_solution=False)

Add a response variable to this system.

The response can be scaled using ref and ref0. The argument ref0 represents the physical value when the scaled value is 0. The argument ref represents the physical value when the scaled value is 1.

Parameters
namestring

Name of the response variable in the system.

type_string

The type of response. Supported values are ‘con’ and ‘obj’

lowerfloat or ndarray, optional

Lower boundary for the variable

upperupper or ndarray, optional

Upper boundary for the variable

equalsequals or ndarray, optional

Equality constraint value for the variable

reffloat or ndarray, optional

Value of response variable that scales to 1.0 in the driver.

ref0upper or ndarray, optional

Value of response variable that scales to 0.0 in the driver.

indicessequence of int, optional

If variable is an array, these indicate which entries are of interest for this particular response.

indexint, optional

If variable is an array, this indicates which entry is of interest for this particular response.

Value to add to the model value to get the scaled value. Adder is first in precedence.

scalerfloat or ndarray, optional

value to multiply the model value to get the scaled value. Scaler is second in precedence.

linearbool

Set to True if constraint is linear. Default is False.

parallel_deriv_colorstring

If specified, this design var will be grouped for parallel derivative calculations with other variables sharing the same parallel_deriv_color.

vectorize_derivsbool

If True, vectorize derivative calculations.

cache_linear_solutionbool

If True, store the linear solution vectors for this variable so they can be used to start the next linear solution with an initial guess equal to the solution from the previous linear solve.

check_config(self, logger)

Perform optional error checks.

Parameters
loggerobject

The object that manages logging output.

cleanup(self)

Clean up resources prior to exit.

compute(self, inputs, outputs)[source]

Execute this component’s assignment statements.

Parameters
inputsVector

Vector containing inputs.

outputsVector

Vector containing outputs.

compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode, discrete_inputs=None)

Compute jac-vector product. The model is assumed to be in an unscaled state.

If mode is:

‘fwd’: d_inputs |-> d_outputs

‘rev’: d_outputs |-> d_inputs

Parameters
inputsVector

unscaled, dimensional input variables read via inputs[key]

d_inputsVector

see inputs; product must be computed only if var_name in d_inputs

d_outputsVector

see outputs; product must be computed only if var_name in d_outputs

modestr

either ‘fwd’ or ‘rev’

discrete_inputsdict or None

If not None, dict containing discrete input values.

compute_partials(self, inputs, partials)[source]

Use complex step method to update the given Jacobian.

Parameters
inputsVecWrapper

VecWrapper containing parameters. (p)

partialsJacobian

Contains sub-jacobians.

declare_partials(self, of, wrt, dependent=True, rows=None, cols=None, val=None, method='exact', step=None, form=None, step_calc=None)

Parameters
ofstr or list of str

The name of the residual(s) that derivatives are being computed for. May also contain a glob pattern.

wrtstr or list 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.

formstring

Form for finite difference, can be ‘forward’, ‘backward’, or ‘central’. Defaults to None, in which case the approximation method provides its default value.

step_calcstring

Step type for finite difference, can be ‘abs’ for absolute’, or ‘rel’ for relative. Defaults to None, in which case the approximation method provides its default value.

distributed

Provide ‘distributed’ property for backwards compatibility.

Returns
bool

reference to the ‘distributed’ option.

get_constraints(self, recurse=True)

Get the Constraint settings from this system.

Retrieve the constraint settings for the current system as a dict, keyed by variable name.

Parameters
recursebool, optional

If True, recurse through the subsystems and return the path of all constraints relative to the this system.

Returns
dict

The constraints defined in the current system.

get_design_vars(self, recurse=True, get_sizes=True)

Get the DesignVariable settings from this system.

Retrieve all design variable settings from the system and, if recurse is True, all of its subsystems.

Parameters
recursebool

If True, recurse through the subsystems and return the path of all design vars relative to the this system.

get_sizesbool, optional

If True, compute the size of each response.

Returns
dict

The design variables defined in the current system and, if recurse=True, its subsystems.

get_linear_vectors(self, vec_name='linear')

Return the linear inputs, outputs, and residuals vectors.

Parameters
vec_namestr

Name of the linear right-hand-side vector. The default is ‘linear’.

Returns
(inputs, outputs, residuals)tuple of <Vector> instances

Yields the inputs, outputs, and residuals linear vectors for vec_name.

get_nonlinear_vectors(self)

Return the inputs, outputs, and residuals vectors.

Returns
(inputs, outputs, residuals)tuple of <Vector> instances

Yields the inputs, outputs, and residuals nonlinear vectors.

get_objectives(self, recurse=True)

Get the Objective settings from this system.

Retrieve all objectives settings from the system as a dict, keyed by variable name.

Parameters
recursebool, optional

If True, recurse through the subsystems and return the path of all objective relative to the this system.

Returns
dict

The objectives defined in the current system.

get_responses(self, recurse=True, get_sizes=True)

Get the response variable settings from this system.

Retrieve all response variable settings from the system as a dict, keyed by variable name.

Parameters
recursebool, optional

If True, recurse through the subsystems and return the path of all responses relative to the this system.

get_sizesbool, optional

If True, compute the size of each response.

Returns
dict

The responses defined in the current system and, if recurse=True, its subsystems.

initialize(self)[source]

Declare options.

is_active(self)

Determine if the system is active on this rank.

Returns
bool

If running under MPI, returns True if this System has a valid communicator. Always returns True if not running under MPI.

linear_solver

Get the linear solver for this system.

list_inputs(self, values=True, prom_name=False, units=False, shape=False, hierarchical=True, print_arrays=False, out_stream=<object object at 0x7facfacd8440>)

Return and optionally log a list of input names and other optional information.

If the model is parallel, only the local variables are returned to the process. Also optionally logs the information to a user defined output stream. If the model is parallel, the rank 0 process logs information about all variables across all processes.

Parameters
valuesbool, optional

When True, display/return input values. Default is True.

prom_namebool, optional

When True, display/return the promoted name of the variable. Default is False.

unitsbool, optional

When True, display/return units. Default is False.

shapebool, optional

When True, display/return the shape of the value. Default is False.

hierarchicalbool, optional

When True, human readable output shows variables in hierarchical format.

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.

out_streamfile-like object

Where to send human readable output. Default is sys.stdout. Set to None to suppress.

Returns
list

list of input names and other optional information about those inputs

list_outputs(self, explicit=True, implicit=True, values=True, prom_name=False, residuals=False, residuals_tol=None, units=False, shape=False, bounds=False, scaling=False, hierarchical=True, print_arrays=False, out_stream=<object object at 0x7facfacd8440>)

Return and optionally log a list of output names and other optional information.

If the model is parallel, only the local variables are returned to the process. Also optionally logs the information to a user defined output stream. If the model is parallel, the rank 0 process logs information about all variables across all processes.

Parameters
explicitbool, optional

include outputs from explicit components. Default is True.

implicitbool, optional

include outputs from implicit components. Default is True.

valuesbool, optional

When True, display/return output values. Default is True.

prom_namebool, optional

When True, display/return the promoted name of the variable. Default is False.

residualsbool, optional

When True, display/return residual values. Default is False.

residuals_tolfloat, optional

If set, limits the output of list_outputs to only variables where the norm of the resids array is greater than the given ‘residuals_tol’. Default is None.

unitsbool, optional

When True, display/return units. Default is False.

shapebool, optional

When True, display/return the shape of the value. Default is False.

boundsbool, optional

When True, display/return bounds (lower and upper). Default is False.

scalingbool, optional

When True, display/return scaling (ref, ref0, and res_ref). Default is False.

hierarchicalbool, optional

When True, human readable output shows variables in hierarchical format.

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.

out_streamfile-like

Where to send human readable output. Default is sys.stdout. Set to None to suppress.

Returns
list

list of output names and other optional information about those outputs

ln_solver

Get the linear solver for this system.

metadata

Get the options for this System.

nl_solver

Get the nonlinear solver for this system.

nonlinear_solver

Get the nonlinear solver for this system.

reconfigure(self)

Perform reconfiguration.

Returns
bool

If True, reconfiguration is to be performed.

record_iteration(self)

Record an iteration of the current System.

resetup(self, setup_mode='full')

Public wrapper for _setup that reconfigures after an initial setup has been performed.

Parameters
setup_modestr

Must be one of ‘full’, ‘reconf’, or ‘update’.

run_apply_linear(self, vec_names, mode, scope_out=None, scope_in=None)

Compute jac-vec product.

This calls _apply_linear, but with the model assumed to be in an unscaled state.

Parameters
vec_names[str, …]

list of names of the right-hand-side vectors.

modestr

‘fwd’ or ‘rev’.

scope_outset or None

Set of absolute output names in the scope of this mat-vec product. If None, all are in the scope.

scope_inset or None

Set of absolute input names in the scope of this mat-vec product. If None, all are in the scope.

run_apply_nonlinear(self)

Compute residuals.

This calls _apply_nonlinear, but with the model assumed to be in an unscaled state.

run_linearize(self, sub_do_ln=True)

Compute jacobian / factorization.

This calls _linearize, but with the model assumed to be in an unscaled state.

Parameters
sub_do_lnboolean

Flag indicating if the children should call linearize on their linear solvers.

run_solve_linear(self, vec_names, mode)

Apply inverse jac product.

This calls _solve_linear, but with the model assumed to be in an unscaled state.

Parameters
vec_names[str, …]

list of names of the right-hand-side vectors.

modestr

‘fwd’ or ‘rev’.

run_solve_nonlinear(self)

Compute outputs.

This calls _solve_nonlinear, but with the model assumed to be in an unscaled state.

set_check_partial_options(self, wrt, method='fd', form=None, step=None, step_calc=None, directional=False)

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

Type of step calculation for check, can be “abs” for absolute (default) or “rel” for relative. Leave undeclared to keep unchanged from previous or default value.

directionalbool

Set to True to perform a single directional derivative for each vector variable in the pattern named in wrt.

set_initial_values(self)

Set all input and output variables to their declared initial values.

setup(self)[source]

Set up variable name and metadata lists.

system_iter(self, include_self=False, recurse=True, typ=None)

Yield a generator of local subsystems of this system.

Parameters
include_selfbool

If True, include this system in the iteration.

recursebool

If True, iterate over the whole tree under this system.

typtype

If not None, only yield Systems that match that are instances of the given type.

openmdao.components.exec_comp.array_idx_iter(shape)[source]

Return an iterator over the indices into a n-dimensional array.

Parameters
shapetuple

shape of the array.

openmdao.components.exec_comp.check_option(option, value)[source]

Check option for validity.

Parameters
optionstr

The name of the option

valueany

The value of the option

Raises
ValueError