Beispiel #1
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 = {}
Beispiel #2
0
    def __init__(self, df, covariance, rotation=None):
        assert isinstance(df, float)
        covariance = numpy.asarray(covariance)
        assert covariance.ndim == 2, "Covariance must be a matrix"
        assert covariance.shape[0] == covariance.shape[1], (
            "Parameters 'covariance' not a square matrix.")

        dependencies, _, rotation = chaospy.declare_dependencies(
            self,
            parameters=dict(covariance=covariance),
            rotation=rotation,
            dependency_type="accumulate",
        )
        correlation = covariance / numpy.sqrt(
            numpy.outer(numpy.diag(covariance), numpy.diag(covariance)))
        self._permute = numpy.eye(len(rotation), dtype=int)[rotation]
        self._correlation = self._permute.dot(correlation).dot(self._permute.T)
        cholesky = numpy.linalg.cholesky(self._correlation)
        self._fwd_transform = self._permute.T.dot(numpy.linalg.inv(cholesky))
        self._inv_transform = self._permute.T.dot(cholesky)

        super(t_copula, self).__init__(
            parameters=dict(df=df),
            dependencies=dependencies,
            rotation=rotation,
            repr_args=[covariance.tolist()],
        )
Beispiel #3
0
    def __init__(
        self,
        mu,
        sigma,
        rotation=None,
    ):
        repr_args = [mu, sigma]
        dependencies, parameters, rotation = chaospy.declare_dependencies(
            self,
            parameters=dict(mu=mu, sigma=sigma),
            rotation=rotation,
            dependency_type="accumulate",
        )

        sigma = parameters["sigma"]
        assert sigma.ndim == 2, "Covariance must either be scalar, vector or matrix"

        self._permute = numpy.eye(len(rotation), dtype=int)[rotation]
        self._psigma = self._permute.dot(sigma).dot(self._permute.T)
        cholesky = numpy.linalg.cholesky(self._psigma)
        self._fwd_transform = self._permute.T.dot(numpy.linalg.inv(cholesky))
        self._inv_transform = self._permute.T.dot(cholesky)

        super(MvLogNormal, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            rotation=rotation,
            repr_args=repr_args,
        )
Beispiel #4
0
 def __init__(
     self,
     dist,
     shift=0,
     scale=1,
     rotation=None,
     repr_args=None,
 ):
     assert isinstance(dist,
                       Distribution), "'dist' should be a distribution"
     if repr_args is None:
         repr_args = dist._repr_args[:]
     repr_args += chaospy.format_repr_kwargs(scale=(scale, 1))
     repr_args += chaospy.format_repr_kwargs(shift=(shift, 0))
     length = len(dist) if len(dist) > 1 else None
     dependencies, parameters, rotation = chaospy.declare_dependencies(
         distribution=self,
         parameters=dict(shift=shift, scale=scale),
         rotation=rotation,
         is_operator=True,
         length=length,
         extra_parameters=dict(dist=dist),
     )
     super(ShiftScaleDistribution, self).__init__(
         parameters=parameters,
         rotation=rotation,
         dependencies=dependencies,
         repr_args=repr_args,
     )
     self._dist = dist
     permute = numpy.zeros((len(self._rotation), len(self._rotation)),
                           dtype=int)
     permute[numpy.arange(len(self._rotation), dtype=int),
             self._rotation] = 1
     self._permute = permute
Beispiel #5
0
    def __init__(
        self,
        dist,
        lower=0.0,
        upper=1.0,
        rotation=None,
        repr_args=None,
    ):
        assert isinstance(dist,
                          Distribution), "'dist' should be a distribution"
        assert len(dist) == 1
        if repr_args is None:
            repr_args = dist._repr_args[:]
        repr_args += chaospy.format_repr_kwargs(lower=(lower, 0),
                                                upper=(upper, 1))

        dependencies, parameters, rotation, = chaospy.declare_dependencies(
            distribution=self,
            parameters=dict(lower=lower, upper=upper),
            is_operator=True,
            rotation=rotation,
            extra_parameters=dict(dist=dist),
        )
        assert len(dependencies) == 1
        assert len(parameters["lower"]) == 1
        assert len(parameters["upper"]) == 1
        super(LowerUpperDistribution, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            rotation=rotation,
            repr_args=repr_args,
        )
        self._dist = dist
