exec_comp.py#
Define the ExecComp class, a component that evaluates an expression.
- class openmdao.components.exec_comp.ExecComp(exprs=[], **kwargs)[source]
Bases:
ExplicitComponentA component defined by an expression string.
- 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 ‘val’ entry of the dict.
- Attributes:
- _kwargsdict of named args
Initial values of variables.
- _exprslist
List of expressions.
- _codeslist
List of code objects.
- _exprs_infolist
List of tuples containing output and inputs for each expression.
- complex_stepsizedouble
Step size used for complex step which is used for derivatives.
- _manual_decl_partialsbool
If True, at least one partial has been declared by the user.
- _requires_fddict
Contains a mapping of ‘of’ variables to a tuple of the form (wrts, functs) for those ‘of’ variables that require finite difference to be used to compute their derivatives.
- _constantsdict of dicts
Constants defined in the expressions. The key is the name of the constant and the value is a dict of metadata.
- _coloring_declaredbool
If True, coloring has been declared manually.
- _inarrayndarray or None
If using internal CS, this is a complex array containing input values.
- _outarrayndarray or None
If using internal CS, this is a complex array containing output values.
- _indictdict or None
If using internal CS, this maps input variable views in _inarray to input names.
- _viewdictdict or None
If using internal CS, this maps input, output, and constant names to their corresponding views/values.
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_expr(expr, **kwargs)Add an expression to the ExecComp.
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(inputs, outputs)Execute this component's assignment statements.
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_jacvec_product(inputs, d_inputs, ...)Compute jac-vector product.
compute_partials(inputs, partials)Use complex step method to update the given 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(*args, **kwargs)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()Declare options.
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'].
override_method(name, method)Dynamically add a method to this component instance.
record_iteration()Record an iteration of the current System.
register(name, callable_obj, complex_safe)Register a callable to be usable within ExecComp expressions.
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()Set up variable name and metadata lists.
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__(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
arctan2(y, x)
4-quadrant arctangent function of y and 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
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
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 import openmdao.api as om excomp = om.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={'val': numpy.ones(10, dtype=float), 'units': 'ft'})
- add_expr(expr, **kwargs)[source]
Add an expression to the ExecComp.
- Parameters:
- exprstr
An assignment statement that expresses 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 ‘val’ entry of the dict. Do not include for inputs whose default kwargs have been declared on previous expressions.
- compute(inputs, outputs)[source]
Execute this component’s assignment statements.
- Parameters:
- inputsVector
Vector containing inputs.
- outputsVector
Vector containing outputs.
- compute_partials(inputs, partials)[source]
Use complex step method to update the given Jacobian.
- Parameters:
- inputsVector or dict
Vector containing parameters (p).
- partialsJacobian
Contains sub-jacobians.
- 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(*args, **kwargs)[source]
Declare information about this component’s subjacobians.
- Parameters:
- *argslist
Positional args to be passed to base class version of declare_partials.
- **kwargsdict
Keyword args to be passed to base class version of declare_partials.
- Returns:
- dict
Metadata dict for the specified partial(s).
- initialize()[source]
Declare options.
- classmethod register(name, callable_obj, complex_safe)[source]
Register a callable to be usable within ExecComp expressions.
- Parameters:
- namestr
Name of the callable.
- callable_objcallable
The callable.
- complex_safebool
If True, the given callable works correctly with complex numbers.
- setup()[source]
Set up variable name and metadata lists.
- 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.
- Yields:
- int
- 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