Exemplo n.º 1
0
    def add_discrete_output(self, name, val, desc='', tags=None):
        """
        Add an output variable to the component.

        Parameters
        ----------
        name : str
            Name of the variable in this component's namespace.
        val : float or list or tuple or ndarray
            The initial value of the variable being added in user-defined units. Default is 1.0.
        desc : str
            Description of the variable.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed when calling list_outputs.

        Returns
        -------
        dict
            Metadata for added variable.
        """
        if tags is None:
            tags = {'indep_var'}
        else:
            tags = make_set(tags, name='tags') | {'indep_var'}

        kwargs = {'desc': desc, 'tags': tags}
        return super().add_discrete_output(name, val, **kwargs)
Exemplo n.º 2
0
    def __init__(self, name=None, val=1.0, **kwargs):
        """
        Initialize all attributes.
        """
        super().__init__(**kwargs)

        if 'tags' not in kwargs:
            kwargs['tags'] = {'indep_var'}
        else:
            kwargs['tags'] = make_set(kwargs['tags'],
                                      name='tags') | {'indep_var'}

        # A single variable is declared during instantiation
        if isinstance(name, str):
            super().add_output(name, val, **kwargs)

        elif name is None:
            pass

        else:
            raise ValueError(
                "first argument to IndepVarComp init must be either of type "
                "`str` or an iterable of tuples of the form (name, value) or "
                "(name, value, keyword_dict).")

        for illegal in ('promotes', 'promotes_inputs', 'promotes_outputs'):
            if illegal in kwargs:
                raise ValueError("IndepVarComp init: '%s' is not supported "
                                 "in IndepVarComp." % illegal)

        self._no_check_partials = True
Exemplo n.º 3
0
    def add_output(self, name, val=1.0, shape=None, units=None, res_units=None, desc='',
                   lower=None, upper=None, ref=1.0, ref0=0.0, res_ref=None, tags=None):
        """
        Add an independent variable to this component.

        Parameters
        ----------
        name : str
            name of the variable in this component's namespace.
        val : float or list or tuple or ndarray
            The initial value of the variable being added in user-defined units. Default is 1.0.
        shape : int or tuple or list or None
            Shape of this variable, only required if val is not an array.
            Default is None.
        units : str or None
            Units in which the output variables will be provided to the component during execution.
            Default is None, which means it has no units.
        res_units : str or None
            Units in which the residuals of this output will be given to the user when requested.
            Default is None, which means it has no units.
        desc : str
            description of the variable
        lower : float or list or tuple or ndarray or None
            lower bound(s) in user-defined units. It can be (1) a float, (2) an array_like
            consistent with the shape arg (if given), or (3) an array_like matching the shape of
            val, if val is array_like. A value of None means this output has no lower bound.
            Default is None.
        upper : float or list or tuple or ndarray or None
            upper bound(s) in user-defined units. It can be (1) a float, (2) an array_like
            consistent with the shape arg (if given), or (3) an array_like matching the shape of
            val, if val is array_like. A value of None means this output has no upper bound.
            Default is None.
        ref : float
            Scaling parameter. The value in the user-defined units of this output variable when
            the scaled value is 1. Default is 1.
        ref0 : float
            Scaling parameter. The value in the user-defined units of this output variable when
            the scaled value is 0. Default is 0.
        res_ref : float
            Scaling parameter. The value in the user-defined res_units of this output's residual
            when the scaled value is 1. Default is None, which means residual scaling matches
            output scaling.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed when calling
            list_outputs.
        """
        if res_ref is None:
            res_ref = ref

        if tags is None:
            tags = {'indep_var'}
        else:
            tags = make_set(tags) | {'indep_var'}

        kwargs = {'shape': shape, 'units': units, 'res_units': res_units, 'desc': desc,
                  'lower': lower, 'upper': upper, 'ref': ref, 'ref0': ref0,
                  'res_ref': res_ref, 'tags': tags
                  }
        super(IndepVarComp, self).add_output(name, val, **kwargs)
