Example #1
0
    def _mom(self, k, left, right, cache):
        """
        Statistical moments.

        Example:
            >>> numpy.around(chaospy.Uniform().mom([0, 1, 2, 3]), 4)
            array([1.    , 0.5   , 0.3333, 0.25  ])
            >>> numpy.around(chaospy.Power(chaospy.Uniform(), 2).mom([0, 1, 2, 3]), 4)
            array([1.    , 0.3333, 0.2   , 0.1429])
            >>> numpy.around(chaospy.Power(chaospy.Uniform(1, 2), -1).mom([0, 1, 2, 3]), 4)
            array([1.    , 0.6931, 0.5   , 0.375 ])
            >>> numpy.around(chaospy.Power(2, chaospy.Uniform()).mom([0, 1, 2, 3]), 4)
            array([1.    , 1.4427, 2.164 , 3.3663])
            >>> numpy.around(chaospy.Power(2, chaospy.Uniform(-1, 0)).mom([0, 1, 2, 3]), 4)
            array([1.    , 0.7213, 0.541 , 0.4208])

        """
        del cache
        if isinstance(right, Distribution):
            raise chaospy.UnsupportedFeature(
                "distribution as exponent not supported.")
        if numpy.any(right < 0):
            raise chaospy.UnsupportedFeature(
                "distribution to negative power not supported.")
        if not numpy.allclose(right, numpy.array(right, dtype=int)):
            raise chaospy.UnsupportedFeature(
                "distribution to fractional power not supported.")
        return left._get_mom(k * right)
Example #2
0
    def __init__(self, left, right, exclusion=None, repr_args=None):
        if not isinstance(left, Distribution):
            left = numpy.atleast_1d(left)
            if left.ndim > 1:
                raise chaospy.UnsupportedFeature(
                    "distribution operators limited to at-most 1D arrays.")
        if not isinstance(right, Distribution):
            right = numpy.atleast_1d(right)
            if right.ndim > 1:
                raise chaospy.UnsupportedFeature(
                    "distribution operators limited to at-most 1D arrays.")
        dependencies, parameters, rotation = chaospy.declare_dependencies(
            distribution=self,
            parameters=dict(left=left, right=right),
            is_operator=True,
        )

        super(OperatorDistribution, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            exclusion=exclusion,
            repr_args=repr_args,
        )
        self._cache_copy = {}
        self._lower_cache = {}
        self._upper_cache = {}
Example #3
0
 def get_mom_parameters(self):
     parameters = self.get_parameters(
         idx=None, cache={}, assert_numerical=False)
     if any([isinstance(value, Distribution) for value in parameters.values()]):
         raise chaospy.UnsupportedFeature(
             "operation not supported for %s with dependencies" % self)
     return parameters
Example #4
0
    def _mom(self, kloc, index):
        """
        Example:
            >>> d0 = chaospy.Uniform()
            >>> dist = chaospy.J(d0, d0+chaospy.Uniform())
            >>> dist.mom([1, 1]).round(4)
            0.5834
            >>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
            >>> dist.mom([[0, 0, 1], [0, 1, 1]]).round(4)
            array([1., 0., 0.])
        """
        output = 1.
        for idx1 in range(len(self._owners)):
            _, dist1 = self._owners[idx1]
            for idx2 in range(idx1 + 1, len(self._owners)):
                _, dist2 = self._owners[idx2]
                if chaospy.shares_dependencies(dist1, dist2):
                    raise chaospy.UnsupportedFeature(
                        "Shared dependencies across joint")

        kloc = kloc[self._rotation]
        for unique_idx in numpy.unique(index[self._rotation]):
            output *= self._owners[unique_idx][1]._get_mom(
                kloc[index == unique_idx])
        return output
Example #5
0
    def get_parameters(self, idx, cache, assert_numerical=True):
        """
        Get distribution parameters.

        Uses the cache to replace parameters that are distribution with cached
        values.

        Args:
            cache (Dict[Distribution, numpy.ndarray]):
                Collection of already calculated values.

        Returns:
            (Dict[str, numpy.ndarray]):
                Collection of parameters. Probability distributions are
                replaced with cached values.

        Raise:
            UnsupportedFeature:
                If a parameter is a probability distribution without cache, it
                means the dependency is unresolved.

        """
        parameters = super(SimpleDistribution, self).get_parameters(
            idx, cache, assert_numerical=assert_numerical)
        del parameters["cache"]
        del parameters["idx"]
        for key, value in parameters.items():
            if isinstance(value, Distribution):
                value = value._get_cache(idx, cache, get=0)
                if isinstance(value, Distribution) and assert_numerical:
                    raise chaospy.UnsupportedFeature(
                        "operation not supported for %s with dependencies" %
                        self)
                parameters[key] = value
        return parameters
Example #6
0
    def _mom(self, k, mean, sigma, cache):
        if isinstance(mean, chaospy.Distribution):
            mean = mean._get_cache(None, cache=cache, get=0)
            if isinstance(mean, chaospy.Distribution):
                raise chaospy.UnsupportedFeature(
                    "Analytical moment of a conditional not supported")
        out = 0.
        for idx, kdx in enumerate(numpy.ndindex(*[_+1 for _ in k])):
            coef = numpy.prod(special.comb(k.T, kdx).T, 0)
            diff = k.T-kdx
            pos = diff >= 0
            diff = diff*pos
            pos = numpy.all(pos)
            location_ = numpy.prod(mean**diff, -1)

            out = out+pos*coef*location_*isserlis_moment(tuple(kdx), sigma)

        return out