Beispiel #6
0
    def __init__(
        self,
        dist,
        lower=0.,
        upper=1.,
        rotation=None,
        repr_args=None,
    ):
        assert isinstance(dist,
                          Distribution), "'dist' should be a distribution"
        if repr_args is None:
            repr_args = dist._repr_args[:]
        repr_args += chaospy.format_repr_kwargs(lower=(lower, 0),
                                                upper=(upper, 1))

        dependencies, parameters, rotation, = chaospy.declare_dependencies(
            distribution=self,
            parameters=dict(lower=lower, upper=upper),
            rotation=rotation,
        )
        super(LowerUpperDistribution, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            repr_args=repr_args,
        )
        self._dist = dist
Beispiel #7
0
    def __init__(self, dist, lower=None, upper=None):
        """
        Constructor.

        Args:
            dist (Distribution):
                Distribution to be truncated.
            lower (Distribution, numpy.ndarray):
                Lower truncation bound.
            upper (Distribution, numpy.ndarray):
                Upper truncation bound.
        """
        assert isinstance(dist, Distribution)
        repr_args = [dist]
        repr_args += chaospy.format_repr_kwargs(lower=(lower, None))
        repr_args += chaospy.format_repr_kwargs(upper=(upper, None))
        exclusion = set()
        for deps in dist._dependencies:
            exclusion.update(deps)
        if isinstance(lower, Distribution):
            if lower.stochastic_dependent:
                raise chaospy.StochasticallyDependentError(
                    "Joint distribution with dependencies not supported."
                )
            assert len(dist) == len(lower)
            lower_ = lower.lower
        elif lower is None:
            lower = lower_ = dist.lower
        else:
            lower = lower_ = numpy.atleast_1d(lower)
        if isinstance(upper, Distribution):
            if upper.stochastic_dependent:
                raise chaospy.StochasticallyDependentError(
                    "Joint distribution with dependencies not supported."
                )
            assert len(dist) == len(upper)
            upper_ = upper.upper
        elif upper is None:
            upper = upper_ = dist.upper
        else:
            upper = upper_ = numpy.atleast_1d(upper)
        assert numpy.all(
            upper_ > lower_
        ), "condition `upper > lower` not satisfied: %s <= %s" % (upper_, lower_)

        dependencies, parameters, rotation = chaospy.declare_dependencies(
            distribution=self,
            parameters=dict(lower=lower, upper=upper),
            length=len(dist),
        )
        super(Trunc, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            exclusion=exclusion,
            repr_args=repr_args,
        )
        self._dist = dist
Beispiel #8
0
 def __init__(self, length, theta=1.0, rotation=None):
     if rotation is not None:
         assert length == len(rotation)
     dependencies, _, rotation = chaospy.declare_dependencies(
         self,
         parameters=dict(theta=theta),
         rotation=rotation,
         dependency_type="accumulate",
         length=length,
     )
     super(Archimedean, self).__init__(
         parameters=dict(theta=float(theta)),
         dependencies=dependencies,
         rotation=rotation,
         repr_args=[length, "theta=%s" % theta],
     )
