repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jonathf/chaospy | chaospy/distributions/sampler/sequences/halton.py | create_halton_samples | def create_halton_samples(order, dim=1, burnin=-1, primes=()):
"""
Create Halton sequence.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Halton sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Halton sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns (numpy.ndarray):
Halton sequence with ``shape == (dim, order)``.
"""
primes = list(primes)
if not primes:
prime_order = 10*dim
while len(primes) < dim:
primes = create_primes(prime_order)
prime_order *= 2
primes = primes[:dim]
assert len(primes) == dim, "not enough primes"
if burnin < 0:
burnin = max(primes)
out = numpy.empty((dim, order))
indices = [idx+burnin for idx in range(order)]
for dim_ in range(dim):
out[dim_] = create_van_der_corput_samples(
indices, number_base=primes[dim_])
return out | python | def create_halton_samples(order, dim=1, burnin=-1, primes=()):
"""
Create Halton sequence.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Halton sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Halton sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns (numpy.ndarray):
Halton sequence with ``shape == (dim, order)``.
"""
primes = list(primes)
if not primes:
prime_order = 10*dim
while len(primes) < dim:
primes = create_primes(prime_order)
prime_order *= 2
primes = primes[:dim]
assert len(primes) == dim, "not enough primes"
if burnin < 0:
burnin = max(primes)
out = numpy.empty((dim, order))
indices = [idx+burnin for idx in range(order)]
for dim_ in range(dim):
out[dim_] = create_van_der_corput_samples(
indices, number_base=primes[dim_])
return out | [
"def",
"create_halton_samples",
"(",
"order",
",",
"dim",
"=",
"1",
",",
"burnin",
"=",
"-",
"1",
",",
"primes",
"=",
"(",
")",
")",
":",
"primes",
"=",
"list",
"(",
"primes",
")",
"if",
"not",
"primes",
":",
"prime_order",
"=",
"10",
"*",
"dim",
... | Create Halton sequence.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Halton sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Halton sequence.
burnin (int):
Skip the first ``burnin`` samples. If negative, the maximum of
``primes`` is used.
primes (tuple):
The (non-)prime base to calculate values along each axis. If
empty, growing prime values starting from 2 will be used.
Returns (numpy.ndarray):
Halton sequence with ``shape == (dim, order)``. | [
"Create",
"Halton",
"sequence",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/halton.py#L34-L72 | train | 206,900 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.range | def range(self, x_data=None):
"""
Generate the upper and lower bounds of a distribution.
Args:
x_data (numpy.ndarray) :
The bounds might vary over the sample space. By providing
x_data you can specify where in the space the bound should be
taken. If omitted, a (pseudo-)random sample is used.
Returns:
(numpy.ndarray):
The lower (out[0]) and upper (out[1]) bound where
out.shape=(2,)+x_data.shape
"""
if x_data is None:
try:
x_data = evaluation.evaluate_inverse(
self, numpy.array([[0.5]]*len(self)))
except StochasticallyDependentError:
x_data = approximation.find_interior_point(self)
shape = (len(self),)
if hasattr(self, "_range"):
return self._range(x_data, {})
else:
x_data = numpy.asfarray(x_data)
shape = x_data.shape
x_data = x_data.reshape(len(self), -1)
q_data = evaluation.evaluate_bound(self, x_data)
q_data = q_data.reshape((2,)+shape)
return q_data | python | def range(self, x_data=None):
"""
Generate the upper and lower bounds of a distribution.
Args:
x_data (numpy.ndarray) :
The bounds might vary over the sample space. By providing
x_data you can specify where in the space the bound should be
taken. If omitted, a (pseudo-)random sample is used.
Returns:
(numpy.ndarray):
The lower (out[0]) and upper (out[1]) bound where
out.shape=(2,)+x_data.shape
"""
if x_data is None:
try:
x_data = evaluation.evaluate_inverse(
self, numpy.array([[0.5]]*len(self)))
except StochasticallyDependentError:
x_data = approximation.find_interior_point(self)
shape = (len(self),)
if hasattr(self, "_range"):
return self._range(x_data, {})
else:
x_data = numpy.asfarray(x_data)
shape = x_data.shape
x_data = x_data.reshape(len(self), -1)
q_data = evaluation.evaluate_bound(self, x_data)
q_data = q_data.reshape((2,)+shape)
return q_data | [
"def",
"range",
"(",
"self",
",",
"x_data",
"=",
"None",
")",
":",
"if",
"x_data",
"is",
"None",
":",
"try",
":",
"x_data",
"=",
"evaluation",
".",
"evaluate_inverse",
"(",
"self",
",",
"numpy",
".",
"array",
"(",
"[",
"[",
"0.5",
"]",
"]",
"*",
... | Generate the upper and lower bounds of a distribution.
Args:
x_data (numpy.ndarray) :
The bounds might vary over the sample space. By providing
x_data you can specify where in the space the bound should be
taken. If omitted, a (pseudo-)random sample is used.
Returns:
(numpy.ndarray):
The lower (out[0]) and upper (out[1]) bound where
out.shape=(2,)+x_data.shape | [
"Generate",
"the",
"upper",
"and",
"lower",
"bounds",
"of",
"a",
"distribution",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L65-L96 | train | 206,901 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.fwd | def fwd(self, x_data):
"""
Forward Rosenblatt transformation.
Args:
x_data (numpy.ndarray):
Location for the distribution function. ``x_data.shape`` must
be compatible with distribution shape.
Returns:
(numpy.ndarray):
Evaluated distribution function values, where
``out.shape==x_data.shape``.
"""
x_data = numpy.asfarray(x_data)
shape = x_data.shape
x_data = x_data.reshape(len(self), -1)
lower, upper = evaluation.evaluate_bound(self, x_data)
q_data = numpy.zeros(x_data.shape)
indices = x_data > upper
q_data[indices] = 1
indices = ~indices & (x_data >= lower)
q_data[indices] = numpy.clip(evaluation.evaluate_forward(
self, x_data), a_min=0, a_max=1)[indices]
q_data = q_data.reshape(shape)
return q_data | python | def fwd(self, x_data):
"""
Forward Rosenblatt transformation.
Args:
x_data (numpy.ndarray):
Location for the distribution function. ``x_data.shape`` must
be compatible with distribution shape.
Returns:
(numpy.ndarray):
Evaluated distribution function values, where
``out.shape==x_data.shape``.
"""
x_data = numpy.asfarray(x_data)
shape = x_data.shape
x_data = x_data.reshape(len(self), -1)
lower, upper = evaluation.evaluate_bound(self, x_data)
q_data = numpy.zeros(x_data.shape)
indices = x_data > upper
q_data[indices] = 1
indices = ~indices & (x_data >= lower)
q_data[indices] = numpy.clip(evaluation.evaluate_forward(
self, x_data), a_min=0, a_max=1)[indices]
q_data = q_data.reshape(shape)
return q_data | [
"def",
"fwd",
"(",
"self",
",",
"x_data",
")",
":",
"x_data",
"=",
"numpy",
".",
"asfarray",
"(",
"x_data",
")",
"shape",
"=",
"x_data",
".",
"shape",
"x_data",
"=",
"x_data",
".",
"reshape",
"(",
"len",
"(",
"self",
")",
",",
"-",
"1",
")",
"low... | Forward Rosenblatt transformation.
Args:
x_data (numpy.ndarray):
Location for the distribution function. ``x_data.shape`` must
be compatible with distribution shape.
Returns:
(numpy.ndarray):
Evaluated distribution function values, where
``out.shape==x_data.shape``. | [
"Forward",
"Rosenblatt",
"transformation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L98-L126 | train | 206,902 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.inv | def inv(self, q_data, max_iterations=100, tollerance=1e-5):
"""
Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
Args:
q_data (numpy.ndarray):
Probabilities to be inverse. If any values are outside ``[0,
1]``, error will be raised. ``q_data.shape`` must be compatible
with distribution shape.
max_iterations (int):
If approximation is used, this sets the maximum number of
allowed iterations in the Newton-Raphson algorithm.
tollerance (float):
If approximation is used, this set the error tolerance level
required to define a sample as converged.
Returns:
(numpy.ndarray):
Inverted probability values where
``out.shape == q_data.shape``.
"""
q_data = numpy.asfarray(q_data)
assert numpy.all((q_data >= 0) & (q_data <= 1)), "sanitize your inputs!"
shape = q_data.shape
q_data = q_data.reshape(len(self), -1)
x_data = evaluation.evaluate_inverse(self, q_data)
lower, upper = evaluation.evaluate_bound(self, x_data)
x_data = numpy.clip(x_data, a_min=lower, a_max=upper)
x_data = x_data.reshape(shape)
return x_data | python | def inv(self, q_data, max_iterations=100, tollerance=1e-5):
"""
Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
Args:
q_data (numpy.ndarray):
Probabilities to be inverse. If any values are outside ``[0,
1]``, error will be raised. ``q_data.shape`` must be compatible
with distribution shape.
max_iterations (int):
If approximation is used, this sets the maximum number of
allowed iterations in the Newton-Raphson algorithm.
tollerance (float):
If approximation is used, this set the error tolerance level
required to define a sample as converged.
Returns:
(numpy.ndarray):
Inverted probability values where
``out.shape == q_data.shape``.
"""
q_data = numpy.asfarray(q_data)
assert numpy.all((q_data >= 0) & (q_data <= 1)), "sanitize your inputs!"
shape = q_data.shape
q_data = q_data.reshape(len(self), -1)
x_data = evaluation.evaluate_inverse(self, q_data)
lower, upper = evaluation.evaluate_bound(self, x_data)
x_data = numpy.clip(x_data, a_min=lower, a_max=upper)
x_data = x_data.reshape(shape)
return x_data | [
"def",
"inv",
"(",
"self",
",",
"q_data",
",",
"max_iterations",
"=",
"100",
",",
"tollerance",
"=",
"1e-5",
")",
":",
"q_data",
"=",
"numpy",
".",
"asfarray",
"(",
"q_data",
")",
"assert",
"numpy",
".",
"all",
"(",
"(",
"q_data",
">=",
"0",
")",
"... | Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
Args:
q_data (numpy.ndarray):
Probabilities to be inverse. If any values are outside ``[0,
1]``, error will be raised. ``q_data.shape`` must be compatible
with distribution shape.
max_iterations (int):
If approximation is used, this sets the maximum number of
allowed iterations in the Newton-Raphson algorithm.
tollerance (float):
If approximation is used, this set the error tolerance level
required to define a sample as converged.
Returns:
(numpy.ndarray):
Inverted probability values where
``out.shape == q_data.shape``. | [
"Inverse",
"Rosenblatt",
"transformation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L154-L187 | train | 206,903 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.sample | def sample(self, size=(), rule="R", antithetic=None):
"""
Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance reduction techniques.
Changing the sampling scheme, use the following ``rule`` flag:
+-------+-------------------------------------------------+
| key | Description |
+=======+=================================================+
| ``C`` | Roots of the first order Chebyshev polynomials. |
+-------+-------------------------------------------------+
| ``NC``| Chebyshev nodes adjusted to ensure nested. |
+-------+-------------------------------------------------+
| ``K`` | Korobov lattice. |
+-------+-------------------------------------------------+
| ``R`` | Classical (Pseudo-)Random samples. |
+-------+-------------------------------------------------+
| ``RG``| Regular spaced grid. |
+-------+-------------------------------------------------+
| ``NG``| Nested regular spaced grid. |
+-------+-------------------------------------------------+
| ``L`` | Latin hypercube samples. |
+-------+-------------------------------------------------+
| ``S`` | Sobol low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``H`` | Halton low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``M`` | Hammersley low-discrepancy sequence. |
+-------+-------------------------------------------------+
All samples are created on the ``[0, 1]``-hypercube, which then is
mapped into the domain of the distribution using the inverse Rosenblatt
transformation.
Args:
size (numpy.ndarray):
The size of the samples to generate.
rule (str):
Indicator defining the sampling scheme.
antithetic (bool, numpy.ndarray):
If provided, will be used to setup antithetic variables. If
array, defines the axes to mirror.
Returns:
(numpy.ndarray):
Random samples with shape ``(len(self),)+self.shape``.
"""
size_ = numpy.prod(size, dtype=int)
dim = len(self)
if dim > 1:
if isinstance(size, (tuple, list, numpy.ndarray)):
shape = (dim,) + tuple(size)
else:
shape = (dim, size)
else:
shape = size
from . import sampler
out = sampler.generator.generate_samples(
order=size_, domain=self, rule=rule, antithetic=antithetic)
try:
out = out.reshape(shape)
except:
if len(self) == 1:
out = out.flatten()
else:
out = out.reshape(dim, int(out.size/dim))
return out | python | def sample(self, size=(), rule="R", antithetic=None):
"""
Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance reduction techniques.
Changing the sampling scheme, use the following ``rule`` flag:
+-------+-------------------------------------------------+
| key | Description |
+=======+=================================================+
| ``C`` | Roots of the first order Chebyshev polynomials. |
+-------+-------------------------------------------------+
| ``NC``| Chebyshev nodes adjusted to ensure nested. |
+-------+-------------------------------------------------+
| ``K`` | Korobov lattice. |
+-------+-------------------------------------------------+
| ``R`` | Classical (Pseudo-)Random samples. |
+-------+-------------------------------------------------+
| ``RG``| Regular spaced grid. |
+-------+-------------------------------------------------+
| ``NG``| Nested regular spaced grid. |
+-------+-------------------------------------------------+
| ``L`` | Latin hypercube samples. |
+-------+-------------------------------------------------+
| ``S`` | Sobol low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``H`` | Halton low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``M`` | Hammersley low-discrepancy sequence. |
+-------+-------------------------------------------------+
All samples are created on the ``[0, 1]``-hypercube, which then is
mapped into the domain of the distribution using the inverse Rosenblatt
transformation.
Args:
size (numpy.ndarray):
The size of the samples to generate.
rule (str):
Indicator defining the sampling scheme.
antithetic (bool, numpy.ndarray):
If provided, will be used to setup antithetic variables. If
array, defines the axes to mirror.
Returns:
(numpy.ndarray):
Random samples with shape ``(len(self),)+self.shape``.
"""
size_ = numpy.prod(size, dtype=int)
dim = len(self)
if dim > 1:
if isinstance(size, (tuple, list, numpy.ndarray)):
shape = (dim,) + tuple(size)
else:
shape = (dim, size)
else:
shape = size
from . import sampler
out = sampler.generator.generate_samples(
order=size_, domain=self, rule=rule, antithetic=antithetic)
try:
out = out.reshape(shape)
except:
if len(self) == 1:
out = out.flatten()
else:
out = out.reshape(dim, int(out.size/dim))
return out | [
"def",
"sample",
"(",
"self",
",",
"size",
"=",
"(",
")",
",",
"rule",
"=",
"\"R\"",
",",
"antithetic",
"=",
"None",
")",
":",
"size_",
"=",
"numpy",
".",
"prod",
"(",
"size",
",",
"dtype",
"=",
"int",
")",
"dim",
"=",
"len",
"(",
"self",
")",
... | Create pseudo-random generated samples.
By default, the samples are created using standard (pseudo-)random
samples. However, if needed, the samples can also be created by either
low-discrepancy sequences, and/or variance reduction techniques.
Changing the sampling scheme, use the following ``rule`` flag:
+-------+-------------------------------------------------+
| key | Description |
+=======+=================================================+
| ``C`` | Roots of the first order Chebyshev polynomials. |
+-------+-------------------------------------------------+
| ``NC``| Chebyshev nodes adjusted to ensure nested. |
+-------+-------------------------------------------------+
| ``K`` | Korobov lattice. |
+-------+-------------------------------------------------+
| ``R`` | Classical (Pseudo-)Random samples. |
+-------+-------------------------------------------------+
| ``RG``| Regular spaced grid. |
+-------+-------------------------------------------------+
| ``NG``| Nested regular spaced grid. |
+-------+-------------------------------------------------+
| ``L`` | Latin hypercube samples. |
+-------+-------------------------------------------------+
| ``S`` | Sobol low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``H`` | Halton low-discrepancy sequence. |
+-------+-------------------------------------------------+
| ``M`` | Hammersley low-discrepancy sequence. |
+-------+-------------------------------------------------+
All samples are created on the ``[0, 1]``-hypercube, which then is
mapped into the domain of the distribution using the inverse Rosenblatt
transformation.
Args:
size (numpy.ndarray):
The size of the samples to generate.
rule (str):
Indicator defining the sampling scheme.
antithetic (bool, numpy.ndarray):
If provided, will be used to setup antithetic variables. If
array, defines the axes to mirror.
Returns:
(numpy.ndarray):
Random samples with shape ``(len(self),)+self.shape``. | [
"Create",
"pseudo",
"-",
"random",
"generated",
"samples",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L226-L298 | train | 206,904 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.mom | def mom(self, K, **kws):
"""
Raw statistical moments.
Creates non-centralized raw moments from the random variable. If
analytical options can not be utilized, Monte Carlo integration
will be used.
Args:
K (numpy.ndarray):
Index of the raw moments. k.shape must be compatible with
distribution shape. Sampling scheme when performing Monte
Carlo
rule (str):
rule for estimating the moment if the analytical method fails.
composite (numpy.ndarray):
If provided, composit quadrature will be used. Ignored in the
case if gaussian=True. If int provided, determines number of
even domain splits. If array of ints, determines number of even
domain splits along each axis. If array of arrays/floats,
determines location of splits.
antithetic (numpy.ndarray):
List of bool. Represents the axes to mirror using antithetic
variable during MCI.
Returns:
(numpy.ndarray):
Shapes are related through the identity
``k.shape == dist.shape+k.shape``.
"""
K = numpy.asarray(K, dtype=int)
shape = K.shape
dim = len(self)
if dim > 1:
shape = shape[1:]
size = int(K.size/dim)
K = K.reshape(dim, size)
cache = {}
out = [evaluation.evaluate_moment(self, kdata, cache) for kdata in K.T]
out = numpy.array(out)
return out.reshape(shape) | python | def mom(self, K, **kws):
"""
Raw statistical moments.
Creates non-centralized raw moments from the random variable. If
analytical options can not be utilized, Monte Carlo integration
will be used.
Args:
K (numpy.ndarray):
Index of the raw moments. k.shape must be compatible with
distribution shape. Sampling scheme when performing Monte
Carlo
rule (str):
rule for estimating the moment if the analytical method fails.
composite (numpy.ndarray):
If provided, composit quadrature will be used. Ignored in the
case if gaussian=True. If int provided, determines number of
even domain splits. If array of ints, determines number of even
domain splits along each axis. If array of arrays/floats,
determines location of splits.
antithetic (numpy.ndarray):
List of bool. Represents the axes to mirror using antithetic
variable during MCI.
Returns:
(numpy.ndarray):
Shapes are related through the identity
``k.shape == dist.shape+k.shape``.
"""
K = numpy.asarray(K, dtype=int)
shape = K.shape
dim = len(self)
if dim > 1:
shape = shape[1:]
size = int(K.size/dim)
K = K.reshape(dim, size)
cache = {}
out = [evaluation.evaluate_moment(self, kdata, cache) for kdata in K.T]
out = numpy.array(out)
return out.reshape(shape) | [
"def",
"mom",
"(",
"self",
",",
"K",
",",
"*",
"*",
"kws",
")",
":",
"K",
"=",
"numpy",
".",
"asarray",
"(",
"K",
",",
"dtype",
"=",
"int",
")",
"shape",
"=",
"K",
".",
"shape",
"dim",
"=",
"len",
"(",
"self",
")",
"if",
"dim",
">",
"1",
... | Raw statistical moments.
Creates non-centralized raw moments from the random variable. If
analytical options can not be utilized, Monte Carlo integration
will be used.
Args:
K (numpy.ndarray):
Index of the raw moments. k.shape must be compatible with
distribution shape. Sampling scheme when performing Monte
Carlo
rule (str):
rule for estimating the moment if the analytical method fails.
composite (numpy.ndarray):
If provided, composit quadrature will be used. Ignored in the
case if gaussian=True. If int provided, determines number of
even domain splits. If array of ints, determines number of even
domain splits along each axis. If array of arrays/floats,
determines location of splits.
antithetic (numpy.ndarray):
List of bool. Represents the axes to mirror using antithetic
variable during MCI.
Returns:
(numpy.ndarray):
Shapes are related through the identity
``k.shape == dist.shape+k.shape``. | [
"Raw",
"statistical",
"moments",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L300-L343 | train | 206,905 |
jonathf/chaospy | chaospy/distributions/baseclass.py | Dist.ttr | def ttr(self, kloc, acc=10**3, verbose=1):
"""
Three terms relation's coefficient generator
Args:
k (numpy.ndarray, int):
The order of the coefficients.
acc (int):
Accuracy of discretized Stieltjes if analytical methods are
unavailable.
Returns:
(Recurrence coefficients):
Where out[0] is the first (A) and out[1] is the second
coefficient With ``out.shape==(2,)+k.shape``.
"""
kloc = numpy.asarray(kloc, dtype=int)
shape = kloc.shape
kloc = kloc.reshape(len(self), -1)
cache = {}
out = [evaluation.evaluate_recurrence_coefficients(self, k)
for k in kloc.T]
out = numpy.array(out).T
return out.reshape((2,)+shape) | python | def ttr(self, kloc, acc=10**3, verbose=1):
"""
Three terms relation's coefficient generator
Args:
k (numpy.ndarray, int):
The order of the coefficients.
acc (int):
Accuracy of discretized Stieltjes if analytical methods are
unavailable.
Returns:
(Recurrence coefficients):
Where out[0] is the first (A) and out[1] is the second
coefficient With ``out.shape==(2,)+k.shape``.
"""
kloc = numpy.asarray(kloc, dtype=int)
shape = kloc.shape
kloc = kloc.reshape(len(self), -1)
cache = {}
out = [evaluation.evaluate_recurrence_coefficients(self, k)
for k in kloc.T]
out = numpy.array(out).T
return out.reshape((2,)+shape) | [
"def",
"ttr",
"(",
"self",
",",
"kloc",
",",
"acc",
"=",
"10",
"**",
"3",
",",
"verbose",
"=",
"1",
")",
":",
"kloc",
"=",
"numpy",
".",
"asarray",
"(",
"kloc",
",",
"dtype",
"=",
"int",
")",
"shape",
"=",
"kloc",
".",
"shape",
"kloc",
"=",
"... | Three terms relation's coefficient generator
Args:
k (numpy.ndarray, int):
The order of the coefficients.
acc (int):
Accuracy of discretized Stieltjes if analytical methods are
unavailable.
Returns:
(Recurrence coefficients):
Where out[0] is the first (A) and out[1] is the second
coefficient With ``out.shape==(2,)+k.shape``. | [
"Three",
"terms",
"relation",
"s",
"coefficient",
"generator"
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/baseclass.py#L349-L372 | train | 206,906 |
jonathf/chaospy | chaospy/descriptives/correlation/auto_correlation.py | Acf | def Acf(poly, dist, N=None, **kws):
"""
Auto-correlation function.
Args:
poly (Poly):
Polynomial of interest. Must have ``len(poly) > N``.
dist (Dist):
Defines the space the correlation is taken on.
N (int):
The number of time steps appart included. If omited set to
``len(poly)/2+1``.
Returns:
(numpy.ndarray) :
Auto-correlation of ``poly`` with shape ``(N,)``. Note that by
definition ``Q[0]=1``.
Examples:
>>> poly = chaospy.prange(10)[1:]
>>> Z = chaospy.Uniform()
>>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))
[1. 0.9915 0.9722 0.9457 0.9127]
"""
if N is None:
N = len(poly)/2 + 1
corr = Corr(poly, dist, **kws)
out = numpy.empty(N)
for n in range(N):
out[n] = numpy.mean(corr.diagonal(n), 0)
return out | python | def Acf(poly, dist, N=None, **kws):
"""
Auto-correlation function.
Args:
poly (Poly):
Polynomial of interest. Must have ``len(poly) > N``.
dist (Dist):
Defines the space the correlation is taken on.
N (int):
The number of time steps appart included. If omited set to
``len(poly)/2+1``.
Returns:
(numpy.ndarray) :
Auto-correlation of ``poly`` with shape ``(N,)``. Note that by
definition ``Q[0]=1``.
Examples:
>>> poly = chaospy.prange(10)[1:]
>>> Z = chaospy.Uniform()
>>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))
[1. 0.9915 0.9722 0.9457 0.9127]
"""
if N is None:
N = len(poly)/2 + 1
corr = Corr(poly, dist, **kws)
out = numpy.empty(N)
for n in range(N):
out[n] = numpy.mean(corr.diagonal(n), 0)
return out | [
"def",
"Acf",
"(",
"poly",
",",
"dist",
",",
"N",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"if",
"N",
"is",
"None",
":",
"N",
"=",
"len",
"(",
"poly",
")",
"/",
"2",
"+",
"1",
"corr",
"=",
"Corr",
"(",
"poly",
",",
"dist",
",",
"*",
... | Auto-correlation function.
Args:
poly (Poly):
Polynomial of interest. Must have ``len(poly) > N``.
dist (Dist):
Defines the space the correlation is taken on.
N (int):
The number of time steps appart included. If omited set to
``len(poly)/2+1``.
Returns:
(numpy.ndarray) :
Auto-correlation of ``poly`` with shape ``(N,)``. Note that by
definition ``Q[0]=1``.
Examples:
>>> poly = chaospy.prange(10)[1:]
>>> Z = chaospy.Uniform()
>>> print(numpy.around(chaospy.Acf(poly, Z, 5), 4))
[1. 0.9915 0.9722 0.9457 0.9127] | [
"Auto",
"-",
"correlation",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/correlation/auto_correlation.py#L7-L40 | train | 206,907 |
jonathf/chaospy | doc/distributions/multivariate.py | plot_figures | def plot_figures():
"""Plot figures for multivariate distribution section."""
rc("figure", figsize=[8.,4.])
rc("figure.subplot", left=.08, top=.95, right=.98)
rc("image", cmap="gray")
seed(1000)
Q1 = cp.Gamma(2)
Q2 = cp.Normal(0, Q1)
Q = cp.J(Q1, Q2)
#end
subplot(121)
s,t = meshgrid(linspace(0,5,200), linspace(-6,6,200))
contourf(s,t,Q.pdf([s,t]),50)
xlabel("$q_1$")
ylabel("$q_2$")
subplot(122)
Qr = Q.sample(500)
scatter(*Qr, s=10, c="k", marker="s")
xlabel("$Q_1$")
ylabel("$Q_2$")
axis([0,5,-6,6])
savefig("multivariate.png"); clf()
Q2 = cp.Gamma(1)
Q1 = cp.Normal(Q2**2, Q2+1)
Q = cp.J(Q1, Q2)
#end
subplot(121)
s,t = meshgrid(linspace(-4,7,200), linspace(0,3,200))
contourf(s,t,Q.pdf([s,t]),30)
xlabel("$q_1$")
ylabel("$q_2$")
subplot(122)
Qr = Q.sample(500)
scatter(*Qr)
xlabel("$Q_1$")
ylabel("$Q_2$")
axis([-4,7,0,3])
savefig("multivariate2.png"); clf() | python | def plot_figures():
"""Plot figures for multivariate distribution section."""
rc("figure", figsize=[8.,4.])
rc("figure.subplot", left=.08, top=.95, right=.98)
rc("image", cmap="gray")
seed(1000)
Q1 = cp.Gamma(2)
Q2 = cp.Normal(0, Q1)
Q = cp.J(Q1, Q2)
#end
subplot(121)
s,t = meshgrid(linspace(0,5,200), linspace(-6,6,200))
contourf(s,t,Q.pdf([s,t]),50)
xlabel("$q_1$")
ylabel("$q_2$")
subplot(122)
Qr = Q.sample(500)
scatter(*Qr, s=10, c="k", marker="s")
xlabel("$Q_1$")
ylabel("$Q_2$")
axis([0,5,-6,6])
savefig("multivariate.png"); clf()
Q2 = cp.Gamma(1)
Q1 = cp.Normal(Q2**2, Q2+1)
Q = cp.J(Q1, Q2)
#end
subplot(121)
s,t = meshgrid(linspace(-4,7,200), linspace(0,3,200))
contourf(s,t,Q.pdf([s,t]),30)
xlabel("$q_1$")
ylabel("$q_2$")
subplot(122)
Qr = Q.sample(500)
scatter(*Qr)
xlabel("$Q_1$")
ylabel("$Q_2$")
axis([-4,7,0,3])
savefig("multivariate2.png"); clf() | [
"def",
"plot_figures",
"(",
")",
":",
"rc",
"(",
"\"figure\"",
",",
"figsize",
"=",
"[",
"8.",
",",
"4.",
"]",
")",
"rc",
"(",
"\"figure.subplot\"",
",",
"left",
"=",
".08",
",",
"top",
"=",
".95",
",",
"right",
"=",
".98",
")",
"rc",
"(",
"\"ima... | Plot figures for multivariate distribution section. | [
"Plot",
"figures",
"for",
"multivariate",
"distribution",
"section",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/doc/distributions/multivariate.py#L5-L48 | train | 206,908 |
jonathf/chaospy | chaospy/poly/shaping.py | flatten | def flatten(vari):
"""
Flatten a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari`` with `len(Q.shape)==1`.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.flatten(P))
[1, q0, q0^2, q0^3]
"""
if isinstance(vari, Poly):
shape = int(numpy.prod(vari.shape))
return reshape(vari, (shape,))
return numpy.array(vari).flatten() | python | def flatten(vari):
"""
Flatten a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari`` with `len(Q.shape)==1`.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.flatten(P))
[1, q0, q0^2, q0^3]
"""
if isinstance(vari, Poly):
shape = int(numpy.prod(vari.shape))
return reshape(vari, (shape,))
return numpy.array(vari).flatten() | [
"def",
"flatten",
"(",
"vari",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"shape",
"=",
"int",
"(",
"numpy",
".",
"prod",
"(",
"vari",
".",
"shape",
")",
")",
"return",
"reshape",
"(",
"vari",
",",
"(",
"shape",
",",
")",
... | Flatten a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari`` with `len(Q.shape)==1`.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.flatten(P))
[1, q0, q0^2, q0^3] | [
"Flatten",
"a",
"shapeable",
"quantity",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L9-L32 | train | 206,909 |
jonathf/chaospy | chaospy/poly/shaping.py | reshape | def reshape(vari, shape):
"""
Reshape the shape of a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
shape (tuple):
The polynomials new shape. Must be compatible with the number of
elements in ``vari``.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> poly = chaospy.prange(6)
>>> print(poly)
[1, q0, q0^2, q0^3, q0^4, q0^5]
>>> print(chaospy.reshape(poly, (2,3)))
[[1, q0, q0^2], [q0^3, q0^4, q0^5]]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = reshape(core[key], shape)
out = Poly(core, vari.dim, shape, vari.dtype)
return out
return numpy.asarray(vari).reshape(shape) | python | def reshape(vari, shape):
"""
Reshape the shape of a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
shape (tuple):
The polynomials new shape. Must be compatible with the number of
elements in ``vari``.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> poly = chaospy.prange(6)
>>> print(poly)
[1, q0, q0^2, q0^3, q0^4, q0^5]
>>> print(chaospy.reshape(poly, (2,3)))
[[1, q0, q0^2], [q0^3, q0^4, q0^5]]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = reshape(core[key], shape)
out = Poly(core, vari.dim, shape, vari.dtype)
return out
return numpy.asarray(vari).reshape(shape) | [
"def",
"reshape",
"(",
"vari",
",",
"shape",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
"[",
"key",
"]",
"=",
"... | Reshape the shape of a shapeable quantity.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Shapeable input quantity.
shape (tuple):
The polynomials new shape. Must be compatible with the number of
elements in ``vari``.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> poly = chaospy.prange(6)
>>> print(poly)
[1, q0, q0^2, q0^3, q0^4, q0^5]
>>> print(chaospy.reshape(poly, (2,3)))
[[1, q0, q0^2], [q0^3, q0^4, q0^5]] | [
"Reshape",
"the",
"shape",
"of",
"a",
"shapeable",
"quantity",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L35-L65 | train | 206,910 |
jonathf/chaospy | chaospy/poly/shaping.py | rollaxis | def rollaxis(vari, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input array or polynomial.
axis (int):
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
start (int):
The axis is rolled until it lies before thes position.
"""
if isinstance(vari, Poly):
core_old = vari.A.copy()
core_new = {}
for key in vari.keys:
core_new[key] = rollaxis(core_old[key], axis, start)
return Poly(core_new, vari.dim, None, vari.dtype)
return numpy.rollaxis(vari, axis, start) | python | def rollaxis(vari, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input array or polynomial.
axis (int):
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
start (int):
The axis is rolled until it lies before thes position.
"""
if isinstance(vari, Poly):
core_old = vari.A.copy()
core_new = {}
for key in vari.keys:
core_new[key] = rollaxis(core_old[key], axis, start)
return Poly(core_new, vari.dim, None, vari.dtype)
return numpy.rollaxis(vari, axis, start) | [
"def",
"rollaxis",
"(",
"vari",
",",
"axis",
",",
"start",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core_old",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"core_new",
"=",
"{",
"}",
"for",
"key",
"in",
"var... | Roll the specified axis backwards, until it lies in a given position.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input array or polynomial.
axis (int):
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
start (int):
The axis is rolled until it lies before thes position. | [
"Roll",
"the",
"specified",
"axis",
"backwards",
"until",
"it",
"lies",
"in",
"a",
"given",
"position",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L68-L88 | train | 206,911 |
jonathf/chaospy | chaospy/poly/shaping.py | swapaxes | def swapaxes(vari, ax1, ax2):
"""Interchange two axes of a polynomial."""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = swapaxes(core[key], ax1, ax2)
return Poly(core, vari.dim, None, vari.dtype)
return numpy.swapaxes(vari, ax1, ax2) | python | def swapaxes(vari, ax1, ax2):
"""Interchange two axes of a polynomial."""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = swapaxes(core[key], ax1, ax2)
return Poly(core, vari.dim, None, vari.dtype)
return numpy.swapaxes(vari, ax1, ax2) | [
"def",
"swapaxes",
"(",
"vari",
",",
"ax1",
",",
"ax2",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
"[",
"key",
... | Interchange two axes of a polynomial. | [
"Interchange",
"two",
"axes",
"of",
"a",
"polynomial",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L91-L100 | train | 206,912 |
jonathf/chaospy | chaospy/poly/shaping.py | roll | def roll(vari, shift, axis=None):
"""Roll array elements along a given axis."""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = roll(core[key], shift, axis)
return Poly(core, vari.dim, None, vari.dtype)
return numpy.roll(vari, shift, axis) | python | def roll(vari, shift, axis=None):
"""Roll array elements along a given axis."""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = roll(core[key], shift, axis)
return Poly(core, vari.dim, None, vari.dtype)
return numpy.roll(vari, shift, axis) | [
"def",
"roll",
"(",
"vari",
",",
"shift",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
... | Roll array elements along a given axis. | [
"Roll",
"array",
"elements",
"along",
"a",
"given",
"axis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L103-L111 | train | 206,913 |
jonathf/chaospy | chaospy/poly/shaping.py | transpose | def transpose(vari):
"""
Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.transpose(P))
[[1, q0^2], [q0, q0^3]]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = transpose(core[key])
return Poly(core, vari.dim, vari.shape[::-1], vari.dtype)
return numpy.transpose(vari) | python | def transpose(vari):
"""
Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.transpose(P))
[[1, q0^2], [q0, q0^3]]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = transpose(core[key])
return Poly(core, vari.dim, vari.shape[::-1], vari.dtype)
return numpy.transpose(vari) | [
"def",
"transpose",
"(",
"vari",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
"[",
"key",
"]",
"=",
"transpose",
"(... | Transpose a shapeable quantety.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Quantety of interest.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Same type as ``vari``.
Examples:
>>> P = chaospy.reshape(chaospy.prange(4), (2,2))
>>> print(P)
[[1, q0], [q0^2, q0^3]]
>>> print(chaospy.transpose(P))
[[1, q0^2], [q0, q0^3]] | [
"Transpose",
"a",
"shapeable",
"quantety",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/shaping.py#L114-L139 | train | 206,914 |
jonathf/chaospy | chaospy/distributions/sampler/antithetic.py | create_antithetic_variates | def create_antithetic_variates(samples, axes=()):
"""
Generate antithetic variables.
Args:
samples (numpy.ndarray):
The samples, assumed to be on the [0, 1]^D hyper-cube, to be
reflected.
axes (tuple):
Boolean array of which axes to reflect. If This to limit the number
of points created in higher dimensions by reflecting all axes at
once.
Returns (numpy.ndarray):
Same as ``samples``, but with samples internally reflected. roughly
equivalent to ``numpy.vstack([samples, 1-samples])`` in one dimensions.
"""
samples = numpy.asfarray(samples)
assert numpy.all(samples <= 1) and numpy.all(samples >= 0), (
"all samples assumed on interval [0, 1].")
if len(samples.shape) == 1:
samples = samples.reshape(1, -1)
inverse_samples = 1-samples
dims = len(samples)
if not len(axes):
axes = (True,)
axes = numpy.asarray(axes, dtype=bool).flatten()
indices = {tuple(axes*idx) for idx in numpy.ndindex((2,)*dims)}
indices = sorted(indices, reverse=True)
indices = sorted(indices, key=lambda idx: sum(idx))
out = [numpy.where(idx, inverse_samples.T, samples.T).T for idx in indices]
out = numpy.dstack(out).reshape(dims, -1)
return out | python | def create_antithetic_variates(samples, axes=()):
"""
Generate antithetic variables.
Args:
samples (numpy.ndarray):
The samples, assumed to be on the [0, 1]^D hyper-cube, to be
reflected.
axes (tuple):
Boolean array of which axes to reflect. If This to limit the number
of points created in higher dimensions by reflecting all axes at
once.
Returns (numpy.ndarray):
Same as ``samples``, but with samples internally reflected. roughly
equivalent to ``numpy.vstack([samples, 1-samples])`` in one dimensions.
"""
samples = numpy.asfarray(samples)
assert numpy.all(samples <= 1) and numpy.all(samples >= 0), (
"all samples assumed on interval [0, 1].")
if len(samples.shape) == 1:
samples = samples.reshape(1, -1)
inverse_samples = 1-samples
dims = len(samples)
if not len(axes):
axes = (True,)
axes = numpy.asarray(axes, dtype=bool).flatten()
indices = {tuple(axes*idx) for idx in numpy.ndindex((2,)*dims)}
indices = sorted(indices, reverse=True)
indices = sorted(indices, key=lambda idx: sum(idx))
out = [numpy.where(idx, inverse_samples.T, samples.T).T for idx in indices]
out = numpy.dstack(out).reshape(dims, -1)
return out | [
"def",
"create_antithetic_variates",
"(",
"samples",
",",
"axes",
"=",
"(",
")",
")",
":",
"samples",
"=",
"numpy",
".",
"asfarray",
"(",
"samples",
")",
"assert",
"numpy",
".",
"all",
"(",
"samples",
"<=",
"1",
")",
"and",
"numpy",
".",
"all",
"(",
... | Generate antithetic variables.
Args:
samples (numpy.ndarray):
The samples, assumed to be on the [0, 1]^D hyper-cube, to be
reflected.
axes (tuple):
Boolean array of which axes to reflect. If This to limit the number
of points created in higher dimensions by reflecting all axes at
once.
Returns (numpy.ndarray):
Same as ``samples``, but with samples internally reflected. roughly
equivalent to ``numpy.vstack([samples, 1-samples])`` in one dimensions. | [
"Generate",
"antithetic",
"variables",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/antithetic.py#L66-L100 | train | 206,915 |
jonathf/chaospy | chaospy/poly/constructor/preprocessing.py | preprocess | def preprocess(core, dim, shape, dtype):
"""Constructor function for the Poly class."""
core, dim_, shape_, dtype_ = chaospy.poly.constructor.identify_core(core)
core, shape = chaospy.poly.constructor.ensure_shape(core, shape, shape_)
core, dtype = chaospy.poly.constructor.ensure_dtype(core, dtype, dtype_)
core, dim = chaospy.poly.constructor.ensure_dim(core, dim, dim_)
# Remove empty elements
for key in list(core.keys()):
if np.all(core[key] == 0):
del core[key]
assert isinstance(dim, int), \
"not recognised type for dim: '%s'" % repr(type(dim))
assert isinstance(shape, tuple), str(shape)
assert dtype is not None, str(dtype)
# assert non-empty container
if not core:
core = {(0,)*dim: np.zeros(shape, dtype=dtype)}
else:
core = {key: np.asarray(value, dtype) for key, value in core.items()}
return core, dim, shape, dtype | python | def preprocess(core, dim, shape, dtype):
"""Constructor function for the Poly class."""
core, dim_, shape_, dtype_ = chaospy.poly.constructor.identify_core(core)
core, shape = chaospy.poly.constructor.ensure_shape(core, shape, shape_)
core, dtype = chaospy.poly.constructor.ensure_dtype(core, dtype, dtype_)
core, dim = chaospy.poly.constructor.ensure_dim(core, dim, dim_)
# Remove empty elements
for key in list(core.keys()):
if np.all(core[key] == 0):
del core[key]
assert isinstance(dim, int), \
"not recognised type for dim: '%s'" % repr(type(dim))
assert isinstance(shape, tuple), str(shape)
assert dtype is not None, str(dtype)
# assert non-empty container
if not core:
core = {(0,)*dim: np.zeros(shape, dtype=dtype)}
else:
core = {key: np.asarray(value, dtype) for key, value in core.items()}
return core, dim, shape, dtype | [
"def",
"preprocess",
"(",
"core",
",",
"dim",
",",
"shape",
",",
"dtype",
")",
":",
"core",
",",
"dim_",
",",
"shape_",
",",
"dtype_",
"=",
"chaospy",
".",
"poly",
".",
"constructor",
".",
"identify_core",
"(",
"core",
")",
"core",
",",
"shape",
"=",... | Constructor function for the Poly class. | [
"Constructor",
"function",
"for",
"the",
"Poly",
"class",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/preprocessing.py#L9-L33 | train | 206,916 |
jonathf/chaospy | chaospy/quad/combine.py | combine | def combine(args, part=None):
"""
All linear combination of a list of list.
Args:
args (numpy.ndarray) : List of input arrays. Components to take linear
combination of with `args[i].shape=(N[i], M[i])` where N is to be
taken linear combination of and M is static. M[i] is set to 1 if
missing.
Returns:
(numpy.array) : matrix of combinations with shape (numpy.prod(N),
numpy.sum(M)).
Examples:
>>> A, B = [1,2], [[4,4],[5,6]]
>>> print(chaospy.quad.combine([A, B]))
[[1. 4. 4.]
[1. 5. 6.]
[2. 4. 4.]
[2. 5. 6.]]
"""
args = [cleanup(arg) for arg in args]
if part is not None:
parts, orders = part
if numpy.array(orders).size == 1:
orders = [int(numpy.array(orders).item())]*len(args)
parts = numpy.array(parts).flatten()
for i, arg in enumerate(args):
m, n = float(parts[i]), float(orders[i])
l = len(arg)
args[i] = arg[int(m/n*l):int((m+1)/n*l)]
shapes = [arg.shape for arg in args]
size = numpy.prod(shapes, 0)[0]*numpy.sum(shapes, 0)[1]
if size > 10**9:
raise MemoryError("Too large sets")
if len(args) == 1:
out = args[0]
elif len(args) == 2:
out = combine_two(*args)
else:
arg1 = combine_two(*args[:2])
out = combine([arg1,]+args[2:])
return out | python | def combine(args, part=None):
"""
All linear combination of a list of list.
Args:
args (numpy.ndarray) : List of input arrays. Components to take linear
combination of with `args[i].shape=(N[i], M[i])` where N is to be
taken linear combination of and M is static. M[i] is set to 1 if
missing.
Returns:
(numpy.array) : matrix of combinations with shape (numpy.prod(N),
numpy.sum(M)).
Examples:
>>> A, B = [1,2], [[4,4],[5,6]]
>>> print(chaospy.quad.combine([A, B]))
[[1. 4. 4.]
[1. 5. 6.]
[2. 4. 4.]
[2. 5. 6.]]
"""
args = [cleanup(arg) for arg in args]
if part is not None:
parts, orders = part
if numpy.array(orders).size == 1:
orders = [int(numpy.array(orders).item())]*len(args)
parts = numpy.array(parts).flatten()
for i, arg in enumerate(args):
m, n = float(parts[i]), float(orders[i])
l = len(arg)
args[i] = arg[int(m/n*l):int((m+1)/n*l)]
shapes = [arg.shape for arg in args]
size = numpy.prod(shapes, 0)[0]*numpy.sum(shapes, 0)[1]
if size > 10**9:
raise MemoryError("Too large sets")
if len(args) == 1:
out = args[0]
elif len(args) == 2:
out = combine_two(*args)
else:
arg1 = combine_two(*args[:2])
out = combine([arg1,]+args[2:])
return out | [
"def",
"combine",
"(",
"args",
",",
"part",
"=",
"None",
")",
":",
"args",
"=",
"[",
"cleanup",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"if",
"part",
"is",
"not",
"None",
":",
"parts",
",",
"orders",
"=",
"part",
"if",
"numpy",
".",
"... | All linear combination of a list of list.
Args:
args (numpy.ndarray) : List of input arrays. Components to take linear
combination of with `args[i].shape=(N[i], M[i])` where N is to be
taken linear combination of and M is static. M[i] is set to 1 if
missing.
Returns:
(numpy.array) : matrix of combinations with shape (numpy.prod(N),
numpy.sum(M)).
Examples:
>>> A, B = [1,2], [[4,4],[5,6]]
>>> print(chaospy.quad.combine([A, B]))
[[1. 4. 4.]
[1. 5. 6.]
[2. 4. 4.]
[2. 5. 6.]] | [
"All",
"linear",
"combination",
"of",
"a",
"list",
"of",
"list",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/combine.py#L8-L59 | train | 206,917 |
jonathf/chaospy | chaospy/quad/combine.py | cleanup | def cleanup(arg):
"""Clean up the input variable."""
arg = numpy.asarray(arg)
if len(arg.shape) <= 1:
arg = arg.reshape(arg.size, 1)
elif len(arg.shape) > 2:
raise ValueError("shapes must be smaller than 3")
return arg | python | def cleanup(arg):
"""Clean up the input variable."""
arg = numpy.asarray(arg)
if len(arg.shape) <= 1:
arg = arg.reshape(arg.size, 1)
elif len(arg.shape) > 2:
raise ValueError("shapes must be smaller than 3")
return arg | [
"def",
"cleanup",
"(",
"arg",
")",
":",
"arg",
"=",
"numpy",
".",
"asarray",
"(",
"arg",
")",
"if",
"len",
"(",
"arg",
".",
"shape",
")",
"<=",
"1",
":",
"arg",
"=",
"arg",
".",
"reshape",
"(",
"arg",
".",
"size",
",",
"1",
")",
"elif",
"len"... | Clean up the input variable. | [
"Clean",
"up",
"the",
"input",
"variable",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/combine.py#L71-L78 | train | 206,918 |
jonathf/chaospy | chaospy/distributions/sampler/sequences/grid.py | create_grid_samples | def create_grid_samples(order, dim=1):
"""
Create samples from a regular grid.
Args:
order (int):
The order of the grid. Defines the number of samples.
dim (int):
The number of dimensions in the grid
Returns (numpy.ndarray):
Regular grid with ``shape == (dim, order)``.
"""
x_data = numpy.arange(1, order+1)/(order+1.)
x_data = chaospy.quad.combine([x_data]*dim)
return x_data.T | python | def create_grid_samples(order, dim=1):
"""
Create samples from a regular grid.
Args:
order (int):
The order of the grid. Defines the number of samples.
dim (int):
The number of dimensions in the grid
Returns (numpy.ndarray):
Regular grid with ``shape == (dim, order)``.
"""
x_data = numpy.arange(1, order+1)/(order+1.)
x_data = chaospy.quad.combine([x_data]*dim)
return x_data.T | [
"def",
"create_grid_samples",
"(",
"order",
",",
"dim",
"=",
"1",
")",
":",
"x_data",
"=",
"numpy",
".",
"arange",
"(",
"1",
",",
"order",
"+",
"1",
")",
"/",
"(",
"order",
"+",
"1.",
")",
"x_data",
"=",
"chaospy",
".",
"quad",
".",
"combine",
"(... | Create samples from a regular grid.
Args:
order (int):
The order of the grid. Defines the number of samples.
dim (int):
The number of dimensions in the grid
Returns (numpy.ndarray):
Regular grid with ``shape == (dim, order)``. | [
"Create",
"samples",
"from",
"a",
"regular",
"grid",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/grid.py#L48-L63 | train | 206,919 |
jonathf/chaospy | chaospy/bertran/operators.py | add | def add(idxi, idxj, dim):
"""
Bertran addition.
Example
-------
>>> print(chaospy.bertran.add(3, 3, 1))
6
>>> print(chaospy.bertran.add(3, 3, 2))
10
"""
idxm = numpy.array(multi_index(idxi, dim))
idxn = numpy.array(multi_index(idxj, dim))
out = single_index(idxm + idxn)
return out | python | def add(idxi, idxj, dim):
"""
Bertran addition.
Example
-------
>>> print(chaospy.bertran.add(3, 3, 1))
6
>>> print(chaospy.bertran.add(3, 3, 2))
10
"""
idxm = numpy.array(multi_index(idxi, dim))
idxn = numpy.array(multi_index(idxj, dim))
out = single_index(idxm + idxn)
return out | [
"def",
"add",
"(",
"idxi",
",",
"idxj",
",",
"dim",
")",
":",
"idxm",
"=",
"numpy",
".",
"array",
"(",
"multi_index",
"(",
"idxi",
",",
"dim",
")",
")",
"idxn",
"=",
"numpy",
".",
"array",
"(",
"multi_index",
"(",
"idxj",
",",
"dim",
")",
")",
... | Bertran addition.
Example
-------
>>> print(chaospy.bertran.add(3, 3, 1))
6
>>> print(chaospy.bertran.add(3, 3, 2))
10 | [
"Bertran",
"addition",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L12-L26 | train | 206,920 |
jonathf/chaospy | chaospy/bertran/operators.py | terms | def terms(order, dim):
"""
Count the number of polynomials in an expansion.
Parameters
----------
order : int
The upper order for the expansion.
dim : int
The number of dimensions of the expansion.
Returns
-------
N : int
The number of terms in an expansion of upper order `M` and
number of dimensions `dim`.
"""
return int(scipy.special.comb(order+dim, dim, 1)) | python | def terms(order, dim):
"""
Count the number of polynomials in an expansion.
Parameters
----------
order : int
The upper order for the expansion.
dim : int
The number of dimensions of the expansion.
Returns
-------
N : int
The number of terms in an expansion of upper order `M` and
number of dimensions `dim`.
"""
return int(scipy.special.comb(order+dim, dim, 1)) | [
"def",
"terms",
"(",
"order",
",",
"dim",
")",
":",
"return",
"int",
"(",
"scipy",
".",
"special",
".",
"comb",
"(",
"order",
"+",
"dim",
",",
"dim",
",",
"1",
")",
")"
] | Count the number of polynomials in an expansion.
Parameters
----------
order : int
The upper order for the expansion.
dim : int
The number of dimensions of the expansion.
Returns
-------
N : int
The number of terms in an expansion of upper order `M` and
number of dimensions `dim`. | [
"Count",
"the",
"number",
"of",
"polynomials",
"in",
"an",
"expansion",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L29-L46 | train | 206,921 |
jonathf/chaospy | chaospy/bertran/operators.py | multi_index | def multi_index(idx, dim):
"""
Single to multi-index using graded reverse lexicographical notation.
Parameters
----------
idx : int
Index in interger notation
dim : int
The number of dimensions in the multi-index notation
Returns
-------
out : tuple
Multi-index of `idx` with `len(out)=dim`
Examples
--------
>>> for idx in range(5):
... print(chaospy.bertran.multi_index(idx, 3))
(0, 0, 0)
(1, 0, 0)
(0, 1, 0)
(0, 0, 1)
(2, 0, 0)
See Also
--------
single_index
"""
def _rec(idx, dim):
idxn = idxm = 0
if not dim:
return ()
if idx == 0:
return (0, )*dim
while terms(idxn, dim) <= idx:
idxn += 1
idx -= terms(idxn-1, dim)
if idx == 0:
return (idxn,) + (0,)*(dim-1)
while terms(idxm, dim-1) <= idx:
idxm += 1
return (int(idxn-idxm),) + _rec(idx, dim-1)
return _rec(idx, dim) | python | def multi_index(idx, dim):
"""
Single to multi-index using graded reverse lexicographical notation.
Parameters
----------
idx : int
Index in interger notation
dim : int
The number of dimensions in the multi-index notation
Returns
-------
out : tuple
Multi-index of `idx` with `len(out)=dim`
Examples
--------
>>> for idx in range(5):
... print(chaospy.bertran.multi_index(idx, 3))
(0, 0, 0)
(1, 0, 0)
(0, 1, 0)
(0, 0, 1)
(2, 0, 0)
See Also
--------
single_index
"""
def _rec(idx, dim):
idxn = idxm = 0
if not dim:
return ()
if idx == 0:
return (0, )*dim
while terms(idxn, dim) <= idx:
idxn += 1
idx -= terms(idxn-1, dim)
if idx == 0:
return (idxn,) + (0,)*(dim-1)
while terms(idxm, dim-1) <= idx:
idxm += 1
return (int(idxn-idxm),) + _rec(idx, dim-1)
return _rec(idx, dim) | [
"def",
"multi_index",
"(",
"idx",
",",
"dim",
")",
":",
"def",
"_rec",
"(",
"idx",
",",
"dim",
")",
":",
"idxn",
"=",
"idxm",
"=",
"0",
"if",
"not",
"dim",
":",
"return",
"(",
")",
"if",
"idx",
"==",
"0",
":",
"return",
"(",
"0",
",",
")",
... | Single to multi-index using graded reverse lexicographical notation.
Parameters
----------
idx : int
Index in interger notation
dim : int
The number of dimensions in the multi-index notation
Returns
-------
out : tuple
Multi-index of `idx` with `len(out)=dim`
Examples
--------
>>> for idx in range(5):
... print(chaospy.bertran.multi_index(idx, 3))
(0, 0, 0)
(1, 0, 0)
(0, 1, 0)
(0, 0, 1)
(2, 0, 0)
See Also
--------
single_index | [
"Single",
"to",
"multi",
"-",
"index",
"using",
"graded",
"reverse",
"lexicographical",
"notation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L49-L98 | train | 206,922 |
jonathf/chaospy | chaospy/bertran/operators.py | bindex | def bindex(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Generator for creating multi-indices.
Args:
start (int):
The lower order of the indices
stop (:py:data:typing.Optional[int]):
the maximum shape included. If omitted: stop <- start; start <- 0
If int is provided, set as largest total order. If array of int,
set as largest order along each axis.
dim (int):
The number of dimensions in the expansion
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
list:
Order list of indices.
Examples:
>>> print(chaospy.bertran.bindex(2, 3, 2))
[[2, 0], [1, 1], [0, 2], [3, 0], [2, 1], [1, 2], [0, 3]]
>>> print(chaospy.bertran.bindex(0, 1, 3))
[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
if stop is None:
start, stop = 0, start
start = numpy.array(start, dtype=int).flatten()
stop = numpy.array(stop, dtype=int).flatten()
sort = sort.upper()
total = numpy.mgrid[(slice(numpy.max(stop), -1, -1),)*dim]
total = numpy.array(total).reshape(dim, -1)
if start.size > 1:
for idx, start_ in enumerate(start):
total = total[:, total[idx] >= start_]
else:
total = total[:, total.sum(0) >= start]
if stop.size > 1:
for idx, stop_ in enumerate(stop):
total = total[:, total[idx] <= stop_]
total = total.T.tolist()
if "G" in sort:
total = sorted(total, key=sum)
else:
def cmp_(idxi, idxj):
"""Old style compare method."""
if not numpy.any(idxi):
return 0
if idxi[0] == idxj[0]:
return cmp(idxi[:-1], idxj[:-1])
return (idxi[-1] > idxj[-1]) - (idxi[-1] < idxj[-1])
key = functools.cmp_to_key(cmp_)
total = sorted(total, key=key)
if "I" in sort:
total = total[::-1]
if "R" in sort:
total = [idx[::-1] for idx in total]
for pos, idx in reversed(list(enumerate(total))):
idx = numpy.array(idx)
cross_truncation = numpy.asfarray(cross_truncation)
try:
if numpy.any(numpy.sum(idx**(1./cross_truncation)) > numpy.max(stop)**(1./cross_truncation)):
del total[pos]
except (OverflowError, ZeroDivisionError):
pass
return total | python | def bindex(start, stop=None, dim=1, sort="G", cross_truncation=1.):
"""
Generator for creating multi-indices.
Args:
start (int):
The lower order of the indices
stop (:py:data:typing.Optional[int]):
the maximum shape included. If omitted: stop <- start; start <- 0
If int is provided, set as largest total order. If array of int,
set as largest order along each axis.
dim (int):
The number of dimensions in the expansion
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
list:
Order list of indices.
Examples:
>>> print(chaospy.bertran.bindex(2, 3, 2))
[[2, 0], [1, 1], [0, 2], [3, 0], [2, 1], [1, 2], [0, 3]]
>>> print(chaospy.bertran.bindex(0, 1, 3))
[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
if stop is None:
start, stop = 0, start
start = numpy.array(start, dtype=int).flatten()
stop = numpy.array(stop, dtype=int).flatten()
sort = sort.upper()
total = numpy.mgrid[(slice(numpy.max(stop), -1, -1),)*dim]
total = numpy.array(total).reshape(dim, -1)
if start.size > 1:
for idx, start_ in enumerate(start):
total = total[:, total[idx] >= start_]
else:
total = total[:, total.sum(0) >= start]
if stop.size > 1:
for idx, stop_ in enumerate(stop):
total = total[:, total[idx] <= stop_]
total = total.T.tolist()
if "G" in sort:
total = sorted(total, key=sum)
else:
def cmp_(idxi, idxj):
"""Old style compare method."""
if not numpy.any(idxi):
return 0
if idxi[0] == idxj[0]:
return cmp(idxi[:-1], idxj[:-1])
return (idxi[-1] > idxj[-1]) - (idxi[-1] < idxj[-1])
key = functools.cmp_to_key(cmp_)
total = sorted(total, key=key)
if "I" in sort:
total = total[::-1]
if "R" in sort:
total = [idx[::-1] for idx in total]
for pos, idx in reversed(list(enumerate(total))):
idx = numpy.array(idx)
cross_truncation = numpy.asfarray(cross_truncation)
try:
if numpy.any(numpy.sum(idx**(1./cross_truncation)) > numpy.max(stop)**(1./cross_truncation)):
del total[pos]
except (OverflowError, ZeroDivisionError):
pass
return total | [
"def",
"bindex",
"(",
"start",
",",
"stop",
"=",
"None",
",",
"dim",
"=",
"1",
",",
"sort",
"=",
"\"G\"",
",",
"cross_truncation",
"=",
"1.",
")",
":",
"if",
"stop",
"is",
"None",
":",
"start",
",",
"stop",
"=",
"0",
",",
"start",
"start",
"=",
... | Generator for creating multi-indices.
Args:
start (int):
The lower order of the indices
stop (:py:data:typing.Optional[int]):
the maximum shape included. If omitted: stop <- start; start <- 0
If int is provided, set as largest total order. If array of int,
set as largest order along each axis.
dim (int):
The number of dimensions in the expansion
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
list:
Order list of indices.
Examples:
>>> print(chaospy.bertran.bindex(2, 3, 2))
[[2, 0], [1, 1], [0, 2], [3, 0], [2, 1], [1, 2], [0, 3]]
>>> print(chaospy.bertran.bindex(0, 1, 3))
[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] | [
"Generator",
"for",
"creating",
"multi",
"-",
"indices",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L101-L177 | train | 206,923 |
jonathf/chaospy | chaospy/bertran/operators.py | single_index | def single_index(idxm):
"""
Multi-index to single integer notation.
Uses graded reverse lexicographical notation.
Parameters
----------
idxm : numpy.ndarray
Index in multi-index notation
Returns
-------
idx : int
Integer index of `idxm`
Examples
--------
>>> for idx in range(3):
... print(chaospy.bertran.single_index(numpy.eye(3)[idx]))
1
2
3
"""
if -1 in idxm:
return 0
order = int(sum(idxm))
dim = len(idxm)
if order == 0:
return 0
return terms(order-1, dim) + single_index(idxm[1:]) | python | def single_index(idxm):
"""
Multi-index to single integer notation.
Uses graded reverse lexicographical notation.
Parameters
----------
idxm : numpy.ndarray
Index in multi-index notation
Returns
-------
idx : int
Integer index of `idxm`
Examples
--------
>>> for idx in range(3):
... print(chaospy.bertran.single_index(numpy.eye(3)[idx]))
1
2
3
"""
if -1 in idxm:
return 0
order = int(sum(idxm))
dim = len(idxm)
if order == 0:
return 0
return terms(order-1, dim) + single_index(idxm[1:]) | [
"def",
"single_index",
"(",
"idxm",
")",
":",
"if",
"-",
"1",
"in",
"idxm",
":",
"return",
"0",
"order",
"=",
"int",
"(",
"sum",
"(",
"idxm",
")",
")",
"dim",
"=",
"len",
"(",
"idxm",
")",
"if",
"order",
"==",
"0",
":",
"return",
"0",
"return",... | Multi-index to single integer notation.
Uses graded reverse lexicographical notation.
Parameters
----------
idxm : numpy.ndarray
Index in multi-index notation
Returns
-------
idx : int
Integer index of `idxm`
Examples
--------
>>> for idx in range(3):
... print(chaospy.bertran.single_index(numpy.eye(3)[idx]))
1
2
3 | [
"Multi",
"-",
"index",
"to",
"single",
"integer",
"notation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L180-L210 | train | 206,924 |
jonathf/chaospy | chaospy/bertran/operators.py | rank | def rank(idx, dim):
"""Calculate the index rank according to Bertran's notation."""
idxm = multi_index(idx, dim)
out = 0
while idxm[-1:] == (0,):
out += 1
idxm = idxm[:-1]
return out | python | def rank(idx, dim):
"""Calculate the index rank according to Bertran's notation."""
idxm = multi_index(idx, dim)
out = 0
while idxm[-1:] == (0,):
out += 1
idxm = idxm[:-1]
return out | [
"def",
"rank",
"(",
"idx",
",",
"dim",
")",
":",
"idxm",
"=",
"multi_index",
"(",
"idx",
",",
"dim",
")",
"out",
"=",
"0",
"while",
"idxm",
"[",
"-",
"1",
":",
"]",
"==",
"(",
"0",
",",
")",
":",
"out",
"+=",
"1",
"idxm",
"=",
"idxm",
"[",
... | Calculate the index rank according to Bertran's notation. | [
"Calculate",
"the",
"index",
"rank",
"according",
"to",
"Bertran",
"s",
"notation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L213-L220 | train | 206,925 |
jonathf/chaospy | chaospy/bertran/operators.py | parent | def parent(idx, dim, axis=None):
"""
Parent node according to Bertran's notation.
Parameters
----------
idx : int
Index of the child node.
dim : int
Dimensionality of the problem.
axis : int
Assume axis direction.
Returns
-------
out : int
Index of parent node with `j<=i`, and `j==i` iff `i==0`.
axis : int
Dimension direction the parent was found.
"""
idxm = multi_index(idx, dim)
if axis is None:
axis = dim - numpy.argmin(1*(numpy.array(idxm)[::-1] == 0))-1
if not idx:
return idx, axis
if idxm[axis] == 0:
idxi = parent(parent(idx, dim)[0], dim)[0]
while child(idxi+1, dim, axis) < idx:
idxi += 1
return idxi, axis
out = numpy.array(idxm) - 1*(numpy.eye(dim)[axis])
return single_index(out), axis | python | def parent(idx, dim, axis=None):
"""
Parent node according to Bertran's notation.
Parameters
----------
idx : int
Index of the child node.
dim : int
Dimensionality of the problem.
axis : int
Assume axis direction.
Returns
-------
out : int
Index of parent node with `j<=i`, and `j==i` iff `i==0`.
axis : int
Dimension direction the parent was found.
"""
idxm = multi_index(idx, dim)
if axis is None:
axis = dim - numpy.argmin(1*(numpy.array(idxm)[::-1] == 0))-1
if not idx:
return idx, axis
if idxm[axis] == 0:
idxi = parent(parent(idx, dim)[0], dim)[0]
while child(idxi+1, dim, axis) < idx:
idxi += 1
return idxi, axis
out = numpy.array(idxm) - 1*(numpy.eye(dim)[axis])
return single_index(out), axis | [
"def",
"parent",
"(",
"idx",
",",
"dim",
",",
"axis",
"=",
"None",
")",
":",
"idxm",
"=",
"multi_index",
"(",
"idx",
",",
"dim",
")",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"dim",
"-",
"numpy",
".",
"argmin",
"(",
"1",
"*",
"(",
"numpy",... | Parent node according to Bertran's notation.
Parameters
----------
idx : int
Index of the child node.
dim : int
Dimensionality of the problem.
axis : int
Assume axis direction.
Returns
-------
out : int
Index of parent node with `j<=i`, and `j==i` iff `i==0`.
axis : int
Dimension direction the parent was found. | [
"Parent",
"node",
"according",
"to",
"Bertran",
"s",
"notation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L223-L257 | train | 206,926 |
jonathf/chaospy | chaospy/bertran/operators.py | child | def child(idx, dim, axis):
"""
Child node according to Bertran's notation.
Parameters
----------
idx : int
Index of the parent node.
dim : int
Dimensionality of the problem.
axis : int
Dimension direction to define a child.
Must have `0<=axis<dim`
Returns
-------
out : int
Index of child node with `out > idx`.
Examples
--------
>>> print(chaospy.bertran.child(4, 1, 0))
5
>>> print(chaospy.bertran.child(4, 2, 1))
8
"""
idxm = multi_index(idx, dim)
out = numpy.array(idxm) + 1*(numpy.eye(len(idxm))[axis])
return single_index(out) | python | def child(idx, dim, axis):
"""
Child node according to Bertran's notation.
Parameters
----------
idx : int
Index of the parent node.
dim : int
Dimensionality of the problem.
axis : int
Dimension direction to define a child.
Must have `0<=axis<dim`
Returns
-------
out : int
Index of child node with `out > idx`.
Examples
--------
>>> print(chaospy.bertran.child(4, 1, 0))
5
>>> print(chaospy.bertran.child(4, 2, 1))
8
"""
idxm = multi_index(idx, dim)
out = numpy.array(idxm) + 1*(numpy.eye(len(idxm))[axis])
return single_index(out) | [
"def",
"child",
"(",
"idx",
",",
"dim",
",",
"axis",
")",
":",
"idxm",
"=",
"multi_index",
"(",
"idx",
",",
"dim",
")",
"out",
"=",
"numpy",
".",
"array",
"(",
"idxm",
")",
"+",
"1",
"*",
"(",
"numpy",
".",
"eye",
"(",
"len",
"(",
"idxm",
")"... | Child node according to Bertran's notation.
Parameters
----------
idx : int
Index of the parent node.
dim : int
Dimensionality of the problem.
axis : int
Dimension direction to define a child.
Must have `0<=axis<dim`
Returns
-------
out : int
Index of child node with `out > idx`.
Examples
--------
>>> print(chaospy.bertran.child(4, 1, 0))
5
>>> print(chaospy.bertran.child(4, 2, 1))
8 | [
"Child",
"node",
"according",
"to",
"Bertran",
"s",
"notation",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/operators.py#L260-L288 | train | 206,927 |
jonathf/chaospy | chaospy/poly/constructor/ensurance.py | ensure_shape | def ensure_shape(core, shape, shape_):
"""Ensure shape is correct."""
core = core.copy()
if shape is None:
shape = shape_
elif isinstance(shape, int):
shape = (shape,)
if tuple(shape) == tuple(shape_):
return core, shape
ones = np.ones(shape, dtype=int)
for key, val in core.items():
core[key] = val*ones
return core, shape | python | def ensure_shape(core, shape, shape_):
"""Ensure shape is correct."""
core = core.copy()
if shape is None:
shape = shape_
elif isinstance(shape, int):
shape = (shape,)
if tuple(shape) == tuple(shape_):
return core, shape
ones = np.ones(shape, dtype=int)
for key, val in core.items():
core[key] = val*ones
return core, shape | [
"def",
"ensure_shape",
"(",
"core",
",",
"shape",
",",
"shape_",
")",
":",
"core",
"=",
"core",
".",
"copy",
"(",
")",
"if",
"shape",
"is",
"None",
":",
"shape",
"=",
"shape_",
"elif",
"isinstance",
"(",
"shape",
",",
"int",
")",
":",
"shape",
"=",... | Ensure shape is correct. | [
"Ensure",
"shape",
"is",
"correct",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/ensurance.py#L10-L25 | train | 206,928 |
jonathf/chaospy | chaospy/poly/constructor/ensurance.py | ensure_dtype | def ensure_dtype(core, dtype, dtype_):
"""Ensure dtype is correct."""
core = core.copy()
if dtype is None:
dtype = dtype_
if dtype_ == dtype:
return core, dtype
for key, val in {
int: chaospy.poly.typing.asint,
float: chaospy.poly.typing.asfloat,
np.float32: chaospy.poly.typing.asfloat,
np.float64: chaospy.poly.typing.asfloat,
}.items():
if dtype == key:
converter = val
break
else:
raise ValueError("dtype not recognised (%s)" % str(dtype))
for key, val in core.items():
core[key] = converter(val)
return core, dtype | python | def ensure_dtype(core, dtype, dtype_):
"""Ensure dtype is correct."""
core = core.copy()
if dtype is None:
dtype = dtype_
if dtype_ == dtype:
return core, dtype
for key, val in {
int: chaospy.poly.typing.asint,
float: chaospy.poly.typing.asfloat,
np.float32: chaospy.poly.typing.asfloat,
np.float64: chaospy.poly.typing.asfloat,
}.items():
if dtype == key:
converter = val
break
else:
raise ValueError("dtype not recognised (%s)" % str(dtype))
for key, val in core.items():
core[key] = converter(val)
return core, dtype | [
"def",
"ensure_dtype",
"(",
"core",
",",
"dtype",
",",
"dtype_",
")",
":",
"core",
"=",
"core",
".",
"copy",
"(",
")",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"dtype_",
"if",
"dtype_",
"==",
"dtype",
":",
"return",
"core",
",",
"dtype",
"fo... | Ensure dtype is correct. | [
"Ensure",
"dtype",
"is",
"correct",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/ensurance.py#L28-L52 | train | 206,929 |
jonathf/chaospy | chaospy/poly/constructor/ensurance.py | ensure_dim | def ensure_dim(core, dim, dim_):
"""Ensure that dim is correct."""
if dim is None:
dim = dim_
if not dim:
return core, 1
if dim_ == dim:
return core, int(dim)
if dim > dim_:
key_convert = lambda vari: vari[:dim_]
else:
key_convert = lambda vari: vari + (0,)*(dim-dim_)
new_core = {}
for key, val in core.items():
key_ = key_convert(key)
if key_ in new_core:
new_core[key_] += val
else:
new_core[key_] = val
return new_core, int(dim) | python | def ensure_dim(core, dim, dim_):
"""Ensure that dim is correct."""
if dim is None:
dim = dim_
if not dim:
return core, 1
if dim_ == dim:
return core, int(dim)
if dim > dim_:
key_convert = lambda vari: vari[:dim_]
else:
key_convert = lambda vari: vari + (0,)*(dim-dim_)
new_core = {}
for key, val in core.items():
key_ = key_convert(key)
if key_ in new_core:
new_core[key_] += val
else:
new_core[key_] = val
return new_core, int(dim) | [
"def",
"ensure_dim",
"(",
"core",
",",
"dim",
",",
"dim_",
")",
":",
"if",
"dim",
"is",
"None",
":",
"dim",
"=",
"dim_",
"if",
"not",
"dim",
":",
"return",
"core",
",",
"1",
"if",
"dim_",
"==",
"dim",
":",
"return",
"core",
",",
"int",
"(",
"di... | Ensure that dim is correct. | [
"Ensure",
"that",
"dim",
"is",
"correct",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/constructor/ensurance.py#L55-L77 | train | 206,930 |
jonathf/chaospy | chaospy/poly/base.py | sort_key | def sort_key(val):
"""Sort key for sorting keys in grevlex order."""
return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val) | python | def sort_key(val):
"""Sort key for sorting keys in grevlex order."""
return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val) | [
"def",
"sort_key",
"(",
"val",
")",
":",
"return",
"numpy",
".",
"sum",
"(",
"(",
"max",
"(",
"val",
")",
"+",
"1",
")",
"**",
"numpy",
".",
"arange",
"(",
"len",
"(",
"val",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
"*",
"val",
"... | Sort key for sorting keys in grevlex order. | [
"Sort",
"key",
"for",
"sorting",
"keys",
"in",
"grevlex",
"order",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/base.py#L411-L413 | train | 206,931 |
jonathf/chaospy | chaospy/poly/base.py | Poly.copy | def copy(self):
"""Return a copy of the polynomial."""
return Poly(self.A.copy(), self.dim, self.shape,
self.dtype) | python | def copy(self):
"""Return a copy of the polynomial."""
return Poly(self.A.copy(), self.dim, self.shape,
self.dtype) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"Poly",
"(",
"self",
".",
"A",
".",
"copy",
"(",
")",
",",
"self",
".",
"dim",
",",
"self",
".",
"shape",
",",
"self",
".",
"dtype",
")"
] | Return a copy of the polynomial. | [
"Return",
"a",
"copy",
"of",
"the",
"polynomial",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/base.py#L392-L395 | train | 206,932 |
jonathf/chaospy | chaospy/poly/base.py | Poly.coefficients | def coefficients(self):
"""Polynomial coefficients."""
out = numpy.array([self.A[key] for key in self.keys])
out = numpy.rollaxis(out, -1)
return out | python | def coefficients(self):
"""Polynomial coefficients."""
out = numpy.array([self.A[key] for key in self.keys])
out = numpy.rollaxis(out, -1)
return out | [
"def",
"coefficients",
"(",
"self",
")",
":",
"out",
"=",
"numpy",
".",
"array",
"(",
"[",
"self",
".",
"A",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"keys",
"]",
")",
"out",
"=",
"numpy",
".",
"rollaxis",
"(",
"out",
",",
"-",
"1",
... | Polynomial coefficients. | [
"Polynomial",
"coefficients",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/base.py#L398-L402 | train | 206,933 |
jonathf/chaospy | chaospy/descriptives/quantity_of_interest.py | QoI_Dist | def QoI_Dist(poly, dist, sample=10000, **kws):
"""
Constructs distributions for the quantity of interests.
The function constructs a kernel density estimator (KDE) for each
polynomial (poly) by sampling it. With the KDEs, distributions (Dists) are
constructed. The Dists can be used for e.g. plotting probability density
functions (PDF), or to make a second uncertainty quantification simulation
with that newly generated Dists.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where the samples for the KDE is taken from the
poly.
sample (int):
Number of samples used in estimation to construct the KDE.
Returns:
(numpy.ndarray):
The constructed quantity of interest (QoI) distributions, where
``qoi_dists.shape==poly.shape``.
Examples:
>>> dist = chaospy.Normal(0, 1)
>>> x = chaospy.variable(1)
>>> poly = chaospy.Poly([x])
>>> qoi_dist = chaospy.QoI_Dist(poly, dist)
>>> values = qoi_dist[0].pdf([-0.75, 0., 0.75])
>>> print(numpy.around(values, 8))
[0.29143037 0.39931708 0.29536329]
"""
shape = poly.shape
poly = polynomials.flatten(poly)
dim = len(dist)
#sample from the inumpyut dist
samples = dist.sample(sample, **kws)
qoi_dists = []
for i in range(0, len(poly)):
#sample the polynomial solution
if dim == 1:
dataset = poly[i](samples)
else:
dataset = poly[i](*samples)
lo = dataset.min()
up = dataset.max()
#creates qoi_dist
qoi_dist = distributions.SampleDist(dataset, lo, up)
qoi_dists.append(qoi_dist)
#reshape the qoi_dists to match the shape of the inumpyut poly
qoi_dists = numpy.array(qoi_dists, distributions.Dist)
qoi_dists = qoi_dists.reshape(shape)
if not shape:
qoi_dists = qoi_dists.item()
return qoi_dists | python | def QoI_Dist(poly, dist, sample=10000, **kws):
"""
Constructs distributions for the quantity of interests.
The function constructs a kernel density estimator (KDE) for each
polynomial (poly) by sampling it. With the KDEs, distributions (Dists) are
constructed. The Dists can be used for e.g. plotting probability density
functions (PDF), or to make a second uncertainty quantification simulation
with that newly generated Dists.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where the samples for the KDE is taken from the
poly.
sample (int):
Number of samples used in estimation to construct the KDE.
Returns:
(numpy.ndarray):
The constructed quantity of interest (QoI) distributions, where
``qoi_dists.shape==poly.shape``.
Examples:
>>> dist = chaospy.Normal(0, 1)
>>> x = chaospy.variable(1)
>>> poly = chaospy.Poly([x])
>>> qoi_dist = chaospy.QoI_Dist(poly, dist)
>>> values = qoi_dist[0].pdf([-0.75, 0., 0.75])
>>> print(numpy.around(values, 8))
[0.29143037 0.39931708 0.29536329]
"""
shape = poly.shape
poly = polynomials.flatten(poly)
dim = len(dist)
#sample from the inumpyut dist
samples = dist.sample(sample, **kws)
qoi_dists = []
for i in range(0, len(poly)):
#sample the polynomial solution
if dim == 1:
dataset = poly[i](samples)
else:
dataset = poly[i](*samples)
lo = dataset.min()
up = dataset.max()
#creates qoi_dist
qoi_dist = distributions.SampleDist(dataset, lo, up)
qoi_dists.append(qoi_dist)
#reshape the qoi_dists to match the shape of the inumpyut poly
qoi_dists = numpy.array(qoi_dists, distributions.Dist)
qoi_dists = qoi_dists.reshape(shape)
if not shape:
qoi_dists = qoi_dists.item()
return qoi_dists | [
"def",
"QoI_Dist",
"(",
"poly",
",",
"dist",
",",
"sample",
"=",
"10000",
",",
"*",
"*",
"kws",
")",
":",
"shape",
"=",
"poly",
".",
"shape",
"poly",
"=",
"polynomials",
".",
"flatten",
"(",
"poly",
")",
"dim",
"=",
"len",
"(",
"dist",
")",
"#sam... | Constructs distributions for the quantity of interests.
The function constructs a kernel density estimator (KDE) for each
polynomial (poly) by sampling it. With the KDEs, distributions (Dists) are
constructed. The Dists can be used for e.g. plotting probability density
functions (PDF), or to make a second uncertainty quantification simulation
with that newly generated Dists.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where the samples for the KDE is taken from the
poly.
sample (int):
Number of samples used in estimation to construct the KDE.
Returns:
(numpy.ndarray):
The constructed quantity of interest (QoI) distributions, where
``qoi_dists.shape==poly.shape``.
Examples:
>>> dist = chaospy.Normal(0, 1)
>>> x = chaospy.variable(1)
>>> poly = chaospy.Poly([x])
>>> qoi_dist = chaospy.QoI_Dist(poly, dist)
>>> values = qoi_dist[0].pdf([-0.75, 0., 0.75])
>>> print(numpy.around(values, 8))
[0.29143037 0.39931708 0.29536329] | [
"Constructs",
"distributions",
"for",
"the",
"quantity",
"of",
"interests",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/quantity_of_interest.py#L6-L68 | train | 206,934 |
jonathf/chaospy | chaospy/quad/collection/gauss_legendre.py | quad_gauss_legendre | def quad_gauss_legendre(order, lower=0, upper=1, composite=None):
"""
Generate the quadrature nodes and weights in Gauss-Legendre quadrature.
Example:
>>> abscissas, weights = quad_gauss_legendre(3)
>>> print(numpy.around(abscissas, 4))
[[0.0694 0.33 0.67 0.9306]]
>>> print(numpy.around(weights, 4))
[0.1739 0.3261 0.3261 0.1739]
"""
order = numpy.asarray(order, dtype=int).flatten()
lower = numpy.asarray(lower).flatten()
upper = numpy.asarray(upper).flatten()
dim = max(lower.size, upper.size, order.size)
order = numpy.ones(dim, dtype=int)*order
lower = numpy.ones(dim)*lower
upper = numpy.ones(dim)*upper
if composite is None:
composite = numpy.array(0)
composite = numpy.asarray(composite)
if not composite.size:
composite = numpy.array([numpy.linspace(0, 1, composite+1)]*dim)
else:
composite = numpy.array(composite)
if len(composite.shape) <= 1:
composite = numpy.transpose([composite])
composite = ((composite.T-lower)/(upper-lower)).T
results = [_gauss_legendre(order[i], composite[i]) for i in range(dim)]
abscis = numpy.array([_[0] for _ in results])
weights = numpy.array([_[1] for _ in results])
abscis = chaospy.quad.combine(abscis)
weights = chaospy.quad.combine(weights)
abscis = (upper-lower)*abscis + lower
weights = numpy.prod(weights*(upper-lower), 1)
return abscis.T, weights | python | def quad_gauss_legendre(order, lower=0, upper=1, composite=None):
"""
Generate the quadrature nodes and weights in Gauss-Legendre quadrature.
Example:
>>> abscissas, weights = quad_gauss_legendre(3)
>>> print(numpy.around(abscissas, 4))
[[0.0694 0.33 0.67 0.9306]]
>>> print(numpy.around(weights, 4))
[0.1739 0.3261 0.3261 0.1739]
"""
order = numpy.asarray(order, dtype=int).flatten()
lower = numpy.asarray(lower).flatten()
upper = numpy.asarray(upper).flatten()
dim = max(lower.size, upper.size, order.size)
order = numpy.ones(dim, dtype=int)*order
lower = numpy.ones(dim)*lower
upper = numpy.ones(dim)*upper
if composite is None:
composite = numpy.array(0)
composite = numpy.asarray(composite)
if not composite.size:
composite = numpy.array([numpy.linspace(0, 1, composite+1)]*dim)
else:
composite = numpy.array(composite)
if len(composite.shape) <= 1:
composite = numpy.transpose([composite])
composite = ((composite.T-lower)/(upper-lower)).T
results = [_gauss_legendre(order[i], composite[i]) for i in range(dim)]
abscis = numpy.array([_[0] for _ in results])
weights = numpy.array([_[1] for _ in results])
abscis = chaospy.quad.combine(abscis)
weights = chaospy.quad.combine(weights)
abscis = (upper-lower)*abscis + lower
weights = numpy.prod(weights*(upper-lower), 1)
return abscis.T, weights | [
"def",
"quad_gauss_legendre",
"(",
"order",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"1",
",",
"composite",
"=",
"None",
")",
":",
"order",
"=",
"numpy",
".",
"asarray",
"(",
"order",
",",
"dtype",
"=",
"int",
")",
".",
"flatten",
"(",
")",
"lowe... | Generate the quadrature nodes and weights in Gauss-Legendre quadrature.
Example:
>>> abscissas, weights = quad_gauss_legendre(3)
>>> print(numpy.around(abscissas, 4))
[[0.0694 0.33 0.67 0.9306]]
>>> print(numpy.around(weights, 4))
[0.1739 0.3261 0.3261 0.1739] | [
"Generate",
"the",
"quadrature",
"nodes",
"and",
"weights",
"in",
"Gauss",
"-",
"Legendre",
"quadrature",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/gauss_legendre.py#L48-L91 | train | 206,935 |
jonathf/chaospy | chaospy/quad/collection/gauss_legendre.py | _gauss_legendre | def _gauss_legendre(order, composite=1):
"""Backend function."""
inner = numpy.ones(order+1)*0.5
outer = numpy.arange(order+1)**2
outer = outer/(16*outer-4.)
banded = numpy.diag(numpy.sqrt(outer[1:]), k=-1) + numpy.diag(inner) + \
numpy.diag(numpy.sqrt(outer[1:]), k=1)
vals, vecs = numpy.linalg.eig(banded)
abscis, weight = vals.real, vecs[0, :]**2
indices = numpy.argsort(abscis)
abscis, weight = abscis[indices], weight[indices]
n_abscis = len(abscis)
composite = numpy.array(composite).flatten()
composite = list(set(composite))
composite = [comp for comp in composite if (comp < 1) and (comp > 0)]
composite.sort()
composite = [0]+composite+[1]
abscissas = numpy.empty(n_abscis*(len(composite)-1))
weights = numpy.empty(n_abscis*(len(composite)-1))
for dim in range(len(composite)-1):
abscissas[dim*n_abscis:(dim+1)*n_abscis] = \
abscis*(composite[dim+1]-composite[dim]) + composite[dim]
weights[dim*n_abscis:(dim+1)*n_abscis] = \
weight*(composite[dim+1]-composite[dim])
return abscissas, weights | python | def _gauss_legendre(order, composite=1):
"""Backend function."""
inner = numpy.ones(order+1)*0.5
outer = numpy.arange(order+1)**2
outer = outer/(16*outer-4.)
banded = numpy.diag(numpy.sqrt(outer[1:]), k=-1) + numpy.diag(inner) + \
numpy.diag(numpy.sqrt(outer[1:]), k=1)
vals, vecs = numpy.linalg.eig(banded)
abscis, weight = vals.real, vecs[0, :]**2
indices = numpy.argsort(abscis)
abscis, weight = abscis[indices], weight[indices]
n_abscis = len(abscis)
composite = numpy.array(composite).flatten()
composite = list(set(composite))
composite = [comp for comp in composite if (comp < 1) and (comp > 0)]
composite.sort()
composite = [0]+composite+[1]
abscissas = numpy.empty(n_abscis*(len(composite)-1))
weights = numpy.empty(n_abscis*(len(composite)-1))
for dim in range(len(composite)-1):
abscissas[dim*n_abscis:(dim+1)*n_abscis] = \
abscis*(composite[dim+1]-composite[dim]) + composite[dim]
weights[dim*n_abscis:(dim+1)*n_abscis] = \
weight*(composite[dim+1]-composite[dim])
return abscissas, weights | [
"def",
"_gauss_legendre",
"(",
"order",
",",
"composite",
"=",
"1",
")",
":",
"inner",
"=",
"numpy",
".",
"ones",
"(",
"order",
"+",
"1",
")",
"*",
"0.5",
"outer",
"=",
"numpy",
".",
"arange",
"(",
"order",
"+",
"1",
")",
"**",
"2",
"outer",
"=",... | Backend function. | [
"Backend",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/gauss_legendre.py#L94-L124 | train | 206,936 |
jonathf/chaospy | chaospy/quad/collection/gauss_patterson.py | quad_gauss_patterson | def quad_gauss_patterson(order, dist):
"""
Generate sets abscissas and weights for Gauss-Patterson quadrature.
Args:
order (int) : The quadrature order. Must be in the interval (0, 8).
dist (Dist) : The domain to create quadrature over.
Returns:
(numpy.ndarray, numpy.ndarray) : Abscissas and weights.
Example:
>>> X, W = chaospy.quad_gauss_patterson(3, chaospy.Uniform(0, 1))
>>> print(numpy.around(X, 4))
[[0.0031 0.0198 0.0558 0.1127 0.1894 0.2829 0.3883 0.5 0.6117 0.7171
0.8106 0.8873 0.9442 0.9802 0.9969]]
>>> print(numpy.around(W, 4))
[0.0085 0.0258 0.0465 0.0672 0.0858 0.1003 0.1096 0.1128 0.1096 0.1003
0.0858 0.0672 0.0465 0.0258 0.0085]
Reference:
Prem Kythe, Michael Schaeferkotter,
Handbook of Computational Methods for Integration,
Chapman and Hall, 2004,
ISBN: 1-58488-428-2,
LC: QA299.3.K98.
Thomas Patterson,
The Optimal Addition of Points to Quadrature Formulae,
Mathematics of Computation,
Volume 22, Number 104, October 1968, pages 847-856.
"""
if len(dist) > 1:
if isinstance(order, int):
values = [quad_gauss_patterson(order, d) for d in dist]
else:
values = [quad_gauss_patterson(order[i], dist[i])
for i in range(len(dist))]
abscissas = [_[0][0] for _ in values]
weights = [_[1] for _ in values]
abscissas = chaospy.quad.combine(abscissas).T
weights = numpy.prod(chaospy.quad.combine(weights), -1)
return abscissas, weights
order = sorted(PATTERSON_VALUES.keys())[order]
abscissas, weights = PATTERSON_VALUES[order]
lower, upper = dist.range()
abscissas = .5*(abscissas*(upper-lower)+upper+lower)
abscissas = abscissas.reshape(1, abscissas.size)
weights /= numpy.sum(weights)
return abscissas, weights | python | def quad_gauss_patterson(order, dist):
"""
Generate sets abscissas and weights for Gauss-Patterson quadrature.
Args:
order (int) : The quadrature order. Must be in the interval (0, 8).
dist (Dist) : The domain to create quadrature over.
Returns:
(numpy.ndarray, numpy.ndarray) : Abscissas and weights.
Example:
>>> X, W = chaospy.quad_gauss_patterson(3, chaospy.Uniform(0, 1))
>>> print(numpy.around(X, 4))
[[0.0031 0.0198 0.0558 0.1127 0.1894 0.2829 0.3883 0.5 0.6117 0.7171
0.8106 0.8873 0.9442 0.9802 0.9969]]
>>> print(numpy.around(W, 4))
[0.0085 0.0258 0.0465 0.0672 0.0858 0.1003 0.1096 0.1128 0.1096 0.1003
0.0858 0.0672 0.0465 0.0258 0.0085]
Reference:
Prem Kythe, Michael Schaeferkotter,
Handbook of Computational Methods for Integration,
Chapman and Hall, 2004,
ISBN: 1-58488-428-2,
LC: QA299.3.K98.
Thomas Patterson,
The Optimal Addition of Points to Quadrature Formulae,
Mathematics of Computation,
Volume 22, Number 104, October 1968, pages 847-856.
"""
if len(dist) > 1:
if isinstance(order, int):
values = [quad_gauss_patterson(order, d) for d in dist]
else:
values = [quad_gauss_patterson(order[i], dist[i])
for i in range(len(dist))]
abscissas = [_[0][0] for _ in values]
weights = [_[1] for _ in values]
abscissas = chaospy.quad.combine(abscissas).T
weights = numpy.prod(chaospy.quad.combine(weights), -1)
return abscissas, weights
order = sorted(PATTERSON_VALUES.keys())[order]
abscissas, weights = PATTERSON_VALUES[order]
lower, upper = dist.range()
abscissas = .5*(abscissas*(upper-lower)+upper+lower)
abscissas = abscissas.reshape(1, abscissas.size)
weights /= numpy.sum(weights)
return abscissas, weights | [
"def",
"quad_gauss_patterson",
"(",
"order",
",",
"dist",
")",
":",
"if",
"len",
"(",
"dist",
")",
">",
"1",
":",
"if",
"isinstance",
"(",
"order",
",",
"int",
")",
":",
"values",
"=",
"[",
"quad_gauss_patterson",
"(",
"order",
",",
"d",
")",
"for",
... | Generate sets abscissas and weights for Gauss-Patterson quadrature.
Args:
order (int) : The quadrature order. Must be in the interval (0, 8).
dist (Dist) : The domain to create quadrature over.
Returns:
(numpy.ndarray, numpy.ndarray) : Abscissas and weights.
Example:
>>> X, W = chaospy.quad_gauss_patterson(3, chaospy.Uniform(0, 1))
>>> print(numpy.around(X, 4))
[[0.0031 0.0198 0.0558 0.1127 0.1894 0.2829 0.3883 0.5 0.6117 0.7171
0.8106 0.8873 0.9442 0.9802 0.9969]]
>>> print(numpy.around(W, 4))
[0.0085 0.0258 0.0465 0.0672 0.0858 0.1003 0.1096 0.1128 0.1096 0.1003
0.0858 0.0672 0.0465 0.0258 0.0085]
Reference:
Prem Kythe, Michael Schaeferkotter,
Handbook of Computational Methods for Integration,
Chapman and Hall, 2004,
ISBN: 1-58488-428-2,
LC: QA299.3.K98.
Thomas Patterson,
The Optimal Addition of Points to Quadrature Formulae,
Mathematics of Computation,
Volume 22, Number 104, October 1968, pages 847-856. | [
"Generate",
"sets",
"abscissas",
"and",
"weights",
"for",
"Gauss",
"-",
"Patterson",
"quadrature",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/gauss_patterson.py#L16-L72 | train | 206,937 |
jonathf/chaospy | chaospy/quad/interface.py | generate_quadrature | def generate_quadrature(
order, domain, accuracy=100, sparse=False, rule="C",
composite=1, growth=None, part=None, normalize=False, **kws
):
"""
Numerical quadrature node and weight generator.
Args:
order (int):
The order of the quadrature.
domain (numpy.ndarray, Dist):
If array is provided domain is the lower and upper bounds (lo,up).
Invalid if gaussian is set. If Dist is provided, bounds and nodes
are adapted to the distribution. This includes weighting the nodes
in Clenshaw-Curtis quadrature.
accuracy (int):
If gaussian is set, but the Dist provieded in domain does not
provide an analytical TTR, ac sets the approximation order for the
descitized Stieltje's method.
sparse (bool):
If True used Smolyak's sparse grid instead of normal tensor product
grid.
rule (str):
Rule for generating abscissas and weights. Either done with
quadrature rules, or with random samples with constant weights.
composite (int):
If provided, composite quadrature will be used. Value determines
the number of domains along an axis. Ignored in the case
gaussian=True.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
growth (bool):
If True sets the growth rule for the composite quadrature rule to
exponential for Clenshaw-Curtis quadrature.
"""
from ..distributions.baseclass import Dist
isdist = isinstance(domain, Dist)
if isdist:
dim = len(domain)
else:
dim = np.array(domain[0]).size
rule = rule.lower()
if len(rule) == 1:
rule = collection.QUAD_SHORT_NAMES[rule]
quad_function = collection.get_function(
rule,
domain,
normalize,
growth=growth,
composite=composite,
accuracy=accuracy,
)
if sparse:
order = np.ones(len(domain), dtype=int)*order
abscissas, weights = sparse_grid.sparse_grid(quad_function, order, dim)
else:
abscissas, weights = quad_function(order)
assert len(weights) == abscissas.shape[1]
assert len(abscissas.shape) == 2
return abscissas, weights | python | def generate_quadrature(
order, domain, accuracy=100, sparse=False, rule="C",
composite=1, growth=None, part=None, normalize=False, **kws
):
"""
Numerical quadrature node and weight generator.
Args:
order (int):
The order of the quadrature.
domain (numpy.ndarray, Dist):
If array is provided domain is the lower and upper bounds (lo,up).
Invalid if gaussian is set. If Dist is provided, bounds and nodes
are adapted to the distribution. This includes weighting the nodes
in Clenshaw-Curtis quadrature.
accuracy (int):
If gaussian is set, but the Dist provieded in domain does not
provide an analytical TTR, ac sets the approximation order for the
descitized Stieltje's method.
sparse (bool):
If True used Smolyak's sparse grid instead of normal tensor product
grid.
rule (str):
Rule for generating abscissas and weights. Either done with
quadrature rules, or with random samples with constant weights.
composite (int):
If provided, composite quadrature will be used. Value determines
the number of domains along an axis. Ignored in the case
gaussian=True.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
growth (bool):
If True sets the growth rule for the composite quadrature rule to
exponential for Clenshaw-Curtis quadrature.
"""
from ..distributions.baseclass import Dist
isdist = isinstance(domain, Dist)
if isdist:
dim = len(domain)
else:
dim = np.array(domain[0]).size
rule = rule.lower()
if len(rule) == 1:
rule = collection.QUAD_SHORT_NAMES[rule]
quad_function = collection.get_function(
rule,
domain,
normalize,
growth=growth,
composite=composite,
accuracy=accuracy,
)
if sparse:
order = np.ones(len(domain), dtype=int)*order
abscissas, weights = sparse_grid.sparse_grid(quad_function, order, dim)
else:
abscissas, weights = quad_function(order)
assert len(weights) == abscissas.shape[1]
assert len(abscissas.shape) == 2
return abscissas, weights | [
"def",
"generate_quadrature",
"(",
"order",
",",
"domain",
",",
"accuracy",
"=",
"100",
",",
"sparse",
"=",
"False",
",",
"rule",
"=",
"\"C\"",
",",
"composite",
"=",
"1",
",",
"growth",
"=",
"None",
",",
"part",
"=",
"None",
",",
"normalize",
"=",
"... | Numerical quadrature node and weight generator.
Args:
order (int):
The order of the quadrature.
domain (numpy.ndarray, Dist):
If array is provided domain is the lower and upper bounds (lo,up).
Invalid if gaussian is set. If Dist is provided, bounds and nodes
are adapted to the distribution. This includes weighting the nodes
in Clenshaw-Curtis quadrature.
accuracy (int):
If gaussian is set, but the Dist provieded in domain does not
provide an analytical TTR, ac sets the approximation order for the
descitized Stieltje's method.
sparse (bool):
If True used Smolyak's sparse grid instead of normal tensor product
grid.
rule (str):
Rule for generating abscissas and weights. Either done with
quadrature rules, or with random samples with constant weights.
composite (int):
If provided, composite quadrature will be used. Value determines
the number of domains along an axis. Ignored in the case
gaussian=True.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
growth (bool):
If True sets the growth rule for the composite quadrature rule to
exponential for Clenshaw-Curtis quadrature. | [
"Numerical",
"quadrature",
"node",
"and",
"weight",
"generator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/interface.py#L10-L79 | train | 206,938 |
jonathf/chaospy | chaospy/distributions/collection/deprecate.py | deprecation_warning | def deprecation_warning(func, name):
"""Add a deprecation warning do each distribution."""
@wraps(func)
def caller(*args, **kwargs):
"""Docs to be replaced."""
logger = logging.getLogger(__name__)
instance = func(*args, **kwargs)
logger.warning(
"Distribution `chaospy.{}` has been renamed to ".format(name) +
"`chaospy.{}` and will be deprecated next release.".format(instance.__class__.__name__))
return instance
return caller | python | def deprecation_warning(func, name):
"""Add a deprecation warning do each distribution."""
@wraps(func)
def caller(*args, **kwargs):
"""Docs to be replaced."""
logger = logging.getLogger(__name__)
instance = func(*args, **kwargs)
logger.warning(
"Distribution `chaospy.{}` has been renamed to ".format(name) +
"`chaospy.{}` and will be deprecated next release.".format(instance.__class__.__name__))
return instance
return caller | [
"def",
"deprecation_warning",
"(",
"func",
",",
"name",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"caller",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Docs to be replaced.\"\"\"",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"... | Add a deprecation warning do each distribution. | [
"Add",
"a",
"deprecation",
"warning",
"do",
"each",
"distribution",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/collection/deprecate.py#L6-L17 | train | 206,939 |
jonathf/chaospy | chaospy/descriptives/conditional.py | E_cond | def E_cond(poly, freeze, dist, **kws):
"""
Conditional expected value operator.
1st order statistics of a polynomial on a given probability space
conditioned on some of the variables.
Args:
poly (Poly):
Polynomial to find conditional expected value on.
freeze (numpy.ndarray):
Boolean values defining the conditional variables. True values
implies that the value is conditioned on, e.g. frozen during the
expected value calculation.
dist (Dist) :
The distributions of the input used in ``poly``.
Returns:
(chaospy.poly.base.Poly) :
Same as ``poly``, but with the variables not tagged in ``frozen``
integrated away.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(chaospy.E_cond(poly, [1, 0], dist))
[1.0, q0, 0.0, 0.0]
>>> print(chaospy.E_cond(poly, [0, 1], dist))
[1.0, 1.0, q1, 10.0q1]
>>> print(chaospy.E_cond(poly, [1, 1], dist))
[1.0, q0, q1, 10.0q0q1]
>>> print(chaospy.E_cond(poly, [0, 0], dist))
[1.0, 1.0, 0.0, 0.0]
"""
if poly.dim < len(dist):
poly = polynomials.setdim(poly, len(dist))
freeze = polynomials.Poly(freeze)
freeze = polynomials.setdim(freeze, len(dist))
keys = freeze.keys
if len(keys) == 1 and keys[0] == (0,)*len(dist):
freeze = list(freeze.A.values())[0]
else:
freeze = numpy.array(keys)
freeze = freeze.reshape(int(freeze.size/len(dist)), len(dist))
shape = poly.shape
poly = polynomials.flatten(poly)
kmax = numpy.max(poly.keys, 0) + 1
keys = [range(k) for k in kmax]
A = poly.A.copy()
keys = poly.keys
out = {}
zeros = [0]*poly.dim
for i in range(len(keys)):
key = list(keys[i])
a = A[tuple(key)]
for d in range(poly.dim):
for j in range(len(freeze)):
if freeze[j, d]:
key[d], zeros[d] = zeros[d], key[d]
break
tmp = a*dist.mom(tuple(key))
if tuple(zeros) in out:
out[tuple(zeros)] = out[tuple(zeros)] + tmp
else:
out[tuple(zeros)] = tmp
for d in range(poly.dim):
for j in range(len(freeze)):
if freeze[j, d]:
key[d], zeros[d] = zeros[d], key[d]
break
out = polynomials.Poly(out, poly.dim, poly.shape, float)
out = polynomials.reshape(out, shape)
return out | python | def E_cond(poly, freeze, dist, **kws):
"""
Conditional expected value operator.
1st order statistics of a polynomial on a given probability space
conditioned on some of the variables.
Args:
poly (Poly):
Polynomial to find conditional expected value on.
freeze (numpy.ndarray):
Boolean values defining the conditional variables. True values
implies that the value is conditioned on, e.g. frozen during the
expected value calculation.
dist (Dist) :
The distributions of the input used in ``poly``.
Returns:
(chaospy.poly.base.Poly) :
Same as ``poly``, but with the variables not tagged in ``frozen``
integrated away.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(chaospy.E_cond(poly, [1, 0], dist))
[1.0, q0, 0.0, 0.0]
>>> print(chaospy.E_cond(poly, [0, 1], dist))
[1.0, 1.0, q1, 10.0q1]
>>> print(chaospy.E_cond(poly, [1, 1], dist))
[1.0, q0, q1, 10.0q0q1]
>>> print(chaospy.E_cond(poly, [0, 0], dist))
[1.0, 1.0, 0.0, 0.0]
"""
if poly.dim < len(dist):
poly = polynomials.setdim(poly, len(dist))
freeze = polynomials.Poly(freeze)
freeze = polynomials.setdim(freeze, len(dist))
keys = freeze.keys
if len(keys) == 1 and keys[0] == (0,)*len(dist):
freeze = list(freeze.A.values())[0]
else:
freeze = numpy.array(keys)
freeze = freeze.reshape(int(freeze.size/len(dist)), len(dist))
shape = poly.shape
poly = polynomials.flatten(poly)
kmax = numpy.max(poly.keys, 0) + 1
keys = [range(k) for k in kmax]
A = poly.A.copy()
keys = poly.keys
out = {}
zeros = [0]*poly.dim
for i in range(len(keys)):
key = list(keys[i])
a = A[tuple(key)]
for d in range(poly.dim):
for j in range(len(freeze)):
if freeze[j, d]:
key[d], zeros[d] = zeros[d], key[d]
break
tmp = a*dist.mom(tuple(key))
if tuple(zeros) in out:
out[tuple(zeros)] = out[tuple(zeros)] + tmp
else:
out[tuple(zeros)] = tmp
for d in range(poly.dim):
for j in range(len(freeze)):
if freeze[j, d]:
key[d], zeros[d] = zeros[d], key[d]
break
out = polynomials.Poly(out, poly.dim, poly.shape, float)
out = polynomials.reshape(out, shape)
return out | [
"def",
"E_cond",
"(",
"poly",
",",
"freeze",
",",
"dist",
",",
"*",
"*",
"kws",
")",
":",
"if",
"poly",
".",
"dim",
"<",
"len",
"(",
"dist",
")",
":",
"poly",
"=",
"polynomials",
".",
"setdim",
"(",
"poly",
",",
"len",
"(",
"dist",
")",
")",
... | Conditional expected value operator.
1st order statistics of a polynomial on a given probability space
conditioned on some of the variables.
Args:
poly (Poly):
Polynomial to find conditional expected value on.
freeze (numpy.ndarray):
Boolean values defining the conditional variables. True values
implies that the value is conditioned on, e.g. frozen during the
expected value calculation.
dist (Dist) :
The distributions of the input used in ``poly``.
Returns:
(chaospy.poly.base.Poly) :
Same as ``poly``, but with the variables not tagged in ``frozen``
integrated away.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> print(chaospy.E_cond(poly, [1, 0], dist))
[1.0, q0, 0.0, 0.0]
>>> print(chaospy.E_cond(poly, [0, 1], dist))
[1.0, 1.0, q1, 10.0q1]
>>> print(chaospy.E_cond(poly, [1, 1], dist))
[1.0, q0, q1, 10.0q0q1]
>>> print(chaospy.E_cond(poly, [0, 0], dist))
[1.0, 1.0, 0.0, 0.0] | [
"Conditional",
"expected",
"value",
"operator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/conditional.py#L8-L92 | train | 206,940 |
jonathf/chaospy | chaospy/distributions/sampler/generator.py | generate_samples | def generate_samples(order, domain=1, rule="R", antithetic=None):
"""
Sample generator.
Args:
order (int):
Sample order. Determines the number of samples to create.
domain (Dist, int, numpy.ndarray):
Defines the space where the samples are generated. If integer is
provided, the space ``[0, 1]^domain`` will be used. If array-like
object is provided, a hypercube it defines will be used. If
distribution, the domain it spans will be used.
rule (str):
rule for generating samples. The various rules are listed in
:mod:`chaospy.distributions.sampler.generator`.
antithetic (tuple):
Sequence of boolean values. Represents the axes to mirror using
antithetic variable.
"""
logger = logging.getLogger(__name__)
logger.debug("generating random samples using rule %s", rule)
rule = rule.upper()
if isinstance(domain, int):
dim = domain
trans = lambda x_data: x_data
elif isinstance(domain, (tuple, list, numpy.ndarray)):
domain = numpy.asfarray(domain)
if len(domain.shape) < 2:
dim = 1
else:
dim = len(domain[0])
trans = lambda x_data: ((domain[1]-domain[0])*x_data.T + domain[0]).T
else:
dist = domain
dim = len(dist)
trans = dist.inv
if antithetic is not None:
from .antithetic import create_antithetic_variates
antithetic = numpy.array(antithetic, dtype=bool).flatten()
if antithetic.size == 1 and dim > 1:
antithetic = numpy.repeat(antithetic, dim)
size = numpy.sum(1*numpy.array(antithetic))
order_saved = order
order = int(numpy.log(order - dim))
order = order if order > 1 else 1
while order**dim < order_saved:
order += 1
trans_ = trans
trans = lambda x_data: trans_(
create_antithetic_variates(x_data, antithetic)[:, :order_saved])
assert rule in SAMPLERS, "rule not recognised"
sampler = SAMPLERS[rule]
x_data = trans(sampler(order=order, dim=dim))
logger.debug("order: %d, dim: %d -> shape: %s", order, dim, x_data.shape)
return x_data | python | def generate_samples(order, domain=1, rule="R", antithetic=None):
"""
Sample generator.
Args:
order (int):
Sample order. Determines the number of samples to create.
domain (Dist, int, numpy.ndarray):
Defines the space where the samples are generated. If integer is
provided, the space ``[0, 1]^domain`` will be used. If array-like
object is provided, a hypercube it defines will be used. If
distribution, the domain it spans will be used.
rule (str):
rule for generating samples. The various rules are listed in
:mod:`chaospy.distributions.sampler.generator`.
antithetic (tuple):
Sequence of boolean values. Represents the axes to mirror using
antithetic variable.
"""
logger = logging.getLogger(__name__)
logger.debug("generating random samples using rule %s", rule)
rule = rule.upper()
if isinstance(domain, int):
dim = domain
trans = lambda x_data: x_data
elif isinstance(domain, (tuple, list, numpy.ndarray)):
domain = numpy.asfarray(domain)
if len(domain.shape) < 2:
dim = 1
else:
dim = len(domain[0])
trans = lambda x_data: ((domain[1]-domain[0])*x_data.T + domain[0]).T
else:
dist = domain
dim = len(dist)
trans = dist.inv
if antithetic is not None:
from .antithetic import create_antithetic_variates
antithetic = numpy.array(antithetic, dtype=bool).flatten()
if antithetic.size == 1 and dim > 1:
antithetic = numpy.repeat(antithetic, dim)
size = numpy.sum(1*numpy.array(antithetic))
order_saved = order
order = int(numpy.log(order - dim))
order = order if order > 1 else 1
while order**dim < order_saved:
order += 1
trans_ = trans
trans = lambda x_data: trans_(
create_antithetic_variates(x_data, antithetic)[:, :order_saved])
assert rule in SAMPLERS, "rule not recognised"
sampler = SAMPLERS[rule]
x_data = trans(sampler(order=order, dim=dim))
logger.debug("order: %d, dim: %d -> shape: %s", order, dim, x_data.shape)
return x_data | [
"def",
"generate_samples",
"(",
"order",
",",
"domain",
"=",
"1",
",",
"rule",
"=",
"\"R\"",
",",
"antithetic",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"generating random sampl... | Sample generator.
Args:
order (int):
Sample order. Determines the number of samples to create.
domain (Dist, int, numpy.ndarray):
Defines the space where the samples are generated. If integer is
provided, the space ``[0, 1]^domain`` will be used. If array-like
object is provided, a hypercube it defines will be used. If
distribution, the domain it spans will be used.
rule (str):
rule for generating samples. The various rules are listed in
:mod:`chaospy.distributions.sampler.generator`.
antithetic (tuple):
Sequence of boolean values. Represents the axes to mirror using
antithetic variable. | [
"Sample",
"generator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/generator.py#L76-L139 | train | 206,941 |
jonathf/chaospy | chaospy/bertran/sparse.py | sparse_segment | def sparse_segment(cords):
r"""
Create a segment of a sparse grid.
Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.
A sparse grid of order ``D`` coencide with the set of sparse_segments where
``||cords||_1 <= D``.
More specifically, a segment of:
.. math::
\cup_{cords \in C} sparse_segment(cords) == sparse_grid(M)
where:
.. math::
C = {cords: M=sum(cords)}
Args:
cords (numpy.ndarray):
The segment to extract. ``cord`` must consist of non-negative
integers.
Returns:
Q (numpy.ndarray):
Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment
specific.
Examples:
>>> print(cp.bertran.sparse_segment([0, 2]))
[[0.5 0.125]
[0.5 0.375]
[0.5 0.625]
[0.5 0.875]]
>>> print(cp.bertran.sparse_segment([0, 1, 0, 0]))
[[0.5 0.25 0.5 0.5 ]
[0.5 0.75 0.5 0.5 ]]
"""
cords = np.array(cords)+1
slices = []
for cord in cords:
slices.append(slice(1, 2**cord+1, 2))
grid = np.mgrid[slices]
indices = grid.reshape(len(cords), np.prod(grid.shape[1:])).T
sgrid = indices*2.**-cords
return sgrid | python | def sparse_segment(cords):
r"""
Create a segment of a sparse grid.
Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.
A sparse grid of order ``D`` coencide with the set of sparse_segments where
``||cords||_1 <= D``.
More specifically, a segment of:
.. math::
\cup_{cords \in C} sparse_segment(cords) == sparse_grid(M)
where:
.. math::
C = {cords: M=sum(cords)}
Args:
cords (numpy.ndarray):
The segment to extract. ``cord`` must consist of non-negative
integers.
Returns:
Q (numpy.ndarray):
Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment
specific.
Examples:
>>> print(cp.bertran.sparse_segment([0, 2]))
[[0.5 0.125]
[0.5 0.375]
[0.5 0.625]
[0.5 0.875]]
>>> print(cp.bertran.sparse_segment([0, 1, 0, 0]))
[[0.5 0.25 0.5 0.5 ]
[0.5 0.75 0.5 0.5 ]]
"""
cords = np.array(cords)+1
slices = []
for cord in cords:
slices.append(slice(1, 2**cord+1, 2))
grid = np.mgrid[slices]
indices = grid.reshape(len(cords), np.prod(grid.shape[1:])).T
sgrid = indices*2.**-cords
return sgrid | [
"def",
"sparse_segment",
"(",
"cords",
")",
":",
"cords",
"=",
"np",
".",
"array",
"(",
"cords",
")",
"+",
"1",
"slices",
"=",
"[",
"]",
"for",
"cord",
"in",
"cords",
":",
"slices",
".",
"append",
"(",
"slice",
"(",
"1",
",",
"2",
"**",
"cord",
... | r"""
Create a segment of a sparse grid.
Convert a ol-index to sparse grid coordinates on ``[0, 1]^N`` hyper-cube.
A sparse grid of order ``D`` coencide with the set of sparse_segments where
``||cords||_1 <= D``.
More specifically, a segment of:
.. math::
\cup_{cords \in C} sparse_segment(cords) == sparse_grid(M)
where:
.. math::
C = {cords: M=sum(cords)}
Args:
cords (numpy.ndarray):
The segment to extract. ``cord`` must consist of non-negative
integers.
Returns:
Q (numpy.ndarray):
Sparse segment where ``Q.shape==(K, sum(M))`` and ``K`` is segment
specific.
Examples:
>>> print(cp.bertran.sparse_segment([0, 2]))
[[0.5 0.125]
[0.5 0.375]
[0.5 0.625]
[0.5 0.875]]
>>> print(cp.bertran.sparse_segment([0, 1, 0, 0]))
[[0.5 0.25 0.5 0.5 ]
[0.5 0.75 0.5 0.5 ]] | [
"r",
"Create",
"a",
"segment",
"of",
"a",
"sparse",
"grid",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/bertran/sparse.py#L6-L52 | train | 206,942 |
jonathf/chaospy | chaospy/orthogonal/lagrange.py | lagrange_polynomial | def lagrange_polynomial(abscissas, sort="GR"):
"""
Create Lagrange polynomials.
Args:
abscissas (numpy.ndarray):
Sample points where the Lagrange polynomials shall be defined.
Example:
>>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4))
[-0.05q0+0.5, 0.05q0+0.5]
>>> print(chaospy.around(lagrange_polynomial([-1, 0, 1]), 4))
[0.5q0^2-0.5q0, -q0^2+1.0, 0.5q0^2+0.5q0]
>>> poly = lagrange_polynomial([[1, 0, 1], [0, 1, 2]])
>>> print(chaospy.around(poly, 4))
[0.5q0-0.5q1+0.5, -q0+1.0, 0.5q0+0.5q1-0.5]
>>> print(numpy.around(poly([1, 0, 1], [0, 1, 2]), 4))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
"""
abscissas = numpy.asfarray(abscissas)
if len(abscissas.shape) == 1:
abscissas = abscissas.reshape(1, abscissas.size)
dim, size = abscissas.shape
order = 1
while chaospy.bertran.terms(order, dim) <= size:
order += 1
indices = numpy.array(chaospy.bertran.bindex(0, order-1, dim, sort)[:size])
idx, idy = numpy.mgrid[:size, :size]
matrix = numpy.prod(abscissas.T[idx]**indices[idy], -1)
det = numpy.linalg.det(matrix)
if det == 0:
raise numpy.linalg.LinAlgError("invertible matrix required")
vec = chaospy.poly.basis(0, order-1, dim, sort)[:size]
coeffs = numpy.zeros((size, size))
if size == 1:
out = chaospy.poly.basis(0, 0, dim, sort)*abscissas.item()
elif size == 2:
coeffs = numpy.linalg.inv(matrix)
out = chaospy.poly.sum(vec*(coeffs.T), 1)
else:
for i in range(size):
for j in range(size):
coeffs[i, j] += numpy.linalg.det(matrix[1:, 1:])
matrix = numpy.roll(matrix, -1, axis=0)
matrix = numpy.roll(matrix, -1, axis=1)
coeffs /= det
out = chaospy.poly.sum(vec*(coeffs.T), 1)
return out | python | def lagrange_polynomial(abscissas, sort="GR"):
"""
Create Lagrange polynomials.
Args:
abscissas (numpy.ndarray):
Sample points where the Lagrange polynomials shall be defined.
Example:
>>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4))
[-0.05q0+0.5, 0.05q0+0.5]
>>> print(chaospy.around(lagrange_polynomial([-1, 0, 1]), 4))
[0.5q0^2-0.5q0, -q0^2+1.0, 0.5q0^2+0.5q0]
>>> poly = lagrange_polynomial([[1, 0, 1], [0, 1, 2]])
>>> print(chaospy.around(poly, 4))
[0.5q0-0.5q1+0.5, -q0+1.0, 0.5q0+0.5q1-0.5]
>>> print(numpy.around(poly([1, 0, 1], [0, 1, 2]), 4))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
"""
abscissas = numpy.asfarray(abscissas)
if len(abscissas.shape) == 1:
abscissas = abscissas.reshape(1, abscissas.size)
dim, size = abscissas.shape
order = 1
while chaospy.bertran.terms(order, dim) <= size:
order += 1
indices = numpy.array(chaospy.bertran.bindex(0, order-1, dim, sort)[:size])
idx, idy = numpy.mgrid[:size, :size]
matrix = numpy.prod(abscissas.T[idx]**indices[idy], -1)
det = numpy.linalg.det(matrix)
if det == 0:
raise numpy.linalg.LinAlgError("invertible matrix required")
vec = chaospy.poly.basis(0, order-1, dim, sort)[:size]
coeffs = numpy.zeros((size, size))
if size == 1:
out = chaospy.poly.basis(0, 0, dim, sort)*abscissas.item()
elif size == 2:
coeffs = numpy.linalg.inv(matrix)
out = chaospy.poly.sum(vec*(coeffs.T), 1)
else:
for i in range(size):
for j in range(size):
coeffs[i, j] += numpy.linalg.det(matrix[1:, 1:])
matrix = numpy.roll(matrix, -1, axis=0)
matrix = numpy.roll(matrix, -1, axis=1)
coeffs /= det
out = chaospy.poly.sum(vec*(coeffs.T), 1)
return out | [
"def",
"lagrange_polynomial",
"(",
"abscissas",
",",
"sort",
"=",
"\"GR\"",
")",
":",
"abscissas",
"=",
"numpy",
".",
"asfarray",
"(",
"abscissas",
")",
"if",
"len",
"(",
"abscissas",
".",
"shape",
")",
"==",
"1",
":",
"abscissas",
"=",
"abscissas",
".",... | Create Lagrange polynomials.
Args:
abscissas (numpy.ndarray):
Sample points where the Lagrange polynomials shall be defined.
Example:
>>> print(chaospy.around(lagrange_polynomial([-10, 10]), 4))
[-0.05q0+0.5, 0.05q0+0.5]
>>> print(chaospy.around(lagrange_polynomial([-1, 0, 1]), 4))
[0.5q0^2-0.5q0, -q0^2+1.0, 0.5q0^2+0.5q0]
>>> poly = lagrange_polynomial([[1, 0, 1], [0, 1, 2]])
>>> print(chaospy.around(poly, 4))
[0.5q0-0.5q1+0.5, -q0+1.0, 0.5q0+0.5q1-0.5]
>>> print(numpy.around(poly([1, 0, 1], [0, 1, 2]), 4))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]] | [
"Create",
"Lagrange",
"polynomials",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/orthogonal/lagrange.py#L13-L71 | train | 206,943 |
jonathf/chaospy | chaospy/distributions/collection/sample_dist.py | SampleDist | def SampleDist(samples, lo=None, up=None):
"""
Distribution based on samples.
Estimates a distribution from the given samples by constructing a kernel
density estimator (KDE).
Args:
samples:
Sample values to construction of the KDE
lo (float) : Location of lower threshold
up (float) : Location of upper threshold
Example:
>>> distribution = chaospy.SampleDist([0, 1, 1, 1, 2])
>>> print(distribution)
sample_dist(lo=0, up=2)
>>> q = numpy.linspace(0, 1, 5)
>>> print(numpy.around(distribution.inv(q), 4))
[0. 0.6016 1. 1.3984 2. ]
>>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))
[0. 0.25 0.5 0.75 1. ]
>>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))
[0.2254 0.4272 0.5135 0.4272 0.2254]
>>> print(numpy.around(distribution.sample(4), 4)) # doctest: +SKIP
[-0.4123 1.1645 -0.0131 1.3302]
>>> print(numpy.around(distribution.mom(1), 4))
1.0
>>> print(numpy.around(distribution.ttr([1, 2, 3]), 4))
[[1.3835 0.7983 1.1872]
[0.2429 0.2693 0.4102]]
"""
samples = numpy.asarray(samples)
if lo is None:
lo = samples.min()
if up is None:
up = samples.max()
try:
#construct the kernel density estimator
dist = sample_dist(samples, lo, up)
#raised by gaussian_kde if dataset is singular matrix
except numpy.linalg.LinAlgError:
dist = Uniform(lower=-numpy.inf, upper=numpy.inf)
return dist | python | def SampleDist(samples, lo=None, up=None):
"""
Distribution based on samples.
Estimates a distribution from the given samples by constructing a kernel
density estimator (KDE).
Args:
samples:
Sample values to construction of the KDE
lo (float) : Location of lower threshold
up (float) : Location of upper threshold
Example:
>>> distribution = chaospy.SampleDist([0, 1, 1, 1, 2])
>>> print(distribution)
sample_dist(lo=0, up=2)
>>> q = numpy.linspace(0, 1, 5)
>>> print(numpy.around(distribution.inv(q), 4))
[0. 0.6016 1. 1.3984 2. ]
>>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))
[0. 0.25 0.5 0.75 1. ]
>>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))
[0.2254 0.4272 0.5135 0.4272 0.2254]
>>> print(numpy.around(distribution.sample(4), 4)) # doctest: +SKIP
[-0.4123 1.1645 -0.0131 1.3302]
>>> print(numpy.around(distribution.mom(1), 4))
1.0
>>> print(numpy.around(distribution.ttr([1, 2, 3]), 4))
[[1.3835 0.7983 1.1872]
[0.2429 0.2693 0.4102]]
"""
samples = numpy.asarray(samples)
if lo is None:
lo = samples.min()
if up is None:
up = samples.max()
try:
#construct the kernel density estimator
dist = sample_dist(samples, lo, up)
#raised by gaussian_kde if dataset is singular matrix
except numpy.linalg.LinAlgError:
dist = Uniform(lower=-numpy.inf, upper=numpy.inf)
return dist | [
"def",
"SampleDist",
"(",
"samples",
",",
"lo",
"=",
"None",
",",
"up",
"=",
"None",
")",
":",
"samples",
"=",
"numpy",
".",
"asarray",
"(",
"samples",
")",
"if",
"lo",
"is",
"None",
":",
"lo",
"=",
"samples",
".",
"min",
"(",
")",
"if",
"up",
... | Distribution based on samples.
Estimates a distribution from the given samples by constructing a kernel
density estimator (KDE).
Args:
samples:
Sample values to construction of the KDE
lo (float) : Location of lower threshold
up (float) : Location of upper threshold
Example:
>>> distribution = chaospy.SampleDist([0, 1, 1, 1, 2])
>>> print(distribution)
sample_dist(lo=0, up=2)
>>> q = numpy.linspace(0, 1, 5)
>>> print(numpy.around(distribution.inv(q), 4))
[0. 0.6016 1. 1.3984 2. ]
>>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))
[0. 0.25 0.5 0.75 1. ]
>>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))
[0.2254 0.4272 0.5135 0.4272 0.2254]
>>> print(numpy.around(distribution.sample(4), 4)) # doctest: +SKIP
[-0.4123 1.1645 -0.0131 1.3302]
>>> print(numpy.around(distribution.mom(1), 4))
1.0
>>> print(numpy.around(distribution.ttr([1, 2, 3]), 4))
[[1.3835 0.7983 1.1872]
[0.2429 0.2693 0.4102]] | [
"Distribution",
"based",
"on",
"samples",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/collection/sample_dist.py#L88-L134 | train | 206,944 |
jonathf/chaospy | chaospy/chol/bastos_ohagen.py | bastos_ohagen | def bastos_ohagen(mat, eps=1e-16):
"""
Bastos-O'Hagen algorithm for modified Cholesky decomposition.
Args:
mat (numpy.ndarray):
Input matrix to decompose. Assumed to close to positive definite.
eps (float):
Tolerance value for the eigenvalues. Values smaller
than `tol*numpy.diag(mat).max()` are considered to be zero.
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]):
perm:
Permutation matrix
lowtri:
Upper triangular decomposition
errors:
Error matrix
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> perm, lowtri = bastos_ohagen(mat)
>>> print(perm)
[[0 1 0]
[1 0 0]
[0 0 1]]
>>> print(numpy.around(lowtri, 4))
[[ 2.4495 0. 0. ]
[ 0.8165 1.8257 0. ]
[ 1.2247 -0. 0.9129]]
>>> comp = numpy.dot(perm, lowtri)
>>> print(numpy.around(numpy.dot(comp, comp.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 2.3333]]
"""
mat_ref = numpy.asfarray(mat)
mat = mat_ref.copy()
diag_max = numpy.diag(mat).max()
assert len(mat.shape) == 2
size = len(mat)
hitri = numpy.zeros((size, size))
piv = numpy.arange(size)
for idx in range(size):
idx_max = numpy.argmax(numpy.diag(mat[idx:, idx:])) + idx
if mat[idx_max, idx_max] <= numpy.abs(diag_max*eps):
if not idx:
raise ValueError("Purly negative definite")
for j in range(idx, size):
hitri[j, j] = hitri[j-1, j-1]/float(j)
break
tmp = mat[:, idx].copy()
mat[:, idx] = mat[:, idx_max]
mat[:, idx_max] = tmp
tmp = hitri[:, idx].copy()
hitri[:, idx] = hitri[:, idx_max]
hitri[:, idx_max] = tmp
tmp = mat[idx, :].copy()
mat[idx, :] = mat[idx_max, :]
mat[idx_max, :] = tmp
piv[idx], piv[idx_max] = piv[idx_max], piv[idx]
hitri[idx, idx] = numpy.sqrt(mat[idx, idx])
rval = mat[idx, idx+1:]/hitri[idx, idx]
hitri[idx, idx+1:] = rval
mat[idx+1:, idx+1:] -= numpy.outer(rval, rval)
perm = numpy.zeros((size, size), dtype=int)
for idx in range(size):
perm[idx, piv[idx]] = 1
return perm, hitri.T | python | def bastos_ohagen(mat, eps=1e-16):
"""
Bastos-O'Hagen algorithm for modified Cholesky decomposition.
Args:
mat (numpy.ndarray):
Input matrix to decompose. Assumed to close to positive definite.
eps (float):
Tolerance value for the eigenvalues. Values smaller
than `tol*numpy.diag(mat).max()` are considered to be zero.
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]):
perm:
Permutation matrix
lowtri:
Upper triangular decomposition
errors:
Error matrix
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> perm, lowtri = bastos_ohagen(mat)
>>> print(perm)
[[0 1 0]
[1 0 0]
[0 0 1]]
>>> print(numpy.around(lowtri, 4))
[[ 2.4495 0. 0. ]
[ 0.8165 1.8257 0. ]
[ 1.2247 -0. 0.9129]]
>>> comp = numpy.dot(perm, lowtri)
>>> print(numpy.around(numpy.dot(comp, comp.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 2.3333]]
"""
mat_ref = numpy.asfarray(mat)
mat = mat_ref.copy()
diag_max = numpy.diag(mat).max()
assert len(mat.shape) == 2
size = len(mat)
hitri = numpy.zeros((size, size))
piv = numpy.arange(size)
for idx in range(size):
idx_max = numpy.argmax(numpy.diag(mat[idx:, idx:])) + idx
if mat[idx_max, idx_max] <= numpy.abs(diag_max*eps):
if not idx:
raise ValueError("Purly negative definite")
for j in range(idx, size):
hitri[j, j] = hitri[j-1, j-1]/float(j)
break
tmp = mat[:, idx].copy()
mat[:, idx] = mat[:, idx_max]
mat[:, idx_max] = tmp
tmp = hitri[:, idx].copy()
hitri[:, idx] = hitri[:, idx_max]
hitri[:, idx_max] = tmp
tmp = mat[idx, :].copy()
mat[idx, :] = mat[idx_max, :]
mat[idx_max, :] = tmp
piv[idx], piv[idx_max] = piv[idx_max], piv[idx]
hitri[idx, idx] = numpy.sqrt(mat[idx, idx])
rval = mat[idx, idx+1:]/hitri[idx, idx]
hitri[idx, idx+1:] = rval
mat[idx+1:, idx+1:] -= numpy.outer(rval, rval)
perm = numpy.zeros((size, size), dtype=int)
for idx in range(size):
perm[idx, piv[idx]] = 1
return perm, hitri.T | [
"def",
"bastos_ohagen",
"(",
"mat",
",",
"eps",
"=",
"1e-16",
")",
":",
"mat_ref",
"=",
"numpy",
".",
"asfarray",
"(",
"mat",
")",
"mat",
"=",
"mat_ref",
".",
"copy",
"(",
")",
"diag_max",
"=",
"numpy",
".",
"diag",
"(",
"mat",
")",
".",
"max",
"... | Bastos-O'Hagen algorithm for modified Cholesky decomposition.
Args:
mat (numpy.ndarray):
Input matrix to decompose. Assumed to close to positive definite.
eps (float):
Tolerance value for the eigenvalues. Values smaller
than `tol*numpy.diag(mat).max()` are considered to be zero.
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]):
perm:
Permutation matrix
lowtri:
Upper triangular decomposition
errors:
Error matrix
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> perm, lowtri = bastos_ohagen(mat)
>>> print(perm)
[[0 1 0]
[1 0 0]
[0 0 1]]
>>> print(numpy.around(lowtri, 4))
[[ 2.4495 0. 0. ]
[ 0.8165 1.8257 0. ]
[ 1.2247 -0. 0.9129]]
>>> comp = numpy.dot(perm, lowtri)
>>> print(numpy.around(numpy.dot(comp, comp.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 2.3333]] | [
"Bastos",
"-",
"O",
"Hagen",
"algorithm",
"for",
"modified",
"Cholesky",
"decomposition",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/chol/bastos_ohagen.py#L10-L90 | train | 206,945 |
jonathf/chaospy | chaospy/descriptives/sensitivity/total.py | Sens_t | def Sens_t(poly, dist, **kws):
"""
Variance-based decomposition
AKA Sobol' indices
Total effect sensitivity index
Args:
poly (Poly):
Polynomial to find first order Sobol indices on.
dist (Dist):
The distributions of the input used in ``poly``.
Returns:
(numpy.ndarray) :
First order sensitivity indices for each parameters in ``poly``,
with shape ``(len(dist),) + poly.shape``.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> indices = chaospy.Sens_t(poly, dist)
>>> print(indices)
[[0. 1. 0. 0.57142857]
[0. 0. 1. 0.57142857]]
"""
dim = len(dist)
if poly.dim < dim:
poly = chaospy.poly.setdim(poly, len(dist))
zero = [1]*dim
out = numpy.zeros((dim,) + poly.shape, dtype=float)
V = Var(poly, dist, **kws)
for i in range(dim):
zero[i] = 0
out[i] = ((V-Var(E_cond(poly, zero, dist, **kws), dist, **kws)) /
(V+(V == 0))**(V!=0))
zero[i] = 1
return out | python | def Sens_t(poly, dist, **kws):
"""
Variance-based decomposition
AKA Sobol' indices
Total effect sensitivity index
Args:
poly (Poly):
Polynomial to find first order Sobol indices on.
dist (Dist):
The distributions of the input used in ``poly``.
Returns:
(numpy.ndarray) :
First order sensitivity indices for each parameters in ``poly``,
with shape ``(len(dist),) + poly.shape``.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> indices = chaospy.Sens_t(poly, dist)
>>> print(indices)
[[0. 1. 0. 0.57142857]
[0. 0. 1. 0.57142857]]
"""
dim = len(dist)
if poly.dim < dim:
poly = chaospy.poly.setdim(poly, len(dist))
zero = [1]*dim
out = numpy.zeros((dim,) + poly.shape, dtype=float)
V = Var(poly, dist, **kws)
for i in range(dim):
zero[i] = 0
out[i] = ((V-Var(E_cond(poly, zero, dist, **kws), dist, **kws)) /
(V+(V == 0))**(V!=0))
zero[i] = 1
return out | [
"def",
"Sens_t",
"(",
"poly",
",",
"dist",
",",
"*",
"*",
"kws",
")",
":",
"dim",
"=",
"len",
"(",
"dist",
")",
"if",
"poly",
".",
"dim",
"<",
"dim",
":",
"poly",
"=",
"chaospy",
".",
"poly",
".",
"setdim",
"(",
"poly",
",",
"len",
"(",
"dist... | Variance-based decomposition
AKA Sobol' indices
Total effect sensitivity index
Args:
poly (Poly):
Polynomial to find first order Sobol indices on.
dist (Dist):
The distributions of the input used in ``poly``.
Returns:
(numpy.ndarray) :
First order sensitivity indices for each parameters in ``poly``,
with shape ``(len(dist),) + poly.shape``.
Examples:
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([1, x, y, 10*x*y])
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> indices = chaospy.Sens_t(poly, dist)
>>> print(indices)
[[0. 1. 0. 0.57142857]
[0. 0. 1. 0.57142857]] | [
"Variance",
"-",
"based",
"decomposition",
"AKA",
"Sobol",
"indices"
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/sensitivity/total.py#L8-L47 | train | 206,946 |
jonathf/chaospy | chaospy/distributions/constructor.py | construct | def construct(parent=None, defaults=None, **kwargs):
"""
Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution used as basis for new distribution. Any other argument
that is omitted will instead take is function from ``parent``.
doc (str]):
Documentation for the distribution.
str (str, :py:data:typing.Callable):
Pretty print of the variable.
pdf:
Probability density function.
ppf:
Point percentile function.
mom:
Raw moment generator.
ttr:
Three terms recursion coefficient generator.
init:
Custom initialiser method.
defaults (dict):
Default values to provide to initialiser.
Returns:
(Dist):
New custom distribution.
"""
for key in kwargs:
assert key in LEGAL_ATTRS, "{} is not legal input".format(key)
if parent is not None:
for key, value in LEGAL_ATTRS.items():
if key not in kwargs and hasattr(parent, value):
kwargs[key] = getattr(parent, value)
assert "cdf" in kwargs, "cdf function must be defined"
assert "bnd" in kwargs, "bnd function must be defined"
if "str" in kwargs and isinstance(kwargs["str"], str):
string = kwargs.pop("str")
kwargs["str"] = lambda *args, **kwargs: string
defaults = defaults if defaults else {}
for key in defaults:
assert key in LEGAL_ATTRS, "invalid default value {}".format(key)
def custom_distribution(**kws):
prm = defaults.copy()
prm.update(kws)
dist = Dist(**prm)
for key, function in kwargs.items():
attr_name = LEGAL_ATTRS[key]
setattr(dist, attr_name, types.MethodType(function, dist))
return dist
if "doc" in kwargs:
custom_distribution.__doc__ = kwargs["doc"]
return custom_distribution | python | def construct(parent=None, defaults=None, **kwargs):
"""
Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution used as basis for new distribution. Any other argument
that is omitted will instead take is function from ``parent``.
doc (str]):
Documentation for the distribution.
str (str, :py:data:typing.Callable):
Pretty print of the variable.
pdf:
Probability density function.
ppf:
Point percentile function.
mom:
Raw moment generator.
ttr:
Three terms recursion coefficient generator.
init:
Custom initialiser method.
defaults (dict):
Default values to provide to initialiser.
Returns:
(Dist):
New custom distribution.
"""
for key in kwargs:
assert key in LEGAL_ATTRS, "{} is not legal input".format(key)
if parent is not None:
for key, value in LEGAL_ATTRS.items():
if key not in kwargs and hasattr(parent, value):
kwargs[key] = getattr(parent, value)
assert "cdf" in kwargs, "cdf function must be defined"
assert "bnd" in kwargs, "bnd function must be defined"
if "str" in kwargs and isinstance(kwargs["str"], str):
string = kwargs.pop("str")
kwargs["str"] = lambda *args, **kwargs: string
defaults = defaults if defaults else {}
for key in defaults:
assert key in LEGAL_ATTRS, "invalid default value {}".format(key)
def custom_distribution(**kws):
prm = defaults.copy()
prm.update(kws)
dist = Dist(**prm)
for key, function in kwargs.items():
attr_name = LEGAL_ATTRS[key]
setattr(dist, attr_name, types.MethodType(function, dist))
return dist
if "doc" in kwargs:
custom_distribution.__doc__ = kwargs["doc"]
return custom_distribution | [
"def",
"construct",
"(",
"parent",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"kwargs",
":",
"assert",
"key",
"in",
"LEGAL_ATTRS",
",",
"\"{} is not legal input\"",
".",
"format",
"(",
"key",
")",
... | Random variable constructor.
Args:
cdf:
Cumulative distribution function. Optional if ``parent`` is used.
bnd:
Boundary interval. Optional if ``parent`` is used.
parent (Dist):
Distribution used as basis for new distribution. Any other argument
that is omitted will instead take is function from ``parent``.
doc (str]):
Documentation for the distribution.
str (str, :py:data:typing.Callable):
Pretty print of the variable.
pdf:
Probability density function.
ppf:
Point percentile function.
mom:
Raw moment generator.
ttr:
Three terms recursion coefficient generator.
init:
Custom initialiser method.
defaults (dict):
Default values to provide to initialiser.
Returns:
(Dist):
New custom distribution. | [
"Random",
"variable",
"constructor",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/constructor.py#L31-L96 | train | 206,947 |
jonathf/chaospy | chaospy/spectral.py | fit_quadrature | def fit_quadrature(orth, nodes, weights, solves, retall=False, norms=None, **kws):
"""
Using spectral projection to create a polynomial approximation over
distribution space.
Args:
orth (chaospy.poly.base.Poly):
Orthogonal polynomial expansion. Must be orthogonal for the
approximation to be accurate.
nodes (numpy.ndarray):
Where to evaluate the polynomial expansion and model to
approximate. ``nodes.shape==(D,K)`` where ``D`` is the number of
dimensions and ``K`` is the number of nodes.
weights (numpy.ndarray):
Weights when doing numerical integration. ``weights.shape == (K,)``
must hold.
solves (numpy.ndarray):
The model evaluation to approximate. If `numpy.ndarray` is
provided, it must have ``len(solves) == K``. If callable, it must
take a single argument X with ``len(X) == D``, and return
a consistent numpy compatible shape.
norms (numpy.ndarray):
In the of TTR using coefficients to estimate the polynomial norm is
more stable than manual calculation. Calculated using quadrature if
no provided. ``norms.shape == (len(orth),)`` must hold.
Returns:
(chaospy.poly.base.Poly):
Fitted model approximation in the form of an polynomial.
"""
orth = chaospy.poly.Poly(orth)
nodes = numpy.asfarray(nodes)
weights = numpy.asfarray(weights)
if callable(solves):
solves = [solves(node) for node in nodes.T]
solves = numpy.asfarray(solves)
shape = solves.shape
solves = solves.reshape(weights.size, int(solves.size/weights.size))
ovals = orth(*nodes)
vals1 = [(val*solves.T*weights).T for val in ovals]
if norms is None:
norms = numpy.sum(ovals**2*weights, -1)
else:
norms = numpy.array(norms).flatten()
assert len(norms) == len(orth)
coefs = (numpy.sum(vals1, 1).T/norms).T
coefs = coefs.reshape(len(coefs), *shape[1:])
approx_model = chaospy.poly.transpose(chaospy.poly.sum(orth*coefs.T, -1))
if retall:
return approx_model, coefs
return approx_model | python | def fit_quadrature(orth, nodes, weights, solves, retall=False, norms=None, **kws):
"""
Using spectral projection to create a polynomial approximation over
distribution space.
Args:
orth (chaospy.poly.base.Poly):
Orthogonal polynomial expansion. Must be orthogonal for the
approximation to be accurate.
nodes (numpy.ndarray):
Where to evaluate the polynomial expansion and model to
approximate. ``nodes.shape==(D,K)`` where ``D`` is the number of
dimensions and ``K`` is the number of nodes.
weights (numpy.ndarray):
Weights when doing numerical integration. ``weights.shape == (K,)``
must hold.
solves (numpy.ndarray):
The model evaluation to approximate. If `numpy.ndarray` is
provided, it must have ``len(solves) == K``. If callable, it must
take a single argument X with ``len(X) == D``, and return
a consistent numpy compatible shape.
norms (numpy.ndarray):
In the of TTR using coefficients to estimate the polynomial norm is
more stable than manual calculation. Calculated using quadrature if
no provided. ``norms.shape == (len(orth),)`` must hold.
Returns:
(chaospy.poly.base.Poly):
Fitted model approximation in the form of an polynomial.
"""
orth = chaospy.poly.Poly(orth)
nodes = numpy.asfarray(nodes)
weights = numpy.asfarray(weights)
if callable(solves):
solves = [solves(node) for node in nodes.T]
solves = numpy.asfarray(solves)
shape = solves.shape
solves = solves.reshape(weights.size, int(solves.size/weights.size))
ovals = orth(*nodes)
vals1 = [(val*solves.T*weights).T for val in ovals]
if norms is None:
norms = numpy.sum(ovals**2*weights, -1)
else:
norms = numpy.array(norms).flatten()
assert len(norms) == len(orth)
coefs = (numpy.sum(vals1, 1).T/norms).T
coefs = coefs.reshape(len(coefs), *shape[1:])
approx_model = chaospy.poly.transpose(chaospy.poly.sum(orth*coefs.T, -1))
if retall:
return approx_model, coefs
return approx_model | [
"def",
"fit_quadrature",
"(",
"orth",
",",
"nodes",
",",
"weights",
",",
"solves",
",",
"retall",
"=",
"False",
",",
"norms",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"orth",
"=",
"chaospy",
".",
"poly",
".",
"Poly",
"(",
"orth",
")",
"nodes",
... | Using spectral projection to create a polynomial approximation over
distribution space.
Args:
orth (chaospy.poly.base.Poly):
Orthogonal polynomial expansion. Must be orthogonal for the
approximation to be accurate.
nodes (numpy.ndarray):
Where to evaluate the polynomial expansion and model to
approximate. ``nodes.shape==(D,K)`` where ``D`` is the number of
dimensions and ``K`` is the number of nodes.
weights (numpy.ndarray):
Weights when doing numerical integration. ``weights.shape == (K,)``
must hold.
solves (numpy.ndarray):
The model evaluation to approximate. If `numpy.ndarray` is
provided, it must have ``len(solves) == K``. If callable, it must
take a single argument X with ``len(X) == D``, and return
a consistent numpy compatible shape.
norms (numpy.ndarray):
In the of TTR using coefficients to estimate the polynomial norm is
more stable than manual calculation. Calculated using quadrature if
no provided. ``norms.shape == (len(orth),)`` must hold.
Returns:
(chaospy.poly.base.Poly):
Fitted model approximation in the form of an polynomial. | [
"Using",
"spectral",
"projection",
"to",
"create",
"a",
"polynomial",
"approximation",
"over",
"distribution",
"space",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/spectral.py#L82-L138 | train | 206,948 |
jonathf/chaospy | chaospy/quad/sparse_grid.py | sparse_grid | def sparse_grid(func, order, dim=None, skew=None):
"""
Smolyak sparse grid constructor.
Args:
func (:py:data:typing.Callable):
Function that takes a single argument ``order`` of type
``numpy.ndarray`` and with ``order.shape = (dim,)``
order (int, numpy.ndarray):
The order of the grid. If ``numpy.ndarray``, it overrides both
``dim`` and ``skew``.
dim (int):
Number of dimension.
skew (list):
Order skewness.
"""
if not isinstance(order, int):
orders = numpy.array(order).flatten()
dim = orders.size
m_order = int(numpy.min(orders))
skew = [order-m_order for order in orders]
return sparse_grid(func, m_order, dim, skew)
abscissas, weights = [], []
bindex = chaospy.bertran.bindex(order-dim+1, order, dim)
if skew is None:
skew = numpy.zeros(dim, dtype=int)
else:
skew = numpy.array(skew, dtype=int)
assert len(skew) == dim
for idx in range(
chaospy.bertran.terms(order, dim)
- chaospy.bertran.terms(order-dim, dim)):
idb = bindex[idx]
abscissa, weight = func(skew+idb)
weight *= (-1)**(order-sum(idb))*comb(dim-1, order-sum(idb))
abscissas.append(abscissa)
weights.append(weight)
abscissas = numpy.concatenate(abscissas, 1)
weights = numpy.concatenate(weights, 0)
abscissas = numpy.around(abscissas, 15)
order = numpy.lexsort(tuple(abscissas))
abscissas = abscissas.T[order].T
weights = weights[order]
# identify non-unique terms
diff = numpy.diff(abscissas.T, axis=0)
unique = numpy.ones(len(abscissas.T), bool)
unique[1:] = (diff != 0).any(axis=1)
# merge duplicate nodes
length = len(weights)
idx = 1
while idx < length:
while idx < length and unique[idx]:
idx += 1
idy = idx+1
while idy < length and not unique[idy]:
idy += 1
if idy-idx > 1:
weights[idx-1] = numpy.sum(weights[idx-1:idy])
idx = idy+1
abscissas = abscissas[:, unique]
weights = weights[unique]
return abscissas, weights | python | def sparse_grid(func, order, dim=None, skew=None):
"""
Smolyak sparse grid constructor.
Args:
func (:py:data:typing.Callable):
Function that takes a single argument ``order`` of type
``numpy.ndarray`` and with ``order.shape = (dim,)``
order (int, numpy.ndarray):
The order of the grid. If ``numpy.ndarray``, it overrides both
``dim`` and ``skew``.
dim (int):
Number of dimension.
skew (list):
Order skewness.
"""
if not isinstance(order, int):
orders = numpy.array(order).flatten()
dim = orders.size
m_order = int(numpy.min(orders))
skew = [order-m_order for order in orders]
return sparse_grid(func, m_order, dim, skew)
abscissas, weights = [], []
bindex = chaospy.bertran.bindex(order-dim+1, order, dim)
if skew is None:
skew = numpy.zeros(dim, dtype=int)
else:
skew = numpy.array(skew, dtype=int)
assert len(skew) == dim
for idx in range(
chaospy.bertran.terms(order, dim)
- chaospy.bertran.terms(order-dim, dim)):
idb = bindex[idx]
abscissa, weight = func(skew+idb)
weight *= (-1)**(order-sum(idb))*comb(dim-1, order-sum(idb))
abscissas.append(abscissa)
weights.append(weight)
abscissas = numpy.concatenate(abscissas, 1)
weights = numpy.concatenate(weights, 0)
abscissas = numpy.around(abscissas, 15)
order = numpy.lexsort(tuple(abscissas))
abscissas = abscissas.T[order].T
weights = weights[order]
# identify non-unique terms
diff = numpy.diff(abscissas.T, axis=0)
unique = numpy.ones(len(abscissas.T), bool)
unique[1:] = (diff != 0).any(axis=1)
# merge duplicate nodes
length = len(weights)
idx = 1
while idx < length:
while idx < length and unique[idx]:
idx += 1
idy = idx+1
while idy < length and not unique[idy]:
idy += 1
if idy-idx > 1:
weights[idx-1] = numpy.sum(weights[idx-1:idy])
idx = idy+1
abscissas = abscissas[:, unique]
weights = weights[unique]
return abscissas, weights | [
"def",
"sparse_grid",
"(",
"func",
",",
"order",
",",
"dim",
"=",
"None",
",",
"skew",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"order",
",",
"int",
")",
":",
"orders",
"=",
"numpy",
".",
"array",
"(",
"order",
")",
".",
"flatten",
... | Smolyak sparse grid constructor.
Args:
func (:py:data:typing.Callable):
Function that takes a single argument ``order`` of type
``numpy.ndarray`` and with ``order.shape = (dim,)``
order (int, numpy.ndarray):
The order of the grid. If ``numpy.ndarray``, it overrides both
``dim`` and ``skew``.
dim (int):
Number of dimension.
skew (list):
Order skewness. | [
"Smolyak",
"sparse",
"grid",
"constructor",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/sparse_grid.py#L52-L123 | train | 206,949 |
jonathf/chaospy | chaospy/distributions/evaluation/bound.py | evaluate_bound | def evaluate_bound(
distribution,
x_data,
parameters=None,
cache=None,
):
"""
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multivariate distributions where the bounds are affected by the
output of other distributions.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The lower and upper bounds of ``distribution`` at location
``x_data`` using parameters ``parameters``.
"""
assert len(x_data) == len(distribution)
assert len(x_data.shape) == 2
cache = cache if cache is not None else {}
parameters = load_parameters(
distribution, "_bnd", parameters=parameters, cache=cache)
out = numpy.zeros((2,) + x_data.shape)
lower, upper = distribution._bnd(x_data.copy(), **parameters)
out.T[:, :, 0] = numpy.asfarray(lower).T
out.T[:, :, 1] = numpy.asfarray(upper).T
cache[distribution] = out
return out | python | def evaluate_bound(
distribution,
x_data,
parameters=None,
cache=None,
):
"""
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multivariate distributions where the bounds are affected by the
output of other distributions.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The lower and upper bounds of ``distribution`` at location
``x_data`` using parameters ``parameters``.
"""
assert len(x_data) == len(distribution)
assert len(x_data.shape) == 2
cache = cache if cache is not None else {}
parameters = load_parameters(
distribution, "_bnd", parameters=parameters, cache=cache)
out = numpy.zeros((2,) + x_data.shape)
lower, upper = distribution._bnd(x_data.copy(), **parameters)
out.T[:, :, 0] = numpy.asfarray(lower).T
out.T[:, :, 1] = numpy.asfarray(upper).T
cache[distribution] = out
return out | [
"def",
"evaluate_bound",
"(",
"distribution",
",",
"x_data",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
")",
":",
"assert",
"len",
"(",
"x_data",
")",
"==",
"len",
"(",
"distribution",
")",
"assert",
"len",
"(",
"x_data",
".",
"sha... | Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multivariate distributions where the bounds are affected by the
output of other distributions.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The lower and upper bounds of ``distribution`` at location
``x_data`` using parameters ``parameters``. | [
"Evaluate",
"lower",
"and",
"upper",
"bounds",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/bound.py#L32-L75 | train | 206,950 |
jonathf/chaospy | chaospy/poly/collection/linalg.py | inner | def inner(*args):
"""
Inner product of a polynomial set.
Args:
args (chaospy.poly.base.Poly):
The polynomials to perform inner product on.
Returns:
(chaospy.poly.base.Poly):
Resulting polynomial.
Examples:
>>> x,y = cp.variable(2)
>>> P = cp.Poly([x-1, y])
>>> Q = cp.Poly([x+1, x*y])
>>> print(cp.inner(P, Q))
q0^2+q0q1^2-1
>>> x = numpy.arange(4)
>>> print(cp.inner(x, x))
14
"""
haspoly = sum([isinstance(arg, Poly) for arg in args])
# Numpy
if not haspoly:
return numpy.sum(numpy.prod(args, 0), 0)
# Poly
out = args[0]
for arg in args[1:]:
out = out * arg
return sum(out) | python | def inner(*args):
"""
Inner product of a polynomial set.
Args:
args (chaospy.poly.base.Poly):
The polynomials to perform inner product on.
Returns:
(chaospy.poly.base.Poly):
Resulting polynomial.
Examples:
>>> x,y = cp.variable(2)
>>> P = cp.Poly([x-1, y])
>>> Q = cp.Poly([x+1, x*y])
>>> print(cp.inner(P, Q))
q0^2+q0q1^2-1
>>> x = numpy.arange(4)
>>> print(cp.inner(x, x))
14
"""
haspoly = sum([isinstance(arg, Poly) for arg in args])
# Numpy
if not haspoly:
return numpy.sum(numpy.prod(args, 0), 0)
# Poly
out = args[0]
for arg in args[1:]:
out = out * arg
return sum(out) | [
"def",
"inner",
"(",
"*",
"args",
")",
":",
"haspoly",
"=",
"sum",
"(",
"[",
"isinstance",
"(",
"arg",
",",
"Poly",
")",
"for",
"arg",
"in",
"args",
"]",
")",
"# Numpy",
"if",
"not",
"haspoly",
":",
"return",
"numpy",
".",
"sum",
"(",
"numpy",
".... | Inner product of a polynomial set.
Args:
args (chaospy.poly.base.Poly):
The polynomials to perform inner product on.
Returns:
(chaospy.poly.base.Poly):
Resulting polynomial.
Examples:
>>> x,y = cp.variable(2)
>>> P = cp.Poly([x-1, y])
>>> Q = cp.Poly([x+1, x*y])
>>> print(cp.inner(P, Q))
q0^2+q0q1^2-1
>>> x = numpy.arange(4)
>>> print(cp.inner(x, x))
14 | [
"Inner",
"product",
"of",
"a",
"polynomial",
"set",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/linalg.py#L12-L44 | train | 206,951 |
jonathf/chaospy | chaospy/poly/collection/linalg.py | outer | def outer(*args):
"""
Polynomial outer product.
Args:
P1 (chaospy.poly.base.Poly, numpy.ndarray):
First term in outer product
P2 (chaospy.poly.base.Poly, numpy.ndarray):
Second term in outer product
Returns:
(chaospy.poly.base.Poly):
Poly set with same dimensions as itter.
Examples:
>>> x = cp.variable()
>>> P = cp.prange(3)
>>> print(P)
[1, q0, q0^2]
>>> print(cp.outer(x, P))
[q0, q0^2, q0^3]
>>> print(cp.outer(P, P))
[[1, q0, q0^2], [q0, q0^2, q0^3], [q0^2, q0^3, q0^4]]
"""
if len(args) > 2:
part1 = args[0]
part2 = outer(*args[1:])
elif len(args) == 2:
part1, part2 = args
else:
return args[0]
dtype = chaospy.poly.typing.dtyping(part1, part2)
if dtype in (list, tuple, numpy.ndarray):
part1 = numpy.array(part1)
part2 = numpy.array(part2)
shape = part1.shape + part2.shape
return numpy.outer(
chaospy.poly.shaping.flatten(part1),
chaospy.poly.shaping.flatten(part2),
)
if dtype == Poly:
if isinstance(part1, Poly) and isinstance(part2, Poly):
if (1,) in (part1.shape, part2.shape):
return part1*part2
shape = part1.shape+part2.shape
out = []
for _ in chaospy.poly.shaping.flatten(part1):
out.append(part2*_)
return chaospy.poly.shaping.reshape(Poly(out), shape)
if isinstance(part1, (int, float, list, tuple)):
part2, part1 = numpy.array(part1), part2
else:
part2 = numpy.array(part2)
core_old = part1.A
core_new = {}
for key in part1.keys:
core_new[key] = outer(core_old[key], part2)
shape = part1.shape+part2.shape
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
return Poly(core_new, part1.dim, shape, dtype)
raise NotImplementedError | python | def outer(*args):
"""
Polynomial outer product.
Args:
P1 (chaospy.poly.base.Poly, numpy.ndarray):
First term in outer product
P2 (chaospy.poly.base.Poly, numpy.ndarray):
Second term in outer product
Returns:
(chaospy.poly.base.Poly):
Poly set with same dimensions as itter.
Examples:
>>> x = cp.variable()
>>> P = cp.prange(3)
>>> print(P)
[1, q0, q0^2]
>>> print(cp.outer(x, P))
[q0, q0^2, q0^3]
>>> print(cp.outer(P, P))
[[1, q0, q0^2], [q0, q0^2, q0^3], [q0^2, q0^3, q0^4]]
"""
if len(args) > 2:
part1 = args[0]
part2 = outer(*args[1:])
elif len(args) == 2:
part1, part2 = args
else:
return args[0]
dtype = chaospy.poly.typing.dtyping(part1, part2)
if dtype in (list, tuple, numpy.ndarray):
part1 = numpy.array(part1)
part2 = numpy.array(part2)
shape = part1.shape + part2.shape
return numpy.outer(
chaospy.poly.shaping.flatten(part1),
chaospy.poly.shaping.flatten(part2),
)
if dtype == Poly:
if isinstance(part1, Poly) and isinstance(part2, Poly):
if (1,) in (part1.shape, part2.shape):
return part1*part2
shape = part1.shape+part2.shape
out = []
for _ in chaospy.poly.shaping.flatten(part1):
out.append(part2*_)
return chaospy.poly.shaping.reshape(Poly(out), shape)
if isinstance(part1, (int, float, list, tuple)):
part2, part1 = numpy.array(part1), part2
else:
part2 = numpy.array(part2)
core_old = part1.A
core_new = {}
for key in part1.keys:
core_new[key] = outer(core_old[key], part2)
shape = part1.shape+part2.shape
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
return Poly(core_new, part1.dim, shape, dtype)
raise NotImplementedError | [
"def",
"outer",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"part1",
"=",
"args",
"[",
"0",
"]",
"part2",
"=",
"outer",
"(",
"*",
"args",
"[",
"1",
":",
"]",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"2",
"... | Polynomial outer product.
Args:
P1 (chaospy.poly.base.Poly, numpy.ndarray):
First term in outer product
P2 (chaospy.poly.base.Poly, numpy.ndarray):
Second term in outer product
Returns:
(chaospy.poly.base.Poly):
Poly set with same dimensions as itter.
Examples:
>>> x = cp.variable()
>>> P = cp.prange(3)
>>> print(P)
[1, q0, q0^2]
>>> print(cp.outer(x, P))
[q0, q0^2, q0^3]
>>> print(cp.outer(P, P))
[[1, q0, q0^2], [q0, q0^2, q0^3], [q0^2, q0^3, q0^4]] | [
"Polynomial",
"outer",
"product",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/linalg.py#L47-L122 | train | 206,952 |
jonathf/chaospy | chaospy/poly/collection/linalg.py | dot | def dot(poly1, poly2):
"""
Dot product of polynomial vectors.
Args:
poly1 (Poly) : left part of product.
poly2 (Poly) : right part of product.
Returns:
(Poly) : product of poly1 and poly2.
Examples:
>>> poly = cp.prange(3, 1)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.dot(poly, numpy.arange(3)))
2q0^2+q0
>>> print(cp.dot(poly, poly))
q0^4+q0^2+1
"""
if not isinstance(poly1, Poly) and not isinstance(poly2, Poly):
return numpy.dot(poly1, poly2)
poly1 = Poly(poly1)
poly2 = Poly(poly2)
poly = poly1*poly2
if numpy.prod(poly1.shape) <= 1 or numpy.prod(poly2.shape) <= 1:
return poly
return chaospy.poly.sum(poly, 0) | python | def dot(poly1, poly2):
"""
Dot product of polynomial vectors.
Args:
poly1 (Poly) : left part of product.
poly2 (Poly) : right part of product.
Returns:
(Poly) : product of poly1 and poly2.
Examples:
>>> poly = cp.prange(3, 1)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.dot(poly, numpy.arange(3)))
2q0^2+q0
>>> print(cp.dot(poly, poly))
q0^4+q0^2+1
"""
if not isinstance(poly1, Poly) and not isinstance(poly2, Poly):
return numpy.dot(poly1, poly2)
poly1 = Poly(poly1)
poly2 = Poly(poly2)
poly = poly1*poly2
if numpy.prod(poly1.shape) <= 1 or numpy.prod(poly2.shape) <= 1:
return poly
return chaospy.poly.sum(poly, 0) | [
"def",
"dot",
"(",
"poly1",
",",
"poly2",
")",
":",
"if",
"not",
"isinstance",
"(",
"poly1",
",",
"Poly",
")",
"and",
"not",
"isinstance",
"(",
"poly2",
",",
"Poly",
")",
":",
"return",
"numpy",
".",
"dot",
"(",
"poly1",
",",
"poly2",
")",
"poly1",... | Dot product of polynomial vectors.
Args:
poly1 (Poly) : left part of product.
poly2 (Poly) : right part of product.
Returns:
(Poly) : product of poly1 and poly2.
Examples:
>>> poly = cp.prange(3, 1)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.dot(poly, numpy.arange(3)))
2q0^2+q0
>>> print(cp.dot(poly, poly))
q0^4+q0^2+1 | [
"Dot",
"product",
"of",
"polynomial",
"vectors",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/linalg.py#L125-L154 | train | 206,953 |
jonathf/chaospy | chaospy/quad/collection/genz_keister/gk16.py | quad_genz_keister_16 | def quad_genz_keister_16(order):
"""
Hermite Genz-Keister 16 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_16(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_16.keys())[order]
abscissas, weights = GENZ_KEISTER_16[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | python | def quad_genz_keister_16(order):
"""
Hermite Genz-Keister 16 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_16(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_16.keys())[order]
abscissas, weights = GENZ_KEISTER_16[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | [
"def",
"quad_genz_keister_16",
"(",
"order",
")",
":",
"order",
"=",
"sorted",
"(",
"GENZ_KEISTER_16",
".",
"keys",
"(",
")",
")",
"[",
"order",
"]",
"abscissas",
",",
"weights",
"=",
"GENZ_KEISTER_16",
"[",
"order",
"]",
"abscissas",
"=",
"numpy",
".",
... | Hermite Genz-Keister 16 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_16(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667] | [
"Hermite",
"Genz",
"-",
"Keister",
"16",
"rule",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/genz_keister/gk16.py#L7-L35 | train | 206,954 |
jonathf/chaospy | chaospy/orthogonal/gram_schmidt.py | orth_gs | def orth_gs(order, dist, normed=False, sort="GR", cross_truncation=1., **kws):
"""
Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly):
The orthogonal polynomial expansion.
Examples:
>>> Z = chaospy.J(chaospy.Normal(), chaospy.Normal())
>>> print(chaospy.around(chaospy.orth_gs(2, Z), 4))
[1.0, q1, q0, q1^2-1.0, q0q1, q0^2-1.0]
"""
logger = logging.getLogger(__name__)
dim = len(dist)
if isinstance(order, int):
if order == 0:
return chaospy.poly.Poly(1, dim=dim)
basis = chaospy.poly.basis(
0, order, dim, sort, cross_truncation=cross_truncation)
else:
basis = order
basis = list(basis)
polynomials = [basis[0]]
if normed:
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy]*orth
# normalize:
norms = chaospy.descriptives.E(polynomials[-1]**2, dist, **kws)
if norms <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
basis[idx] = basis[idx] / numpy.sqrt(norms)
polynomials.append(basis[idx])
else:
norms = [1.]
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy] * orth / norms[idy]
norms.append(
chaospy.descriptives.E(polynomials[-1]**2, dist, **kws))
if norms[-1] <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
polynomials.append(basis[idx])
return chaospy.poly.Poly(polynomials, dim=dim, shape=(len(polynomials),)) | python | def orth_gs(order, dist, normed=False, sort="GR", cross_truncation=1., **kws):
"""
Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly):
The orthogonal polynomial expansion.
Examples:
>>> Z = chaospy.J(chaospy.Normal(), chaospy.Normal())
>>> print(chaospy.around(chaospy.orth_gs(2, Z), 4))
[1.0, q1, q0, q1^2-1.0, q0q1, q0^2-1.0]
"""
logger = logging.getLogger(__name__)
dim = len(dist)
if isinstance(order, int):
if order == 0:
return chaospy.poly.Poly(1, dim=dim)
basis = chaospy.poly.basis(
0, order, dim, sort, cross_truncation=cross_truncation)
else:
basis = order
basis = list(basis)
polynomials = [basis[0]]
if normed:
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy]*orth
# normalize:
norms = chaospy.descriptives.E(polynomials[-1]**2, dist, **kws)
if norms <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
basis[idx] = basis[idx] / numpy.sqrt(norms)
polynomials.append(basis[idx])
else:
norms = [1.]
for idx in range(1, len(basis)):
# orthogonalize polynomial:
for idy in range(idx):
orth = chaospy.descriptives.E(
basis[idx]*polynomials[idy], dist, **kws)
basis[idx] = basis[idx] - polynomials[idy] * orth / norms[idy]
norms.append(
chaospy.descriptives.E(polynomials[-1]**2, dist, **kws))
if norms[-1] <= 0:
logger.warning("Warning: Polynomial cutoff at term %d", idx)
break
polynomials.append(basis[idx])
return chaospy.poly.Poly(polynomials, dim=dim, shape=(len(polynomials),)) | [
"def",
"orth_gs",
"(",
"order",
",",
"dist",
",",
"normed",
"=",
"False",
",",
"sort",
"=",
"\"GR\"",
",",
"cross_truncation",
"=",
"1.",
",",
"*",
"*",
"kws",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"dim",
"=",
... | Gram-Schmidt process for generating orthogonal polynomials.
Args:
order (int, Poly):
The upper polynomial order. Alternative a custom polynomial basis
can be used.
dist (Dist):
Weighting distribution(s) defining orthogonality.
normed (bool):
If True orthonormal polynomials will be used instead of monic.
sort (str):
Ordering argument passed to poly.basis. If custom basis is used,
argument is ignored.
cross_truncation (float):
Use hyperbolic cross truncation scheme to reduce the number of
terms in expansion.
Returns:
(Poly):
The orthogonal polynomial expansion.
Examples:
>>> Z = chaospy.J(chaospy.Normal(), chaospy.Normal())
>>> print(chaospy.around(chaospy.orth_gs(2, Z), 4))
[1.0, q1, q0, q1^2-1.0, q0q1, q0^2-1.0] | [
"Gram",
"-",
"Schmidt",
"process",
"for",
"generating",
"orthogonal",
"polynomials",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/orthogonal/gram_schmidt.py#L12-L92 | train | 206,955 |
jonathf/chaospy | chaospy/distributions/evaluation/parameters.py | load_parameters | def load_parameters(
distribution,
method_name,
parameters=None,
cache=None,
cache_key=lambda x:x,
):
"""
Load parameter values by filling them in from cache.
Args:
distribution (Dist):
The distribution to load parameters from.
method_name (str):
Name of the method for where the parameters should be used.
Typically ``"_pdf"``, ``_cdf`` or the like.
parameters (:py:data:typing.Any):
Default parameters to use if there are no cache to retrieve. Use
the distributions internal parameters, if not provided.
cache (:py:data:typing.Any):
A dictionary containing previous evaluations from the stack. If
a parameters contains a distribution that contains in the cache, it
will be replaced with the cache value. If omitted, a new one will
be created.
cache_key (:py:data:typing.Any)
Redefine the keys of the cache to suite other purposes.
Returns:
Same as ``parameters``, if provided. The ``distribution`` parameter if
not. In either case, parameters may be updated with cache values (if
provided) or by ``cache`` if the call signature of ``method_name`` (on
``distribution``) contains an ``cache`` argument.
"""
from .. import baseclass
if cache is None:
cache = {}
if parameters is None:
parameters = {}
parameters_ = distribution.prm.copy()
parameters_.update(**parameters)
parameters = parameters_
# self aware and should handle things itself:
if contains_call_signature(getattr(distribution, method_name), "cache"):
parameters["cache"] = cache
# dumb distribution and just wants to evaluate:
else:
for key, value in parameters.items():
if isinstance(value, baseclass.Dist):
value = cache_key(value)
if value in cache:
parameters[key] = cache[value]
else:
raise baseclass.StochasticallyDependentError(
"evaluating under-defined distribution {}.".format(distribution))
return parameters | python | def load_parameters(
distribution,
method_name,
parameters=None,
cache=None,
cache_key=lambda x:x,
):
"""
Load parameter values by filling them in from cache.
Args:
distribution (Dist):
The distribution to load parameters from.
method_name (str):
Name of the method for where the parameters should be used.
Typically ``"_pdf"``, ``_cdf`` or the like.
parameters (:py:data:typing.Any):
Default parameters to use if there are no cache to retrieve. Use
the distributions internal parameters, if not provided.
cache (:py:data:typing.Any):
A dictionary containing previous evaluations from the stack. If
a parameters contains a distribution that contains in the cache, it
will be replaced with the cache value. If omitted, a new one will
be created.
cache_key (:py:data:typing.Any)
Redefine the keys of the cache to suite other purposes.
Returns:
Same as ``parameters``, if provided. The ``distribution`` parameter if
not. In either case, parameters may be updated with cache values (if
provided) or by ``cache`` if the call signature of ``method_name`` (on
``distribution``) contains an ``cache`` argument.
"""
from .. import baseclass
if cache is None:
cache = {}
if parameters is None:
parameters = {}
parameters_ = distribution.prm.copy()
parameters_.update(**parameters)
parameters = parameters_
# self aware and should handle things itself:
if contains_call_signature(getattr(distribution, method_name), "cache"):
parameters["cache"] = cache
# dumb distribution and just wants to evaluate:
else:
for key, value in parameters.items():
if isinstance(value, baseclass.Dist):
value = cache_key(value)
if value in cache:
parameters[key] = cache[value]
else:
raise baseclass.StochasticallyDependentError(
"evaluating under-defined distribution {}.".format(distribution))
return parameters | [
"def",
"load_parameters",
"(",
"distribution",
",",
"method_name",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"cache_key",
"=",
"lambda",
"x",
":",
"x",
",",
")",
":",
"from",
".",
".",
"import",
"baseclass",
"if",
"cache",
"is",
"... | Load parameter values by filling them in from cache.
Args:
distribution (Dist):
The distribution to load parameters from.
method_name (str):
Name of the method for where the parameters should be used.
Typically ``"_pdf"``, ``_cdf`` or the like.
parameters (:py:data:typing.Any):
Default parameters to use if there are no cache to retrieve. Use
the distributions internal parameters, if not provided.
cache (:py:data:typing.Any):
A dictionary containing previous evaluations from the stack. If
a parameters contains a distribution that contains in the cache, it
will be replaced with the cache value. If omitted, a new one will
be created.
cache_key (:py:data:typing.Any)
Redefine the keys of the cache to suite other purposes.
Returns:
Same as ``parameters``, if provided. The ``distribution`` parameter if
not. In either case, parameters may be updated with cache values (if
provided) or by ``cache`` if the call signature of ``method_name`` (on
``distribution``) contains an ``cache`` argument. | [
"Load",
"parameter",
"values",
"by",
"filling",
"them",
"in",
"from",
"cache",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/parameters.py#L57-L114 | train | 206,956 |
jonathf/chaospy | chaospy/quad/collection/genz_keister/gk18.py | quad_genz_keister_18 | def quad_genz_keister_18(order):
"""
Hermite Genz-Keister 18 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_18(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_18.keys())[order]
abscissas, weights = GENZ_KEISTER_18[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | python | def quad_genz_keister_18(order):
"""
Hermite Genz-Keister 18 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_18(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_18.keys())[order]
abscissas, weights = GENZ_KEISTER_18[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | [
"def",
"quad_genz_keister_18",
"(",
"order",
")",
":",
"order",
"=",
"sorted",
"(",
"GENZ_KEISTER_18",
".",
"keys",
"(",
")",
")",
"[",
"order",
"]",
"abscissas",
",",
"weights",
"=",
"GENZ_KEISTER_18",
"[",
"order",
"]",
"abscissas",
"=",
"numpy",
".",
... | Hermite Genz-Keister 18 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_18(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667] | [
"Hermite",
"Genz",
"-",
"Keister",
"18",
"rule",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/genz_keister/gk18.py#L7-L35 | train | 206,957 |
jonathf/chaospy | chaospy/poly/typing.py | dtyping | def dtyping(*args):
"""
Find least common denominator dtype.
Examples:
>>> str(dtyping(int, float)) in ("<class 'float'>", "<type 'float'>")
True
>>> print(dtyping(int, Poly))
<class 'chaospy.poly.base.Poly'>
"""
args = list(args)
for idx, arg in enumerate(args):
if isinstance(arg, Poly):
args[idx] = Poly
elif isinstance(arg, numpy.generic):
args[idx] = numpy.asarray(arg).dtype
elif isinstance(arg, (float, int)):
args[idx] = type(arg)
for type_ in DATATYPES:
if type_ in args:
return type_
raise ValueError(
"dtypes not recognised " + str([str(_) for _ in args])) | python | def dtyping(*args):
"""
Find least common denominator dtype.
Examples:
>>> str(dtyping(int, float)) in ("<class 'float'>", "<type 'float'>")
True
>>> print(dtyping(int, Poly))
<class 'chaospy.poly.base.Poly'>
"""
args = list(args)
for idx, arg in enumerate(args):
if isinstance(arg, Poly):
args[idx] = Poly
elif isinstance(arg, numpy.generic):
args[idx] = numpy.asarray(arg).dtype
elif isinstance(arg, (float, int)):
args[idx] = type(arg)
for type_ in DATATYPES:
if type_ in args:
return type_
raise ValueError(
"dtypes not recognised " + str([str(_) for _ in args])) | [
"def",
"dtyping",
"(",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"for",
"idx",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Poly",
")",
":",
"args",
"[",
"idx",
"]",
"=",
"Poly"... | Find least common denominator dtype.
Examples:
>>> str(dtyping(int, float)) in ("<class 'float'>", "<type 'float'>")
True
>>> print(dtyping(int, Poly))
<class 'chaospy.poly.base.Poly'> | [
"Find",
"least",
"common",
"denominator",
"dtype",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/typing.py#L22-L50 | train | 206,958 |
jonathf/chaospy | chaospy/poly/typing.py | toarray | def toarray(vari):
"""
Convert polynomial array into a numpy.asarray of polynomials.
Args:
vari (Poly, numpy.ndarray):
Input data.
Returns:
(numpy.ndarray):
A numpy array with ``Q.shape==A.shape``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> array = cp.toarray(poly)
>>> print(isinstance(array, numpy.ndarray))
True
>>> print(array[1])
q0
"""
if isinstance(vari, Poly):
shape = vari.shape
out = numpy.asarray(
[{} for _ in range(numpy.prod(shape))],
dtype=object
)
core = vari.A.copy()
for key in core.keys():
core[key] = core[key].flatten()
for i in range(numpy.prod(shape)):
if not numpy.all(core[key][i] == 0):
out[i][key] = core[key][i]
for i in range(numpy.prod(shape)):
out[i] = Poly(out[i], vari.dim, (), vari.dtype)
out = out.reshape(shape)
return out
return numpy.asarray(vari) | python | def toarray(vari):
"""
Convert polynomial array into a numpy.asarray of polynomials.
Args:
vari (Poly, numpy.ndarray):
Input data.
Returns:
(numpy.ndarray):
A numpy array with ``Q.shape==A.shape``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> array = cp.toarray(poly)
>>> print(isinstance(array, numpy.ndarray))
True
>>> print(array[1])
q0
"""
if isinstance(vari, Poly):
shape = vari.shape
out = numpy.asarray(
[{} for _ in range(numpy.prod(shape))],
dtype=object
)
core = vari.A.copy()
for key in core.keys():
core[key] = core[key].flatten()
for i in range(numpy.prod(shape)):
if not numpy.all(core[key][i] == 0):
out[i][key] = core[key][i]
for i in range(numpy.prod(shape)):
out[i] = Poly(out[i], vari.dim, (), vari.dtype)
out = out.reshape(shape)
return out
return numpy.asarray(vari) | [
"def",
"toarray",
"(",
"vari",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"shape",
"=",
"vari",
".",
"shape",
"out",
"=",
"numpy",
".",
"asarray",
"(",
"[",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"numpy",
".",
"prod",
... | Convert polynomial array into a numpy.asarray of polynomials.
Args:
vari (Poly, numpy.ndarray):
Input data.
Returns:
(numpy.ndarray):
A numpy array with ``Q.shape==A.shape``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> array = cp.toarray(poly)
>>> print(isinstance(array, numpy.ndarray))
True
>>> print(array[1])
q0 | [
"Convert",
"polynomial",
"array",
"into",
"a",
"numpy",
".",
"asarray",
"of",
"polynomials",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/typing.py#L115-L159 | train | 206,959 |
jonathf/chaospy | chaospy/distributions/operators/iid.py | Iid._bnd | def _bnd(self, xloc, dist, length, cache):
"""
boundary function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).range(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[[0. 0. 0.]
[0. 0. 0.]]
<BLANKLINE>
[[2. 2. 2.]
[2. 2. 2.]]]
"""
lower, upper = evaluation.evaluate_bound(
dist, xloc.reshape(1, -1))
lower = lower.reshape(length, -1)
upper = upper.reshape(length, -1)
assert lower.shape == xloc.shape, (lower.shape, xloc.shape)
assert upper.shape == xloc.shape
return lower, upper | python | def _bnd(self, xloc, dist, length, cache):
"""
boundary function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).range(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[[0. 0. 0.]
[0. 0. 0.]]
<BLANKLINE>
[[2. 2. 2.]
[2. 2. 2.]]]
"""
lower, upper = evaluation.evaluate_bound(
dist, xloc.reshape(1, -1))
lower = lower.reshape(length, -1)
upper = upper.reshape(length, -1)
assert lower.shape == xloc.shape, (lower.shape, xloc.shape)
assert upper.shape == xloc.shape
return lower, upper | [
"def",
"_bnd",
"(",
"self",
",",
"xloc",
",",
"dist",
",",
"length",
",",
"cache",
")",
":",
"lower",
",",
"upper",
"=",
"evaluation",
".",
"evaluate_bound",
"(",
"dist",
",",
"xloc",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
")",
"lower",
"=... | boundary function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).range(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[[0. 0. 0.]
[0. 0. 0.]]
<BLANKLINE>
[[2. 2. 2.]
[2. 2. 2.]]] | [
"boundary",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/iid.py#L75-L94 | train | 206,960 |
jonathf/chaospy | chaospy/distributions/operators/iid.py | Iid._mom | def _mom(self, k, dist, length, cache):
"""
Moment generating function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(), 2).mom(
... [[0, 0, 1], [0, 1, 1]]))
[1. 0.5 0.25]
"""
return numpy.prod(dist.mom(k), 0) | python | def _mom(self, k, dist, length, cache):
"""
Moment generating function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(), 2).mom(
... [[0, 0, 1], [0, 1, 1]]))
[1. 0.5 0.25]
"""
return numpy.prod(dist.mom(k), 0) | [
"def",
"_mom",
"(",
"self",
",",
"k",
",",
"dist",
",",
"length",
",",
"cache",
")",
":",
"return",
"numpy",
".",
"prod",
"(",
"dist",
".",
"mom",
"(",
"k",
")",
",",
"0",
")"
] | Moment generating function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(), 2).mom(
... [[0, 0, 1], [0, 1, 1]]))
[1. 0.5 0.25] | [
"Moment",
"generating",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/iid.py#L96-L105 | train | 206,961 |
jonathf/chaospy | chaospy/poly/collection/numpy_.py | sum | def sum(vari, axis=None): # pylint: disable=redefined-builtin
"""
Sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.sum(vari))
q0^2+q0+1
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = sum(core[key], axis)
return Poly(core, vari.dim, None, vari.dtype)
return np.sum(vari, axis) | python | def sum(vari, axis=None): # pylint: disable=redefined-builtin
"""
Sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.sum(vari))
q0^2+q0+1
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = sum(core[key], axis)
return Poly(core, vari.dim, None, vari.dtype)
return np.sum(vari, axis) | [
"def",
"sum",
"(",
"vari",
",",
"axis",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys... | Sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.sum(vari))
q0^2+q0+1 | [
"Sum",
"the",
"components",
"of",
"a",
"shapeable",
"quantity",
"along",
"a",
"given",
"axis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/numpy_.py#L11-L43 | train | 206,962 |
jonathf/chaospy | chaospy/poly/collection/numpy_.py | cumsum | def cumsum(vari, axis=None):
"""
Cumulative sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.cumsum(poly))
[1, q0+1, q0^2+q0+1]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key, val in core.items():
core[key] = cumsum(val, axis)
return Poly(core, vari.dim, None, vari.dtype)
return np.cumsum(vari, axis) | python | def cumsum(vari, axis=None):
"""
Cumulative sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.cumsum(poly))
[1, q0+1, q0^2+q0+1]
"""
if isinstance(vari, Poly):
core = vari.A.copy()
for key, val in core.items():
core[key] = cumsum(val, axis)
return Poly(core, vari.dim, None, vari.dtype)
return np.cumsum(vari, axis) | [
"def",
"cumsum",
"(",
"vari",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
",",
"val",
"in",
"core",
".",
"items",
"(",
")",
":... | Cumulative sum the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``.
Examples:
>>> poly = cp.prange(3)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.cumsum(poly))
[1, q0+1, q0^2+q0+1] | [
"Cumulative",
"sum",
"the",
"components",
"of",
"a",
"shapeable",
"quantity",
"along",
"a",
"given",
"axis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/numpy_.py#L46-L74 | train | 206,963 |
jonathf/chaospy | chaospy/poly/collection/numpy_.py | prod | def prod(vari, axis=None):
"""
Product of the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.prod(vari))
q0^3
"""
if isinstance(vari, Poly):
if axis is None:
vari = chaospy.poly.shaping.flatten(vari)
axis = 0
vari = chaospy.poly.shaping.rollaxis(vari, axis)
out = vari[0]
for poly in vari[1:]:
out = out*poly
return out
return np.prod(vari, axis) | python | def prod(vari, axis=None):
"""
Product of the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.prod(vari))
q0^3
"""
if isinstance(vari, Poly):
if axis is None:
vari = chaospy.poly.shaping.flatten(vari)
axis = 0
vari = chaospy.poly.shaping.rollaxis(vari, axis)
out = vari[0]
for poly in vari[1:]:
out = out*poly
return out
return np.prod(vari, axis) | [
"def",
"prod",
"(",
"vari",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"if",
"axis",
"is",
"None",
":",
"vari",
"=",
"chaospy",
".",
"poly",
".",
"shaping",
".",
"flatten",
"(",
"vari",
")",
"axis"... | Product of the components of a shapeable quantity along a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly, numpy.ndarray):
Polynomial array with same shape as ``vari``, with the specified
axis removed. If ``vari`` is an 0-d array, or ``axis`` is None,
a (non-iterable) component is returned.
Examples:
>>> vari = cp.prange(3)
>>> print(vari)
[1, q0, q0^2]
>>> print(cp.prod(vari))
q0^3 | [
"Product",
"of",
"the",
"components",
"of",
"a",
"shapeable",
"quantity",
"along",
"a",
"given",
"axis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/numpy_.py#L77-L112 | train | 206,964 |
jonathf/chaospy | chaospy/poly/collection/numpy_.py | cumprod | def cumprod(vari, axis=None):
"""
Perform the cumulative product of a shapeable quantity over a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly):
An array shaped as ``vari`` but with the specified axis removed.
Examples:
>>> vari = cp.prange(4)
>>> print(vari)
[1, q0, q0^2, q0^3]
>>> print(cp.cumprod(vari))
[1, q0, q0^3, q0^6]
"""
if isinstance(vari, Poly):
if np.prod(vari.shape) == 1:
return vari.copy()
if axis is None:
vari = chaospy.poly.shaping.flatten(vari)
axis = 0
vari = chaospy.poly.shaping.rollaxis(vari, axis)
out = [vari[0]]
for poly in vari[1:]:
out.append(out[-1]*poly)
return Poly(out, vari.dim, vari.shape, vari.dtype)
return np.cumprod(vari, axis) | python | def cumprod(vari, axis=None):
"""
Perform the cumulative product of a shapeable quantity over a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly):
An array shaped as ``vari`` but with the specified axis removed.
Examples:
>>> vari = cp.prange(4)
>>> print(vari)
[1, q0, q0^2, q0^3]
>>> print(cp.cumprod(vari))
[1, q0, q0^3, q0^6]
"""
if isinstance(vari, Poly):
if np.prod(vari.shape) == 1:
return vari.copy()
if axis is None:
vari = chaospy.poly.shaping.flatten(vari)
axis = 0
vari = chaospy.poly.shaping.rollaxis(vari, axis)
out = [vari[0]]
for poly in vari[1:]:
out.append(out[-1]*poly)
return Poly(out, vari.dim, vari.shape, vari.dtype)
return np.cumprod(vari, axis) | [
"def",
"cumprod",
"(",
"vari",
",",
"axis",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"if",
"np",
".",
"prod",
"(",
"vari",
".",
"shape",
")",
"==",
"1",
":",
"return",
"vari",
".",
"copy",
"(",
")",
"if",
... | Perform the cumulative product of a shapeable quantity over a given axis.
Args:
vari (chaospy.poly.base.Poly, numpy.ndarray):
Input data.
axis (int):
Axis over which the sum is taken. By default ``axis`` is None, and
all elements are summed.
Returns:
(chaospy.poly.base.Poly):
An array shaped as ``vari`` but with the specified axis removed.
Examples:
>>> vari = cp.prange(4)
>>> print(vari)
[1, q0, q0^2, q0^3]
>>> print(cp.cumprod(vari))
[1, q0, q0^3, q0^6] | [
"Perform",
"the",
"cumulative",
"product",
"of",
"a",
"shapeable",
"quantity",
"over",
"a",
"given",
"axis",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/numpy_.py#L115-L151 | train | 206,965 |
jonathf/chaospy | chaospy/quad/collection/leja.py | quad_leja | def quad_leja(order, dist):
"""
Generate Leja quadrature node.
Example:
>>> abscisas, weights = quad_leja(3, chaospy.Normal(0, 1))
>>> print(numpy.around(abscisas, 4))
[[-2.7173 -1.4142 0. 1.7635]]
>>> print(numpy.around(weights, 4))
[0.022 0.1629 0.6506 0.1645]
"""
from chaospy.distributions import evaluation
if len(dist) > 1 and evaluation.get_dependencies(*list(dist)):
raise evaluation.DependencyError(
"Leja quadrature do not supper distribution with dependencies.")
if len(dist) > 1:
if isinstance(order, int):
out = [quad_leja(order, _) for _ in dist]
else:
out = [quad_leja(order[_], dist[_]) for _ in range(len(dist))]
abscissas = [_[0][0] for _ in out]
weights = [_[1] for _ in out]
abscissas = chaospy.quad.combine(abscissas).T
weights = chaospy.quad.combine(weights)
weights = numpy.prod(weights, -1)
return abscissas, weights
lower, upper = dist.range()
abscissas = [lower, dist.mom(1), upper]
for _ in range(int(order)):
obj = create_objective(dist, abscissas)
opts, vals = zip(
*[fminbound(
obj, abscissas[idx], abscissas[idx+1], full_output=1)[:2]
for idx in range(len(abscissas)-1)]
)
index = numpy.argmin(vals)
abscissas.insert(index+1, opts[index])
abscissas = numpy.asfarray(abscissas).flatten()[1:-1]
weights = create_weights(abscissas, dist)
abscissas = abscissas.reshape(1, abscissas.size)
return numpy.array(abscissas), numpy.array(weights) | python | def quad_leja(order, dist):
"""
Generate Leja quadrature node.
Example:
>>> abscisas, weights = quad_leja(3, chaospy.Normal(0, 1))
>>> print(numpy.around(abscisas, 4))
[[-2.7173 -1.4142 0. 1.7635]]
>>> print(numpy.around(weights, 4))
[0.022 0.1629 0.6506 0.1645]
"""
from chaospy.distributions import evaluation
if len(dist) > 1 and evaluation.get_dependencies(*list(dist)):
raise evaluation.DependencyError(
"Leja quadrature do not supper distribution with dependencies.")
if len(dist) > 1:
if isinstance(order, int):
out = [quad_leja(order, _) for _ in dist]
else:
out = [quad_leja(order[_], dist[_]) for _ in range(len(dist))]
abscissas = [_[0][0] for _ in out]
weights = [_[1] for _ in out]
abscissas = chaospy.quad.combine(abscissas).T
weights = chaospy.quad.combine(weights)
weights = numpy.prod(weights, -1)
return abscissas, weights
lower, upper = dist.range()
abscissas = [lower, dist.mom(1), upper]
for _ in range(int(order)):
obj = create_objective(dist, abscissas)
opts, vals = zip(
*[fminbound(
obj, abscissas[idx], abscissas[idx+1], full_output=1)[:2]
for idx in range(len(abscissas)-1)]
)
index = numpy.argmin(vals)
abscissas.insert(index+1, opts[index])
abscissas = numpy.asfarray(abscissas).flatten()[1:-1]
weights = create_weights(abscissas, dist)
abscissas = abscissas.reshape(1, abscissas.size)
return numpy.array(abscissas), numpy.array(weights) | [
"def",
"quad_leja",
"(",
"order",
",",
"dist",
")",
":",
"from",
"chaospy",
".",
"distributions",
"import",
"evaluation",
"if",
"len",
"(",
"dist",
")",
">",
"1",
"and",
"evaluation",
".",
"get_dependencies",
"(",
"*",
"list",
"(",
"dist",
")",
")",
":... | Generate Leja quadrature node.
Example:
>>> abscisas, weights = quad_leja(3, chaospy.Normal(0, 1))
>>> print(numpy.around(abscisas, 4))
[[-2.7173 -1.4142 0. 1.7635]]
>>> print(numpy.around(weights, 4))
[0.022 0.1629 0.6506 0.1645] | [
"Generate",
"Leja",
"quadrature",
"node",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/leja.py#L29-L76 | train | 206,966 |
jonathf/chaospy | chaospy/quad/collection/leja.py | create_objective | def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
return obj | python | def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
return obj | [
"def",
"create_objective",
"(",
"dist",
",",
"abscissas",
")",
":",
"abscissas_",
"=",
"numpy",
".",
"array",
"(",
"abscissas",
"[",
"1",
":",
"-",
"1",
"]",
")",
"def",
"obj",
"(",
"absisa",
")",
":",
"\"\"\"Local objective function.\"\"\"",
"out",
"=",
... | Create objective function. | [
"Create",
"objective",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/leja.py#L79-L87 | train | 206,967 |
jonathf/chaospy | chaospy/quad/collection/leja.py | create_weights | def create_weights(nodes, dist):
"""Create weights for the Laja method."""
poly = chaospy.quad.generate_stieltjes(dist, len(nodes)-1, retall=True)[0]
poly = chaospy.poly.flatten(chaospy.poly.Poly(poly))
weights_inverse = poly(nodes)
weights = numpy.linalg.inv(weights_inverse)
return weights[:, 0] | python | def create_weights(nodes, dist):
"""Create weights for the Laja method."""
poly = chaospy.quad.generate_stieltjes(dist, len(nodes)-1, retall=True)[0]
poly = chaospy.poly.flatten(chaospy.poly.Poly(poly))
weights_inverse = poly(nodes)
weights = numpy.linalg.inv(weights_inverse)
return weights[:, 0] | [
"def",
"create_weights",
"(",
"nodes",
",",
"dist",
")",
":",
"poly",
"=",
"chaospy",
".",
"quad",
".",
"generate_stieltjes",
"(",
"dist",
",",
"len",
"(",
"nodes",
")",
"-",
"1",
",",
"retall",
"=",
"True",
")",
"[",
"0",
"]",
"poly",
"=",
"chaosp... | Create weights for the Laja method. | [
"Create",
"weights",
"for",
"the",
"Laja",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/leja.py#L90-L96 | train | 206,968 |
jonathf/chaospy | chaospy/chol/gill_king.py | gill_king | def gill_king(mat, eps=1e-16):
"""
Gill-King algorithm for modified cholesky decomposition.
Args:
mat (numpy.ndarray):
Must be a non-singular and symmetric matrix. If sparse, the result
will also be sparse.
eps (float):
Error tolerance used in algorithm.
Returns:
(numpy.ndarray):
Lower triangular Cholesky factor.
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> lowtri = gill_king(mat)
>>> print(numpy.around(lowtri, 4))
[[2. 0. 0. ]
[1. 2.2361 0. ]
[0.5 1.118 1.2264]]
>>> print(numpy.around(numpy.dot(lowtri, lowtri.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 3.004]]
"""
if not scipy.sparse.issparse(mat):
mat = numpy.asfarray(mat)
assert numpy.allclose(mat, mat.T)
size = mat.shape[0]
mat_diag = mat.diagonal()
gamma = abs(mat_diag).max()
off_diag = abs(mat - numpy.diag(mat_diag)).max()
delta = eps*max(gamma + off_diag, 1)
beta = numpy.sqrt(max(gamma, off_diag/size, eps))
lowtri = _gill_king(mat, beta, delta)
return lowtri | python | def gill_king(mat, eps=1e-16):
"""
Gill-King algorithm for modified cholesky decomposition.
Args:
mat (numpy.ndarray):
Must be a non-singular and symmetric matrix. If sparse, the result
will also be sparse.
eps (float):
Error tolerance used in algorithm.
Returns:
(numpy.ndarray):
Lower triangular Cholesky factor.
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> lowtri = gill_king(mat)
>>> print(numpy.around(lowtri, 4))
[[2. 0. 0. ]
[1. 2.2361 0. ]
[0.5 1.118 1.2264]]
>>> print(numpy.around(numpy.dot(lowtri, lowtri.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 3.004]]
"""
if not scipy.sparse.issparse(mat):
mat = numpy.asfarray(mat)
assert numpy.allclose(mat, mat.T)
size = mat.shape[0]
mat_diag = mat.diagonal()
gamma = abs(mat_diag).max()
off_diag = abs(mat - numpy.diag(mat_diag)).max()
delta = eps*max(gamma + off_diag, 1)
beta = numpy.sqrt(max(gamma, off_diag/size, eps))
lowtri = _gill_king(mat, beta, delta)
return lowtri | [
"def",
"gill_king",
"(",
"mat",
",",
"eps",
"=",
"1e-16",
")",
":",
"if",
"not",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"mat",
")",
":",
"mat",
"=",
"numpy",
".",
"asfarray",
"(",
"mat",
")",
"assert",
"numpy",
".",
"allclose",
"(",
"mat",
... | Gill-King algorithm for modified cholesky decomposition.
Args:
mat (numpy.ndarray):
Must be a non-singular and symmetric matrix. If sparse, the result
will also be sparse.
eps (float):
Error tolerance used in algorithm.
Returns:
(numpy.ndarray):
Lower triangular Cholesky factor.
Examples:
>>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]
>>> lowtri = gill_king(mat)
>>> print(numpy.around(lowtri, 4))
[[2. 0. 0. ]
[1. 2.2361 0. ]
[0.5 1.118 1.2264]]
>>> print(numpy.around(numpy.dot(lowtri, lowtri.T), 4))
[[4. 2. 1. ]
[2. 6. 3. ]
[1. 3. 3.004]] | [
"Gill",
"-",
"King",
"algorithm",
"for",
"modified",
"cholesky",
"decomposition",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/chol/gill_king.py#L12-L54 | train | 206,969 |
jonathf/chaospy | chaospy/chol/gill_king.py | _gill_king | def _gill_king(mat, beta, delta):
"""Backend function for the Gill-King algorithm."""
size = mat.shape[0]
# initialize d_vec and lowtri
if scipy.sparse.issparse(mat):
lowtri = scipy.sparse.eye(*mat.shape)
else:
lowtri = numpy.eye(size)
d_vec = numpy.zeros(size, dtype=float)
# there are no inner for loops, everything implemented with
# vector operations for a reasonable level of efficiency
for idx in range(size):
if idx == 0:
idz = [] # column index: all columns to left of diagonal
# d_vec(idz) doesn't work in case idz is empty
else:
idz = numpy.s_[:idx]
djtemp = mat[idx, idx] - numpy.dot(
lowtri[idx, idz], d_vec[idz]*lowtri[idx, idz].T)
# C(idx, idx) in book
if idx < size - 1:
idy = numpy.s_[idx+1:size]
# row index: all rows below diagonal
ccol = mat[idy, idx] - numpy.dot(
lowtri[idy, idz], d_vec[idz]*lowtri[idx, idz].T)
# C(idy, idx) in book
theta = abs(ccol).max()
# guarantees d_vec(idx) not too small and lowtri(idy, idx) not too
# big in sufficiently positive definite case, d_vec(idx) = djtemp
d_vec[idx] = max(abs(djtemp), (theta/beta)**2, delta)
lowtri[idy, idx] = ccol/d_vec[idx]
else:
d_vec[idx] = max(abs(djtemp), delta)
# convert to usual output format: replace lowtri by lowtri*sqrt(D) and
# transpose
for idx in range(size):
lowtri[:, idx] = lowtri[:, idx]*numpy.sqrt(d_vec[idx])
# lowtri = lowtri*diag(sqrt(d_vec)) bad in sparse case
return lowtri | python | def _gill_king(mat, beta, delta):
"""Backend function for the Gill-King algorithm."""
size = mat.shape[0]
# initialize d_vec and lowtri
if scipy.sparse.issparse(mat):
lowtri = scipy.sparse.eye(*mat.shape)
else:
lowtri = numpy.eye(size)
d_vec = numpy.zeros(size, dtype=float)
# there are no inner for loops, everything implemented with
# vector operations for a reasonable level of efficiency
for idx in range(size):
if idx == 0:
idz = [] # column index: all columns to left of diagonal
# d_vec(idz) doesn't work in case idz is empty
else:
idz = numpy.s_[:idx]
djtemp = mat[idx, idx] - numpy.dot(
lowtri[idx, idz], d_vec[idz]*lowtri[idx, idz].T)
# C(idx, idx) in book
if idx < size - 1:
idy = numpy.s_[idx+1:size]
# row index: all rows below diagonal
ccol = mat[idy, idx] - numpy.dot(
lowtri[idy, idz], d_vec[idz]*lowtri[idx, idz].T)
# C(idy, idx) in book
theta = abs(ccol).max()
# guarantees d_vec(idx) not too small and lowtri(idy, idx) not too
# big in sufficiently positive definite case, d_vec(idx) = djtemp
d_vec[idx] = max(abs(djtemp), (theta/beta)**2, delta)
lowtri[idy, idx] = ccol/d_vec[idx]
else:
d_vec[idx] = max(abs(djtemp), delta)
# convert to usual output format: replace lowtri by lowtri*sqrt(D) and
# transpose
for idx in range(size):
lowtri[:, idx] = lowtri[:, idx]*numpy.sqrt(d_vec[idx])
# lowtri = lowtri*diag(sqrt(d_vec)) bad in sparse case
return lowtri | [
"def",
"_gill_king",
"(",
"mat",
",",
"beta",
",",
"delta",
")",
":",
"size",
"=",
"mat",
".",
"shape",
"[",
"0",
"]",
"# initialize d_vec and lowtri",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"mat",
")",
":",
"lowtri",
"=",
"scipy",
".",
... | Backend function for the Gill-King algorithm. | [
"Backend",
"function",
"for",
"the",
"Gill",
"-",
"King",
"algorithm",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/chol/gill_king.py#L57-L103 | train | 206,970 |
jonathf/chaospy | chaospy/distributions/approximation.py | approximate_moment | def approximate_moment(
dist,
K,
retall=False,
control_var=None,
rule="F",
order=1000,
**kws
):
"""
Approximation method for estimation of raw statistical moments.
Args:
dist : Dist
Distribution domain with dim=len(dist)
K : numpy.ndarray
The exponents of the moments of interest with shape (dim,K).
control_var : Dist
If provided will be used as a control variable to try to reduce
the error.
acc (:py:data:typing.Optional[int]):
The order of quadrature/MCI
sparse : bool
If True used Smolyak's sparse grid instead of normal tensor
product grid in numerical integration.
rule : str
Quadrature rule
Key Description
---- -----------
"G" Optiomal Gaussian quadrature from Golub-Welsch
Slow for high order and composit is ignored.
"E" Gauss-Legendre quadrature
"C" Clenshaw-Curtis quadrature. Exponential growth rule is
used when sparse is True to make the rule nested.
Monte Carlo Integration
Key Description
---- -----------
"H" Halton sequence
"K" Korobov set
"L" Latin hypercube sampling
"M" Hammersley sequence
"R" (Pseudo-)Random sampling
"S" Sobol sequence
composite (:py:data:typing.Optional[int, numpy.ndarray]):
If provided, composite quadrature will be used.
Ignored in the case if gaussian=True.
If int provided, determines number of even domain splits
If array of ints, determines number of even domain splits along
each axis
If array of arrays/floats, determines location of splits
antithetic (:py:data:typing.Optional[numpy.ndarray]):
List of bool. Represents the axes to mirror using antithetic
variable during MCI.
"""
dim = len(dist)
shape = K.shape
size = int(K.size/dim)
K = K.reshape(dim, size)
if dim > 1:
shape = shape[1:]
X, W = quad.generate_quadrature(order, dist, rule=rule, normalize=True, **kws)
grid = numpy.mgrid[:len(X[0]), :size]
X = X.T[grid[0]].T
K = K.T[grid[1]].T
out = numpy.prod(X**K, 0)*W
if control_var is not None:
Y = control_var.ppf(dist.fwd(X))
mu = control_var.mom(numpy.eye(len(control_var)))
if (mu.size == 1) and (dim > 1):
mu = mu.repeat(dim)
for d in range(dim):
alpha = numpy.cov(out, Y[d])[0, 1]/numpy.var(Y[d])
out -= alpha*(Y[d]-mu)
out = numpy.sum(out, -1)
return out | python | def approximate_moment(
dist,
K,
retall=False,
control_var=None,
rule="F",
order=1000,
**kws
):
"""
Approximation method for estimation of raw statistical moments.
Args:
dist : Dist
Distribution domain with dim=len(dist)
K : numpy.ndarray
The exponents of the moments of interest with shape (dim,K).
control_var : Dist
If provided will be used as a control variable to try to reduce
the error.
acc (:py:data:typing.Optional[int]):
The order of quadrature/MCI
sparse : bool
If True used Smolyak's sparse grid instead of normal tensor
product grid in numerical integration.
rule : str
Quadrature rule
Key Description
---- -----------
"G" Optiomal Gaussian quadrature from Golub-Welsch
Slow for high order and composit is ignored.
"E" Gauss-Legendre quadrature
"C" Clenshaw-Curtis quadrature. Exponential growth rule is
used when sparse is True to make the rule nested.
Monte Carlo Integration
Key Description
---- -----------
"H" Halton sequence
"K" Korobov set
"L" Latin hypercube sampling
"M" Hammersley sequence
"R" (Pseudo-)Random sampling
"S" Sobol sequence
composite (:py:data:typing.Optional[int, numpy.ndarray]):
If provided, composite quadrature will be used.
Ignored in the case if gaussian=True.
If int provided, determines number of even domain splits
If array of ints, determines number of even domain splits along
each axis
If array of arrays/floats, determines location of splits
antithetic (:py:data:typing.Optional[numpy.ndarray]):
List of bool. Represents the axes to mirror using antithetic
variable during MCI.
"""
dim = len(dist)
shape = K.shape
size = int(K.size/dim)
K = K.reshape(dim, size)
if dim > 1:
shape = shape[1:]
X, W = quad.generate_quadrature(order, dist, rule=rule, normalize=True, **kws)
grid = numpy.mgrid[:len(X[0]), :size]
X = X.T[grid[0]].T
K = K.T[grid[1]].T
out = numpy.prod(X**K, 0)*W
if control_var is not None:
Y = control_var.ppf(dist.fwd(X))
mu = control_var.mom(numpy.eye(len(control_var)))
if (mu.size == 1) and (dim > 1):
mu = mu.repeat(dim)
for d in range(dim):
alpha = numpy.cov(out, Y[d])[0, 1]/numpy.var(Y[d])
out -= alpha*(Y[d]-mu)
out = numpy.sum(out, -1)
return out | [
"def",
"approximate_moment",
"(",
"dist",
",",
"K",
",",
"retall",
"=",
"False",
",",
"control_var",
"=",
"None",
",",
"rule",
"=",
"\"F\"",
",",
"order",
"=",
"1000",
",",
"*",
"*",
"kws",
")",
":",
"dim",
"=",
"len",
"(",
"dist",
")",
"shape",
... | Approximation method for estimation of raw statistical moments.
Args:
dist : Dist
Distribution domain with dim=len(dist)
K : numpy.ndarray
The exponents of the moments of interest with shape (dim,K).
control_var : Dist
If provided will be used as a control variable to try to reduce
the error.
acc (:py:data:typing.Optional[int]):
The order of quadrature/MCI
sparse : bool
If True used Smolyak's sparse grid instead of normal tensor
product grid in numerical integration.
rule : str
Quadrature rule
Key Description
---- -----------
"G" Optiomal Gaussian quadrature from Golub-Welsch
Slow for high order and composit is ignored.
"E" Gauss-Legendre quadrature
"C" Clenshaw-Curtis quadrature. Exponential growth rule is
used when sparse is True to make the rule nested.
Monte Carlo Integration
Key Description
---- -----------
"H" Halton sequence
"K" Korobov set
"L" Latin hypercube sampling
"M" Hammersley sequence
"R" (Pseudo-)Random sampling
"S" Sobol sequence
composite (:py:data:typing.Optional[int, numpy.ndarray]):
If provided, composite quadrature will be used.
Ignored in the case if gaussian=True.
If int provided, determines number of even domain splits
If array of ints, determines number of even domain splits along
each axis
If array of arrays/floats, determines location of splits
antithetic (:py:data:typing.Optional[numpy.ndarray]):
List of bool. Represents the axes to mirror using antithetic
variable during MCI. | [
"Approximation",
"method",
"for",
"estimation",
"of",
"raw",
"statistical",
"moments",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/approximation.py#L229-L315 | train | 206,971 |
jonathf/chaospy | chaospy/distributions/approximation.py | approximate_density | def approximate_density(
dist,
xloc,
parameters=None,
cache=None,
eps=1.e-7
):
"""
Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
Location coordinates. Requires that xloc.shape=(len(dist), K).
eps : float
Acceptable error level for the approximations
retall : bool
If True return Graph with the next calculation state with the
approximation.
Returns:
numpy.ndarray: Local probability density function with
``out.shape == xloc.shape``. To calculate actual density function,
evaluate ``numpy.prod(out, 0)``.
Example:
>>> distribution = chaospy.Normal(1000, 10)
>>> xloc = numpy.array([[990, 1000, 1010]])
>>> print(numpy.around(approximate_density(distribution, xloc), 4))
[[0.0242 0.0399 0.0242]]
>>> print(numpy.around(distribution.pdf(xloc), 4))
[[0.0242 0.0399 0.0242]]
"""
if parameters is None:
parameters = dist.prm.copy()
if cache is None:
cache = {}
xloc = numpy.asfarray(xloc)
lo, up = numpy.min(xloc), numpy.max(xloc)
mu = .5*(lo+up)
eps = numpy.where(xloc < mu, eps, -eps)*xloc
floc = evaluation.evaluate_forward(
dist, xloc, parameters=parameters.copy(), cache=cache.copy())
for d in range(len(dist)):
xloc[d] += eps[d]
tmp = evaluation.evaluate_forward(
dist, xloc, parameters=parameters.copy(), cache=cache.copy())
floc[d] -= tmp[d]
xloc[d] -= eps[d]
floc = numpy.abs(floc / eps)
return floc | python | def approximate_density(
dist,
xloc,
parameters=None,
cache=None,
eps=1.e-7
):
"""
Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
Location coordinates. Requires that xloc.shape=(len(dist), K).
eps : float
Acceptable error level for the approximations
retall : bool
If True return Graph with the next calculation state with the
approximation.
Returns:
numpy.ndarray: Local probability density function with
``out.shape == xloc.shape``. To calculate actual density function,
evaluate ``numpy.prod(out, 0)``.
Example:
>>> distribution = chaospy.Normal(1000, 10)
>>> xloc = numpy.array([[990, 1000, 1010]])
>>> print(numpy.around(approximate_density(distribution, xloc), 4))
[[0.0242 0.0399 0.0242]]
>>> print(numpy.around(distribution.pdf(xloc), 4))
[[0.0242 0.0399 0.0242]]
"""
if parameters is None:
parameters = dist.prm.copy()
if cache is None:
cache = {}
xloc = numpy.asfarray(xloc)
lo, up = numpy.min(xloc), numpy.max(xloc)
mu = .5*(lo+up)
eps = numpy.where(xloc < mu, eps, -eps)*xloc
floc = evaluation.evaluate_forward(
dist, xloc, parameters=parameters.copy(), cache=cache.copy())
for d in range(len(dist)):
xloc[d] += eps[d]
tmp = evaluation.evaluate_forward(
dist, xloc, parameters=parameters.copy(), cache=cache.copy())
floc[d] -= tmp[d]
xloc[d] -= eps[d]
floc = numpy.abs(floc / eps)
return floc | [
"def",
"approximate_density",
"(",
"dist",
",",
"xloc",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"eps",
"=",
"1.e-7",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"dist",
".",
"prm",
".",
"copy",
"(",
")"... | Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
Location coordinates. Requires that xloc.shape=(len(dist), K).
eps : float
Acceptable error level for the approximations
retall : bool
If True return Graph with the next calculation state with the
approximation.
Returns:
numpy.ndarray: Local probability density function with
``out.shape == xloc.shape``. To calculate actual density function,
evaluate ``numpy.prod(out, 0)``.
Example:
>>> distribution = chaospy.Normal(1000, 10)
>>> xloc = numpy.array([[990, 1000, 1010]])
>>> print(numpy.around(approximate_density(distribution, xloc), 4))
[[0.0242 0.0399 0.0242]]
>>> print(numpy.around(distribution.pdf(xloc), 4))
[[0.0242 0.0399 0.0242]] | [
"Approximate",
"the",
"probability",
"density",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/approximation.py#L318-L372 | train | 206,972 |
jonathf/chaospy | chaospy/distributions/sampler/sequences/van_der_corput.py | create_van_der_corput_samples | def create_van_der_corput_samples(idx, number_base=2):
"""
Van der Corput samples.
Args:
idx (int, numpy.ndarray):
The index of the sequence. If array is provided, all values in
array is returned.
number_base (int):
The numerical base from where to create the samples from.
Returns (float, numpy.ndarray):
Van der Corput samples.
"""
assert number_base > 1
idx = numpy.asarray(idx).flatten() + 1
out = numpy.zeros(len(idx), dtype=float)
base = float(number_base)
active = numpy.ones(len(idx), dtype=bool)
while numpy.any(active):
out[active] += (idx[active] % number_base)/base
idx //= number_base
base *= number_base
active = idx > 0
return out | python | def create_van_der_corput_samples(idx, number_base=2):
"""
Van der Corput samples.
Args:
idx (int, numpy.ndarray):
The index of the sequence. If array is provided, all values in
array is returned.
number_base (int):
The numerical base from where to create the samples from.
Returns (float, numpy.ndarray):
Van der Corput samples.
"""
assert number_base > 1
idx = numpy.asarray(idx).flatten() + 1
out = numpy.zeros(len(idx), dtype=float)
base = float(number_base)
active = numpy.ones(len(idx), dtype=bool)
while numpy.any(active):
out[active] += (idx[active] % number_base)/base
idx //= number_base
base *= number_base
active = idx > 0
return out | [
"def",
"create_van_der_corput_samples",
"(",
"idx",
",",
"number_base",
"=",
"2",
")",
":",
"assert",
"number_base",
">",
"1",
"idx",
"=",
"numpy",
".",
"asarray",
"(",
"idx",
")",
".",
"flatten",
"(",
")",
"+",
"1",
"out",
"=",
"numpy",
".",
"zeros",
... | Van der Corput samples.
Args:
idx (int, numpy.ndarray):
The index of the sequence. If array is provided, all values in
array is returned.
number_base (int):
The numerical base from where to create the samples from.
Returns (float, numpy.ndarray):
Van der Corput samples. | [
"Van",
"der",
"Corput",
"samples",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/van_der_corput.py#L31-L57 | train | 206,973 |
jonathf/chaospy | chaospy/poly/collection/arithmetics.py | add | def add(*args):
"""Polynomial addition."""
if len(args) > 2:
return add(args[0], add(args[1], args[1:]))
if len(args) == 1:
return args[0]
part1, part2 = args
if isinstance(part2, Poly):
if part2.dim > part1.dim:
part1 = chaospy.dimension.setdim(part1, part2.dim)
elif part2.dim < part1.dim:
part2 = chaospy.dimension.setdim(part2, part1.dim)
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
core1 = part1.A.copy()
core2 = part2.A.copy()
if np.prod(part2.shape) > np.prod(part1.shape):
shape = part2.shape
ones = np.ones(shape, dtype=int)
for key in core1:
core1[key] = core1[key]*ones
else:
shape = part1.shape
ones = np.ones(shape, dtype=int)
for key in core2:
core2[key] = core2[key]*ones
for idx in core1:
if idx in core2:
core2[idx] = core2[idx] + core1[idx]
else:
core2[idx] = core1[idx]
out = core2
return Poly(out, part1.dim, shape, dtype)
part2 = np.asarray(part2)
core = part1.A.copy()
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
zero = (0,)*part1.dim
if zero not in core:
core[zero] = np.zeros(part1.shape, dtype=int)
core[zero] = core[zero] + part2
if np.prod(part2.shape) > np.prod(part1.shape):
ones = np.ones(part2.shape, dtype=dtype)
for key in core:
core[key] = core[key]*ones
return Poly(core, part1.dim, None, dtype) | python | def add(*args):
"""Polynomial addition."""
if len(args) > 2:
return add(args[0], add(args[1], args[1:]))
if len(args) == 1:
return args[0]
part1, part2 = args
if isinstance(part2, Poly):
if part2.dim > part1.dim:
part1 = chaospy.dimension.setdim(part1, part2.dim)
elif part2.dim < part1.dim:
part2 = chaospy.dimension.setdim(part2, part1.dim)
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
core1 = part1.A.copy()
core2 = part2.A.copy()
if np.prod(part2.shape) > np.prod(part1.shape):
shape = part2.shape
ones = np.ones(shape, dtype=int)
for key in core1:
core1[key] = core1[key]*ones
else:
shape = part1.shape
ones = np.ones(shape, dtype=int)
for key in core2:
core2[key] = core2[key]*ones
for idx in core1:
if idx in core2:
core2[idx] = core2[idx] + core1[idx]
else:
core2[idx] = core1[idx]
out = core2
return Poly(out, part1.dim, shape, dtype)
part2 = np.asarray(part2)
core = part1.A.copy()
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
zero = (0,)*part1.dim
if zero not in core:
core[zero] = np.zeros(part1.shape, dtype=int)
core[zero] = core[zero] + part2
if np.prod(part2.shape) > np.prod(part1.shape):
ones = np.ones(part2.shape, dtype=dtype)
for key in core:
core[key] = core[key]*ones
return Poly(core, part1.dim, None, dtype) | [
"def",
"add",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"return",
"add",
"(",
"args",
"[",
"0",
"]",
",",
"add",
"(",
"args",
"[",
"1",
"]",
",",
"args",
"[",
"1",
":",
"]",
")",
")",
"if",
"len",
"(",
"a... | Polynomial addition. | [
"Polynomial",
"addition",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/arithmetics.py#L13-L73 | train | 206,974 |
jonathf/chaospy | chaospy/poly/collection/arithmetics.py | mul | def mul(*args):
"""Polynomial multiplication."""
if len(args) > 2:
return add(args[0], add(args[1], args[1:]))
if len(args) == 1:
return args[0]
part1, part2 = args
if not isinstance(part2, Poly):
if isinstance(part2, (float, int)):
part2 = np.asarray(part2)
if not part2.shape:
core = part1.A.copy()
dtype = chaospy.poly.typing.dtyping(
part1.dtype, part2.dtype)
for key in part1.keys:
core[key] = np.asarray(core[key]*part2, dtype)
return Poly(core, part1.dim, part1.shape, dtype)
part2 = Poly(part2)
if part2.dim > part1.dim:
part1 = chaospy.dimension.setdim(part1, part2.dim)
elif part2.dim < part1.dim:
part2 = chaospy.dimension.setdim(part2, part1.dim)
if np.prod(part1.shape) >= np.prod(part2.shape):
shape = part1.shape
else:
shape = part2.shape
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
if part1.dtype != part2.dtype:
if part1.dtype == dtype:
part2 = chaospy.poly.typing.asfloat(part2)
else:
part1 = chaospy.poly.typing.asfloat(part1)
core = {}
for idx1 in part2.A:
for idx2 in part1.A:
key = tuple(np.array(idx1) + np.array(idx2))
core[key] = np.asarray(
core.get(key, 0) + part2.A[idx1]*part1.A[idx2])
core = {key: value for key, value in core.items() if np.any(value)}
out = Poly(core, part1.dim, shape, dtype)
return out | python | def mul(*args):
"""Polynomial multiplication."""
if len(args) > 2:
return add(args[0], add(args[1], args[1:]))
if len(args) == 1:
return args[0]
part1, part2 = args
if not isinstance(part2, Poly):
if isinstance(part2, (float, int)):
part2 = np.asarray(part2)
if not part2.shape:
core = part1.A.copy()
dtype = chaospy.poly.typing.dtyping(
part1.dtype, part2.dtype)
for key in part1.keys:
core[key] = np.asarray(core[key]*part2, dtype)
return Poly(core, part1.dim, part1.shape, dtype)
part2 = Poly(part2)
if part2.dim > part1.dim:
part1 = chaospy.dimension.setdim(part1, part2.dim)
elif part2.dim < part1.dim:
part2 = chaospy.dimension.setdim(part2, part1.dim)
if np.prod(part1.shape) >= np.prod(part2.shape):
shape = part1.shape
else:
shape = part2.shape
dtype = chaospy.poly.typing.dtyping(part1.dtype, part2.dtype)
if part1.dtype != part2.dtype:
if part1.dtype == dtype:
part2 = chaospy.poly.typing.asfloat(part2)
else:
part1 = chaospy.poly.typing.asfloat(part1)
core = {}
for idx1 in part2.A:
for idx2 in part1.A:
key = tuple(np.array(idx1) + np.array(idx2))
core[key] = np.asarray(
core.get(key, 0) + part2.A[idx1]*part1.A[idx2])
core = {key: value for key, value in core.items() if np.any(value)}
out = Poly(core, part1.dim, shape, dtype)
return out | [
"def",
"mul",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"return",
"add",
"(",
"args",
"[",
"0",
"]",
",",
"add",
"(",
"args",
"[",
"1",
"]",
",",
"args",
"[",
"1",
":",
"]",
")",
")",
"if",
"len",
"(",
"a... | Polynomial multiplication. | [
"Polynomial",
"multiplication",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/arithmetics.py#L76-L130 | train | 206,975 |
jonathf/chaospy | tutorial/Heaviside.py | PiecewiseConstant.plot | def plot(self,
resolution_constant_regions=20,
resolution_smooth_regions=200):
"""
Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plotting intervals
are insed in the constant regions with `resolution_smooth_regions`
plotting intervals in the smoothed regions.
"""
if self.eps == 0:
x = []; y = []
for I, value in zip(self._indicator_functions, self._values):
x.append(I.L)
y.append(value)
x.append(I.R)
y.append(value)
return x, y
else:
n = float(resolution_smooth_regions)/self.eps
if len(self.data) == 1:
return [self.L, self.R], [self._values[0], self._values[0]]
else:
x = [np.linspace(self.data[0][0], self.data[1][0]-self.eps,
resolution_constant_regions+1)]
# Iterate over all internal discontinuities
for I in self._indicator_functions[1:]:
x.append(np.linspace(I.L-self.eps, I.L+self.eps,
resolution_smooth_regions+1))
x.append(np.linspace(I.L+self.eps, I.R-self.eps,
resolution_constant_regions+1))
# Last part
x.append(np.linspace(I.R-self.eps, I.R, 3))
x = np.concatenate(x)
y = self(x)
return x, y | python | def plot(self,
resolution_constant_regions=20,
resolution_smooth_regions=200):
"""
Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plotting intervals
are insed in the constant regions with `resolution_smooth_regions`
plotting intervals in the smoothed regions.
"""
if self.eps == 0:
x = []; y = []
for I, value in zip(self._indicator_functions, self._values):
x.append(I.L)
y.append(value)
x.append(I.R)
y.append(value)
return x, y
else:
n = float(resolution_smooth_regions)/self.eps
if len(self.data) == 1:
return [self.L, self.R], [self._values[0], self._values[0]]
else:
x = [np.linspace(self.data[0][0], self.data[1][0]-self.eps,
resolution_constant_regions+1)]
# Iterate over all internal discontinuities
for I in self._indicator_functions[1:]:
x.append(np.linspace(I.L-self.eps, I.L+self.eps,
resolution_smooth_regions+1))
x.append(np.linspace(I.L+self.eps, I.R-self.eps,
resolution_constant_regions+1))
# Last part
x.append(np.linspace(I.R-self.eps, I.R, 3))
x = np.concatenate(x)
y = self(x)
return x, y | [
"def",
"plot",
"(",
"self",
",",
"resolution_constant_regions",
"=",
"20",
",",
"resolution_smooth_regions",
"=",
"200",
")",
":",
"if",
"self",
".",
"eps",
"==",
"0",
":",
"x",
"=",
"[",
"]",
"y",
"=",
"[",
"]",
"for",
"I",
",",
"value",
"in",
"zi... | Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plotting intervals
are insed in the constant regions with `resolution_smooth_regions`
plotting intervals in the smoothed regions. | [
"Return",
"arrays",
"x",
"y",
"for",
"plotting",
"the",
"piecewise",
"constant",
"function",
".",
"Just",
"the",
"minimum",
"number",
"of",
"straight",
"lines",
"are",
"returned",
"if",
"eps",
"=",
"0",
"otherwise",
"resolution_constant_regions",
"plotting",
"in... | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/tutorial/Heaviside.py#L490-L525 | train | 206,976 |
jonathf/chaospy | chaospy/poly/collection/derivative.py | gradient | def gradient(poly):
"""
Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
[2, q2, q1]
"""
return differential(poly, chaospy.poly.collection.basis(1, 1, poly.dim)) | python | def gradient(poly):
"""
Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
[2, q2, q1]
"""
return differential(poly, chaospy.poly.collection.basis(1, 1, poly.dim)) | [
"def",
"gradient",
"(",
"poly",
")",
":",
"return",
"differential",
"(",
"poly",
",",
"chaospy",
".",
"poly",
".",
"collection",
".",
"basis",
"(",
"1",
",",
"1",
",",
"poly",
".",
"dim",
")",
")"
] | Gradient of a polynomial.
Args:
poly (Poly) : polynomial to take gradient of.
Returns:
(Poly) : The resulting gradient.
Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
[2, q2, q1] | [
"Gradient",
"of",
"a",
"polynomial",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/derivative.py#L65-L81 | train | 206,977 |
jonathf/chaospy | chaospy/distributions/sampler/sequences/korobov.py | create_korobov_samples | def create_korobov_samples(order, dim, base=17797):
"""
Create Korobov lattice samples.
Args:
order (int):
The order of the Korobov latice. Defines the number of
samples.
dim (int):
The number of dimensions in the output.
base (int):
The number based used to calculate the distribution of values.
Returns (numpy.ndarray):
Korobov lattice with ``shape == (dim, order)``
"""
values = numpy.empty(dim)
values[0] = 1
for idx in range(1, dim):
values[idx] = base*values[idx-1] % (order+1)
grid = numpy.mgrid[:dim, :order+1]
out = values[grid[0]] * (grid[1]+1) / (order+1.) % 1.
return out[:, :order] | python | def create_korobov_samples(order, dim, base=17797):
"""
Create Korobov lattice samples.
Args:
order (int):
The order of the Korobov latice. Defines the number of
samples.
dim (int):
The number of dimensions in the output.
base (int):
The number based used to calculate the distribution of values.
Returns (numpy.ndarray):
Korobov lattice with ``shape == (dim, order)``
"""
values = numpy.empty(dim)
values[0] = 1
for idx in range(1, dim):
values[idx] = base*values[idx-1] % (order+1)
grid = numpy.mgrid[:dim, :order+1]
out = values[grid[0]] * (grid[1]+1) / (order+1.) % 1.
return out[:, :order] | [
"def",
"create_korobov_samples",
"(",
"order",
",",
"dim",
",",
"base",
"=",
"17797",
")",
":",
"values",
"=",
"numpy",
".",
"empty",
"(",
"dim",
")",
"values",
"[",
"0",
"]",
"=",
"1",
"for",
"idx",
"in",
"range",
"(",
"1",
",",
"dim",
")",
":",... | Create Korobov lattice samples.
Args:
order (int):
The order of the Korobov latice. Defines the number of
samples.
dim (int):
The number of dimensions in the output.
base (int):
The number based used to calculate the distribution of values.
Returns (numpy.ndarray):
Korobov lattice with ``shape == (dim, order)`` | [
"Create",
"Korobov",
"lattice",
"samples",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/korobov.py#L22-L45 | train | 206,978 |
jonathf/chaospy | chaospy/quad/collection/genz_keister/genz_keister.py | quad_genz_keister | def quad_genz_keister(order, dist, rule=24):
"""
Genz-Keister quadrature rule.
Eabsicassample:
>>> abscissas, weights = quad_genz_keister(
... order=1, dist=chaospy.Uniform(0, 1))
>>> print(numpy.around(abscissas, 4))
[[0.0416 0.5 0.9584]]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
assert isinstance(rule, int)
if len(dist) > 1:
if isinstance(order, int):
values = [quad_genz_keister(order, d, rule) for d in dist]
else:
values = [quad_genz_keister(order[i], dist[i], rule)
for i in range(len(dist))]
abscissas = [_[0][0] for _ in values]
abscissas = chaospy.quad.combine(abscissas).T
weights = [_[1] for _ in values]
weights = np.prod(chaospy.quad.combine(weights), -1)
return abscissas, weights
foo = chaospy.quad.genz_keister.COLLECTION[rule]
abscissas, weights = foo(order)
abscissas = dist.inv(scipy.special.ndtr(abscissas))
abscissas = abscissas.reshape(1, abscissas.size)
return abscissas, weights | python | def quad_genz_keister(order, dist, rule=24):
"""
Genz-Keister quadrature rule.
Eabsicassample:
>>> abscissas, weights = quad_genz_keister(
... order=1, dist=chaospy.Uniform(0, 1))
>>> print(numpy.around(abscissas, 4))
[[0.0416 0.5 0.9584]]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
assert isinstance(rule, int)
if len(dist) > 1:
if isinstance(order, int):
values = [quad_genz_keister(order, d, rule) for d in dist]
else:
values = [quad_genz_keister(order[i], dist[i], rule)
for i in range(len(dist))]
abscissas = [_[0][0] for _ in values]
abscissas = chaospy.quad.combine(abscissas).T
weights = [_[1] for _ in values]
weights = np.prod(chaospy.quad.combine(weights), -1)
return abscissas, weights
foo = chaospy.quad.genz_keister.COLLECTION[rule]
abscissas, weights = foo(order)
abscissas = dist.inv(scipy.special.ndtr(abscissas))
abscissas = abscissas.reshape(1, abscissas.size)
return abscissas, weights | [
"def",
"quad_genz_keister",
"(",
"order",
",",
"dist",
",",
"rule",
"=",
"24",
")",
":",
"assert",
"isinstance",
"(",
"rule",
",",
"int",
")",
"if",
"len",
"(",
"dist",
")",
">",
"1",
":",
"if",
"isinstance",
"(",
"order",
",",
"int",
")",
":",
"... | Genz-Keister quadrature rule.
Eabsicassample:
>>> abscissas, weights = quad_genz_keister(
... order=1, dist=chaospy.Uniform(0, 1))
>>> print(numpy.around(abscissas, 4))
[[0.0416 0.5 0.9584]]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667] | [
"Genz",
"-",
"Keister",
"quadrature",
"rule",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/genz_keister/genz_keister.py#L11-L45 | train | 206,979 |
jonathf/chaospy | chaospy/descriptives/percentile.py | Perc | def Perc(poly, q, dist, sample=10000, **kws):
"""
Percentile function.
Note that this function is an empirical function that operates using Monte
Carlo sampling.
Args:
poly (Poly):
Polynomial of interest.
q (numpy.ndarray):
positions where percentiles are taken. Must be a number or an
array, where all values are on the interval ``[0, 100]``.
dist (Dist):
Defines the space where percentile is taken.
sample (int):
Number of samples used in estimation.
Returns:
(numpy.ndarray):
Percentiles of ``poly`` with ``Q.shape=poly.shape+q.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([0.05*x, 0.2*y, 0.01*x*y])
>>> print(numpy.around(chaospy.Perc(poly, [0, 5, 50, 95, 100], dist), 2))
[[ 0. -3. -6.3 ]
[ 0. -0.64 -0.04]
[ 0.03 -0.01 -0. ]
[ 0.15 0.66 0.04]
[ 2.1 3. 6.3 ]]
"""
shape = poly.shape
poly = polynomials.flatten(poly)
q = numpy.array(q)/100.
dim = len(dist)
# Interior
Z = dist.sample(sample, **kws)
if dim==1:
Z = (Z, )
q = numpy.array([q])
poly1 = poly(*Z)
# Min/max
mi, ma = dist.range().reshape(2, dim)
ext = numpy.mgrid[(slice(0, 2, 1), )*dim].reshape(dim, 2**dim).T
ext = numpy.where(ext, mi, ma).T
poly2 = poly(*ext)
poly2 = numpy.array([_ for _ in poly2.T if not numpy.any(numpy.isnan(_))]).T
# Finish
if poly2.shape:
poly1 = numpy.concatenate([poly1, poly2], -1)
samples = poly1.shape[-1]
poly1.sort()
out = poly1.T[numpy.asarray(q*(samples-1), dtype=int)]
out = out.reshape(q.shape + shape)
return out | python | def Perc(poly, q, dist, sample=10000, **kws):
"""
Percentile function.
Note that this function is an empirical function that operates using Monte
Carlo sampling.
Args:
poly (Poly):
Polynomial of interest.
q (numpy.ndarray):
positions where percentiles are taken. Must be a number or an
array, where all values are on the interval ``[0, 100]``.
dist (Dist):
Defines the space where percentile is taken.
sample (int):
Number of samples used in estimation.
Returns:
(numpy.ndarray):
Percentiles of ``poly`` with ``Q.shape=poly.shape+q.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([0.05*x, 0.2*y, 0.01*x*y])
>>> print(numpy.around(chaospy.Perc(poly, [0, 5, 50, 95, 100], dist), 2))
[[ 0. -3. -6.3 ]
[ 0. -0.64 -0.04]
[ 0.03 -0.01 -0. ]
[ 0.15 0.66 0.04]
[ 2.1 3. 6.3 ]]
"""
shape = poly.shape
poly = polynomials.flatten(poly)
q = numpy.array(q)/100.
dim = len(dist)
# Interior
Z = dist.sample(sample, **kws)
if dim==1:
Z = (Z, )
q = numpy.array([q])
poly1 = poly(*Z)
# Min/max
mi, ma = dist.range().reshape(2, dim)
ext = numpy.mgrid[(slice(0, 2, 1), )*dim].reshape(dim, 2**dim).T
ext = numpy.where(ext, mi, ma).T
poly2 = poly(*ext)
poly2 = numpy.array([_ for _ in poly2.T if not numpy.any(numpy.isnan(_))]).T
# Finish
if poly2.shape:
poly1 = numpy.concatenate([poly1, poly2], -1)
samples = poly1.shape[-1]
poly1.sort()
out = poly1.T[numpy.asarray(q*(samples-1), dtype=int)]
out = out.reshape(q.shape + shape)
return out | [
"def",
"Perc",
"(",
"poly",
",",
"q",
",",
"dist",
",",
"sample",
"=",
"10000",
",",
"*",
"*",
"kws",
")",
":",
"shape",
"=",
"poly",
".",
"shape",
"poly",
"=",
"polynomials",
".",
"flatten",
"(",
"poly",
")",
"q",
"=",
"numpy",
".",
"array",
"... | Percentile function.
Note that this function is an empirical function that operates using Monte
Carlo sampling.
Args:
poly (Poly):
Polynomial of interest.
q (numpy.ndarray):
positions where percentiles are taken. Must be a number or an
array, where all values are on the interval ``[0, 100]``.
dist (Dist):
Defines the space where percentile is taken.
sample (int):
Number of samples used in estimation.
Returns:
(numpy.ndarray):
Percentiles of ``poly`` with ``Q.shape=poly.shape+q.shape``.
Examples:
>>> dist = chaospy.J(chaospy.Gamma(1, 1), chaospy.Normal(0, 2))
>>> x, y = chaospy.variable(2)
>>> poly = chaospy.Poly([0.05*x, 0.2*y, 0.01*x*y])
>>> print(numpy.around(chaospy.Perc(poly, [0, 5, 50, 95, 100], dist), 2))
[[ 0. -3. -6.3 ]
[ 0. -0.64 -0.04]
[ 0.03 -0.01 -0. ]
[ 0.15 0.66 0.04]
[ 2.1 3. 6.3 ]] | [
"Percentile",
"function",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/percentile.py#L6-L67 | train | 206,980 |
jonathf/chaospy | chaospy/quad/collection/probabilistic.py | probabilistic_collocation | def probabilistic_collocation(order, dist, subset=.1):
"""
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples.
"""
abscissas, weights = chaospy.quad.collection.golub_welsch(order, dist)
likelihood = dist.pdf(abscissas)
alpha = numpy.random.random(len(weights))
alpha = likelihood > alpha*subset*numpy.max(likelihood)
abscissas = abscissas.T[alpha].T
weights = weights[alpha]
return abscissas, weights | python | def probabilistic_collocation(order, dist, subset=.1):
"""
Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples.
"""
abscissas, weights = chaospy.quad.collection.golub_welsch(order, dist)
likelihood = dist.pdf(abscissas)
alpha = numpy.random.random(len(weights))
alpha = likelihood > alpha*subset*numpy.max(likelihood)
abscissas = abscissas.T[alpha].T
weights = weights[alpha]
return abscissas, weights | [
"def",
"probabilistic_collocation",
"(",
"order",
",",
"dist",
",",
"subset",
"=",
".1",
")",
":",
"abscissas",
",",
"weights",
"=",
"chaospy",
".",
"quad",
".",
"collection",
".",
"golub_welsch",
"(",
"order",
",",
"dist",
")",
"likelihood",
"=",
"dist",
... | Probabilistic collocation method.
Args:
order (int, numpy.ndarray) : Quadrature order along each axis.
dist (Dist) : Distribution to generate samples from.
subset (float) : Rate of which to removed samples. | [
"Probabilistic",
"collocation",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/probabilistic.py#L11-L29 | train | 206,981 |
jonathf/chaospy | chaospy/quad/collection/frontend.py | get_function | def get_function(rule, domain, normalize, **parameters):
"""
Create a quadrature function and set default parameter values.
Args:
rule (str):
Name of quadrature rule defined in ``QUAD_FUNCTIONS``.
domain (Dist, numpy.ndarray):
Defines ``lower`` and ``upper`` that is passed quadrature rule. If
``Dist``, ``domain`` is renamed to ``dist`` and also
passed.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
parameters (:py:data:typing.Any):
Redefining of the parameter defaults. Only add parameters that the
quadrature rule expect.
Returns:
(:py:data:typing.Callable):
Function that can be called only using argument ``order``.
"""
from ...distributions.baseclass import Dist
if isinstance(domain, Dist):
lower, upper = domain.range()
parameters["dist"] = domain
else:
lower, upper = numpy.array(domain)
parameters["lower"] = lower
parameters["upper"] = upper
quad_function = QUAD_FUNCTIONS[rule]
parameters_spec = inspect.getargspec(quad_function)[0]
parameters_spec = {key: None for key in parameters_spec}
del parameters_spec["order"]
for key in parameters_spec:
if key in parameters:
parameters_spec[key] = parameters[key]
def _quad_function(order, *args, **kws):
"""Implementation of quadrature function."""
params = parameters_spec.copy()
params.update(kws)
abscissas, weights = quad_function(order, *args, **params)
# normalize if prudent:
if rule in UNORMALIZED_QUADRATURE_RULES and normalize:
if isinstance(domain, Dist):
if len(domain) == 1:
weights *= domain.pdf(abscissas).flatten()
else:
weights *= domain.pdf(abscissas)
weights /= numpy.sum(weights)
return abscissas, weights
return _quad_function | python | def get_function(rule, domain, normalize, **parameters):
"""
Create a quadrature function and set default parameter values.
Args:
rule (str):
Name of quadrature rule defined in ``QUAD_FUNCTIONS``.
domain (Dist, numpy.ndarray):
Defines ``lower`` and ``upper`` that is passed quadrature rule. If
``Dist``, ``domain`` is renamed to ``dist`` and also
passed.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
parameters (:py:data:typing.Any):
Redefining of the parameter defaults. Only add parameters that the
quadrature rule expect.
Returns:
(:py:data:typing.Callable):
Function that can be called only using argument ``order``.
"""
from ...distributions.baseclass import Dist
if isinstance(domain, Dist):
lower, upper = domain.range()
parameters["dist"] = domain
else:
lower, upper = numpy.array(domain)
parameters["lower"] = lower
parameters["upper"] = upper
quad_function = QUAD_FUNCTIONS[rule]
parameters_spec = inspect.getargspec(quad_function)[0]
parameters_spec = {key: None for key in parameters_spec}
del parameters_spec["order"]
for key in parameters_spec:
if key in parameters:
parameters_spec[key] = parameters[key]
def _quad_function(order, *args, **kws):
"""Implementation of quadrature function."""
params = parameters_spec.copy()
params.update(kws)
abscissas, weights = quad_function(order, *args, **params)
# normalize if prudent:
if rule in UNORMALIZED_QUADRATURE_RULES and normalize:
if isinstance(domain, Dist):
if len(domain) == 1:
weights *= domain.pdf(abscissas).flatten()
else:
weights *= domain.pdf(abscissas)
weights /= numpy.sum(weights)
return abscissas, weights
return _quad_function | [
"def",
"get_function",
"(",
"rule",
",",
"domain",
",",
"normalize",
",",
"*",
"*",
"parameters",
")",
":",
"from",
".",
".",
".",
"distributions",
".",
"baseclass",
"import",
"Dist",
"if",
"isinstance",
"(",
"domain",
",",
"Dist",
")",
":",
"lower",
"... | Create a quadrature function and set default parameter values.
Args:
rule (str):
Name of quadrature rule defined in ``QUAD_FUNCTIONS``.
domain (Dist, numpy.ndarray):
Defines ``lower`` and ``upper`` that is passed quadrature rule. If
``Dist``, ``domain`` is renamed to ``dist`` and also
passed.
normalize (bool):
In the case of distributions, the abscissas and weights are not
tailored to a distribution beyond matching the bounds. If True, the
samples are normalized multiplying the weights with the density of
the distribution evaluated at the abscissas and normalized
afterwards to sum to one.
parameters (:py:data:typing.Any):
Redefining of the parameter defaults. Only add parameters that the
quadrature rule expect.
Returns:
(:py:data:typing.Callable):
Function that can be called only using argument ``order``. | [
"Create",
"a",
"quadrature",
"function",
"and",
"set",
"default",
"parameter",
"values",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/frontend.py#L43-L102 | train | 206,982 |
jonathf/chaospy | chaospy/regression.py | fit_regression | def fit_regression(
polynomials,
abscissas,
evals,
rule="LS",
retall=False,
order=0,
alpha=-1,
):
"""
Fit a polynomial chaos expansion using linear regression.
Args:
polynomials (chaospy.poly.base.Poly):
Polynomial expansion with ``polynomials.shape=(M,)`` and
`polynomials.dim=D`.
abscissas (numpy.ndarray):
Collocation nodes with ``abscissas.shape == (D, K)``.
evals (numpy.ndarray):
Model evaluations with ``len(evals)=K``.
retall (bool):
If True return Fourier coefficients in addition to R.
order (int):
Tikhonov regularization order.
alpha (float):
Dampning parameter for the Tikhonov regularization. Calculated
automatically if negative.
Returns:
(Poly, numpy.ndarray):
Fitted polynomial with ``R.shape=evals.shape[1:]`` and ``R.dim=D``.
The Fourier coefficients in the estimation.
Examples:
>>> x, y = chaospy.variable(2)
>>> polynomials = chaospy.Poly([1, x, y])
>>> abscissas = [[-1,-1,1,1], [-1,1,-1,1]]
>>> evals = [0,1,1,2]
>>> print(chaospy.around(chaospy.fit_regression(
... polynomials, abscissas, evals), 14))
0.5q0+0.5q1+1.0
"""
abscissas = numpy.asarray(abscissas)
if len(abscissas.shape) == 1:
abscissas = abscissas.reshape(1, *abscissas.shape)
evals = numpy.array(evals)
poly_evals = polynomials(*abscissas).T
shape = evals.shape[1:]
evals = evals.reshape(evals.shape[0], int(numpy.prod(evals.shape[1:])))
if isinstance(rule, str):
rule = rule.upper()
if rule == "LS":
uhat = linalg.lstsq(poly_evals, evals)[0]
elif rule == "T":
uhat = rlstsq(poly_evals, evals, order=order, alpha=alpha, cross=False)
elif rule == "TC":
uhat = rlstsq(poly_evals, evals, order=order, alpha=alpha, cross=True)
else:
from sklearn.linear_model.base import LinearModel
assert isinstance(rule, LinearModel)
uhat = rule.fit(poly_evals, evals).coef_.T
evals = evals.reshape(evals.shape[0], *shape)
approx_model = chaospy.poly.sum((polynomials*uhat.T), -1)
approx_model = chaospy.poly.reshape(approx_model, shape)
if retall == 1:
return approx_model, uhat
elif retall == 2:
return approx_model, uhat, poly_evals
return approx_model | python | def fit_regression(
polynomials,
abscissas,
evals,
rule="LS",
retall=False,
order=0,
alpha=-1,
):
"""
Fit a polynomial chaos expansion using linear regression.
Args:
polynomials (chaospy.poly.base.Poly):
Polynomial expansion with ``polynomials.shape=(M,)`` and
`polynomials.dim=D`.
abscissas (numpy.ndarray):
Collocation nodes with ``abscissas.shape == (D, K)``.
evals (numpy.ndarray):
Model evaluations with ``len(evals)=K``.
retall (bool):
If True return Fourier coefficients in addition to R.
order (int):
Tikhonov regularization order.
alpha (float):
Dampning parameter for the Tikhonov regularization. Calculated
automatically if negative.
Returns:
(Poly, numpy.ndarray):
Fitted polynomial with ``R.shape=evals.shape[1:]`` and ``R.dim=D``.
The Fourier coefficients in the estimation.
Examples:
>>> x, y = chaospy.variable(2)
>>> polynomials = chaospy.Poly([1, x, y])
>>> abscissas = [[-1,-1,1,1], [-1,1,-1,1]]
>>> evals = [0,1,1,2]
>>> print(chaospy.around(chaospy.fit_regression(
... polynomials, abscissas, evals), 14))
0.5q0+0.5q1+1.0
"""
abscissas = numpy.asarray(abscissas)
if len(abscissas.shape) == 1:
abscissas = abscissas.reshape(1, *abscissas.shape)
evals = numpy.array(evals)
poly_evals = polynomials(*abscissas).T
shape = evals.shape[1:]
evals = evals.reshape(evals.shape[0], int(numpy.prod(evals.shape[1:])))
if isinstance(rule, str):
rule = rule.upper()
if rule == "LS":
uhat = linalg.lstsq(poly_evals, evals)[0]
elif rule == "T":
uhat = rlstsq(poly_evals, evals, order=order, alpha=alpha, cross=False)
elif rule == "TC":
uhat = rlstsq(poly_evals, evals, order=order, alpha=alpha, cross=True)
else:
from sklearn.linear_model.base import LinearModel
assert isinstance(rule, LinearModel)
uhat = rule.fit(poly_evals, evals).coef_.T
evals = evals.reshape(evals.shape[0], *shape)
approx_model = chaospy.poly.sum((polynomials*uhat.T), -1)
approx_model = chaospy.poly.reshape(approx_model, shape)
if retall == 1:
return approx_model, uhat
elif retall == 2:
return approx_model, uhat, poly_evals
return approx_model | [
"def",
"fit_regression",
"(",
"polynomials",
",",
"abscissas",
",",
"evals",
",",
"rule",
"=",
"\"LS\"",
",",
"retall",
"=",
"False",
",",
"order",
"=",
"0",
",",
"alpha",
"=",
"-",
"1",
",",
")",
":",
"abscissas",
"=",
"numpy",
".",
"asarray",
"(",
... | Fit a polynomial chaos expansion using linear regression.
Args:
polynomials (chaospy.poly.base.Poly):
Polynomial expansion with ``polynomials.shape=(M,)`` and
`polynomials.dim=D`.
abscissas (numpy.ndarray):
Collocation nodes with ``abscissas.shape == (D, K)``.
evals (numpy.ndarray):
Model evaluations with ``len(evals)=K``.
retall (bool):
If True return Fourier coefficients in addition to R.
order (int):
Tikhonov regularization order.
alpha (float):
Dampning parameter for the Tikhonov regularization. Calculated
automatically if negative.
Returns:
(Poly, numpy.ndarray):
Fitted polynomial with ``R.shape=evals.shape[1:]`` and ``R.dim=D``.
The Fourier coefficients in the estimation.
Examples:
>>> x, y = chaospy.variable(2)
>>> polynomials = chaospy.Poly([1, x, y])
>>> abscissas = [[-1,-1,1,1], [-1,1,-1,1]]
>>> evals = [0,1,1,2]
>>> print(chaospy.around(chaospy.fit_regression(
... polynomials, abscissas, evals), 14))
0.5q0+0.5q1+1.0 | [
"Fit",
"a",
"polynomial",
"chaos",
"expansion",
"using",
"linear",
"regression",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/regression.py#L92-L170 | train | 206,983 |
jonathf/chaospy | chaospy/quad/collection/genz_keister/gk24.py | quad_genz_keister_24 | def quad_genz_keister_24 ( order ):
"""
Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_24(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_24.keys())[order]
abscissas, weights = GENZ_KEISTER_24[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | python | def quad_genz_keister_24 ( order ):
"""
Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_24(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667]
"""
order = sorted(GENZ_KEISTER_24.keys())[order]
abscissas, weights = GENZ_KEISTER_24[order]
abscissas = numpy.array(abscissas)
weights = numpy.array(weights)
weights /= numpy.sum(weights)
abscissas *= numpy.sqrt(2)
return abscissas, weights | [
"def",
"quad_genz_keister_24",
"(",
"order",
")",
":",
"order",
"=",
"sorted",
"(",
"GENZ_KEISTER_24",
".",
"keys",
"(",
")",
")",
"[",
"order",
"]",
"abscissas",
",",
"weights",
"=",
"GENZ_KEISTER_24",
"[",
"order",
"]",
"abscissas",
"=",
"numpy",
".",
... | Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_24(1)
>>> print(numpy.around(abscissas, 4))
[-1.7321 0. 1.7321]
>>> print(numpy.around(weights, 4))
[0.1667 0.6667 0.1667] | [
"Hermite",
"Genz",
"-",
"Keister",
"24",
"rule",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/genz_keister/gk24.py#L7-L35 | train | 206,984 |
jonathf/chaospy | chaospy/distributions/evaluation/common.py | contains_call_signature | def contains_call_signature(caller, key):
"""
Check if a function or method call signature contains a specific
argument.
Args:
caller (Callable):
Method or function to check if signature is contain in.
key (str):
Signature to look for.
Returns:
True if ``key`` exits in ``caller`` call signature.
Examples:
>>> def foo(param): pass
>>> contains_call_signature(foo, "param")
True
>>> contains_call_signature(foo, "not_param")
False
>>> class Bar:
... def baz(self, param): pass
>>> bar = Bar()
>>> contains_call_signature(bar.baz, "param")
True
>>> contains_call_signature(bar.baz, "not_param")
False
"""
try:
args = inspect.signature(caller).parameters
except AttributeError:
args = inspect.getargspec(caller).args
return key in args | python | def contains_call_signature(caller, key):
"""
Check if a function or method call signature contains a specific
argument.
Args:
caller (Callable):
Method or function to check if signature is contain in.
key (str):
Signature to look for.
Returns:
True if ``key`` exits in ``caller`` call signature.
Examples:
>>> def foo(param): pass
>>> contains_call_signature(foo, "param")
True
>>> contains_call_signature(foo, "not_param")
False
>>> class Bar:
... def baz(self, param): pass
>>> bar = Bar()
>>> contains_call_signature(bar.baz, "param")
True
>>> contains_call_signature(bar.baz, "not_param")
False
"""
try:
args = inspect.signature(caller).parameters
except AttributeError:
args = inspect.getargspec(caller).args
return key in args | [
"def",
"contains_call_signature",
"(",
"caller",
",",
"key",
")",
":",
"try",
":",
"args",
"=",
"inspect",
".",
"signature",
"(",
"caller",
")",
".",
"parameters",
"except",
"AttributeError",
":",
"args",
"=",
"inspect",
".",
"getargspec",
"(",
"caller",
"... | Check if a function or method call signature contains a specific
argument.
Args:
caller (Callable):
Method or function to check if signature is contain in.
key (str):
Signature to look for.
Returns:
True if ``key`` exits in ``caller`` call signature.
Examples:
>>> def foo(param): pass
>>> contains_call_signature(foo, "param")
True
>>> contains_call_signature(foo, "not_param")
False
>>> class Bar:
... def baz(self, param): pass
>>> bar = Bar()
>>> contains_call_signature(bar.baz, "param")
True
>>> contains_call_signature(bar.baz, "not_param")
False | [
"Check",
"if",
"a",
"function",
"or",
"method",
"call",
"signature",
"contains",
"a",
"specific",
"argument",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/common.py#L9-L41 | train | 206,985 |
jonathf/chaospy | chaospy/saltelli.py | Sens_m_sample | def Sens_m_sample(poly, dist, samples, rule="R"):
"""
First order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the first sensitivity index for distribution dimensions `dim` and
polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m_sample(poly, dist, 10000, rule="M"), 4))
[[0.008 0.0026 0. ]
[0. 0.6464 2.1321]]
"""
dim = len(dist)
generator = Saltelli(dist, samples, poly, rule=rule)
zeros = [0]*dim
ones = [1]*dim
index = [0]*dim
variance = numpy.var(generator[zeros], -1)
matrix_0 = generator[zeros]
matrix_1 = generator[ones]
mean = .5*(numpy.mean(matrix_1) + numpy.mean(matrix_0))
matrix_0 -= mean
matrix_1 -= mean
out = [
numpy.mean(matrix_1*((generator[index]-mean)-matrix_0), -1) /
numpy.where(variance, variance, 1)
for index in numpy.eye(dim, dtype=bool)
]
return numpy.array(out) | python | def Sens_m_sample(poly, dist, samples, rule="R"):
"""
First order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the first sensitivity index for distribution dimensions `dim` and
polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m_sample(poly, dist, 10000, rule="M"), 4))
[[0.008 0.0026 0. ]
[0. 0.6464 2.1321]]
"""
dim = len(dist)
generator = Saltelli(dist, samples, poly, rule=rule)
zeros = [0]*dim
ones = [1]*dim
index = [0]*dim
variance = numpy.var(generator[zeros], -1)
matrix_0 = generator[zeros]
matrix_1 = generator[ones]
mean = .5*(numpy.mean(matrix_1) + numpy.mean(matrix_0))
matrix_0 -= mean
matrix_1 -= mean
out = [
numpy.mean(matrix_1*((generator[index]-mean)-matrix_0), -1) /
numpy.where(variance, variance, 1)
for index in numpy.eye(dim, dtype=bool)
]
return numpy.array(out) | [
"def",
"Sens_m_sample",
"(",
"poly",
",",
"dist",
",",
"samples",
",",
"rule",
"=",
"\"R\"",
")",
":",
"dim",
"=",
"len",
"(",
"dist",
")",
"generator",
"=",
"Saltelli",
"(",
"dist",
",",
"samples",
",",
"poly",
",",
"rule",
"=",
"rule",
")",
"zero... | First order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the first sensitivity index for distribution dimensions `dim` and
polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m_sample(poly, dist, 10000, rule="M"), 4))
[[0.008 0.0026 0. ]
[0. 0.6464 2.1321]] | [
"First",
"order",
"sensitivity",
"indices",
"estimated",
"using",
"Saltelli",
"s",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/saltelli.py#L83-L134 | train | 206,986 |
jonathf/chaospy | chaospy/saltelli.py | Sens_m2_sample | def Sens_m2_sample(poly, dist, samples, rule="R"):
"""
Second order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(dist), len(poly))` where
`sens[dim1][dim2][pol]` is the correlating sensitivity between
dimension `dim1` and `dim2` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m2_sample(poly, dist, 10000, rule="H"), 4))
[[[ 0.008 0.0026 0. ]
[-0.0871 1.1516 1.2851]]
<BLANKLINE>
[[-0.0871 1.1516 1.2851]
[ 0. 0.7981 1.38 ]]]
"""
dim = len(dist)
generator = Saltelli(dist, samples, poly, rule=rule)
zeros = [0]*dim
ones = [1]*dim
index = [0]*dim
variance = numpy.var(generator[zeros], -1)
matrix_0 = generator[zeros]
matrix_1 = generator[ones]
mean = .5*(numpy.mean(matrix_1) + numpy.mean(matrix_0))
matrix_0 -= mean
matrix_1 -= mean
out = numpy.empty((dim, dim)+poly.shape)
for dim1 in range(dim):
index[dim1] = 1
matrix = generator[index]-mean
out[dim1, dim1] = numpy.mean(
matrix_1*(matrix-matrix_0),
-1,
) / numpy.where(variance, variance, 1)
for dim2 in range(dim1+1, dim):
index[dim2] = 1
matrix = generator[index]-mean
out[dim1, dim2] = out[dim2, dim1] = numpy.mean(
matrix_1*(matrix-matrix_0),
-1,
) / numpy.where(variance, variance, 1)
index[dim2] = 0
index[dim1] = 0
return out | python | def Sens_m2_sample(poly, dist, samples, rule="R"):
"""
Second order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(dist), len(poly))` where
`sens[dim1][dim2][pol]` is the correlating sensitivity between
dimension `dim1` and `dim2` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m2_sample(poly, dist, 10000, rule="H"), 4))
[[[ 0.008 0.0026 0. ]
[-0.0871 1.1516 1.2851]]
<BLANKLINE>
[[-0.0871 1.1516 1.2851]
[ 0. 0.7981 1.38 ]]]
"""
dim = len(dist)
generator = Saltelli(dist, samples, poly, rule=rule)
zeros = [0]*dim
ones = [1]*dim
index = [0]*dim
variance = numpy.var(generator[zeros], -1)
matrix_0 = generator[zeros]
matrix_1 = generator[ones]
mean = .5*(numpy.mean(matrix_1) + numpy.mean(matrix_0))
matrix_0 -= mean
matrix_1 -= mean
out = numpy.empty((dim, dim)+poly.shape)
for dim1 in range(dim):
index[dim1] = 1
matrix = generator[index]-mean
out[dim1, dim1] = numpy.mean(
matrix_1*(matrix-matrix_0),
-1,
) / numpy.where(variance, variance, 1)
for dim2 in range(dim1+1, dim):
index[dim2] = 1
matrix = generator[index]-mean
out[dim1, dim2] = out[dim2, dim1] = numpy.mean(
matrix_1*(matrix-matrix_0),
-1,
) / numpy.where(variance, variance, 1)
index[dim2] = 0
index[dim1] = 0
return out | [
"def",
"Sens_m2_sample",
"(",
"poly",
",",
"dist",
",",
"samples",
",",
"rule",
"=",
"\"R\"",
")",
":",
"dim",
"=",
"len",
"(",
"dist",
")",
"generator",
"=",
"Saltelli",
"(",
"dist",
",",
"samples",
",",
"poly",
",",
"rule",
"=",
"rule",
")",
"zer... | Second order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(dist), len(poly))` where
`sens[dim1][dim2][pol]` is the correlating sensitivity between
dimension `dim1` and `dim2` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_m2_sample(poly, dist, 10000, rule="H"), 4))
[[[ 0.008 0.0026 0. ]
[-0.0871 1.1516 1.2851]]
<BLANKLINE>
[[-0.0871 1.1516 1.2851]
[ 0. 0.7981 1.38 ]]] | [
"Second",
"order",
"sensitivity",
"indices",
"estimated",
"using",
"Saltelli",
"s",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/saltelli.py#L137-L211 | train | 206,987 |
jonathf/chaospy | chaospy/saltelli.py | Sens_t_sample | def Sens_t_sample(poly, dist, samples, rule="R"):
"""
Total order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the total order sensitivity index for distribution dimensions
`dim` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_t_sample(poly, dist, 10000, rule="H"), 4))
[[ 1. 0.2 -0.3807]
[ 0.9916 0.9962 1. ]]
"""
generator = Saltelli(dist, samples, poly, rule=rule)
dim = len(dist)
zeros = [0]*dim
variance = numpy.var(generator[zeros], -1)
return numpy.array([
1-numpy.mean((generator[~index]-generator[zeros])**2, -1,) /
(2*numpy.where(variance, variance, 1))
for index in numpy.eye(dim, dtype=bool)
]) | python | def Sens_t_sample(poly, dist, samples, rule="R"):
"""
Total order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the total order sensitivity index for distribution dimensions
`dim` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_t_sample(poly, dist, 10000, rule="H"), 4))
[[ 1. 0.2 -0.3807]
[ 0.9916 0.9962 1. ]]
"""
generator = Saltelli(dist, samples, poly, rule=rule)
dim = len(dist)
zeros = [0]*dim
variance = numpy.var(generator[zeros], -1)
return numpy.array([
1-numpy.mean((generator[~index]-generator[zeros])**2, -1,) /
(2*numpy.where(variance, variance, 1))
for index in numpy.eye(dim, dtype=bool)
]) | [
"def",
"Sens_t_sample",
"(",
"poly",
",",
"dist",
",",
"samples",
",",
"rule",
"=",
"\"R\"",
")",
":",
"generator",
"=",
"Saltelli",
"(",
"dist",
",",
"samples",
",",
"poly",
",",
"rule",
"=",
"rule",
")",
"dim",
"=",
"len",
"(",
"dist",
")",
"zero... | Total order sensitivity indices estimated using Saltelli's method.
Args:
poly (chaospy.Poly):
If provided, evaluated samples through polynomials before returned.
dist (chaopy.Dist):
distribution to sample from.
samples (int):
The number of samples to draw for each matrix.
rule (str):
Scheme for generating random samples.
Return:
(numpy.ndarray):
array with `shape == (len(dist), len(poly))` where `sens[dim][pol]`
is the total order sensitivity index for distribution dimensions
`dim` and polynomial index `pol`.
Examples:
>>> dist = chaospy.Iid(chaospy.Uniform(0, 1), 2)
>>> poly = chaospy.basis(2, 2, dim=2)
>>> print(poly)
[q0^2, q0q1, q1^2]
>>> print(numpy.around(Sens_t_sample(poly, dist, 10000, rule="H"), 4))
[[ 1. 0.2 -0.3807]
[ 0.9916 0.9962 1. ]] | [
"Total",
"order",
"sensitivity",
"indices",
"estimated",
"using",
"Saltelli",
"s",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/saltelli.py#L214-L252 | train | 206,988 |
jonathf/chaospy | chaospy/saltelli.py | Saltelli.get_matrix | def get_matrix(self, indices):
"""Retrieve Saltelli matrix."""
new = numpy.empty(self.samples1.shape)
for idx in range(len(indices)):
if indices[idx]:
new[idx] = self.samples1[idx]
else:
new[idx] = self.samples2[idx]
if self.poly:
new = self.poly(*new)
return new | python | def get_matrix(self, indices):
"""Retrieve Saltelli matrix."""
new = numpy.empty(self.samples1.shape)
for idx in range(len(indices)):
if indices[idx]:
new[idx] = self.samples1[idx]
else:
new[idx] = self.samples2[idx]
if self.poly:
new = self.poly(*new)
return new | [
"def",
"get_matrix",
"(",
"self",
",",
"indices",
")",
":",
"new",
"=",
"numpy",
".",
"empty",
"(",
"self",
".",
"samples1",
".",
"shape",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"indices",
")",
")",
":",
"if",
"indices",
"[",
"idx",
"... | Retrieve Saltelli matrix. | [
"Retrieve",
"Saltelli",
"matrix",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/saltelli.py#L54-L65 | train | 206,989 |
jonathf/chaospy | chaospy/quad/stieltjes.py | generate_stieltjes | def generate_stieltjes(
dist, order, accuracy=100, normed=False, retall=False, **kws):
"""
Discretized Stieltjes' method.
Args:
dist (Dist):
Distribution defining the space to create weights for.
order (int):
The polynomial order create.
accuracy (int):
The quadrature order of the Clenshaw-Curtis nodes to
use at each step, if approximation is used.
retall (bool):
If included, more values are returned
Returns:
(list): List of polynomials, norms of polynomials and three terms
coefficients. The list created from the method with
``len(orth) == order+1``. If ``len(dist) > 1``, then each
polynomials are multivariate.
(numpy.ndarray, numpy.ndarray, numpy.ndarray): If ``retall`` is true,
also return polynomial norms and the three term coefficients.
The norms of the polynomials with ``norms.shape = (dim, order+1)``
where ``dim`` are the number of dimensions in dist. The
coefficients have ``shape == (dim, order+1)``.
Examples:
>>> dist = chaospy.J(chaospy.Normal(), chaospy.Weibull())
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 5))
[q0^2-1.0, q1^2-4.0q1+2.0]
>>> print(numpy.around(norms, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> print(numpy.around(coeffs1, 5))
[[0. 0. 0.]
[1. 3. 5.]]
>>> print(numpy.around(coeffs2, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> dist = chaospy.Uniform()
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 8))
q0^2-q0+0.16666667
>>> print(numpy.around(norms, 4))
[[1. 0.0833 0.0056]]
"""
from .. import distributions
assert not distributions.evaluation.get_dependencies(dist)
if len(dist) > 1:
# one for each dimension:
orth, norms, coeff1, coeff2 = zip(*[generate_stieltjes(
_, order, accuracy, normed, retall=True, **kws) for _ in dist])
# ensure each polynomial has its own dimension:
orth = [[chaospy.setdim(_, len(orth)) for _ in poly] for poly in orth]
orth = [[chaospy.rolldim(_, len(dist)-idx) for _ in poly] for idx, poly in enumerate(orth)]
orth = [chaospy.poly.base.Poly(_) for _ in zip(*orth)]
if not retall:
return orth
# stack results:
norms = numpy.vstack(norms)
coeff1 = numpy.vstack(coeff1)
coeff2 = numpy.vstack(coeff2)
return orth, norms, coeff1, coeff2
try:
orth, norms, coeff1, coeff2 = _stieltjes_analytical(
dist, order, normed)
except NotImplementedError:
orth, norms, coeff1, coeff2 = _stieltjes_approx(
dist, order, accuracy, normed, **kws)
if retall:
assert not numpy.any(numpy.isnan(coeff1))
assert not numpy.any(numpy.isnan(coeff2))
return orth, norms, coeff1, coeff2
return orth | python | def generate_stieltjes(
dist, order, accuracy=100, normed=False, retall=False, **kws):
"""
Discretized Stieltjes' method.
Args:
dist (Dist):
Distribution defining the space to create weights for.
order (int):
The polynomial order create.
accuracy (int):
The quadrature order of the Clenshaw-Curtis nodes to
use at each step, if approximation is used.
retall (bool):
If included, more values are returned
Returns:
(list): List of polynomials, norms of polynomials and three terms
coefficients. The list created from the method with
``len(orth) == order+1``. If ``len(dist) > 1``, then each
polynomials are multivariate.
(numpy.ndarray, numpy.ndarray, numpy.ndarray): If ``retall`` is true,
also return polynomial norms and the three term coefficients.
The norms of the polynomials with ``norms.shape = (dim, order+1)``
where ``dim`` are the number of dimensions in dist. The
coefficients have ``shape == (dim, order+1)``.
Examples:
>>> dist = chaospy.J(chaospy.Normal(), chaospy.Weibull())
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 5))
[q0^2-1.0, q1^2-4.0q1+2.0]
>>> print(numpy.around(norms, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> print(numpy.around(coeffs1, 5))
[[0. 0. 0.]
[1. 3. 5.]]
>>> print(numpy.around(coeffs2, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> dist = chaospy.Uniform()
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 8))
q0^2-q0+0.16666667
>>> print(numpy.around(norms, 4))
[[1. 0.0833 0.0056]]
"""
from .. import distributions
assert not distributions.evaluation.get_dependencies(dist)
if len(dist) > 1:
# one for each dimension:
orth, norms, coeff1, coeff2 = zip(*[generate_stieltjes(
_, order, accuracy, normed, retall=True, **kws) for _ in dist])
# ensure each polynomial has its own dimension:
orth = [[chaospy.setdim(_, len(orth)) for _ in poly] for poly in orth]
orth = [[chaospy.rolldim(_, len(dist)-idx) for _ in poly] for idx, poly in enumerate(orth)]
orth = [chaospy.poly.base.Poly(_) for _ in zip(*orth)]
if not retall:
return orth
# stack results:
norms = numpy.vstack(norms)
coeff1 = numpy.vstack(coeff1)
coeff2 = numpy.vstack(coeff2)
return orth, norms, coeff1, coeff2
try:
orth, norms, coeff1, coeff2 = _stieltjes_analytical(
dist, order, normed)
except NotImplementedError:
orth, norms, coeff1, coeff2 = _stieltjes_approx(
dist, order, accuracy, normed, **kws)
if retall:
assert not numpy.any(numpy.isnan(coeff1))
assert not numpy.any(numpy.isnan(coeff2))
return orth, norms, coeff1, coeff2
return orth | [
"def",
"generate_stieltjes",
"(",
"dist",
",",
"order",
",",
"accuracy",
"=",
"100",
",",
"normed",
"=",
"False",
",",
"retall",
"=",
"False",
",",
"*",
"*",
"kws",
")",
":",
"from",
".",
".",
"import",
"distributions",
"assert",
"not",
"distributions",
... | Discretized Stieltjes' method.
Args:
dist (Dist):
Distribution defining the space to create weights for.
order (int):
The polynomial order create.
accuracy (int):
The quadrature order of the Clenshaw-Curtis nodes to
use at each step, if approximation is used.
retall (bool):
If included, more values are returned
Returns:
(list): List of polynomials, norms of polynomials and three terms
coefficients. The list created from the method with
``len(orth) == order+1``. If ``len(dist) > 1``, then each
polynomials are multivariate.
(numpy.ndarray, numpy.ndarray, numpy.ndarray): If ``retall`` is true,
also return polynomial norms and the three term coefficients.
The norms of the polynomials with ``norms.shape = (dim, order+1)``
where ``dim`` are the number of dimensions in dist. The
coefficients have ``shape == (dim, order+1)``.
Examples:
>>> dist = chaospy.J(chaospy.Normal(), chaospy.Weibull())
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 5))
[q0^2-1.0, q1^2-4.0q1+2.0]
>>> print(numpy.around(norms, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> print(numpy.around(coeffs1, 5))
[[0. 0. 0.]
[1. 3. 5.]]
>>> print(numpy.around(coeffs2, 5))
[[1. 1. 2.]
[1. 1. 4.]]
>>> dist = chaospy.Uniform()
>>> orth, norms, coeffs1, coeffs2 = chaospy.generate_stieltjes(
... dist, 2, retall=True)
>>> print(chaospy.around(orth[2], 8))
q0^2-q0+0.16666667
>>> print(numpy.around(norms, 4))
[[1. 0.0833 0.0056]] | [
"Discretized",
"Stieltjes",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/stieltjes.py#L9-L95 | train | 206,990 |
jonathf/chaospy | chaospy/quad/stieltjes.py | _stieltjes_analytical | def _stieltjes_analytical(dist, order, normed):
"""Stieltjes' method with analytical recurrence coefficients."""
dimensions = len(dist)
mom_order = numpy.arange(order+1).repeat(dimensions)
mom_order = mom_order.reshape(order+1, dimensions).T
coeff1, coeff2 = dist.ttr(mom_order)
coeff2[:, 0] = 1.
poly = chaospy.poly.collection.core.variable(dimensions)
if normed:
orth = [
poly**0*numpy.ones(dimensions),
(poly-coeff1[:, 0])/numpy.sqrt(coeff2[:, 1]),
]
for order_ in range(1, order):
orth.append(
(orth[-1]*(poly-coeff1[:, order_])
-orth[-2]*numpy.sqrt(coeff2[:, order_]))
/numpy.sqrt(coeff2[:, order_+1])
)
norms = numpy.ones(coeff2.shape)
else:
orth = [poly-poly, poly**0*numpy.ones(dimensions)]
for order_ in range(order):
orth.append(
orth[-1]*(poly-coeff1[:, order_])
- orth[-2]*coeff2[:, order_]
)
orth = orth[1:]
norms = numpy.cumprod(coeff2, 1)
return orth, norms, coeff1, coeff2 | python | def _stieltjes_analytical(dist, order, normed):
"""Stieltjes' method with analytical recurrence coefficients."""
dimensions = len(dist)
mom_order = numpy.arange(order+1).repeat(dimensions)
mom_order = mom_order.reshape(order+1, dimensions).T
coeff1, coeff2 = dist.ttr(mom_order)
coeff2[:, 0] = 1.
poly = chaospy.poly.collection.core.variable(dimensions)
if normed:
orth = [
poly**0*numpy.ones(dimensions),
(poly-coeff1[:, 0])/numpy.sqrt(coeff2[:, 1]),
]
for order_ in range(1, order):
orth.append(
(orth[-1]*(poly-coeff1[:, order_])
-orth[-2]*numpy.sqrt(coeff2[:, order_]))
/numpy.sqrt(coeff2[:, order_+1])
)
norms = numpy.ones(coeff2.shape)
else:
orth = [poly-poly, poly**0*numpy.ones(dimensions)]
for order_ in range(order):
orth.append(
orth[-1]*(poly-coeff1[:, order_])
- orth[-2]*coeff2[:, order_]
)
orth = orth[1:]
norms = numpy.cumprod(coeff2, 1)
return orth, norms, coeff1, coeff2 | [
"def",
"_stieltjes_analytical",
"(",
"dist",
",",
"order",
",",
"normed",
")",
":",
"dimensions",
"=",
"len",
"(",
"dist",
")",
"mom_order",
"=",
"numpy",
".",
"arange",
"(",
"order",
"+",
"1",
")",
".",
"repeat",
"(",
"dimensions",
")",
"mom_order",
"... | Stieltjes' method with analytical recurrence coefficients. | [
"Stieltjes",
"method",
"with",
"analytical",
"recurrence",
"coefficients",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/stieltjes.py#L98-L129 | train | 206,991 |
jonathf/chaospy | chaospy/quad/stieltjes.py | _stieltjes_approx | def _stieltjes_approx(dist, order, accuracy, normed, **kws):
"""Stieltjes' method with approximative recurrence coefficients."""
kws["rule"] = kws.get("rule", "C")
assert kws["rule"].upper() != "G"
absisas, weights = chaospy.quad.generate_quadrature(
accuracy, dist.range(), **kws)
weights = weights*dist.pdf(absisas)
poly = chaospy.poly.variable(len(dist))
orth = [poly*0, poly**0]
inner = numpy.sum(absisas*weights, -1)
norms = [numpy.ones(len(dist)), numpy.ones(len(dist))]
coeff1 = []
coeff2 = []
for _ in range(order):
coeff1.append(inner/norms[-1])
coeff2.append(norms[-1]/norms[-2])
orth.append((poly-coeff1[-1])*orth[-1] - orth[-2]*coeff2[-1])
raw_nodes = orth[-1](*absisas)**2*weights
inner = numpy.sum(absisas*raw_nodes, -1)
norms.append(numpy.sum(raw_nodes, -1))
if normed:
orth[-1] = orth[-1]/numpy.sqrt(norms[-1])
coeff1.append(inner/norms[-1])
coeff2.append(norms[-1]/norms[-2])
coeff1 = numpy.transpose(coeff1)
coeff2 = numpy.transpose(coeff2)
norms = numpy.array(norms[1:]).T
orth = orth[1:]
return orth, norms, coeff1, coeff2 | python | def _stieltjes_approx(dist, order, accuracy, normed, **kws):
"""Stieltjes' method with approximative recurrence coefficients."""
kws["rule"] = kws.get("rule", "C")
assert kws["rule"].upper() != "G"
absisas, weights = chaospy.quad.generate_quadrature(
accuracy, dist.range(), **kws)
weights = weights*dist.pdf(absisas)
poly = chaospy.poly.variable(len(dist))
orth = [poly*0, poly**0]
inner = numpy.sum(absisas*weights, -1)
norms = [numpy.ones(len(dist)), numpy.ones(len(dist))]
coeff1 = []
coeff2 = []
for _ in range(order):
coeff1.append(inner/norms[-1])
coeff2.append(norms[-1]/norms[-2])
orth.append((poly-coeff1[-1])*orth[-1] - orth[-2]*coeff2[-1])
raw_nodes = orth[-1](*absisas)**2*weights
inner = numpy.sum(absisas*raw_nodes, -1)
norms.append(numpy.sum(raw_nodes, -1))
if normed:
orth[-1] = orth[-1]/numpy.sqrt(norms[-1])
coeff1.append(inner/norms[-1])
coeff2.append(norms[-1]/norms[-2])
coeff1 = numpy.transpose(coeff1)
coeff2 = numpy.transpose(coeff2)
norms = numpy.array(norms[1:]).T
orth = orth[1:]
return orth, norms, coeff1, coeff2 | [
"def",
"_stieltjes_approx",
"(",
"dist",
",",
"order",
",",
"accuracy",
",",
"normed",
",",
"*",
"*",
"kws",
")",
":",
"kws",
"[",
"\"rule\"",
"]",
"=",
"kws",
".",
"get",
"(",
"\"rule\"",
",",
"\"C\"",
")",
"assert",
"kws",
"[",
"\"rule\"",
"]",
"... | Stieltjes' method with approximative recurrence coefficients. | [
"Stieltjes",
"method",
"with",
"approximative",
"recurrence",
"coefficients",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/stieltjes.py#L132-L168 | train | 206,992 |
jonathf/chaospy | chaospy/distributions/sampler/sequences/sobol.py | set_state | def set_state(seed_value=None, step=None):
"""Set random seed."""
global RANDOM_SEED # pylint: disable=global-statement
if seed_value is not None:
RANDOM_SEED = seed_value
if step is not None:
RANDOM_SEED += step | python | def set_state(seed_value=None, step=None):
"""Set random seed."""
global RANDOM_SEED # pylint: disable=global-statement
if seed_value is not None:
RANDOM_SEED = seed_value
if step is not None:
RANDOM_SEED += step | [
"def",
"set_state",
"(",
"seed_value",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"global",
"RANDOM_SEED",
"# pylint: disable=global-statement",
"if",
"seed_value",
"is",
"not",
"None",
":",
"RANDOM_SEED",
"=",
"seed_value",
"if",
"step",
"is",
"not",
"N... | Set random seed. | [
"Set",
"random",
"seed",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/sequences/sobol.py#L109-L115 | train | 206,993 |
jonathf/chaospy | chaospy/quad/generator.py | rule_generator | def rule_generator(*funcs):
"""
Constructor for creating multivariate quadrature generator.
Args:
funcs (:py:data:typing.Callable):
One dimensional integration rule where each rule returns
``abscissas`` and ``weights`` as one dimensional arrays. They must
take one positional argument ``order``.
Returns:
(:py:data:typing.Callable):
Multidimensional integration quadrature function that takes the
arguments ``order`` and ``sparse``, and a optional ``part``. The
argument ``sparse`` is used to select for if Smolyak sparse grid is
used, and ``part`` defines if subset of rule should be generated
(for parallelization).
Example:
>>> clenshaw_curtis = lambda order: chaospy.quad_clenshaw_curtis(
... order, lower=-1, upper=1, growth=True)
>>> gauss_legendre = lambda order: chaospy.quad_gauss_legendre(
... order, lower=0, upper=1)
>>> quad_func = chaospy.rule_generator(clenshaw_curtis, gauss_legendre)
>>> abscissas, weights = quad_func(1)
>>> print(numpy.around(abscissas, 4))
[[-1. -1. 0. 0. 1. 1. ]
[ 0.2113 0.7887 0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(weights, 4))
[0.1667 0.1667 0.6667 0.6667 0.1667 0.1667]
"""
dim = len(funcs)
tensprod_rule = create_tensorprod_function(funcs)
assert hasattr(tensprod_rule, "__call__")
mv_rule = create_mv_rule(tensprod_rule, dim)
assert hasattr(mv_rule, "__call__")
return mv_rule | python | def rule_generator(*funcs):
"""
Constructor for creating multivariate quadrature generator.
Args:
funcs (:py:data:typing.Callable):
One dimensional integration rule where each rule returns
``abscissas`` and ``weights`` as one dimensional arrays. They must
take one positional argument ``order``.
Returns:
(:py:data:typing.Callable):
Multidimensional integration quadrature function that takes the
arguments ``order`` and ``sparse``, and a optional ``part``. The
argument ``sparse`` is used to select for if Smolyak sparse grid is
used, and ``part`` defines if subset of rule should be generated
(for parallelization).
Example:
>>> clenshaw_curtis = lambda order: chaospy.quad_clenshaw_curtis(
... order, lower=-1, upper=1, growth=True)
>>> gauss_legendre = lambda order: chaospy.quad_gauss_legendre(
... order, lower=0, upper=1)
>>> quad_func = chaospy.rule_generator(clenshaw_curtis, gauss_legendre)
>>> abscissas, weights = quad_func(1)
>>> print(numpy.around(abscissas, 4))
[[-1. -1. 0. 0. 1. 1. ]
[ 0.2113 0.7887 0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(weights, 4))
[0.1667 0.1667 0.6667 0.6667 0.1667 0.1667]
"""
dim = len(funcs)
tensprod_rule = create_tensorprod_function(funcs)
assert hasattr(tensprod_rule, "__call__")
mv_rule = create_mv_rule(tensprod_rule, dim)
assert hasattr(mv_rule, "__call__")
return mv_rule | [
"def",
"rule_generator",
"(",
"*",
"funcs",
")",
":",
"dim",
"=",
"len",
"(",
"funcs",
")",
"tensprod_rule",
"=",
"create_tensorprod_function",
"(",
"funcs",
")",
"assert",
"hasattr",
"(",
"tensprod_rule",
",",
"\"__call__\"",
")",
"mv_rule",
"=",
"create_mv_r... | Constructor for creating multivariate quadrature generator.
Args:
funcs (:py:data:typing.Callable):
One dimensional integration rule where each rule returns
``abscissas`` and ``weights`` as one dimensional arrays. They must
take one positional argument ``order``.
Returns:
(:py:data:typing.Callable):
Multidimensional integration quadrature function that takes the
arguments ``order`` and ``sparse``, and a optional ``part``. The
argument ``sparse`` is used to select for if Smolyak sparse grid is
used, and ``part`` defines if subset of rule should be generated
(for parallelization).
Example:
>>> clenshaw_curtis = lambda order: chaospy.quad_clenshaw_curtis(
... order, lower=-1, upper=1, growth=True)
>>> gauss_legendre = lambda order: chaospy.quad_gauss_legendre(
... order, lower=0, upper=1)
>>> quad_func = chaospy.rule_generator(clenshaw_curtis, gauss_legendre)
>>> abscissas, weights = quad_func(1)
>>> print(numpy.around(abscissas, 4))
[[-1. -1. 0. 0. 1. 1. ]
[ 0.2113 0.7887 0.2113 0.7887 0.2113 0.7887]]
>>> print(numpy.around(weights, 4))
[0.1667 0.1667 0.6667 0.6667 0.1667 0.1667] | [
"Constructor",
"for",
"creating",
"multivariate",
"quadrature",
"generator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/generator.py#L9-L46 | train | 206,994 |
jonathf/chaospy | chaospy/quad/generator.py | create_tensorprod_function | def create_tensorprod_function(funcs):
"""Combine 1-D rules into multivariate rule using tensor product."""
dim = len(funcs)
def tensprod_rule(order, part=None):
"""Tensor product rule."""
order = order*numpy.ones(dim, int)
values = [funcs[idx](order[idx]) for idx in range(dim)]
abscissas = [numpy.array(_[0]).flatten() for _ in values]
abscissas = chaospy.quad.combine(abscissas, part=part).T
weights = [numpy.array(_[1]).flatten() for _ in values]
weights = numpy.prod(chaospy.quad.combine(weights, part=part), -1)
return abscissas, weights
return tensprod_rule | python | def create_tensorprod_function(funcs):
"""Combine 1-D rules into multivariate rule using tensor product."""
dim = len(funcs)
def tensprod_rule(order, part=None):
"""Tensor product rule."""
order = order*numpy.ones(dim, int)
values = [funcs[idx](order[idx]) for idx in range(dim)]
abscissas = [numpy.array(_[0]).flatten() for _ in values]
abscissas = chaospy.quad.combine(abscissas, part=part).T
weights = [numpy.array(_[1]).flatten() for _ in values]
weights = numpy.prod(chaospy.quad.combine(weights, part=part), -1)
return abscissas, weights
return tensprod_rule | [
"def",
"create_tensorprod_function",
"(",
"funcs",
")",
":",
"dim",
"=",
"len",
"(",
"funcs",
")",
"def",
"tensprod_rule",
"(",
"order",
",",
"part",
"=",
"None",
")",
":",
"\"\"\"Tensor product rule.\"\"\"",
"order",
"=",
"order",
"*",
"numpy",
".",
"ones",... | Combine 1-D rules into multivariate rule using tensor product. | [
"Combine",
"1",
"-",
"D",
"rules",
"into",
"multivariate",
"rule",
"using",
"tensor",
"product",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/generator.py#L49-L66 | train | 206,995 |
jonathf/chaospy | chaospy/quad/generator.py | create_mv_rule | def create_mv_rule(tensorprod_rule, dim):
"""Convert tensor product rule into a multivariate quadrature generator."""
def mv_rule(order, sparse=False, part=None):
"""
Multidimensional integration rule.
Args:
order (int, numpy.ndarray) : order of integration rule. If numpy.ndarray,
order along each axis.
sparse (bool) : use Smolyak sparse grid.
Returns:
(numpy.ndarray, numpy.ndarray) abscissas and weights.
"""
if sparse:
order = numpy.ones(dim, dtype=int)*order
tensorprod_rule_ = lambda order, part=part:\
tensorprod_rule(order, part=part)
return chaospy.quad.sparse_grid(tensorprod_rule_, order)
return tensorprod_rule(order, part=part)
return mv_rule | python | def create_mv_rule(tensorprod_rule, dim):
"""Convert tensor product rule into a multivariate quadrature generator."""
def mv_rule(order, sparse=False, part=None):
"""
Multidimensional integration rule.
Args:
order (int, numpy.ndarray) : order of integration rule. If numpy.ndarray,
order along each axis.
sparse (bool) : use Smolyak sparse grid.
Returns:
(numpy.ndarray, numpy.ndarray) abscissas and weights.
"""
if sparse:
order = numpy.ones(dim, dtype=int)*order
tensorprod_rule_ = lambda order, part=part:\
tensorprod_rule(order, part=part)
return chaospy.quad.sparse_grid(tensorprod_rule_, order)
return tensorprod_rule(order, part=part)
return mv_rule | [
"def",
"create_mv_rule",
"(",
"tensorprod_rule",
",",
"dim",
")",
":",
"def",
"mv_rule",
"(",
"order",
",",
"sparse",
"=",
"False",
",",
"part",
"=",
"None",
")",
":",
"\"\"\"\n Multidimensional integration rule.\n\n Args:\n order (int, numpy.ndar... | Convert tensor product rule into a multivariate quadrature generator. | [
"Convert",
"tensor",
"product",
"rule",
"into",
"a",
"multivariate",
"quadrature",
"generator",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/generator.py#L69-L91 | train | 206,996 |
jonathf/chaospy | chaospy/quad/collection/fejer.py | quad_fejer | def quad_fejer(order, lower=0, upper=1, growth=False, part=None):
"""
Generate the quadrature abscissas and weights in Fejer quadrature.
Example:
>>> abscissas, weights = quad_fejer(3, 0, 1)
>>> print(numpy.around(abscissas, 4))
[[0.0955 0.3455 0.6545 0.9045]]
>>> print(numpy.around(weights, 4))
[0.1804 0.2996 0.2996 0.1804]
"""
order = numpy.asarray(order, dtype=int).flatten()
lower = numpy.asarray(lower).flatten()
upper = numpy.asarray(upper).flatten()
dim = max(lower.size, upper.size, order.size)
order = numpy.ones(dim, dtype=int)*order
lower = numpy.ones(dim)*lower
upper = numpy.ones(dim)*upper
composite = numpy.array([numpy.arange(2)]*dim)
if growth:
results = [
_fejer(numpy.where(order[i] == 0, 0, 2.**(order[i]+1)-2))
for i in range(dim)
]
else:
results = [
_fejer(order[i], composite[i]) for i in range(dim)
]
abscis = [_[0] for _ in results]
weight = [_[1] for _ in results]
abscis = chaospy.quad.combine(abscis, part=part).T
weight = chaospy.quad.combine(weight, part=part)
abscis = ((upper-lower)*abscis.T + lower).T
weight = numpy.prod(weight*(upper-lower), -1)
assert len(abscis) == dim
assert len(weight) == len(abscis.T)
return abscis, weight | python | def quad_fejer(order, lower=0, upper=1, growth=False, part=None):
"""
Generate the quadrature abscissas and weights in Fejer quadrature.
Example:
>>> abscissas, weights = quad_fejer(3, 0, 1)
>>> print(numpy.around(abscissas, 4))
[[0.0955 0.3455 0.6545 0.9045]]
>>> print(numpy.around(weights, 4))
[0.1804 0.2996 0.2996 0.1804]
"""
order = numpy.asarray(order, dtype=int).flatten()
lower = numpy.asarray(lower).flatten()
upper = numpy.asarray(upper).flatten()
dim = max(lower.size, upper.size, order.size)
order = numpy.ones(dim, dtype=int)*order
lower = numpy.ones(dim)*lower
upper = numpy.ones(dim)*upper
composite = numpy.array([numpy.arange(2)]*dim)
if growth:
results = [
_fejer(numpy.where(order[i] == 0, 0, 2.**(order[i]+1)-2))
for i in range(dim)
]
else:
results = [
_fejer(order[i], composite[i]) for i in range(dim)
]
abscis = [_[0] for _ in results]
weight = [_[1] for _ in results]
abscis = chaospy.quad.combine(abscis, part=part).T
weight = chaospy.quad.combine(weight, part=part)
abscis = ((upper-lower)*abscis.T + lower).T
weight = numpy.prod(weight*(upper-lower), -1)
assert len(abscis) == dim
assert len(weight) == len(abscis.T)
return abscis, weight | [
"def",
"quad_fejer",
"(",
"order",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"1",
",",
"growth",
"=",
"False",
",",
"part",
"=",
"None",
")",
":",
"order",
"=",
"numpy",
".",
"asarray",
"(",
"order",
",",
"dtype",
"=",
"int",
")",
".",
"flatten"... | Generate the quadrature abscissas and weights in Fejer quadrature.
Example:
>>> abscissas, weights = quad_fejer(3, 0, 1)
>>> print(numpy.around(abscissas, 4))
[[0.0955 0.3455 0.6545 0.9045]]
>>> print(numpy.around(weights, 4))
[0.1804 0.2996 0.2996 0.1804] | [
"Generate",
"the",
"quadrature",
"abscissas",
"and",
"weights",
"in",
"Fejer",
"quadrature",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/fejer.py#L53-L98 | train | 206,997 |
jonathf/chaospy | chaospy/quad/collection/fejer.py | _fejer | def _fejer(order, composite=None):
r"""
Backend method.
Examples:
>>> abscissas, weights = _fejer(0)
>>> print(abscissas)
[0.5]
>>> print(weights)
[1.]
>>> abscissas, weights = _fejer(1)
>>> print(abscissas)
[0.25 0.75]
>>> print(weights)
[0.44444444 0.44444444]
>>> abscissas, weights = _fejer(2)
>>> print(abscissas)
[0.14644661 0.5 0.85355339]
>>> print(weights)
[0.26666667 0.4 0.26666667]
>>> abscissas, weights = _fejer(3)
>>> print(abscissas)
[0.0954915 0.3454915 0.6545085 0.9045085]
>>> print(weights)
[0.18037152 0.29962848 0.29962848 0.18037152]
>>> abscissas, weights = _fejer(4)
>>> print(abscissas)
[0.0669873 0.25 0.5 0.75 0.9330127]
>>> print(weights)
[0.12698413 0.22857143 0.26031746 0.22857143 0.12698413]
>>> abscissas, weights = _fejer(5)
>>> print(abscissas)
[0.04951557 0.1882551 0.38873953 0.61126047 0.8117449 0.95048443]
>>> print(weights)
[0.0950705 0.17612121 0.2186042 0.2186042 0.17612121 0.0950705 ]
"""
order = int(order)
if order == 0:
return numpy.array([.5]), numpy.array([1.])
order += 2
theta = (order-numpy.arange(order+1))*numpy.pi/order
abscisas = 0.5*numpy.cos(theta) + 0.5
N, K = numpy.mgrid[:order+1, :order//2]
weights = 2*numpy.cos(2*(K+1)*theta[N])/(4*K*(K+2)+3)
if order % 2 == 0:
weights[:, -1] *= 0.5
weights = (1-numpy.sum(weights, -1)) / order
return abscisas[1:-1], weights[1:-1] | python | def _fejer(order, composite=None):
r"""
Backend method.
Examples:
>>> abscissas, weights = _fejer(0)
>>> print(abscissas)
[0.5]
>>> print(weights)
[1.]
>>> abscissas, weights = _fejer(1)
>>> print(abscissas)
[0.25 0.75]
>>> print(weights)
[0.44444444 0.44444444]
>>> abscissas, weights = _fejer(2)
>>> print(abscissas)
[0.14644661 0.5 0.85355339]
>>> print(weights)
[0.26666667 0.4 0.26666667]
>>> abscissas, weights = _fejer(3)
>>> print(abscissas)
[0.0954915 0.3454915 0.6545085 0.9045085]
>>> print(weights)
[0.18037152 0.29962848 0.29962848 0.18037152]
>>> abscissas, weights = _fejer(4)
>>> print(abscissas)
[0.0669873 0.25 0.5 0.75 0.9330127]
>>> print(weights)
[0.12698413 0.22857143 0.26031746 0.22857143 0.12698413]
>>> abscissas, weights = _fejer(5)
>>> print(abscissas)
[0.04951557 0.1882551 0.38873953 0.61126047 0.8117449 0.95048443]
>>> print(weights)
[0.0950705 0.17612121 0.2186042 0.2186042 0.17612121 0.0950705 ]
"""
order = int(order)
if order == 0:
return numpy.array([.5]), numpy.array([1.])
order += 2
theta = (order-numpy.arange(order+1))*numpy.pi/order
abscisas = 0.5*numpy.cos(theta) + 0.5
N, K = numpy.mgrid[:order+1, :order//2]
weights = 2*numpy.cos(2*(K+1)*theta[N])/(4*K*(K+2)+3)
if order % 2 == 0:
weights[:, -1] *= 0.5
weights = (1-numpy.sum(weights, -1)) / order
return abscisas[1:-1], weights[1:-1] | [
"def",
"_fejer",
"(",
"order",
",",
"composite",
"=",
"None",
")",
":",
"order",
"=",
"int",
"(",
"order",
")",
"if",
"order",
"==",
"0",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
".5",
"]",
")",
",",
"numpy",
".",
"array",
"(",
"[",
"1."... | r"""
Backend method.
Examples:
>>> abscissas, weights = _fejer(0)
>>> print(abscissas)
[0.5]
>>> print(weights)
[1.]
>>> abscissas, weights = _fejer(1)
>>> print(abscissas)
[0.25 0.75]
>>> print(weights)
[0.44444444 0.44444444]
>>> abscissas, weights = _fejer(2)
>>> print(abscissas)
[0.14644661 0.5 0.85355339]
>>> print(weights)
[0.26666667 0.4 0.26666667]
>>> abscissas, weights = _fejer(3)
>>> print(abscissas)
[0.0954915 0.3454915 0.6545085 0.9045085]
>>> print(weights)
[0.18037152 0.29962848 0.29962848 0.18037152]
>>> abscissas, weights = _fejer(4)
>>> print(abscissas)
[0.0669873 0.25 0.5 0.75 0.9330127]
>>> print(weights)
[0.12698413 0.22857143 0.26031746 0.22857143 0.12698413]
>>> abscissas, weights = _fejer(5)
>>> print(abscissas)
[0.04951557 0.1882551 0.38873953 0.61126047 0.8117449 0.95048443]
>>> print(weights)
[0.0950705 0.17612121 0.2186042 0.2186042 0.17612121 0.0950705 ] | [
"r",
"Backend",
"method",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/collection/fejer.py#L101-L152 | train | 206,998 |
jonathf/chaospy | chaospy/distributions/sampler/latin_hypercube.py | create_latin_hypercube_samples | def create_latin_hypercube_samples(order, dim=1):
"""
Latin Hypercube sampling.
Args:
order (int):
The order of the latin hyper-cube. Defines the number of samples.
dim (int):
The number of dimensions in the latin hyper-cube.
Returns (numpy.ndarray):
Latin hyper-cube with ``shape == (dim, order)``.
"""
randoms = numpy.random.random(order*dim).reshape((dim, order))
for dim_ in range(dim):
perm = numpy.random.permutation(order) # pylint: disable=no-member
randoms[dim_] = (perm + randoms[dim_])/order
return randoms | python | def create_latin_hypercube_samples(order, dim=1):
"""
Latin Hypercube sampling.
Args:
order (int):
The order of the latin hyper-cube. Defines the number of samples.
dim (int):
The number of dimensions in the latin hyper-cube.
Returns (numpy.ndarray):
Latin hyper-cube with ``shape == (dim, order)``.
"""
randoms = numpy.random.random(order*dim).reshape((dim, order))
for dim_ in range(dim):
perm = numpy.random.permutation(order) # pylint: disable=no-member
randoms[dim_] = (perm + randoms[dim_])/order
return randoms | [
"def",
"create_latin_hypercube_samples",
"(",
"order",
",",
"dim",
"=",
"1",
")",
":",
"randoms",
"=",
"numpy",
".",
"random",
".",
"random",
"(",
"order",
"*",
"dim",
")",
".",
"reshape",
"(",
"(",
"dim",
",",
"order",
")",
")",
"for",
"dim_",
"in",... | Latin Hypercube sampling.
Args:
order (int):
The order of the latin hyper-cube. Defines the number of samples.
dim (int):
The number of dimensions in the latin hyper-cube.
Returns (numpy.ndarray):
Latin hyper-cube with ``shape == (dim, order)``. | [
"Latin",
"Hypercube",
"sampling",
"."
] | 25ecfa7bf5608dc10c0b31d142ded0e3755f5d74 | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/sampler/latin_hypercube.py#L15-L32 | train | 206,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.