当前位置: 首页>>代码示例>>Python>>正文


Python recording_manager.RecordingManager类代码示例

本文整理汇总了Python中openmdao.recorders.recording_manager.RecordingManager的典型用法代码示例。如果您正苦于以下问题:Python RecordingManager类的具体用法?Python RecordingManager怎么用?Python RecordingManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了RecordingManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __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 = {}
开发者ID:colinxs,项目名称:OpenMDAO,代码行数:33,代码来源:driver.py

示例2: __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 = {}
开发者ID:fzahle,项目名称:OpenMDAO,代码行数:29,代码来源:driver.py

示例3: __init__

    def __init__(self, **kwargs):
        """
        Initialize all attributes.

        Parameters
        ----------
        **kwargs : dict
            options dictionary.
        """
        self._system = None
        self._depth = 0
        self._vec_names = None
        self._mode = 'fwd'
        self._iter_count = 0

        self.options = OptionsDictionary()
        self.recording_options = OptionsDictionary()
        self.options.declare('maxiter', types=int, default=10,
                             desc='maximum number of iterations')
        self.options.declare('atol', default=1e-10,
                             desc='absolute error tolerance')
        self.options.declare('rtol', default=1e-10,
                             desc='relative error tolerance')
        self.options.declare('iprint', types=int, default=1,
                             desc='whether to print output')
        self.options.declare('err_on_maxiter', types=bool, default=False,
                             desc="When True, AnalysisError will be raised if we don't converge.")
        # Case recording options
        self.recording_options.declare('record_abs_error', types=bool, default=True,
                                       desc='Set to True to record absolute error at the \
                                       solver level')
        self.recording_options.declare('record_rel_error', types=bool, default=True,
                                       desc='Set to True to record relative error at the \
                                       solver level')
        self.recording_options.declare('record_solver_residuals', types=bool, default=False,
                                       desc='Set to True to record residuals at the solver level')
        self.recording_options.declare('record_metadata', types=bool, desc='Record metadata',
                                       default=True)
        self.recording_options.declare('includes', types=list, default=['*'],
                                       desc='Patterns for variables to include in recording')
        self.recording_options.declare('excludes', types=list, default=[],
                                       desc='Patterns for vars to exclude in recording '
                                       '(processed post-includes)')
        # Case recording related
        self._filtered_vars_to_record = {}
        self._norm0 = 0.0

        # What the solver supports.
        self.supports = OptionsDictionary()
        self.supports.declare('gradients', types=bool, default=False)

        self._declare_options()
        self.options.update(kwargs)

        self.metadata = {}
        self._rec_mgr = RecordingManager()

        self.cite = ""
开发者ID:samtx,项目名称:OpenMDAO,代码行数:58,代码来源:solver.py

示例4: __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
开发者ID:alexanderzimmerman,项目名称:OpenMDAO,代码行数:9,代码来源:solver_base.py

示例5: __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.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
开发者ID:sanbales,项目名称:OpenMDAO,代码行数:11,代码来源:solver_base.py

示例6: __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
开发者ID:shamsheersc19,项目名称:OpenMDAO,代码行数:12,代码来源:solver_base.py

示例7: 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

#.........这里部分代码省略.........
开发者ID:colinxs,项目名称:OpenMDAO,代码行数:101,代码来源:driver.py

示例8: Solver