Exemplo n.º 4
0
    def __init__(self, name=None, val=1.0, **kwargs):
        """
        Initialize all attributes.

        Parameters
        ----------
        name : str or None
            name of the variable.
            If None, variables should be defined external to this class by calling add_output.
        val : float or ndarray
            value of the variable if a single variable is being defined.
        **kwargs : dict
            keyword arguments.
        """
        super(IndepVarComp, self).__init__()
        self._indep = []
        self._indep_external = []
        self._indep_external_discrete = []

        if 'tags' not in kwargs:
            kwargs['tags'] = {'indep_var'}
        else:
            kwargs['tags'] = make_set(kwargs['tags'],
                                      name='tags') | {'indep_var'}

        # A single variable is declared during instantiation
        if isinstance(name, str):
            self._indep.append((name, val, kwargs))

        elif name is None:
            pass

        else:
            raise ValueError(
                "first argument to IndepVarComp init must be either of type "
                "`str` or an iterable of tuples of the form (name, value) or "
                "(name, value, keyword_dict).")

        for illegal in ('promotes', 'promotes_inputs', 'promotes_outputs'):
            if illegal in kwargs:
                raise ValueError("IndepVarComp init: '%s' is not supported "
                                 "in IndepVarComp." % illegal)
Exemplo n.º 5
0
    def list_outputs(self,
                     explicit=True,
                     implicit=True,
                     values=True,
                     prom_name=False,
                     residuals=False,
                     residuals_tol=None,
                     units=False,
                     shape=False,
                     bounds=False,
                     scaling=False,
                     desc=False,
                     hierarchical=True,
                     print_arrays=False,
                     tags=None,
                     includes=None,
                     excludes=None,
                     list_autoivcs=False,
                     out_stream=_DEFAULT_OUT_STREAM):
        """
        Return and optionally log a list of output names and other optional information.

        Parameters
        ----------
        explicit : bool, optional
            include outputs from explicit components. Default is True.
        implicit : bool, optional
            include outputs from implicit components. Default is True.
        values : bool, optional
            When True, display/return output values. Default is True.
        prom_name : bool, optional
            When True, display/return the promoted name of the variable.
            Default is False.
        residuals : bool, optional
            When True, display/return residual values. Default is False.
        residuals_tol : float, optional
            If set, limits the output of list_outputs to only variables where
            the norm of the resids array is greater than the given 'residuals_tol'.
            Default is None.
        units : bool, optional
            When True, display/return units. Default is False.
        shape : bool, optional
            When True, display/return the shape of the value. Default is False.
        bounds : bool, optional
            When True, display/return bounds (lower and upper). Default is False.
        scaling : bool, optional
            When True, display/return scaling (ref, ref0, and res_ref). Default is False.
        desc : bool, optional
            When True, display/return description. Default is False.
        hierarchical : bool, optional
            When True, human readable output shows variables in hierarchical format.
        print_arrays : bool, optional
            When False, in the columnar display, just display norm of any ndarrays with size > 1.
            The norm is surrounded by vertical bars to indicate that it is a norm.
            When True, also display full values of the ndarray below the row. Format  is affected
            by the values set with numpy.set_printoptions
            Default is False.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed. Only outputs with the
            given tags will be listed.
            Default is None, which means there will be no filtering based on tags.
        includes : iter of str or None
            Glob patterns for pathnames to include in the check. Default is None, which
            includes all.
        excludes : iter of str or None
            Glob patterns for pathnames to exclude from the check. Default is None, which
            excludes nothing.
        list_autoivcs : bool
            If True, include auto_ivc outputs in the listing.  Defaults to False.
        out_stream : file-like
            Where to send human readable output. Default is sys.stdout.
            Set to None to suppress.

        Returns
        -------
        list
            list of output names and other optional information about those outputs
        """
        meta = self._abs2meta
        expl_outputs = []
        impl_outputs = []

        for var_name in self.outputs.absolute_names():
            if not list_autoivcs and var_name.startswith('_auto_ivc.'):
                continue

            # Filter based on tags
            if tags and not (make_set(tags)
                             & make_set(meta[var_name]['tags'])):
                continue

            var_name_prom = self._abs2prom['output'][var_name]

            if not match_prom_or_abs(var_name, var_name_prom, includes,
                                     excludes):
                continue

            # check if residuals were recorded, skip if within specifed tolerance
            if residuals and self.residuals and var_name in self.residuals.absolute_names(
            ):
                resids = self.residuals[var_name]
                if residuals_tol and np.linalg.norm(resids) < residuals_tol:
                    continue
            else:
                resids = 'Not Recorded'

            val = self.outputs[var_name]

            var_meta = {}
            if values:
                var_meta['value'] = val
            if prom_name:
                var_meta['prom_name'] = var_name_prom
            if residuals:
                var_meta['resids'] = resids
            if units:
                var_meta['units'] = meta[var_name]['units']
            if shape:
                var_meta['shape'] = val.shape
            if bounds:
                var_meta['lower'] = meta[var_name]['lower']
                var_meta['upper'] = meta[var_name]['upper']
            if scaling:
                var_meta['ref'] = meta[var_name]['ref']
                var_meta['ref0'] = meta[var_name]['ref0']
                var_meta['res_ref'] = meta[var_name]['res_ref']
            if desc:
                var_meta['desc'] = meta[var_name]['desc']
            if meta[var_name]['explicit']:
                expl_outputs.append((var_name, var_meta))
            else:
                impl_outputs.append((var_name, var_meta))

        if out_stream:
            if not self.outputs:
                ostream = sys.stdout if out_stream is _DEFAULT_OUT_STREAM else out_stream
                ostream.write(
                    'WARNING: Outputs not recorded. Make sure your recording '
                    + 'settings have record_outputs set to True\n')
            if explicit:
                self._write_table('explicit', expl_outputs, hierarchical,
                                  print_arrays, out_stream)
            if implicit:
                self._write_table('implicit', impl_outputs, hierarchical,
                                  print_arrays, out_stream)

        if explicit and implicit:
            return expl_outputs + impl_outputs
        elif explicit:
            return expl_outputs
        elif implicit:
            return impl_outputs
        else:
            raise RuntimeError(
                'You have excluded both Explicit and Implicit components.')