Beispiel #9
0
    def __init__(
        self,
        parameters=None,
        rotation=None,
        exclusion=None,
        repr_args=None,
    ):
        """
        Args:
            parameters (Optional[Distribution[str, Union[ndarray, Distribution]]]):
                Collection of model parameters.
            rotation (None, Sequence[int], Sequence[Sequence[bool]]):
                The order of which to resolve conditionals. Either as
                a sequence of column rotations, or as a permutation
                matrix. Defaults to `range(len(distribution))` which
                is the same as `p(x0), p(x1|x0), p(x2|x0,x1), ...`.
            repr_args (Optional[Sequence[str]]):
                Positional arguments to place in the object string
                representation. The repr output will then be:
                `<class name>(<arg1>, <arg2>, ...)`.

        """
        if parameters is None:
            parameters = {}
        dependencies, parameters, rotation = chaospy.declare_dependencies(
            distribution=self,
            parameters=parameters,
            rotation=rotation,
        )
        super(SimpleDistribution, self).__init__(
            parameters=parameters,
            dependencies=dependencies,
            rotation=rotation,
            exclusion=exclusion,
            repr_args=repr_args,
        )
Beispiel #10
0
    def __init__(
        self,
        samples,
        h_mat=None,
        estimator_rule="scott",
        weights=None,
        rotation=None,
    ):
        """
        Args:
            samples (numpy.ndarray):
                The samples to generate density estimation. Assumed to have
                shape either as `(n_samples,)`, or `(n_dim, n_samples)`.
            h_mat (Optional[numpy.ndarray]):
                The H-matrix, also known as the smoothing matrix or bandwidth
                matrix. In one dimension it correspond to the square of the
                bandwidth parameters often used in the one-dimensional case.
                Assumes shape either something compatible with
                `(n_dim, n_dim)`, or `(n_dim, n_dim, n_samples)` in the case
                where each sample have their own H-matrix. If omitted, it is
                automatically calculated using `estimator_rule`.
            estimator_rule (str):
                Which method to use to select smoothing matrix from, assuming
                it is omitted. Choose from 'scott' and 'silverman'.
            weights (Optional[numpy.ndarray]):
                Weights of the samples. This must have the shape
                `(n_samples,)`. If omitted, each sample is assumed to be
                equally weighted.

        """
        samples = numpy.atleast_2d(samples)
        assert samples.ndim == 2

        # the scale is taken from Scott-92.
        # The Scott factor is taken from scipy docs.
        if h_mat is None:

            if estimator_rule in ("scott", "silverman"):
                qrange = numpy.quantile(samples, [0.25, 0.75],
                                        axis=1).ptp(axis=0)
                scale = numpy.min([numpy.std(samples, axis=1), qrange / 1.34],
                                  axis=0)
                factor = samples.shape[1]
                if estimator_rule == "silverman":
                    factor *= (len(samples) + 2) / 4.0
                factor **= -1.0 / (len(samples) + 4)
                covariance = numpy.diag(scale * factor)**2

            else:
                raise ValueError("unknown estimator rule: %s" % estimator_rule)

        else:
            covariance = numpy.asfarray(h_mat)
            if covariance.ndim in (0, 1):
                covariance = covariance * numpy.eye(len(samples))
        if covariance.ndim == 2:
            covariance = covariance[numpy.newaxis]
        else:
            covariance = numpy.rollaxis(covariance, 2, 0)
        assert covariance.shape[1:] == (len(samples), len(samples))

        if weights is None:
            weights = 1.0 / samples.shape[1]
        self.weights = weights

        dependencies, _, rotation = chaospy.declare_dependencies(
            self,
            dict(),
            rotation=rotation,
            dependency_type="accumulate",
            length=len(samples),
        )

        self._samples = samples
        self._covariance = covariance
        self._permute = numpy.eye(len(rotation), dtype=int)[rotation]
        self._pcovariance = numpy.matmul(
            numpy.matmul(self._permute, covariance), self._permute.T)
        cholesky = numpy.linalg.cholesky(self._pcovariance)
        self._fwd_transform = numpy.linalg.inv(cholesky)
        self._inv_transform = cholesky

        super(KernelDensityBaseclass, self).__init__(
            parameters={},
            dependencies=dependencies,
            rotation=rotation,
        )
        self._zloc = None
        self._kernel0 = None
        self._kernel1 = None