Exemple #1
0
    def update_ma_coefs(self):
        """Determine the MA coefficients.

        The number of MA coefficients is subsequently increased until the
        required precision :attr:`~ARMA.max_dev_coefs` is reached.  Otherwise,
        a :class:`~exceptions.RuntimeError` is raised.
        """
        self.ma_coefs = []
        for ma_order in range(1, self.ma.order+1):
            self.calc_next_ma_coef(ma_order, self.ma)
            if self.dev_coefs < self.max_dev_coefs:
                self.norm_coefs()
                break
        else:
            raise RuntimeError(
                'Method `update_ma_coefs` is not able to determine the MA '
                'coefficients of the ARMA model with the desired accuracy.  '
                'You can set the tolerance value ´max_dev_coefs` to a '
                'higher value.  An accuracy of `%s` has been reached using '
                '`%d` MA coefficients.'
                % (objecttools.repr_(self.dev_coefs, 12), ma_order))
        if numpy.min(self.response) < 0.:
            warnings.warn(
                'Note that the smallest response to a standard impulse of the '
                'determined ARMA model is negative (`%s`).'
                % objecttools.repr_(numpy.min(self.response)))
Exemple #2
0
 def raw_body_strings(self):
     """All raw strings for the tables body."""
     strings = []
     for (idx, first_string) in enumerate(self.raw_first_col_strings):
         strings.append([first_string])
         for parseq in self.parseqs:
             array = self.get_output_array(parseq)
             if parseq.NDIM == 0:
                 strings[-1].append(objecttools.repr_(array[idx]))
             elif parseq.NDIM == 1:
                 if parseq.shape[0] > 0:
                     strings[-1].extend(
                         objecttools.repr_(value) for value in array[idx])
                 else:
                     strings[-1].append('empty')
             else:
                 thing = ('sequence' if isinstance(
                     parseq, abctools.SequenceABC) else 'parameter')
                 raise RuntimeError(
                     'An instance of class `Test` of module `testtools` '
                     'is requested to print the results of %s `%s`. '
                     'Unfortunately, for %d-dimensional sequences this '
                     'feature is not supported yet.' %
                     (thing, parseq.name, parseq.NDIM))
     return strings
Exemple #3
0
 def _print_results(self):
     strings = [['date'] + [
         seq.subseqs.node.name if seq.name == 'sim' else seq.name
         for seq in self.seqs
     ]]
     lengths = numpy.zeros((len(pub.timegrids.sim) + 1, len(self.seqs) + 1),
                           dtype=int)
     lengths[0, :] = [len(string) for string in strings[0]]
     for (idx, date) in enumerate(pub.timegrids.sim):
         strings.append([date.datetime.strftime(self.dateformat)])
         for seq in self.seqs:
             if seq.NDIM == 0:
                 strings[-1].append(objecttools.repr_(seq.series[idx]))
             elif seq.NDIM == 1 and seq.shape == (1, ):
                 strings[-1].append(objecttools.repr_(seq.series[idx, 0]))
             else:
                 raise RuntimeError(
                     'An instance of class `Test` of module `testtools` '
                     'is requested to print the results of sequence `%s`. '
                     'Unfortunately, for %d-dimensional sequences with '
                     'shape `%s` this feature is not supported yet.' %
                     (seq.name, seq.NDIM, seq.shape))
         lengths[idx + 1, :] = [len(string) for string in strings[-1]]
     maxlengths = numpy.max(lengths, axis=0)
     for (idx, linestrings) in enumerate(strings):
         print(
             '|', ' | '.join(
                 string.rjust(maxlengths[jdx])
                 for (jdx, string) in enumerate(linestrings)), '|')
         if idx == 0:
             print('-' * (numpy.sum(maxlengths) + 3 * (len(self.seqs)) + 4))
Exemple #4
0
 def raw_body_strings(self):
     """All raw strings for the tables body."""
     strings = []
     for (idx, first_string) in enumerate(self.raw_first_col_strings):
         strings.append([first_string])
         for parseq in self.parseqs:
             array = self.get_output_array(parseq)
             if parseq.NDIM == 0:
                 strings[-1].append(objecttools.repr_(array[idx]))
             else:
                 strings[-1].extend(
                     objecttools.repr_(value) for value in array[idx])
     return strings