Exemplo n.º 6
0
    def list_inputs(self,
                    values=True,
                    prom_name=False,
                    units=False,
                    shape=False,
                    desc=False,
                    hierarchical=True,
                    print_arrays=False,
                    tags=None,
                    includes=None,
                    excludes=None,
                    out_stream=_DEFAULT_OUT_STREAM):
        """
        Return and optionally log a list of input names and other optional information.

        Parameters
        ----------
        values : bool, optional
            When True, display/return input values. Default is True.
        prom_name : bool, optional
            When True, display/return the promoted name of the variable.
            Default is False.
        units : bool, optional
            When True, display/return units. Default is False.
        shape : bool, optional
            When True, display/return the shape of the value. Default is False.
        desc : bool, optional
            When True, display/return description. Default is False.
        hierarchical : bool, optional
            When True, human readable output shows variables in hierarchical format.
        print_arrays : bool, optional
            When False, in the columnar display, just display norm of any ndarrays with size > 1.
            The norm is surrounded by vertical bars to indicate that it is a norm.
            When True, also display full values of the ndarray below the row. Format is affected
            by the values set with numpy.set_printoptions
            Default is False.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed. Only inputs with the
            given tags will be listed.
            Default is None, which means there will be no filtering based on tags.
        includes : iter of str or None
            Glob patterns for pathnames to include in the check. Default is None, which
            includes all.
        excludes : iter of str or None
            Glob patterns for pathnames to exclude from the check. Default is None, which
            excludes nothing.
        out_stream : file-like object
            Where to send human readable output. Default is sys.stdout.
            Set to None to suppress.

        Returns
        -------
        list
            list of input names and other optional information about those inputs
        """
        meta = self._abs2meta
        inputs = []

        if self.inputs is not None:
            for var_name in self.inputs.absolute_names():
                # Filter based on tags
                if tags and not (make_set(tags)
                                 & make_set(meta[var_name]['tags'])):
                    continue

                var_name_prom = self._abs2prom['input'][var_name]

                if not match_prom_or_abs(var_name, var_name_prom, includes,
                                         excludes):
                    continue

                val = self.inputs[var_name]

                var_meta = {}
                if values:
                    var_meta['value'] = val
                if prom_name:
                    var_meta['prom_name'] = var_name_prom
                if units:
                    var_meta['units'] = meta[var_name]['units']
                if shape:
                    var_meta['shape'] = val.shape
                if desc:
                    var_meta['desc'] = meta[var_name]['desc']

                inputs.append((var_name, var_meta))

        if out_stream:
            if self.inputs:
                self._write_table('input', inputs, hierarchical, print_arrays,
                                  out_stream)
            else:
                ostream = sys.stdout if out_stream is _DEFAULT_OUT_STREAM else out_stream
                ostream.write(
                    'WARNING: Inputs not recorded. Make sure your recording ' +
                    'settings have record_inputs set to True\n')

        return inputs