class Solver(object):
    """
    Base solver class.

    This class is subclassed by NonlinearSolver and LinearSolver,
    which are in turn subclassed by actual solver implementations.

    Attributes
    ----------
    _system : <System>
        Pointer to the owning system.
    _depth : int
        How many subsolvers deep this solver is (0 means not a subsolver).
    _vec_names : [str, ...]
        List of right-hand-side (RHS) vector names.
    _mode : str
        'fwd' or 'rev', applicable to linear solvers only.
    _iter_count : int
        Number of iterations for the current invocation of the solver.
    _rec_mgr : <RecordingManager>
        object that manages all recorders added to this solver
    cite : str
        Listing of relevant citations that should be referenced when
        publishing work that uses this class.
    options : <OptionsDictionary>
        Options dictionary.
    recording_options : <OptionsDictionary>
        Recording options dictionary.
    supports : <OptionsDictionary>
        Options dictionary describing what features are supported by this
        solver.
    _filtered_vars_to_record: Dict
        Dict of list of var names to record
    _norm0: float
        Normalization factor
    _solver_info : SolverInfo
        A stack-like object shared by all Solvers in the model.
    """

    # Object to store some formatting for iprint that is shared across all solvers.
    SOLVER = 'base_solver'

    def __init__(self, **kwargs):
        """
        Initialize all attributes.

        Parameters
        ----------
        **kwargs : dict of keyword arguments
            Keyword arguments that will be mapped into the Solver options.
        """
        self._system = None
        self._depth = 0
        self._vec_names = None
        self._mode = 'fwd'
        self._iter_count = 0
        self._solver_info = None

        # Solver options
        self.options = OptionsDictionary()
        self.options.declare('maxiter', types=int, default=10,
                             desc='maximum number of iterations')
        self.options.declare('atol', default=1e-10,
                             desc='absolute error tolerance')
        self.options.declare('rtol', default=1e-10,
                             desc='relative error tolerance')
        self.options.declare('iprint', types=int, default=1,
                             desc='whether to print output')
        self.options.declare('err_on_maxiter', types=bool, default=False,
                             desc="When True, AnalysisError will be raised if we don't converge.")

        # Case recording options
        self.recording_options = OptionsDictionary()
        self.recording_options.declare('record_abs_error', types=bool, default=True,
                                       desc='Set to True to record absolute error at the \
                                       solver level')
        self.recording_options.declare('record_rel_error', types=bool, default=True,
                                       desc='Set to True to record relative error at the \
                                       solver level')
        self.recording_options.declare('record_inputs', types=bool, default=True,
                                       desc='Set to True to record inputs at the solver level')
        self.recording_options.declare('record_outputs', types=bool, default=True,
                                       desc='Set to True to record outputs at the solver level')
        self.recording_options.declare('record_solver_residuals', types=bool, default=False,
                                       desc='Set to True to record residuals at the solver level')
        self.recording_options.declare('record_metadata', types=bool, desc='Record metadata',
                                       default=True)
        self.recording_options.declare('includes', types=list, default=['*'],
                                       desc='Patterns for variables to include in recording')
        self.recording_options.declare('excludes', types=list, default=[],
                                       desc='Patterns for vars to exclude in recording '
                                            '(processed post-includes)')
        # Case recording related
        self._filtered_vars_to_record = {}
        self._norm0 = 0.0

        # What the solver supports.
        self.supports = OptionsDictionary()
        self.supports.declare('gradients', types=bool, default=False)
        self.supports.declare('implicit_components', types=bool, default=False)
#.........这里部分代码省略.........
开发者ID:OpenMDAO,项目名称:OpenMDAO,代码行数:101,代码来源:solver.py

示例9: SolverBase

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.

#.........这里部分代码省略.........
开发者ID:sanbales,项目名称:OpenMDAO,代码行数:101,代码来源:solver_base.py

