本文整理汇总了Python中openmdao.util.options.OptionsDictionary类的典型用法代码示例。如果您正苦于以下问题:Python OptionsDictionary类的具体用法?Python OptionsDictionary怎么用?Python OptionsDictionary使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OptionsDictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: KSComp
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
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: __init__
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 = {}
示例4: __init__
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 = {}
示例5: __init__
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"
示例6: __init__
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)
# 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 = {}
示例7: __init__
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)
示例8: __init__
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
示例9: __init__
def __init__(self):
self.iter_count = 0
self.options = OptionsDictionary()
desc = "Set to 0 to print only failures, set to 1 to print iteration totals to" + \
"stdout, set to 2 to print the residual each iteration to stdout," + \
"or -1 to suppress all printing."
self.options.add_option('iprint', 0, values=[-1, 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
示例10: __init__
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 = []
示例11: __init__
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 = 0.01
self.violated = []
示例12: __init__
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()
示例13: Driver
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
#.........这里部分代码省略.........
示例14: ExternalCode
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()]
#.........这里部分代码省略.........
示例15: ExternalCode
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']:
#.........这里部分代码省略.........