Exemplo n.º 7
0
    def add_output(self,
                   name,
                   val=1.0,
                   shape=None,
                   units=None,
                   res_units=None,
                   desc='',
                   lower=None,
                   upper=None,
                   ref=None,
                   ref0=None,
                   res_ref=None,
                   tags=None,
                   shape_by_conn=False,
                   copy_shape=None):
        """
        Add an independent variable to this component.

        Parameters
        ----------
        name : str
            name of the variable in this component's namespace.
        val : float or list or tuple or ndarray
            The initial value of the variable being added in user-defined units. Default is 1.0.
        shape : int or tuple or list or None
            Shape of this variable, only required if val is not an array.
            Default is None.
        units : str or None
            Units in which the output variables will be provided to the component during execution.
            Default is None, which means it has no units.
        res_units : None
            This argument is deprecated because it was unused.
        desc : str
            description of the variable
        lower : None
            This argument is deprecated because it was unused.
        upper : None
            This argument is deprecated because it was unused.
        ref : None
            This argument is deprecated because it was unused.
        ref0 : None
            This argument is deprecated because it was unused.
        res_ref : None
            This argument is deprecated because it was unused.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed when calling
            list_outputs.
        shape_by_conn : bool
            If True, shape this output to match its connected input(s).
        copy_shape : str or None
            If a str, that str is the name of a variable. Shape this output to match that of
            the named variable.
        """
        if res_units is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'res_units' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")
        if lower is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'lower' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")
        if upper is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'upper' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")
        if ref0 is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'ref0' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")
        if res_ref is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'res_ref' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")
        if ref is not None:
            warn_deprecation(
                f"{self.msginfo}: The 'ref' argument was used when adding "
                f"output '{name}'. This argument has been deprecated and will be "
                "removed in a future version.")

        ref = 1.0
        ref0 = 0.0

        if res_ref is None:
            res_ref = ref

        if tags is None:
            tags = {'indep_var'}
        else:
            tags = make_set(tags) | {'indep_var'}

        kwargs = {
            'shape': shape,
            'units': units,
            'res_units': res_units,
            'desc': desc,
            'lower': lower,
            'upper': upper,
            'ref': ref,
            'ref0': ref0,
            'res_ref': res_ref,
            'tags': tags,
            'shape_by_conn': shape_by_conn,
            'copy_shape': copy_shape,
        }
        super().add_output(name, val, **kwargs)