Example #7
0
 def _ttr(self, kloc, idx, dist, cache):
     """
     Example:
         >>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal(), chaospy.Exponential())
         >>> dist.ttr([[1, 2, 3], [1, 2, 3], [1, 2, 3]]).round(4)
         array([[[0.5   , 0.5   , 0.5   ],
                 [0.    , 0.    , 0.    ],
                 [3.    , 5.    , 7.    ]],
         <BLANKLINE>
                [[0.0833, 0.0667, 0.0643],
                 [1.    , 2.    , 3.    ],
                 [1.    , 4.    , 9.    ]]])
         >>> d0 = chaospy.Uniform()
         >>> dist = chaospy.J(d0, d0+chaospy.Uniform())
         >>> dist.ttr([1, 1])  # doctest: +IGNORE_EXCEPTION_DETAIL
         Traceback (most recent call last):
             ...
         chaospy.distributions.baseclass.UnsupportedFeature: Joint ...
     """
     if self.stochastic_dependent:
         raise chaospy.UnsupportedFeature(
             "Joint distribution with dependencies not supported.")
     return dist._get_ttr(kloc, idx)
Example #8
0
 def _pdf(self, xloc, idx, df, cache):
     raise chaospy.UnsupportedFeature("Copula not supported.")
Example #9
0
 def _ttr(self, kloc, **kwargs):
     """Default TTR generator, throws error."""
     raise chaospy.UnsupportedFeature(
         "%s: does not support analytical recurrence coefficients." % self)
Example #10
0
 def _mom(self, kloc, **kwargs):
     """Default moment generator, throws error."""
     raise chaospy.UnsupportedFeature(
         "%s: does not support analytical raw moments." % self)
Example #11
0
 def _ttr(self, kloc, idx, left, right, cache):
     raise chaospy.UnsupportedFeature(
         "%s: Analytical TTR for logarithm not supported", self)
Example #12
0
 def _mom(self, kloc, left, right, cache):
     raise chaospy.UnsupportedFeature(
         "%s: Analytical moments for logarithm not supported", self)
Example #13
0
 def _ttr(self, kloc, **kwargs):
     raise chaospy.UnsupportedFeature(
         "three terms recursion not supported for this distribution")
Example #14
0
    def __init__(self,
                 cdf,
                 pdf=None,
                 lower=None,
                 upper=None,
                 ppf=None,
                 mom=None,
                 ttr=None,
                 parameters=None):
        """
        Args:
            cdf (Callable[[numpy.ndarray, ...], numpy.ndarray]):
                Cumulative distribution function.
            pdf (Callable[[numpy.ndarray, ...], numpy.ndarray]):
                Probability density function.
            lower (Callable[[...], numpy.ndarray]):
                Lower boundary.
            upper (Callable[[...], numpy.ndarray]):
                Upper boundary.
            ppf (Callable[[numpy.ndarray, ...], numpy.ndarray]):
                Point percentile function.
            mom (Callable[[numpy.ndarray, ...], numpy.ndarray]):
                Raw moment generator.
            ttr (Callable[[numpy.ndarray, ...], numpy.ndarray]):
                Three terms recurrence coefficient generator.
            parameters (Dict[str, numpy.ndarray]):
                Parameters to pass to each of the distribution methods.

        """
        self._cdf = cdf
        repr_args = [str(cdf)]
        if ppf is None and (lower is None or upper is None):
            raise chaospy.UnsupportedFeature(
                "either ppf or lower+upper should be provided.")
        if pdf is not None:
            repr_args.append("pdf=%s" % pdf)
            self._pdf = pdf
        if lower is not None:
            repr_args.append("lower=%s" % lower)
            self._lower = lower
        if upper is not None:
            repr_args.append("upper=%s" % upper)
            self._upper = upper
        if ppf is not None:
            repr_args.append("ppf=%s" % ppf)
            self._ppf = ppf
        if mom is not None:
            repr_args.append("mom=%s" % mom)
            self._mom = mom
        if ttr is not None:
            repr_args.append("ttr=%s" % ttr)
            self._ttr = ttr

        parameters = parameters if parameters else {}
        if parameters:
            params = [("%s=%s" % (key, parameters[key]))
                      for key in sorted(parameters)]
            repr_args.append("parameters=dict(%s)" % ", ".join(params))

        super(UserDistribution, self).__init__(repr_args=repr_args,
                                               parameters=parameters)
Example #15
0
 def _mom(self, kloc, **kwargs):
     raise chaospy.UnsupportedFeature(
         "moments not supported for this distribution")
Example #16
0
 def _pdf(self, xloc, **kwargs):
     raise chaospy.UnsupportedFeature(
         "%s: does not support analytical pdf." % self)
Example #17
0
 def _upper(self, **kwargs):  # pragma: no cover
     """Backend upper bound."""
     raise chaospy.UnsupportedFeature("lower not supported")
Example #18
0
 def _ppf(self, qloc, idx, theta, cache):
     raise chaospy.UnsupportedFeature("Copula not supported.")
Example #19
0
 def _lower(self, **kwargs):
     """Backend lower bound."""
     raise chaospy.UnsupportedFeature("lower not supported")
 def not_implemented(*args, **kwargs):
     raise chaospy.UnsupportedFeature()
Example #21
0
 def _ttr(self, xloc, idx, dist, trans, cache):
     raise chaospy.UnsupportedFeature("Copula not supported.")