Exemple #5
0
 def __call__(self, *args, **kwargs):
     """The prefered way to pass values to |TInd| instances
     within parameter control files.
     """
     try:
         super().__call__(*args, **kwargs)
     except NotImplementedError:
         try:
             tal = float(kwargs['tal'])
             hot = float(kwargs['hot'])
             hut = float(kwargs['hut'])
         except KeyError:
             raise ValueError(
                 'For the alternative calculation of parameter `tind`, '
                 'values for all three keyword keyword arguments `tal`, '
                 '`hot`, and `hut` must be given.')
         if (tal <= 0.) or (hot <= hut):
             raise ValueError(
                 'For the alternative calculation of parameter '
                 '`tind`, the value assigned to keyword argument '
                 '`tal` must be greater then zero and the one of '
                 '`hot` must be greater than the one of `hut`.  '
                 'However, for element %s, the values `%s`, `%s` '
                 'and `%s` were given respectively.' %
                 (objecttools.devicename(self), tal, hot, hut))
         self.value = (.868 * tal**3 / (hot - hut))**.385
         if (self > 1000.) or (self < .001):
             warnings.warn(
                 'Due to the given values for the keyword arguments '
                 '`tal` (%s), `hot` (%s) and `hut` (%s), parameter '
                 '`tind` of element `%s` has been set to an '
                 'unrealistic value of `%s hours`.' %
                 (tal, hot, hut, objecttools.devicename(self),
                  objecttools.repr_(self.value)))
         self.value *= timetools.Period('1h') / self.simulationstep
Exemple #6
0
    def update_ma_coefs(self):
        """Determine the MA coefficients.

        The number of MA coefficients is subsequently increased until the
        required precision |ARMA.max_dev_coefs| is reached.  Otherwise,
        a |RuntimeError| is raised.
        """
        self.ma_coefs = []
        for ma_order in range(1, self.ma.order + 1):
            self.calc_next_ma_coef(ma_order, self.ma)
            if self.dev_coefs < self.max_dev_coefs:
                self.norm_coefs()
                break
        else:
            with hydpy.pub.options.reprdigits(12):
                raise RuntimeError(
                    f"Method `update_ma_coefs` is not able to determine the "
                    f"MA coefficients of the ARMA model with the desired "
                    f"accuracy.  You can set the tolerance value "
                    f"´max_dev_coefs` to a higher value.  An accuracy of "
                    f"`{objecttools.repr_(self.dev_coefs)}` has been reached "
                    f"using `{self.ma.order}` MA coefficients.")
        if numpy.min(self.response) < 0.0:
            warnings.warn(
                "Note that the smallest response to a standard impulse of the "
                "determined ARMA model is negative (`%s`)." %
                objecttools.repr_(numpy.min(self.response)))
Exemple #7
0
    def yield_name2value(self,
                         idx1=None,
                         idx2=None) -> Iterator[Tuple[str, str]]:
        """Sequentially return name-value-pairs describing the current state
        of the target variables.

        The names are automatically generated and contain both the name of
        the |Device| of the respective |Variable| object and the target
        description:

        >>> from hydpy.examples import prepare_full_example_2
        >>> hp, pub, TestIO = prepare_full_example_2()
        >>> from hydpy.core.itemtools import SetItem
        >>> item = GetItem("hland_v1", "states.lz")
        >>> item.collect_variables(pub.selections)
        >>> hp.elements.land_dill.model.sequences.states.lz = 100.0
        >>> for name, value in item.yield_name2value():
        ...     print(name, value)
        land_dill_states_lz 100.0
        land_lahn_1_states_lz 8.18711
        land_lahn_2_states_lz 10.14007
        land_lahn_3_states_lz 7.52648
        >>> item = GetItem("hland_v1", "states.sm")
        >>> item.collect_variables(pub.selections)
        >>> hp.elements.land_dill.model.sequences.states.sm = 2.0
        >>> for name, value in item.yield_name2value():
        ...     print(name, value)    # doctest: +ELLIPSIS
        land_dill_states_sm [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, \
2.0, 2.0, 2.0, 2.0]
        land_lahn_1_states_sm [99.27505, ..., 142.84148]
        ...

        When querying time series, one can restrict the span of interest
        by passing index values:

        >>> item = GetItem("nodes", "sim.series")
        >>> item.collect_variables(pub.selections)
        >>> hp.nodes.dill.sequences.sim.series = 1.0, 2.0, 3.0, 4.0
        >>> for name, value in item.yield_name2value():
        ...     print(name, value)    # doctest: +ELLIPSIS
        dill_sim_series [1.0, 2.0, 3.0, 4.0]
        lahn_1_sim_series [nan, ...
        ...
        >>> for name, value in item.yield_name2value(2, 3):
        ...     print(name, value)    # doctest: +ELLIPSIS
        dill_sim_series [3.0]
        lahn_1_sim_series [nan]
        ...
        """
        for device, name in self._device2name.items():
            target = self.device2target[device]
            if self.targetspecs.series:
                values = target.series[idx1:idx2]
            else:
                values = target.values
            if self.ndim == 0:
                values = objecttools.repr_(float(values))
            else:
                values = objecttools.repr_list(values.tolist())
            yield name, values