Exemplo n.º 8
0
    def __init__(self, name=None, val=1.0, **kwargs):
        """
        Initialize all attributes.

        Parameters
        ----------
        name : str or None or [(str, value), ...] or [(str, value, kwargs), ...]
            name of the variable.
            If None, variables should be defined external to this class by calling add_output.
            For backwards compatibility with OpenMDAO v1, this can also be a list of tuples
            in the case of declaring multiple variables at once.
        val : float or ndarray
            value of the variable if a single variable is being defined.
        **kwargs : dict
            keyword arguments.
        """
        super(IndepVarComp, self).__init__()
        self._indep = []
        self._indep_external = []
        self._indep_external_discrete = []

        if 'tags' not in kwargs:
            kwargs['tags'] = {'indep_var'}
        else:
            kwargs['tags'] = make_set(kwargs['tags'],
                                      name='tags') | {'indep_var'}

        # A single variable is declared during instantiation
        if isinstance(name, string_types):
            self._indep.append((name, val, kwargs))
        # Mutiple variables are declared during instantiation (deprecated)
        elif isinstance(name, collections.Iterable):
            warn_deprecation(
                'Declaring multiple variables in this way is deprecated. '
                'In OpenMDAO 2.x or later, multiple variables should be declared '
                'as separate add_output calls.')

            # Loop through each variable (i.e., each tuple)
            for tup in name:
                # If valid tuple, assign to (name, val, kwargs); otherwise, raise an exception
                if isinstance(tup, tuple) and len(tup) == 3:
                    name_, val, kwargs = tup
                elif isinstance(tup, tuple) and len(tup) == 2:
                    name_, val = tup
                    kwargs = {}
                else:
                    raise ValueError(
                        "IndepVarComp init: arg %s must be a tuple of the "
                        "form (name, value) or (name, value, keyword_dict)." %
                        str(tup))
                self._indep.append((name_, val, kwargs))
        elif name is None:
            pass
        else:
            raise ValueError(
                "first argument to IndepVarComp init must be either of type "
                "`str` or an iterable of tuples of the form (name, value) or "
                "(name, value, keyword_dict).")

        for illegal in ('promotes', 'promotes_inputs', 'promotes_outputs'):
            if illegal in kwargs:
                raise ValueError("IndepVarComp init: '%s' is not supported "
                                 "in IndepVarComp." % illegal)
Exemplo n.º 9
0
    def add_output(self,
                   name,
                   val=1.0,
                   shape=None,
                   units=None,
                   res_units=None,
                   desc='',
                   lower=None,
                   upper=None,
                   ref=None,
                   ref0=None,
                   res_ref=None,
                   tags=None):
        """
        Add an independent variable to this component.

        Parameters
        ----------
        name : str
            name of the variable in this component's namespace.
        val : float or list or tuple or ndarray
            The initial value of the variable being added in user-defined units. Default is 1.0.
        shape : int or tuple or list or None
            Shape of this variable, only required if val is not an array.
            Default is None.
        units : str or None
            Units in which the output variables will be provided to the component during execution.
            Default is None, which means it has no units.
        res_units : None
            This argument is deprecated because it was unused.
        desc : str
            description of the variable
        lower : None
            This argument is deprecated because it was unused.
        upper : None
            This argument is deprecated because it was unused.
        ref : None
            This argument is deprecated because it was unused.
        ref0 : None
            This argument is deprecated because it was unused.
        res_ref : None
            This argument is deprecated because it was unused.
        tags : str or list of strs
            User defined tags that can be used to filter what gets listed when calling
            list_outputs.
        """
        if res_units is not None:
            warn_deprecation(
                "'res_units' has been deprecated and will be removed in a future version"
            )
        elif lower is not None:
            warn_deprecation(
                "'lower' has been deprecated and will be removed in a future version"
            )
        elif upper is not None:
            warn_deprecation(
                "'upper' has been deprecated and will be removed in a future version"
            )
        elif ref0 is not None:
            warn_deprecation(
                "'ref0' has been deprecated and will be removed in a future version"
            )
        elif res_ref is not None:
            warn_deprecation(
                "'res_ref' has been deprecated and will be removed in a future version"
            )
        elif ref is not None:
            warn_deprecation(
                "'ref' has been deprecated and will be removed in a future version"
            )

        ref = 1.0
        ref0 = 0.0

        if res_ref is None:
            res_ref = ref

        if tags is None:
            tags = {'indep_var'}
        else:
            tags = make_set(tags) | {'indep_var'}

        kwargs = {
            'shape': shape,
            'units': units,
            'res_units': res_units,
            'desc': desc,
            'lower': lower,
            'upper': upper,
            'ref': ref,
            'ref0': ref0,
            'res_ref': res_ref,
            'tags': tags
        }
        super(IndepVarComp, self).add_output(name, val, **kwargs)