def test_trucation_multivariate(): """Ensure that multivariate bounds works as expected.""" dist1 = chaospy.Iid(chaospy.Normal(), 2) dist2 = chaospy.Trunc(chaospy.Iid(chaospy.Normal(), 2), lower=dist1, upper=[1, 1]) joint = chaospy.J(dist1, dist2) assert numpy.allclose( joint.fwd([[-1, -1, -1, -1], [-1, -1, -1, -1], [0, 0, -2, 2], [-2, 2, 0, 0]]), [[0.15865525, 0.15865525, 0.15865525, 0.15865525], [0.15865525, 0.15865525, 0.15865525, 0.15865525], [0.48222003, 0.48222003, 0., 1.], [0., 1., 0.48222003, 0.48222003]], )
def test_integration(): dist = cp.Iid(cp.Normal(), dim) orth, norms = cp.orth_ttr(order, dist, retall=1) gq = cp.generate_quadrature nodes, weights = gq(order, dist, rule="C") vals = np.zeros((len(weights), size)) cp.fit_quadrature(orth, nodes, weights, vals, norms=norms)
def test_regression(): dist = cp.Iid(cp.Normal(), dim) orth, norms = cp.orth_ttr(order, dist, retall=1) data = dist.sample(samples) vals = np.zeros((samples, size)) cp.fit_regression(orth, data, vals, "LS") cp.fit_regression(orth, data, vals, "T", order=0) cp.fit_regression(orth, data, vals, "TC", order=0)
def test_quadrature(): dist = cp.Iid(cp.Normal(), dim) gq = cp.generate_quadrature nodes, weights = gq(order, dist, rule="C") nodes, weights = gq(order, dist, rule="E") nodes, weights = gq(order, dist, rule="G") nodes, weights = gq(order, dist, rule="C", sparse=True) nodes, weights = gq(order, dist, rule="E", sparse=True) nodes, weights = gq(order, dist, rule="G", sparse=True)
def make_sampling(): dist = chaospy.Iid(chaospy.Uniform(0, 1), 2) samples = dist.sample(20, rule="sobol") size = 80 pyplot.scatter(*samples[:, ::2], s=size, lw=3, color="w", edgecolors=COLOR1) pyplot.scatter(*samples[:, ::2], s=size, color=COLOR1, alpha=0.6) pyplot.scatter(*samples[:, 1::2], s=size, lw=3, color="w", edgecolor=COLOR2) pyplot.scatter(*samples[:, 1::2], s=size, color=COLOR2, alpha=0.6) save("sampling")
def make_quadrature(): dist = chaospy.Iid(chaospy.Uniform(0, 1), 2) nodes, weights = chaospy.generate_quadrature(2, dist, growth=True, rule="fejer", sparse=True) size = (weights*500).astype(int) indices = weights < 0 pyplot.scatter(*nodes[:, indices], s=-size[indices], lw=3, color="w", edgecolors=COLOR2) pyplot.scatter(*nodes[:, indices], s=-size[indices], color=COLOR2, alpha=0.6) pyplot.scatter(*nodes[:, ~indices], s=size[~indices], lw=3, color="w", edgecolor=COLOR1) pyplot.scatter(*nodes[:, ~indices], s=size[~indices], color=COLOR1, alpha=0.6) save("quadrature")
def __init__(self, dimension=None, input=None, output=None, order=None): self.dimension = dimension self.input = np.transpose(input) self.output = output self.order = order self.distribution = cp.Iid(cp.Uniform(0, 1), self.dimension) orthogonal_expansion = cp.orth_ttr(self.order, self.distribution) self.poly = cp.fit_regression(orthogonal_expansion, self.input, self.output)
def make_recurrence(): dist = chaospy.Iid(chaospy.Uniform(0, 1), 2) samples1 = numpy.array([[0, 1, 2, 3], [0, 1, 2, 3]]) samples2 = numpy.array([[0, 0, 0, 1, 1, 2], [1, 2, 3, 2, 3, 3]]) size = 100 pyplot.plot([.16, .84], [2, 2], COLOR2, lw=4) pyplot.plot([.16, .84], [3, 3], COLOR2, lw=4) pyplot.plot([1.16, 1.84], [3, 3], COLOR2, lw=4) pyplot.scatter(*samples1, s=size, lw=3, color="w", edgecolors=COLOR1) pyplot.scatter(*samples1, s=size, color=COLOR1, alpha=0.6) pyplot.scatter(*samples2, s=size, lw=3, color="w", edgecolor=COLOR2) pyplot.scatter(*samples2, s=size, color=COLOR2, alpha=0.6) save("recurrence")
def init_mv_normal( self, dist, mean=0, covariance=1, rotation=None, repr_args=None, ): mean = np.atleast_1d(mean) length = max(len(dist), len(mean), len(covariance)) exclusion = dist._exclusion.copy() dist = chaospy.Iid(dist, length) covariance = np.asarray(covariance) rotation = [ key for key, _ in sorted(enumerate(dist._dependencies), key=lambda x: len(x[1])) ] accumulant = set() dependencies = [deps.copy() for deps in dist._dependencies] for idx in rotation: accumulant.update(dist._dependencies[idx]) dependencies[idx] = accumulant.copy() self._permute = np.eye(len(rotation), dtype=int)[rotation] self._covariance = covariance self._pcovariance = self._permute.dot(covariance).dot(self._permute.T) try: cholesky = np.linalg.cholesky(self._pcovariance) self._fwd_transform = self._permute.T.dot(np.linalg.inv(cholesky)) except np.linalg.LinAlgError as err: cholesky = np.real(sqrtm(self._pcovariance)) self._fwd_transform = self._permute.T.dot(np.linalg.pinv(cholesky)) self._inv_transform = self._permute.T.dot(cholesky) self._dist = dist super(chaospy.distributions.MeanCovarianceDistribution, self).__init__( parameters=dict(mean=mean, covariance=covariance), dependencies=dependencies, rotation=rotation, exclusion=exclusion, repr_args=repr_args, )
def test_3d_quadrature_creation(analytical_distribution, recurrence_algorithm): """Check 3-D quadrature rule.""" distribution = chaospy.Iid(analytical_distribution, 3) abscissas, weights = chaospy.quadrature.gaussian( order=3, dist=distribution, recurrence_algorithm=recurrence_algorithm, ) assert abscissas.shape == (3, 4**3) assert weights.shape == (4**3, ) kloc = numpy.eye(3, dtype=int) assert numpy.allclose(numpy.sum(abscissas * weights, -1), distribution.mom(kloc)) assert numpy.allclose(numpy.sum(abscissas**2 * weights, -1), distribution.mom(2 * kloc)) assert numpy.allclose(numpy.sum(abscissas**5 * weights, -1), distribution.mom(5 * kloc))
def _criterion(rho_c, arg, distributions, order=15): """ Evaluates the integral using a Gauss-Hermite rule in 2 dimensions. It requires the Cholesky decomposition of the covariance matrix in order to transform the integral properly. """ cov = np.identity(2) cov[1, 0] = cov[0, 1] = rho_c chol = np.linalg.cholesky(cov) distribution = cp.Iid(cp.Normal(0, 1), 2) nodes, weights = cp.generate_quadrature(order, distribution, rule="gaussian") x_1, x_2 = np.split(chol @ nodes, 2) standard_norm_cdf = cp.Normal().cdf arg_1 = distributions[0].inv(standard_norm_cdf(x_1)) arg_2 = distributions[1].inv(standard_norm_cdf(x_2)) point = arg_1 * arg_2 return (sum(point[0] * weights) - arg)**2
def test_descriptives(): dist = cp.Iid(cp.Normal(), dim) orth = cp.expansion.stieltjes(order, dist) cp.E(orth, dist) cp.Var(orth, dist) cp.Cov(orth, dist)
def test_approx_quadrature(): dist = cp.Iid(normal(), dim) gq = cp.generate_quadrature nodes, weights = gq(order, dist, rule="C")
# === Distributions === # simple distributions rv1 = cp.Uniform(0, 1) rv2 = cp.Normal(0, 1) rv3 = cp.Lognormal(0, 1, 0.2, 0.8) print(rv1, rv2, rv3) # end simple distributions # joint distributions joint_distribution = cp.J(rv1, rv2, rv3) print(joint_distribution) # end joint distributions # creating iid variables X = cp.Normal() Y = cp.Iid(X, 4) print(Y) # end creating iid variables # === Sampling === # sampling in chaospy u = cp.Uniform(0,1) u.sample? # end sampling chaospy # example sampling u1 = cp.Uniform(0,1) u2 = cp.Uniform(0,1) joint_distribution = cp.J(u1, u2) number_of_samples = 350 samples_random = joint_distribution.sample(size=number_of_samples, rule='R')
def test_orthogonals(): dist = cp.Iid(cp.Normal(), dim) cp.orth_gs(order, dist) cp.orth_ttr(order, dist) cp.orth_chol(order, dist)
print(df.head()) comp = df['Compound'] pos = df['Positive'] neg = df['Negative'] neu = df['Neutral'] loc = df['Locations'] D = np.vstack((loc, comp, pos, neg, neu)).T print(D) cp_kde = KDE(D) np.set_printoptions(precision=3) np.set_printoptions(suppress=True) samples = cp.Iid(cp.Uniform(), 5).sample(len(df)) R = cp.approximation.approximate_inverse(cp_kde, samples, iterations=1000, tol=1e-5) cols = ["Locations", "Compound", "Negative", "Neutral", "Positive"] df1 = pd.DataFrame(R.T, columns=cols) df1['Compound'] = df1['Compound'].round(3) df1['Positive'] = df1['Positive'].round(3) df1['Negative'] = df1['Negative'].round(3) df1['Neutral'] = df1['Neutral'].round(3) df1['Locations'] = df1['Locations'].round().astype(int) df1['Locations'] = df1['Locations'].map(dic).fillna('EARTH')
import numpoly import chaospy as cpy import numpy as np from time import time from chaospy import Normal, generate_expansion if __name__ == '__main__': prior_mean = 0. prior_sigma = 5. dim = 2 prior = cpy.Iid(Normal(prior_mean, prior_sigma), dim) poly_order = 2 abscissas, weights = cpy.generate_quadrature(poly_order, prior, rule='gaussian') expansion = generate_expansion(poly_order, prior, retall=False) def forward_model(params): return np.prod(np.exp(-params**2)) evals = np.array([forward_model(sample) for sample in abscissas.T]) surrogate = cpy.fit_quadrature(expansion, abscissas, weights, evals) coefficients = np.array(surrogate.coefficients) indeterminants = surrogate.indeterminants exponents = surrogate.exponents
# -*- coding: utf-8 -*- """ Created on Tue Sep 17 08:51:15 2019 @author: loukrezis Probability density function for the meromorphic function using Chaospy """ import chaospy as cp # num RVs N = 50 # marginal pdfs jpdf = cp.Iid(cp.Uniform(-1, 1), N) #jpdf = cp.Iid(cp.TruncNormal(lower=0, upper=3, mu=0, sigma=1), N)
def test_orthogonals(): dist = cp.Iid(cp.Normal(), dim) cp.expansion.gram_schmidt(order, dist) cp.expansion.stieltjes(order, dist) cp.expansion.cholesky(order, dist)
def test_regression(): dist = cp.Iid(cp.Normal(), dim) orth, norms = cp.expansion.stieltjes(order, dist, retall=1) data = dist.sample(samples) vals = np.zeros((samples, size)) cp.fit_regression(orth, data, vals)
def test_descriptives(): dist = cp.Iid(cp.Normal(), dim) orth = cp.orth_ttr(order, dist) cp.E(orth, dist) cp.Var(orth, dist) cp.Cov(orth, dist)
def __init__( self, dist, mean=0, covariance=1, rotation=None, repr_args=None, ): assert isinstance(dist, Distribution), "'dist' should be a distribution" mean = mean if isinstance(mean, Distribution) else numpy.atleast_1d(mean) assert not isinstance(covariance, Distribution) length = max(len(dist), len(mean), len(covariance)) if not isinstance(mean, Distribution): assert mean.ndim == 1, "Parameter 'mean' have too many dimensions" assert len(mean) == length assert len(mean) in (1, length) exclusion = dist._exclusion.copy() if len(dist) == 1 and length > 1: dist = chaospy.Iid(dist, length) covariance = numpy.asarray(covariance) assert covariance.ndim <= 2, ( "Covariance must either be scalar, vector or matrix") if covariance.ndim == 0: covariance = numpy.eye(length) * covariance elif covariance.ndim == 1: covariance = numpy.diag(covariance) assert covariance.shape == (length, length), ( "Parameters 'mean' and 'covariance' have shape mismatch.") assert len(covariance) == length if rotation is not None: rotation = list(rotation) else: rotation = [ key for key, _ in sorted(enumerate(dist._dependencies), key=lambda x: len(x[1])) ] accumulant = set() dependencies = [deps.copy() for deps in dist._dependencies] for idx in rotation: accumulant.update(dist._dependencies[idx]) dependencies[idx] = accumulant.copy() if isinstance(mean, Distribution): if len(mean) == 1: for dependency in dependencies: dependency.update(mean._dependencies[0]) else: for dep1, dep2 in zip(dependencies, mean._dependencies): dep1.update(dep2) self._permute = numpy.eye(len(rotation), dtype=int)[rotation] self._covariance = covariance self._pcovariance = self._permute.dot(covariance).dot(self._permute.T) cholesky = numpy.linalg.cholesky(self._pcovariance) self._fwd_transform = self._permute.T.dot(numpy.linalg.inv(cholesky)) self._inv_transform = self._permute.T.dot(cholesky) self._dist = dist super(MeanCovarianceDistribution, self).__init__( parameters=dict(mean=mean, covariance=covariance), dependencies=dependencies, rotation=rotation, exclusion=exclusion, repr_args=repr_args, )