Exemple #8
0
 def __repr__(self) -> str:
     parts = [type(self).__name__, "("]
     for (name, primpar) in sorted(self._PRIMARY_PARAMETERS.items()):
         value = primpar.__get__(self)
         if value is not None:
             parts.extend([name, "=", objecttools.repr_(value), ", "])
     if parts[-1] == ", ":
         parts[-1] = ")"
     else:
         parts.append(")")
     return "".join(parts)
Exemple #9
0
 def __repr__(self):
     parts = [objecttools.classname(self), '(']
     for (name, primpar) in sorted(self._primary_parameters.items()):
         value = primpar.__get__(self)
         if value is not None:
             parts.extend([name, '=', objecttools.repr_(value), ', '])
     if parts[-1] == ', ':
         parts[-1] = ')'
     else:
         parts.append(')')
     return ''.join(parts)
Exemple #10
0
 def repr_(self, values, islong):
     prefix = '%s(' % self.name
     if self.NDIM == 0:
         string = '%s(%s)' % (self.name, objecttools.repr_(values))
     elif self.NDIM == 1:
         if islong:
             string = objecttools.assignrepr_list(values, prefix, 75) + ')'
         else:
             string = objecttools.assignrepr_values(
                 values, prefix, 75) + ')'
     elif self.NDIM == 2:
         string = objecttools.assignrepr_list2(values, prefix, 75) + ')'
     else:
         raise NotImplementedError(
             '`repr` does not yet support parameters or sequences like `%s`'
             'of element `%s` which handle %d-dimensional matrices.'
             % self.NDIM)
     return '\n'.join(self.commentrepr() + [string])
Exemple #11
0
    def update_ar_coefs(self):
        """Determine the AR coefficients.

        The number of AR coefficients is subsequently increased until the
        required precision :attr:`~ARMA.max_rel_rmse` is reached.  Otherwise,
        a :class:`~exceptions.RuntimeError` is raised.
        """
        del self.ar_coefs
        for ar_order in range(1, self.effective_max_ar_order+1):
            self.calc_all_ar_coefs(ar_order, self.ma)
            if self.rel_rmse < self.max_rel_rmse:
                break
        else:
            raise RuntimeError(
                'Method `update_ar_coefs` is not able to determine the AR '
                'coefficients of the ARMA model with the desired accuracy.  '
                'You can either set the tolerance value `max_rel_rmse` to '
                'a higher value or increase the allowed `max_ar_order`.  '
                'An accuracy of `%s` has been reached using `%d` coefficients.'
                % (objecttools.repr_(self.rel_rmse, 12), ar_order))
Exemple #12
0
    def update_ar_coefs(self):
        """Determine the AR coefficients.

        The number of AR coefficients is subsequently increased until the
        required precision |ARMA.max_rel_rmse| is reached.  Otherwise,
        a |RuntimeError| is raised.
        """
        del self.ar_coefs
        for ar_order in range(1, self.effective_max_ar_order + 1):
            self.calc_all_ar_coefs(ar_order, self.ma)
            if self._rel_rmse < self.max_rel_rmse:
                break
        else:
            with pub.options.reprdigits(12):
                raise RuntimeError(
                    'Method `update_ar_coefs` is not able to determine '
                    'the AR coefficients of the ARMA model with the desired '
                    'accuracy.  You can either set the tolerance value '
                    '`max_rel_rmse` to a higher value or increase the '
                    'allowed `max_ar_order`.  An accuracy of `%s` has been '
                    'reached using `%d` coefficients.' %
                    (objecttools.repr_(self._rel_rmse), ar_order))