示例10: SolverBase

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 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"):
        """ 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.
#.........这里部分代码省略.........
开发者ID:mkn9,项目名称:OpenMDAO,代码行数:101,代码来源:solver_base.py

示例11: Driver

class Driver(object):
    """
    Top-level container for the systems and drivers.

    Options
    -------
    options['debug_print'] :  list of strings([])
        Indicates what variables to print at each iteration. The valid options are:
            'desvars','ln_cons','nl_cons',and 'objs'.
    recording_options['record_metadata'] :  bool(True)
        Tells recorder whether to record variable attribute metadata.
    recording_options['record_desvars'] :  bool(True)
        Tells recorder whether to record the desvars of the Driver.
    recording_options['record_responses'] :  bool(False)
        Tells recorder whether to record the responses of the Driver.
    recording_options['record_objectives'] :  bool(False)
        Tells recorder whether to record the objectives of the Driver.
    recording_options['record_constraints'] :  bool(False)
        Tells recorder whether to record the constraints of the Driver.
    recording_options['includes'] :  list of strings("*")
        Patterns for variables to include in recording.
    recording_options['excludes'] :  list of strings('')
        Patterns for variables to exclude in recording (processed after includes).


    Attributes
    ----------
    fail : bool
        Reports whether the driver ran successfully.
    iter_count : int
        Keep track of iterations for case recording.
    metadata : list
        List of metadata
    options : <OptionsDictionary>
        Dictionary with general pyoptsparse options.
    recording_options : <OptionsDictionary>
        Dictionary with driver recording options.
    debug_print : <OptionsDictionary>
        Dictionary with debugging printing options.
    cite : str
        Listing of relevant citataions that should be referenced when
        publishing work that uses this class.
    _problem : <Problem>
        Pointer to the containing problem.
    supports : <OptionsDictionary>
        Provides a consistant way for drivers to declare what features they support.
    _designvars : dict
        Contains all design variable info.
    _cons : dict
        Contains all constraint info.
    _objs : dict
        Contains all objective info.
    _responses : dict
        Contains all response info.
    _rec_mgr : <RecordingManager>
        Object that manages all recorders added to this driver.
    _vars_to_record: dict
        Dict of lists of var names indicating what to record
    _model_viewer_data : dict
        Structure of model, used to make n2 diagram.
    _remote_dvs : dict
        Dict of design variables that are remote on at least one proc. Values are
        (owning rank, size).
    _remote_cons : dict
        Dict of constraints that are remote on at least one proc. Values are
        (owning rank, size).
    _remote_objs : dict
        Dict of objectives that are remote on at least one proc. Values are
        (owning rank, size).
    _remote_responses : dict
        A combined dict containing entries from _remote_cons and _remote_objs.
    _simul_coloring_info : tuple of dicts
        A data structure describing coloring for simultaneous derivs.
    _res_jacs : dict
        Dict of sparse subjacobians for use with certain optimizers, e.g. pyOptSparseDriver.
    """

    def __init__(self):
        """
        Initialize the driver.
        """
        self._rec_mgr = RecordingManager()
        self._vars_to_record = {
            'desvarnames': set(),
            'responsenames': set(),
            'objectivenames': set(),
            'constraintnames': set(),
            'sysinclnames': set(),
        }

        self._problem = None
        self._designvars = None
        self._cons = None
        self._objs = None
        self._responses = None
        self.options = OptionsDictionary()
        self.recording_options = OptionsDictionary()

        ###########################
        self.options.declare('debug_print', types=list, is_valid=_is_debug_print_opts_valid,
#.........这里部分代码省略.........
开发者ID:samtx,项目名称:OpenMDAO,代码行数:101,代码来源:driver.py

示例12: __init__

    def __init__(self):
        """
        Initialize the driver.
        """
        self._rec_mgr = RecordingManager()
        self._vars_to_record = {
            'desvarnames': set(),
            'responsenames': set(),
            'objectivenames': set(),
            'constraintnames': set(),
            'sysinclnames': set(),
        }

        self._problem = None
        self._designvars = None
        self._cons = None
        self._objs = None
        self._responses = None
        self.options = OptionsDictionary()
        self.recording_options = OptionsDictionary()

        ###########################
        self.options.declare('debug_print', types=list, is_valid=_is_debug_print_opts_valid,
                             desc="List of what type of Driver variables to print at each "
                             "iteration. Valid items in list are 'desvars','ln_cons',"
                             "'nl_cons','objs'",
                             default=[])

        ###########################
        self.recording_options.declare('record_metadata', types=bool, desc='Record metadata',
                                       default=True)
        self.recording_options.declare('record_desvars', types=bool, default=True,
                                       desc='Set to True to record design variables at the \
                                       driver level')
        self.recording_options.declare('record_responses', types=bool, default=False,
                                       desc='Set to True to record responses at the driver level')
        self.recording_options.declare('record_objectives', types=bool, default=True,
                                       desc='Set to True to record objectives at the \
                                       driver level')
        self.recording_options.declare('record_constraints', types=bool, default=True,
                                       desc='Set to True to record constraints at the \
                                       driver level')
        self.recording_options.declare('includes', types=list, default=['*'],
                                       desc='Patterns for variables to include in recording')
        self.recording_options.declare('excludes', types=list, default=[],
                                       desc='Patterns for vars to exclude in recording '
                                       '(processed post-includes)')
        self.recording_options.declare('record_derivatives', types=bool, default=False,
                                       desc='Set to True to record derivatives at the driver \
                                       level')
        ###########################

        # What the driver supports.
        self.supports = OptionsDictionary()
        self.supports.declare('inequality_constraints', types=bool, default=False)
        self.supports.declare('equality_constraints', types=bool, default=False)
        self.supports.declare('linear_constraints', types=bool, default=False)
        self.supports.declare('two_sided_constraints', types=bool, default=False)
        self.supports.declare('multiple_objectives', types=bool, default=False)
        self.supports.declare('integer_design_vars', types=bool, default=False)
        self.supports.declare('gradients', types=bool, default=False)
        self.supports.declare('active_set', types=bool, default=False)
        self.supports.declare('simultaneous_derivatives', types=bool, default=False)

        # Debug printing.
        self.debug_print = OptionsDictionary()
        self.debug_print.declare('debug_print', types=bool, default=False,
                                 desc='Overall option to turn on Driver debug printing')
        self.debug_print.declare('debug_print_desvars', types=bool, default=False,
                                 desc='Print design variables')
        self.debug_print.declare('debug_print_nl_con', types=bool, default=False,
                                 desc='Print nonlinear constraints')
        self.debug_print.declare('debug_print_ln_con', types=bool, default=False,
                                 desc='Print linear constraints')
        self.debug_print.declare('debug_print_objective', types=bool, default=False,
                                 desc='Print objectives')

        self.iter_count = 0
        self.metadata = None
        self._model_viewer_data = None
        self.cite = ""

        # TODO, support these in OpenMDAO
        self.supports.declare('integer_design_vars', types=bool, default=False)

        self._simul_coloring_info = None
        self._res_jacs = {}

        self.fail = False
开发者ID:samtx,项目名称:OpenMDAO,代码行数:89,代码来源:driver.py

示例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)

        # 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

    def _setup(self, root):
        """ Updates metadata for params, constraints and objectives, and
        check for errors. Also determines all variables that need to be
        gathered for case recording.
        """
        self.root = root

        desvars = OrderedDict()
        objs = OrderedDict()
        cons = OrderedDict()

        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):
                rootmeta = root.unknowns.metadata(name)

                if MPI and "src_indices" in rootmeta:  # pragma: no cover
                    raise ValueError(
                        "'%s' is a distributed variable and may "
                        "not be used as a design var, objective, "
                        "or constraint." % name
                    )

                # Check validity of variable
                if name not in root.unknowns:
                    msg = "{} '{}' not found in unknowns."
                    msg = msg.format(item_name, name)
                    raise ValueError(msg)

                # Size is useful metadata to save
                if "indices" in meta:
                    meta["size"] = len(meta["indices"])
                else:
                    meta["size"] = rootmeta["size"]

                newitem[name] = meta

        self._desvars = desvars
        self._objs = objs
        self._cons = cons

    def _map_voi_indices(self):
        poi_indices = {}
        qoi_indices = {}
        for name, meta in chain(iteritems(self._cons), iteritems(self._objs)):
            # set indices of interest
            if "indices" in meta:
                qoi_indices[name] = meta["indices"]

        for name, meta in iteritems(self._desvars):
            # set indices of interest
            if "indices" in meta:
                poi_indices[name] = meta["indices"]

        return poi_indices, qoi_indices

    def _of_interest(self, voi_list):
        """Return a list of tuples, with the given voi_list organized
        into tuples based on the previously defined grouping of VOIs.
        """
        vois = []
#.........这里部分代码省略.........
开发者ID:briantomko,项目名称:OpenMDAO,代码行数:101,代码来源:driver.py

示例14: __init__

    def __init__(self, **kwargs):
        """
        Initialize the driver.

        Parameters
        ----------
        **kwargs : dict of keyword arguments
            Keyword arguments that will be mapped into the Driver options.
        """
        self._rec_mgr = RecordingManager()
        self._vars_to_record = {
            'desvarnames': set(),
            'responsenames': set(),
            'objectivenames': set(),
            'constraintnames': set(),
            'sysinclnames': set(),
        }

        self._problem = None
        self._designvars = None
        self._cons = None
        self._objs = None
        self._responses = None

        # Driver options
        self.options = OptionsDictionary()

        self.options.declare('debug_print', types=list, check_valid=_check_debug_print_opts_valid,
                             desc="List of what type of Driver variables to print at each "
                                  "iteration. Valid items in list are 'desvars', 'ln_cons', "
                                  "'nl_cons', 'objs', 'totals'",
                             default=[])

        # Case recording options
        self.recording_options = OptionsDictionary()

        self.recording_options.declare('record_model_metadata', types=bool, default=True,
                                       desc='Record metadata for all Systems in the model')
        self.recording_options.declare('record_desvars', types=bool, default=True,
                                       desc='Set to True to record design variables at the '
                                            'driver level')
        self.recording_options.declare('record_responses', types=bool, default=False,
                                       desc='Set to True to record responses at the driver level')
        self.recording_options.declare('record_objectives', types=bool, default=True,
                                       desc='Set to True to record objectives at the driver level')
        self.recording_options.declare('record_constraints', types=bool, default=True,
                                       desc='Set to True to record constraints at the '
                                            'driver level')
        self.recording_options.declare('includes', types=list, default=[],
                                       desc='Patterns for variables to include in recording')
        self.recording_options.declare('excludes', types=list, default=[],
                                       desc='Patterns for vars to exclude in recording '
                                            '(processed post-includes)')
        self.recording_options.declare('record_derivatives', types=bool, default=False,
                                       desc='Set to True to record derivatives at the driver '
                                            'level')
        self.recording_options.declare('record_inputs', types=bool, default=True,
                                       desc='Set to True to record inputs at the driver level')

        # What the driver supports.
        self.supports = OptionsDictionary()
        self.supports.declare('inequality_constraints', types=bool, default=False)
        self.supports.declare('equality_constraints', types=bool, default=False)
        self.supports.declare('linear_constraints', types=bool, default=False)
        self.supports.declare('two_sided_constraints', types=bool, default=False)
        self.supports.declare('multiple_objectives', types=bool, default=False)
        self.supports.declare('integer_design_vars', types=bool, default=False)
        self.supports.declare('gradients', types=bool, default=False)
        self.supports.declare('active_set', types=bool, default=False)
        self.supports.declare('simultaneous_derivatives', types=bool, default=False)
        self.supports.declare('total_jac_sparsity', types=bool, default=False)

        self.iter_count = 0
        self._model_viewer_data = None
        self.cite = ""

        self._simul_coloring_info = None
        self._total_jac_sparsity = None
        self._res_jacs = {}
        self._total_jac = None

        self.fail = False

        self._declare_options()
        self.options.update(kwargs)
开发者ID:johnjasa,项目名称:OpenMDAO,代码行数:85,代码来源:driver.py

示例15: Driver

class Driver(object):
    """
    Top-level container for the systems and drivers.

    Attributes
    ----------
    fail : bool
        Reports whether the driver ran successfully.
    iter_count : int
        Keep track of iterations for case recording.
    options : <OptionsDictionary>
        Dictionary with general pyoptsparse options.
    recording_options : <OptionsDictionary>
        Dictionary with driver recording options.
    cite : str
        Listing of relevant citations that should be referenced when
        publishing work that uses this class.
    _problem : <Problem>
        Pointer to the containing problem.
    supports : <OptionsDictionary>
        Provides a consistent way for drivers to declare what features they support.
    _designvars : dict
        Contains all design variable info.
    _cons : dict
        Contains all constraint info.
    _objs : dict
        Contains all objective info.
    _responses : dict
        Contains all response info.
    _rec_mgr : <RecordingManager>
        Object that manages all recorders added to this driver.
    _vars_to_record: dict
        Dict of lists of var names indicating what to record
    _model_viewer_data : dict
        Structure of model, used to make n2 diagram.
    _simul_coloring_info : tuple of dicts
        A data structure describing coloring for simultaneous derivs.
    _total_jac_sparsity : dict, str, or None
        Specifies sparsity of sub-jacobians of the total jacobian. Only used by pyOptSparseDriver.
    _res_jacs : dict
        Dict of sparse subjacobians for use with certain optimizers, e.g. pyOptSparseDriver.
    _total_jac : _TotalJacInfo or None
        Cached total jacobian handling object.
    """

    def __init__(self, **kwargs):
        """
        Initialize the driver.

        Parameters
        ----------
        **kwargs : dict of keyword arguments
            Keyword arguments that will be mapped into the Driver options.
        """
        self._rec_mgr = RecordingManager()
        self._vars_to_record = {
            'desvarnames': set(),
            'responsenames': set(),
            'objectivenames': set(),
            'constraintnames': set(),
            'sysinclnames': set(),
        }

        self._problem = None
        self._designvars = None
        self._cons = None
        self._objs = None
        self._responses = None

        # Driver options
        self.options = OptionsDictionary()

        self.options.declare('debug_print', types=list, check_valid=_check_debug_print_opts_valid,
                             desc="List of what type of Driver variables to print at each "
                                  "iteration. Valid items in list are 'desvars', 'ln_cons', "
                                  "'nl_cons', 'objs', 'totals'",
                             default=[])

        # Case recording options
        self.recording_options = OptionsDictionary()

        self.recording_options.declare('record_model_metadata', types=bool, default=True,
                                       desc='Record metadata for all Systems in the model')
        self.recording_options.declare('record_desvars', types=bool, default=True,
                                       desc='Set to True to record design variables at the '
                                            'driver level')
        self.recording_options.declare('record_responses', types=bool, default=False,
                                       desc='Set to True to record responses at the driver level')
        self.recording_options.declare('record_objectives', types=bool, default=True,
                                       desc='Set to True to record objectives at the driver level')
        self.recording_options.declare('record_constraints', types=bool, default=True,
                                       desc='Set to True to record constraints at the '
                                            'driver level')
        self.recording_options.declare('includes', types=list, default=[],
                                       desc='Patterns for variables to include in recording')
        self.recording_options.declare('excludes', types=list, default=[],
                                       desc='Patterns for vars to exclude in recording '
                                            '(processed post-includes)')
        self.recording_options.declare('record_derivatives', types=bool, default=False,
                                       desc='Set to True to record derivatives at the driver '
#.........这里部分代码省略.........
开发者ID:johnjasa,项目名称:OpenMDAO,代码行数:101,代码来源:driver.py


注:本文中的openmdao.recorders.recording_manager.RecordingManager类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。