本文整理汇总了Python中openmdao.util.options.OptionsDictionary.add_option方法的典型用法代码示例。如果您正苦于以下问题:Python OptionsDictionary.add_option方法的具体用法?Python OptionsDictionary.add_option怎么用?Python OptionsDictionary.add_option使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类openmdao.util.options.OptionsDictionary
的用法示例。
在下文中一共展示了OptionsDictionary.add_option方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: KSComp
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class KSComp(Component):
"""Aggregates a number of functions to a single value via the
Kreisselmeier-Steinhauser Function."""
def __init__(self, n=2):
super(KS, self).__init__()
self.n = n
# Inputs
self.add_param('g', np.zeros((n, )),
desc="Array of function values to be aggregated")
# Outputs
self.add_output('KS', 0.0,
desc="Value of the aggregate KS function")
self.options = OptionsDictionary()
self.options.add_option(rho, 0.1,
desc="Hyperparameter for the KS function")
self._ks = KSfunction()
def solve_nonlinear(self, params, unknowns, resids):
""" Calculate output. """
unknowns['KS'] = self._ks.compute(params['g'], self.options['rho'])
def jacobian(self, params, unknowns, resids):
""" Calculate and save derivatives. (i.e., Jacobian) """
#use g_max, exponsnte, summation from last executed point
J = {}
J['KS', 'g'] = np.hstack(self._ks.derivatives())
示例2: NonLinearSolver
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class NonLinearSolver(SolverBase):
""" Base class for all nonlinear solvers. Inherit from this class to create a
new custom nonlinear solver.
Options
-------
options['iprint'] : int(0)
Set to 0 to disable printing, set to 1 to print the residual to stdout
each iteration, set to 2 to print subiteration residuals as well.
"""
def __init__(self):
""" Initialize the default supports for nl solvers."""
super(NonLinearSolver, self).__init__()
# What this solver supports
self.supports = OptionsDictionary(read_only=True)
self.supports.add_option('uses_derivatives', False)
def add_recorder(self, recorder):
"""Appends the given recorder to this solver's list of recorders.
Args
----
recorder: `BaseRecorder`
A recorder object.
"""
self.recorders.append(recorder)
def solve(self, params, unknowns, resids, system, metadata=None):
""" Drive all residuals in self.system and all subsystems to zero.
This includes all implicit components. This function must be defined
when inheriting.
Args
----
params : `VecWrapper`
`VecWrapper` containing parameters. (p)
unknowns : `VecWrapper`
`VecWrapper` containing outputs and states. (u)
resids : `VecWrapper`
`VecWrapper` containing residuals. (r)
system : `System`
Parent `System` object.
metadata : dict, optional
Dictionary containing execution metadata (e.g. iteration coordinate).
"""
pass
示例3: BaseRecorder
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class BaseRecorder(object):
""" This is a base class for all case recorders and is not a functioning
case recorder on its own.
Options
-------
options['record_metadata'] : bool(True)
Tells recorder whether to record variable attribute metadata.
options['record_unknowns'] : bool(True)
Tells recorder whether to record the unknowns vector.
options['record_params'] : bool(False)
Tells recorder whether to record the params vector.
options['record_resids'] : bool(False)
Tells recorder whether to record the ressiduals vector.
options['record_derivs'] : bool(True)
Tells recorder whether to record derivatives that are requested by a `Driver`.
options['includes'] : list of strings
Patterns for variables to include in recording.
options['excludes'] : list of strings
Patterns for variables to exclude in recording (processed after includes).
"""
def __init__(self):
self.options = OptionsDictionary()
self.options.add_option('record_metadata', True)
self.options.add_option('record_unknowns', True)
self.options.add_option('record_params', False)
self.options.add_option('record_resids', False)
self.options.add_option('record_derivs', True,
desc='Set to True to record derivatives at the driver level')
self.options.add_option('includes', ['*'],
desc='Patterns for variables to include in recording')
self.options.add_option('excludes', [],
desc='Patterns for variables to exclude from recording '
'(processed after includes)')
self.out = None
# This is for drivers to determine if a recorder supports
# real parallel recording (recording on each process), because
# if it doesn't, the driver figures out what variables must
# be gathered to rank 0 if running under MPI.
#
# By default, this is False, but it should be set to True
# if the recorder will record data on each process to avoid
# unnecessary gathering.
self._parallel = False
self._filtered = {}
# TODO: System specific includes/excludes
def startup(self, group):
""" Prepare for a new run.
Args
----
group : `Group`
Group that owns this recorder.
"""
myparams = myunknowns = myresids = set()
if MPI:
rank = group.comm.rank
owned = group._owning_ranks
# Compute the inclusion lists for recording
if self.options['record_params']:
myparams = set(filter(self._check_path, group.params))
if self.options['record_unknowns']:
myunknowns = set(filter(self._check_path, group.unknowns))
if self.options['record_resids']:
myresids = set(filter(self._check_path, group.resids))
self._filtered[group.pathname] = {
'p': myparams,
'u': myunknowns,
'r': myresids
}
def _check_path(self, path):
""" Return True if `path` should be recorded. """
excludes = self.options['excludes']
# First see if it's included
for pattern in self.options['includes']:
if fnmatch(path, pattern):
# We found a match. Check to see if it is excluded.
for ex_pattern in excludes:
if fnmatch(path, ex_pattern):
return False
return True
# Did not match anything in includes.
return False
def _get_pathname(self, iteration_coordinate):
'''
Converts an iteration coordinate to key to index
`_filtered` to retrieve names of variables to be recorded.
#.........这里部分代码省略.........
示例4: Driver
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class Driver(object):
""" Base class for drivers in OpenMDAO. Drivers can only be placed in a
Problem, and every problem has a Driver. Driver is the simplest driver that
runs (solves using solve_nonlinear) a problem once.
"""
def __init__(self):
super(Driver, self).__init__()
self.recorders = RecordingManager()
# What this driver supports
self.supports = OptionsDictionary(read_only=True)
self.supports.add_option('inequality_constraints', True)
self.supports.add_option('equality_constraints', True)
self.supports.add_option('linear_constraints', True)
self.supports.add_option('multiple_objectives', True)
self.supports.add_option('two_sided_constraints', True)
self.supports.add_option('integer_design_vars', True)
# inheriting Drivers should override this setting and set it to False
# if they don't use gradients.
self.supports.add_option('gradients', True)
# This driver's options
self.options = OptionsDictionary()
self._desvars = OrderedDict()
self._objs = OrderedDict()
self._cons = OrderedDict()
self._voi_sets = []
self._vars_to_record = None
# We take root during setup
self.root = None
self.iter_count = 0
self.dv_conversions = {}
self.fn_conversions = {}
def _setup(self):
""" Updates metadata for params, constraints and objectives, and
check for errors. Also determines all variables that need to be
gathered for case recording.
"""
root = self.root
desvars = OrderedDict()
objs = OrderedDict()
cons = OrderedDict()
if self.__class__ is Driver:
has_gradients = False
else:
has_gradients = self.supports['gradients']
item_tups = [
('Parameter', self._desvars, desvars),
('Objective', self._objs, objs),
('Constraint', self._cons, cons)
]
for item_name, item, newitem in item_tups:
for name, meta in iteritems(item):
# Check validity of variable
if name not in root.unknowns:
msg = "{} '{}' not found in unknowns."
msg = msg.format(item_name, name)
raise ValueError(msg)
rootmeta = root.unknowns.metadata(name)
if name in self._desvars:
rootmeta['is_desvar'] = True
if name in self._objs:
rootmeta['is_objective'] = True
if name in self._cons:
rootmeta['is_constraint'] = True
if MPI and 'src_indices' in rootmeta:
raise ValueError("'%s' is a distributed variable and may "
"not be used as a design var, objective, "
"or constraint." % name)
if has_gradients and rootmeta.get('pass_by_obj'):
if 'optimizer' in self.options:
oname = self.options['optimizer']
else:
oname = self.__class__.__name__
raise RuntimeError("%s '%s' is a 'pass_by_obj' variable "
"and can't be used with a gradient "
"based driver of type '%s'." %
(item_name, name, oname))
# Size is useful metadata to save
if 'indices' in meta:
meta['size'] = len(meta['indices'])
else:
meta['size'] = rootmeta['size']
newitem[name] = meta
#.........这里部分代码省略.........
示例5: ExternalCode
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class ExternalCode(Component):
"""
Run an external code as a component
Default stdin is the 'null' device, default stdout is the console, and
default stderr is ``error.out``.
Options
-------
fd_options['force_fd'] : bool(False)
Set to True to finite difference this system.
fd_options['form'] : str('forward')
Finite difference mode. (forward, backward, central) You can also set to 'complex_step' to peform the complex step method if your components support it.
fd_options['step_size'] : float(1e-06)
Default finite difference stepsize
fd_options['step_type'] : str('absolute')
Set to absolute, relative
options['check_external_outputs'] : bool(True)
Check that all input or output external files exist
options['command'] : list([])
command to be executed
options['env_vars'] : dict({})
Environment variables required by the command
options['external_input_files'] : list([])
(optional) list of input file names to check the pressence of before solve_nonlinear
options['external_output_files'] : list([])
(optional) list of input file names to check the pressence of after solve_nonlinear
options['poll_delay'] : float(0.0)
Delay between polling for command completion. A value of zero will use an internally computed default
options['timeout'] : float(0.0)
Maximum time to wait for command completion. A value of zero implies an infinite wait
"""
def __init__(self):
super(ExternalCode, self).__init__()
self.STDOUT = STDOUT
self.DEV_NULL = DEV_NULL
# Input options for this Component
self.options = OptionsDictionary()
self.options.add_option('command', [], desc='command to be executed')
self.options.add_option('env_vars', {}, desc='Environment variables required by the command')
self.options.add_option('poll_delay', 0.0, lower=0.0,
desc='Delay between polling for command completion. A value of zero will use an internally computed default')
self.options.add_option('timeout', 0.0, lower=0.0,
desc='Maximum time to wait for command completion. A value of zero implies an infinite wait')
self.options.add_option('check_external_outputs', True,
desc='Check that all input or output external files exist')
self.options.add_option( 'external_input_files', [],
desc='(optional) list of input file names to check the pressence of before solve_nonlinear')
self.options.add_option( 'external_output_files', [],
desc='(optional) list of input file names to check the pressence of after solve_nonlinear')
# Outputs of the run of the component or items that will not work with the OptionsDictionary
self.return_code = 0 # Return code from the command
self.timed_out = False # True if the command timed-out
self.stdin = self.DEV_NULL
self.stdout = None
self.stderr = "error.out"
def check_setup(self, out_stream=sys.stdout):
"""Write a report to the given stream indicating any potential problems found
with the current configuration of this ``Problem``.
Args
----
out_stream : a file-like object, optional
"""
# check for the command
if not self.options['command']:
out_stream.write( "The command cannot be empty")
else:
if isinstance(self.options['command'], str):
program_to_execute = self.options['command']
else:
program_to_execute = self.options['command'][0]
command_full_path = find_executable( program_to_execute )
if not command_full_path:
msg = "The command to be executed, '%s', cannot be found" % program_to_execute
out_stream.write(msg)
# Check for missing input files
missing_files = self._check_for_files(input=True)
for iotype, path in missing_files:
msg = "The %s file %s is missing" % ( iotype, path )
out_stream.write(msg)
def solve_nonlinear(self, params, unknowns, resids):
"""Runs the component
"""
self.return_code = -12345678
self.timed_out = False
if not self.options['command']:
#.........这里部分代码省略.........
示例6: SolverBase
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class SolverBase(object):
""" Common base class for Linear and Nonlinear solver. Should not be used
by users. Always inherit from `LinearSolver` or `NonlinearSolver`."""
def __init__(self):
self.iter_count = 0
self.options = OptionsDictionary()
desc = 'Set to 0 to disable printing, set to 1 to print the ' \
'residual to stdout each iteration, set to 2 to print ' \
'subiteration residuals as well.'
self.options.add_option('iprint', 0, values=[0, 1, 2], desc=desc)
self.options.add_option('err_on_maxiter', False,
desc='If True, raise an AnalysisError if not converged at maxiter.')
self.recorders = RecordingManager()
self.local_meta = None
def setup(self, sub):
""" Solvers override to define post-setup initiailzation.
Args
----
sub: `System`
System that owns this solver.
"""
pass
def cleanup(self):
""" Clean up resources prior to exit. """
self.recorders.close()
def print_norm(self, solver_string, pathname, iteration, res, res0,
msg=None, indent=0, solver='NL', u_norm=None):
""" Prints out the norm of the residual in a neat readable format.
Args
----
solver_string: string
Unique string to identify your solver type (e.g., 'LN_GS' or
'NEWTON').
pathname: dict
Parent system pathname.
iteration: int
Current iteration number
res: float
Norm of the absolute residual value.
res0: float
Norm of the baseline initial residual for relative comparison.
msg: string, optional
Message that indicates convergence.
ident: int, optional
Additional indentation levels for subiterations.
solver: string, optional
Solver type if not LN or NL (mostly for line search operations.)
u_norm: float, optional
Norm of the u vector, if applicable.
"""
if pathname=='':
name = 'root'
else:
name = 'root.' + pathname
# Find indentation level
level = pathname.count('.')
# No indentation for driver; top solver is no indentation.
level = level + indent
indent = ' ' * level
if msg is not None:
form = indent + '[%s] %s: %s %d | %s'
if u_norm:
form += ' (%s)' % u_norm
print(form % (name, solver, solver_string, iteration, msg))
return
form = indent + '[%s] %s: %s %d | %.9g %.9g'
if u_norm:
form += ' (%s)' % u_norm
print(form % (name, solver, solver_string, iteration, res, res/res0))
def print_all_convergence(self):
""" Turns on iprint for this solver and all subsolvers. Override if
your solver has subsolvers."""
self.options['iprint'] = 1
def generate_docstring(self):
"""
Generates a numpy-style docstring for a user-created System class.
#.........这里部分代码省略.........
示例7: SolverBase
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class SolverBase(object):
""" Common base class for Linear and Nonlinear solver. Should not be used
by users. Always inherit from `LinearSolver` or `NonlinearSolver`."""
def __init__(self):
self.iter_count = 0
self.options = OptionsDictionary()
desc = 'Set to 0 to disable printing, set to 1 to print the ' \
'residual to stdout each iteration, set to 2 to print ' \
'subiteration residuals as well.'
self.options.add_option('iprint', 0, values=[0, 1, 2], desc=desc)
self.recorders = RecordingManager()
self.local_meta = None
def setup(self, sub):
""" Solvers override to define post-setup initiailzation.
Args
----
sub: `System`
System that owns this solver.
"""
pass
def print_norm(self, solver_string, pathname, iteration, res, res0,
msg=None, indent=0, solver='NL'):
""" Prints out the norm of the residual in a neat readable format.
Args
----
solver_string: string
Unique string to identify your solver type (e.g., 'LN_GS' or
'NEWTON').
pathname: dict
Parent system pathname.
iteration: int
Current iteration number
res: float
Absolute residual value.
res0: float
Baseline initial residual for relative comparison.
msg: string, optional
Message that indicates convergence.
ident: int, optional
Additional indentation levels for subiterations.
solver: string, optional
Solver type if not LN or NL (mostly for line search operations.)
"""
if pathname=='':
name = 'root'
else:
name = 'root.' + pathname
# Find indentation level
level = pathname.count('.')
# No indentation for driver; top solver is no indentation.
level = level + indent
indent = ' ' * level
if msg is not None:
form = indent + '[%s] %s: %s %d | %s'
print(form % (name, solver, solver_string, iteration, msg))
return
form = indent + '[%s] %s: %s %d | %.9g %.9g'
print(form % (name, solver, solver_string, iteration, res, res/res0))
def print_all_convergence(self):
""" Turns on iprint for this solver and all subsolvers. Override if
your solver has subsolvers."""
self.options['iprint'] = 1
def generate_docstring(self):
"""
Generates a numpy-style docstring for a user-created System class.
Returns
-------
docstring : str
string that contains a basic numpy docstring.
"""
#start the docstring off
docstring = ' \"\"\"\n'
#Put options into docstring
firstTime = 1
#for py3.4, items from vars must come out in same order.
from collections import OrderedDict
v = OrderedDict(sorted(vars(self).items()))
for key, value in v.items():
if type(value)==OptionsDictionary:
if firstTime: #start of Options docstring
#.........这里部分代码省略.........
示例8: BaseRecorder
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class BaseRecorder(object):
""" Base class for all case recorders. """
def __init__(self):
self.options = OptionsDictionary()
self.options.add_option('record_metadata', True)
self.options.add_option('record_unknowns', True)
self.options.add_option('record_params', False)
self.options.add_option('record_resids', False)
self.options.add_option('includes', ['*'],
desc='Patterns for variables to include in recording')
self.options.add_option('excludes', [],
desc='Patterns for variables to exclude from recording '
'(processed after includes)')
self.out = None
# This is for drivers to determine if a recorder supports
# real parallel recording (recording on each process), because
# if it doesn't, the driver figures out what variables must
# be gathered to rank 0 if running under MPI.
#
# By default, this is False, but it should be set to True
# if the recorder will record data on each process to avoid
# unnecessary gathering.
self._parallel = False
self._filtered = {}
# TODO: System specific includes/excludes
def startup(self, group):
""" Prepare for a new run.
Args
----
group : `Group`
Group that owns this recorder.
"""
# Compute the inclusion lists for recording
params = list(filter(self._check_path, group.params))
unknowns = list(filter(self._check_path, group.unknowns))
resids = list(filter(self._check_path, group.resids))
self._filtered[group.pathname] = (params, unknowns, resids)
def _check_path(self, path):
""" Return True if `path` should be recorded. """
includes = self.options['includes']
excludes = self.options['excludes']
# First see if it's included
for pattern in includes:
if fnmatch(path, pattern):
# We found a match. Check to see if it is excluded.
for ex_pattern in excludes:
if fnmatch(path, ex_pattern):
return False
return True
# Did not match anything in includes.
return False
def _get_pathname(self, iteration_coordinate):
'''
Converts an iteration coordinate to key to index
`_filtered` to retrieve names of variables to be recorder
'''
return '.'.join(iteration_coordinate[4::2])
def _filter_vectors(self, params, unknowns, resids, iteration_coordinate):
'''
Returns subset of `params`, `unknowns` and `resids` to be recoder
'''
pathname = self._get_pathname(iteration_coordinate)
pnames, unames, rnames = self._filtered[pathname]
params = {key: params[key] for key in pnames}
unknowns = {key: unknowns[key] for key in unames}
resids = {key: resids[key] for key in rnames}
return params, unknowns, resids
def record_iteration(self, params, unknowns, resids, metadata):
"""
Writes the provided data.
Args
----
params : dict
Dictionary containing parameters. (p)
unknowns : dict
Dictionary containing outputs and states. (u)
resids : dict
Dictionary containing residuals. (r)
metadata : dict, optional
Dictionary containing execution metadata (e.g. iteration coordinate).
#.........这里部分代码省略.........
示例9: MySimpleDriver
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class MySimpleDriver(Driver):
def __init__(self):
super(MySimpleDriver, self).__init__()
# What we support
self.supports['inequality_constraints'] = True
self.supports['equality_constraints'] = False
self.supports['linear_constraints'] = False
self.supports['multiple_objectives'] = False
# My driver options
self.options = OptionsDictionary()
self.options.add_option('tol', 1e-4)
self.options.add_option('maxiter', 10)
self.alpha = .01
self.violated = []
def run(self, problem):
""" Mimic a very simplistic unconstrained optimization."""
# Get dicts with pointers to our vectors
params = self.get_desvars()
objective = self.get_objectives()
constraints = self.get_constraints()
indep_list = params.keys()
objective_names = list(objective.keys())
constraint_names = list(constraints.keys())
unknown_list = objective_names + constraint_names
itercount = 0
while itercount < self.options['maxiter']:
# Run the model
problem.root.solve_nonlinear()
#print('z1: %f, z2: %f, x1: %f, y1: %f, y2: %f' % (problem['z'][0],
#problem['z'][1],
#problem['x'],
#problem['y1'],
#problem['y2']))
#print('obj: %f, con1: %f, con2: %f' % (problem['obj'], problem['con1'],
#problem['con2']))
# Calculate gradient
J = problem.calc_gradient(indep_list, unknown_list, return_format='dict')
objective = self.get_objectives()
constraints = self.get_constraints()
for key1 in objective_names:
for key2 in indep_list:
grad = J[key1][key2] * objective[key1]
new_val = params[key2] - self.alpha*grad
# Set parameter
self.set_desvar(key2, new_val)
self.violated = []
for name, val in constraints.items():
if np.linalg.norm(val) > 0.0:
self.violated.append(name)
itercount += 1
示例10: ExternalCode
# 需要导入模块: from openmdao.util.options import OptionsDictionary [as 别名]
# 或者: from openmdao.util.options.OptionsDictionary import add_option [as 别名]
class ExternalCode(Component):
"""
Run an external code as a component
Default stdin is the 'null' device, default stdout is the console, and
default stderr is ``error.out``.
Options
-------
deriv_options['type'] : str('user')
Derivative calculation type ('user', 'fd', 'cs')
Default is 'user', where derivative is calculated from
user-supplied derivatives. Set to 'fd' to finite difference
this system. Set to 'cs' to perform the complex step
if your components support it.
deriv_options['form'] : str('forward')
Finite difference mode. (forward, backward, central)
deriv_options['step_size'] : float(1e-06)
Default finite difference stepsize
deriv_options['step_calc'] : str('absolute')
Set to absolute, relative
deriv_options['check_type'] : str('fd')
Type of derivative check for check_partial_derivatives. Set
to 'fd' to finite difference this system. Set to
'cs' to perform the complex step method if
your components support it.
deriv_options['check_form'] : str('forward')
Finite difference mode: ("forward", "backward", "central")
During check_partial_derivatives, the difference form that is used
for the check.
deriv_options['check_step_calc'] : str('absolute',)
Set to 'absolute' or 'relative'. Default finite difference
step calculation for the finite difference check in check_partial_derivatives.
deriv_options['check_step_size'] : float(1e-06)
Default finite difference stepsize for the finite difference check
in check_partial_derivatives"
deriv_options['linearize'] : bool(False)
Set to True if you want linearize to be called even though you are using FD.
options['command'] : list([])
Command to be executed. Command must be a list of command line args.
options['env_vars'] : dict({})
Environment variables required by the command
options['external_input_files'] : list([])
(optional) list of input file names to check the existence of before solve_nonlinear
options['external_output_files'] : list([])
(optional) list of input file names to check the existence of after solve_nonlinear
options['poll_delay'] : float(0.0)
Delay between polling for command completion. A value of zero will use
an internally computed default.
options['timeout'] : float(0.0)
Maximum time in seconds to wait for command completion. A value of zero
implies an infinite wait. If the timeout interval is exceeded, an
AnalysisError will be raised.
options['fail_hard'] : bool(True)
Behavior on error returned from code, either raise a 'hard' error (RuntimeError) if True
or a 'soft' error (AnalysisError) if False.
"""
def __init__(self):
super(ExternalCode, self).__init__()
self.STDOUT = STDOUT
self.DEV_NULL = DEV_NULL
# Input options for this Component
self.options = OptionsDictionary()
self.options.add_option('command', [], desc='command to be executed')
self.options.add_option('env_vars', {},
desc='Environment variables required by the command')
self.options.add_option('poll_delay', 0.0, lower=0.0,
desc='Delay between polling for command completion. A value of zero will use an internally computed default')
self.options.add_option('timeout', 0.0, lower=0.0,
desc='Maximum time to wait for command completion. A value of zero implies an infinite wait')
self.options.add_option( 'external_input_files', [],
desc='(optional) list of input file names to check the existence of before solve_nonlinear')
self.options.add_option( 'external_output_files', [],
desc='(optional) list of input file names to check the existence of after solve_nonlinear')
self.options.add_option('fail_hard', True,
desc="If True, external code errors raise a 'hard' exception (RuntimeError). Otherwise raise a 'soft' exception (AnalysisError).")
# Outputs of the run of the component or items that will not work with the OptionsDictionary
self.return_code = 0 # Return code from the command
self.stdin = self.DEV_NULL
self.stdout = None
self.stderr = "error.out"
def check_setup(self, out_stream=sys.stdout):
"""Write a report to the given stream indicating any potential problems found
with the current configuration of this ``Problem``.
Args
----
out_stream : a file-like object, optional
"""
# check for the command
cmd = [c for c in self.options['command'] if c.strip()]
#.........这里部分代码省略.........