code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return numpy.log10(evaluation.evaluate_bound(
dist, 10**xloc, cache=cache)) | def _bnd(self, xloc, dist, cache) | Distribution bounds. | 11.143881 | 10.871576 | 1.025047 |
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, **kw... | 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... | 4.725328 | 5.008917 | 0.943383 |
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,... | 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
... | 2.917506 | 2.807802 | 1.039071 |
return evaluation.evaluate_density(
dist, numpy.arctan(x), cache=cache)/(1+x*x) | def _pdf(self, x, dist, cache) | Probability density function. | 11.441137 | 11.465957 | 0.997835 |
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.si... | 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... | 3.146378 | 2.938619 | 1.070699 |
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.b... | 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 overrid... | 2.760751 | 2.802157 | 0.985224 |
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... | 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 oth... | 3.554734 | 3.421045 | 1.039079 |
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) | 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 ... | 4.71994 | 7.181394 | 0.657246 |
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)
pa... | 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... | 2.777348 | 2.770744 | 1.002383 |
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) | 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(pol... | 2.772937 | 3.216313 | 0.862148 |
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) | 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)
>... | 2.614681 | 3.60144 | 0.72601 |
output = evaluation.evaluate_density(dist, numpy.arccosh(x), cache=cache)
output /= numpy.where(x != 1, numpy.sqrt(x*x-1), numpy.inf)
return output | def _pdf(self, x, dist, cache) | Probability density function. | 6.18156 | 6.430818 | 0.96124 |
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 = l... | 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):
I... | 2.43097 | 2.45714 | 0.989349 |
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(geta... | 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... | 6.18969 | 5.913178 | 1.046762 |
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) | 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)
>... | 2.628624 | 3.663012 | 0.717613 |
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... | 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'> | 3.590744 | 3.664485 | 0.979877 |
if limit is None:
limit = 10**300
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = core[key]*1.
return Poly(core, vari.dim, vari.shape, float)
return numpy.asfarray(vari) | def asfloat(vari, limit=None) | Convert dtype of polynomial coefficients to float.
Example:
>>> poly = 2*cp.variable()+1
>>> print(poly)
2q0+1
>>> print(cp.asfloat(poly))
2.0q0+1.0 | 5.470446 | 6.028703 | 0.9074 |
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = numpy.asarray(core[key], dtype=int)
return Poly(core, vari.dim, vari.shape, int)
return numpy.asarray(vari, dtype=int) | def asint(vari) | Convert dtype of polynomial coefficients to float.
Example:
>>> poly = 1.5*cp.variable()+2.25
>>> print(poly)
1.5q0+2.25
>>> print(cp.asint(poly))
q0+2 | 5.087651 | 5.956754 | 0.854098 |
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.p... | 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]
... | 3.279006 | 3.255975 | 1.007074 |
output = evaluation.evaluate_density(
dist, xloc.reshape(1, -1)).reshape(length, -1)
assert xloc.shape == output.shape
return output | def _pdf(self, xloc, dist, length, cache) | Probability density function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(), 2).pdf(
... [[0.5, 1.5], [0.5, 0.5]]))
[1. 0.] | 6.091562 | 13.068237 | 0.466135 |
output = evaluation.evaluate_forward(
dist, xloc.reshape(1, -1)).reshape(length, -1)
assert xloc.shape == output.shape
return output | def _cdf(self, xloc, dist, length, cache) | Cumulative distribution function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).fwd(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[0.05 0.1 0.15]
[0.1 0.1 0.15]] | 6.629615 | 10.454229 | 0.634156 |
output = evaluation.evaluate_inverse(
dist, uloc.reshape(1, -1)).reshape(length, -1)
assert uloc.shape == output.shape
return output | def _ppf(self, uloc, dist, length, cache) | Point percentile function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).inv(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[0.2 0.4 0.6]
[0.4 0.4 0.6]] | 6.276289 | 10.344861 | 0.606706 |
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) | 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.]]] | 3.047548 | 3.599135 | 0.846744 |
return numpy.prod(dist.mom(k), 0) | 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] | 11.222154 | 13.542467 | 0.828664 |
assert len(x_data) == len(distribution)
assert len(x_data.shape) == 2
cache = cache if cache is not None else {}
out = numpy.zeros(x_data.shape)
# Distribution self know how to handle density evaluation.
if hasattr(distribution, "_pdf"):
parameters = load_parameters(
d... | def evaluate_density(
distribution,
x_data,
parameters=None,
cache=None,
) | Evaluate probability density function (PDF).
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate density at.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in t... | 3.325184 | 3.353857 | 0.991451 |
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) | 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.p... | 3.848225 | 10.085525 | 0.381559 |
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) | 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:
... | 3.995687 | 6.065583 | 0.658748 |
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, ax... | 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:
(ch... | 3.44522 | 3.754272 | 0.91768 |
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:]:
... | 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:
... | 3.446298 | 3.655376 | 0.942802 |
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 = [qua... | 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] | 3.07805 | 3.063303 | 1.004814 |
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
return obj | def create_objective(dist, abscissas) | Create objective function. | 4.990664 | 4.995146 | 0.999103 |
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) | Create weights for the Laja method. | 5.279099 | 5.383077 | 0.980684 |
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(... | 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):
... | 4.01831 | 4.075337 | 0.986007 |
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... | def _gill_king(mat, beta, delta) | Backend function for the Gill-King algorithm. | 4.82156 | 4.814476 | 1.001471 |
random_state = numpy.random.get_state()
numpy.random.seed(seed)
forward = partial(evaluation.evaluate_forward, cache=cache,
distribution=distribution, parameters=parameters)
dim = len(distribution)
upper = numpy.ones((dim, 1))
for _ in range(100):
indices = f... | def find_interior_point(
distribution,
parameters=None,
cache=None,
iterations=1000,
retall=False,
seed=None,
) | Find interior point of the distribution where forward evaluation is
guarantied to be both ``distribution.fwd(xloc) > 0`` and
``distribution.fwd(xloc) < 1``.
Args:
distribution (Dist): Distribution to find interior on.
parameters (Optional[Dict[Dist, numpy.ndarray]]): Parameters for the
... | 2.581609 | 2.690463 | 0.959541 |
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
... | 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 contro... | 4.123574 | 4.03844 | 1.021081 |
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, p... | 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 appro... | 2.804732 | 3.227944 | 0.868891 |
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
b... | 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... | 3.379241 | 3.658727 | 0.923611 |
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:
... | def add(*args) | Polynomial addition. | 2.23145 | 2.16917 | 1.028711 |
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 = p... | def mul(*args) | Polynomial multiplication. | 2.389755 | 2.35039 | 1.016748 |
if self.eps == 0:
return [xmin, center, xmax], [0, 0, xmax]
else:
n = float(resolution_inside)/self.eps
x = np.concatenate((
np.linspace(xmin, center-self.eps, resolution_outside+1),
np.linspace(center-self.eps, center+self.eps... | def plot(self, xmin=-1, xmax=1, center=0,
resolution_outside=20, resolution_inside=200) | Return arrays x, y for plotting the Heaviside function
H(x-`center`) on [`xmin`, `xmax`]. For the exact
Heaviside function,
``x = [xmin, center, xmax]; y = [0, 0, 1]``,
while for the smoothed version, the ``x`` array
is computed on basis of the `eps` parameter, with
`reso... | 2.648593 | 2.383379 | 1.111277 |
if xmin > self.L or xmax < self.R:
raise ValueError('xmin=%g > L=%g or xmax=%g < R=%g is meaningless for plot' % (xmin, self.L, xmax, self.R))
if self.eps_L == 0 and self.eps_R == 0:
return ([xmin, self.L, self.L, self.R, self.R, xmax],
[0, 0, 1, 1, ... | def plot(self, xmin=-1, xmax=1,
resolution_outside=20, resolution_inside=200) | Return arrays x, y for plotting IndicatorFunction
on [`xmin`, `xmax`]. For the exact discontinuous
indicator function, we typically have
``x = [xmin, L, L, R, R, xmax]; y = [0, 0, 1, 1, 0, 0]``,
while for the smoothed version, the densities of
coordinates in the ``x`` array is co... | 2.367666 | 2.128472 | 1.112378 |
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(... | 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 sm... | 2.725188 | 2.528022 | 1.077992 |
poly = Poly(poly)
diffvar = Poly(diffvar)
if not chaospy.poly.caller.is_decomposed(diffvar):
sum(differential(poly, chaospy.poly.caller.decompose(diffvar)))
if diffvar.shape:
return Poly([differential(poly, pol) for pol in diffvar])
if diffvar.dim > poly.dim:
poly = c... | def differential(poly, diffvar) | Polynomial differential operator.
Args:
poly (Poly) : Polynomial to be differentiated.
diffvar (Poly) : Polynomial to differentiate by. Must be decomposed. If
polynomial array, the output is the Jacobian matrix.
Examples:
>>> q0, q1 = chaospy.variable(2)
>>> pol... | 3.685789 | 3.64904 | 1.010071 |
return differential(poly, chaospy.poly.collection.basis(1, 1, poly.dim)) | 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] | 20.786161 | 30.576591 | 0.679806 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
"under-defined distribution {} or {}".format(le... | def _bnd(self, xloc, left, right, cache) | Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.P... | 2.671868 | 2.72842 | 0.979273 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
"under-defined distribution {} or {}".format(le... | def _cdf(self, xloc, left, right, cache) | Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.70710678 1. 1. ]
>>> print(chaosp... | 4.120614 | 4.318824 | 0.954106 |
left = evaluation.get_inverse_cache(left, cache)
right = evaluation.get_inverse_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
"under-defined distribution {} or {}".format(le... | def _ppf(self, q, left, right, cache) | Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[0.01 0.04 0.81]
>>> print(chaospy.Pow(chaospy.Uniform(1, 2), -1).inv([0.1, 0.2, 0.9]... | 3.688947 | 3.934699 | 0.937542 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
"under-defined distribution {} or {}".format(le... | def _pdf(self, xloc, left, right, cache) | Probability density function.
Example:
>>> print(chaospy.Uniform().pdf([-0.5, 0.5, 1.5, 2.5]))
[0. 1. 0. 0.]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).pdf([-0.5, 0.5, 1.5, 2.5]))
[0. 0.70710678 0. 0. ]
>>> print(chaospy.Pow(ch... | 4.009871 | 4.158485 | 0.964262 |
if isinstance(right, Dist):
raise StochasticallyDependentError(
"distribution as exponent not supported.")
if not isinstance(left, Dist):
return left**(right*k)
if numpy.any(right < 0):
raise StochasticallyDependentError(
... | def _mom(self, k, left, right, cache) | Statistical moments.
Example:
>>> print(numpy.around(chaospy.Uniform().mom([0, 1, 2, 3]), 4))
[1. 0.5 0.3333 0.25 ]
>>> print(numpy.around(chaospy.Pow(chaospy.Uniform(), 2).mom([0, 1, 2, 3]), 4))
[1. 0.3333 0.2 0.1429]
>>> print(numpy.a... | 4.560004 | 4.315637 | 1.056624 |
assert len(k_data) == len(distribution), (
"distribution %s is not of length %d" % (distribution, len(k_data)))
assert len(k_data.shape) == 1
def cache_key(distribution):
return (tuple(k_data), distribution)
if cache is None:
cache = {}
else:
if cache_key(distr... | def evaluate_recurrence_coefficients(
distribution,
k_data,
parameters=None,
cache=None,
) | Evaluate three terms recurrence coefficients (TTR).
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate recurrence coefficients for.
parameters (:py:data:typing.Any):
Collection of parameters to overri... | 3.397789 | 3.266083 | 1.040325 |
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) | 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.
... | 3.998649 | 4.228079 | 0.945737 |
return evaluation.evaluate_forward(dist, numpy.e**xloc, cache=cache) | def _cdf(self, xloc, dist, cache) | Cumulative distribution function. | 15.80227 | 12.797116 | 1.234831 |
return numpy.log(evaluation.evaluate_bound(
dist, numpy.e**xloc, cache=cache)) | def _bnd(self, xloc, dist, cache) | Distribution bounds. | 14.761956 | 14.341515 | 1.029316 |
numpy.random.seed(1000)
def foo(coord, param):
return param[0] * numpy.e ** (-param[1] * coord)
coord = numpy.linspace(0, 10, 200)
distribution = cp.J(cp.Uniform(1, 2), cp.Uniform(0.1, 0.2))
samples = distribution.sample(50)
evals = numpy.array([foo(coord, sample) for sample in ... | def plot_figures() | Plot figures for tutorial. | 2.43712 | 2.422279 | 1.006127 |
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 = [_[... | 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] | 2.777441 | 2.779853 | 0.999132 |
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... | 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 v... | 4.790602 | 5.190289 | 0.922993 |
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, weight... | 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. | 5.002216 | 5.687972 | 0.879438 |
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]
... | 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 rename... | 3.286551 | 2.693012 | 1.2204 |
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:])))
... | 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)``.
... | 2.425124 | 2.573086 | 0.942496 |
coef_mat = numpy.array(coef_mat)
ordinate = numpy.array(ordinate)
dim1, dim2 = coef_mat.shape
if cross:
out = numpy.empty((dim1, dim2) + ordinate.shape[1:])
coef_mat_ = numpy.empty((dim1-1, dim2))
ordinate_ = numpy.empty((dim1-1,) + ordinate.shape[1:])
for i in rang... | def rlstsq(coef_mat, ordinate, order=1, alpha=-1, cross=False) | Least Squares Minimization using Tikhonov regularization.
Includes method for robust generalized cross-validation.
Args:
coef_mat (numpy.ndarray):
Coefficient matrix with shape ``(M, N)``.
ordinate (numpy.ndarray):
Ordinate or "dependent variable" values with shape ``(M... | 2.235733 | 2.274507 | 0.982953 |
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 ) | 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)
>... | 2.768613 | 3.528265 | 0.784695 |
try:
args = inspect.signature(caller).parameters
except AttributeError:
args = inspect.getargspec(caller).args
return key in args | 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.
Ex... | 3.316486 | 4.966848 | 0.667724 |
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))
m... | 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... | 4.492112 | 5.032916 | 0.892547 |
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))
... | 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 dra... | 2.957716 | 3.024245 | 0.978001 |
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.ey... | 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... | 7.236266 | 8.502597 | 0.851065 |
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) | Retrieve Saltelli matrix. | 3.690748 | 3.636377 | 1.014952 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise evaluation.DependencyError(
"under-defined distribution {} or {}".format(left... | def _bnd(self, xloc, left, right, cache) | Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Add(chaospy.Uniform(), 2).range([-2, 0, 2, 4]))
[[2. 2. 2. 2.]
[3. 3. 3. 3.]]
>>> print(chaospy.A... | 2.246402 | 2.302068 | 0.975819 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise evaluation.DependencyError(
"under-defined distribution {} or {}".format(left... | def _cdf(self, xloc, left, right, cache) | Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Add(chaospy.Uniform(), 1).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0. 0.5 1. ]
>>> print(chaospy.Add(1, chaospy.Uniform()).... | 4.178553 | 4.541179 | 0.920147 |
left = evaluation.get_forward_cache(left, cache)
right = evaluation.get_forward_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise evaluation.DependencyError(
"under-defined distribution {} or {}".format(left... | def _pdf(self, xloc, left, right, cache) | Probability density function.
Example:
>>> print(chaospy.Uniform().pdf([-2, 0, 2, 4]))
[0. 1. 0. 0.]
>>> print(chaospy.Add(chaospy.Uniform(), 2).pdf([-2, 0, 2, 4]))
[0. 0. 1. 0.]
>>> print(chaospy.Add(2, chaospy.Uniform()).pdf([-2, 0, 2, 4]))
... | 4.129701 | 4.577256 | 0.902222 |
left = evaluation.get_inverse_cache(left, cache)
right = evaluation.get_inverse_cache(right, cache)
if isinstance(left, Dist):
if isinstance(right, Dist):
raise evaluation.DependencyError(
"under-defined distribution {} or {}".format(left... | def _ppf(self, uloc, left, right, cache) | Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Add(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[2.1 2.2 2.9]
>>> print(chaospy.Add(2, chaospy.Uniform()).inv([0.1, 0.2, 0.9]))
... | 4.383789 | 4.991502 | 0.878251 |
if evaluation.get_dependencies(left, right):
raise evaluation.DependencyError(
"sum of dependent distributions not feasible: "
"{} and {}".format(left, right)
)
keys_ = numpy.mgrid[tuple(slice(0, key+1, 1) for key in keys)]
keys_ ... | def _mom(self, keys, left, right, cache) | Statistical moments.
Example:
>>> print(numpy.around(chaospy.Uniform().mom([0, 1, 2, 3]), 4))
[1. 0.5 0.3333 0.25 ]
>>> print(numpy.around(chaospy.Add(chaospy.Uniform(), 2).mom([0, 1, 2, 3]), 4))
[ 1. 2.5 6.3333 16.25 ]
>>> print(num... | 3.365453 | 3.448684 | 0.975866 |
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
"sum of distributions not feasible: "
"{} and {}".format(left, right)
)
else:
if not isinstance(right, Dist)... | def _ttr(self, kloc, left, right, cache) | Three terms recursion coefficients.
Example:
>>> print(numpy.around(chaospy.Uniform().ttr([0, 1, 2, 3]), 4))
[[ 0.5 0.5 0.5 0.5 ]
[-0. 0.0833 0.0667 0.0643]]
>>> print(numpy.around(chaospy.Add(chaospy.Uniform(), 2).ttr([0, 1, 2, 3]), 4))
... | 4.772212 | 4.011666 | 1.189584 |
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 eac... | 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 approx... | 3.121947 | 2.791192 | 1.1185 |
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*... | def _stieltjes_analytical(dist, order, normed) | Stieltjes' method with analytical recurrence coefficients. | 3.352756 | 3.357859 | 0.99848 |
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(absi... | def _stieltjes_approx(dist, order, accuracy, normed, **kws) | Stieltjes' method with approximative recurrence coefficients. | 3.391399 | 3.344496 | 1.014024 |
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) | Set random seed. | 2.277779 | 2.031771 | 1.12108 |
assert 0 < dim < DIM_MAX, "dim in [1, 40]"
# global RANDOM_SEED # pylint: disable=global-statement
# if seed is None:
# seed = RANDOM_SEED
# RANDOM_SEED += order
set_state(seed_value=seed)
seed = RANDOM_SEED
set_state(step=order)
# Initialize row 1 of V.
samples = SOU... | def create_sobol_samples(order, dim, seed=1) | Args:
order (int):
Number of unique samples to generate.
dim (int):
Number of spacial dimensions. Must satisfy ``0 < dim < 41``.
seed (int):
Starting seed. Non-positive values are treated as 1. If omitted,
consecutive samples are used.
Returns... | 5.386804 | 5.369176 | 1.003283 |
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) | 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``.
Re... | 4.869684 | 7.647551 | 0.636764 |
dim = len(funcs)
def tensprod_rule(order, part=None):
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
... | def create_tensorprod_function(funcs) | Combine 1-D rules into multivariate rule using tensor product. | 3.760374 | 3.510577 | 1.071155 |
def mv_rule(order, sparse=False, part=None):
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)
... | def create_mv_rule(tensorprod_rule, dim) | Convert tensor product rule into a multivariate quadrature generator. | 5.065554 | 4.809331 | 1.053276 |
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
compo... | 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] | 2.864366 | 2.882109 | 0.993844 |
r
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)
... | 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]
... | 4.569037 | 4.336087 | 1.053724 |
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) | 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)``. | 3.999766 | 4.679789 | 0.85469 |
if dim == 1:
return create_halton_samples(
order=order, dim=1, burnin=burnin, primes=primes)
out = numpy.empty((dim, order), dtype=float)
out[:dim-1] = create_halton_samples(
order=order, dim=dim-1, burnin=burnin, primes=primes)
out[dim-1] = numpy.linspace(0, 1, order+2)... | def create_hammersley_samples(order, dim=1, burnin=-1, primes=()) | Create samples from the Hammersley set.
For ``dim == 1`` the sequence falls back to Van Der Corput sequence.
Args:
order (int):
The order of the Hammersley sequence. Defines the number of samples.
dim (int):
The number of dimensions in the Hammersley sequence.
b... | 2.15474 | 2.248474 | 0.958312 |
if threshold == 2:
return [2]
elif threshold < 2:
return []
numbers = list(range(3, threshold+1, 2))
root_of_threshold = threshold ** 0.5
half = int((threshold+1)/2-1)
idx = 0
counter = 3
while counter <= root_of_threshold:
if numbers[idx]:
idy ... | def create_primes(threshold) | Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``. | 2.975603 | 2.904883 | 1.024345 |
if cache is None:
cache = {}
out = numpy.zeros(u_data.shape)
# Distribution self know how to handle inverse Rosenblatt.
if hasattr(distribution, "_ppf"):
parameters = load_parameters(
distribution, "_ppf", parameters=parameters, cache=cache)
out[:] = distributio... | def evaluate_inverse(
distribution,
u_data,
cache=None,
parameters=None
) | Evaluate inverse Rosenblatt transformation.
Args:
distribution (Dist):
Distribution to evaluate.
u_data (numpy.ndarray):
Locations for where evaluate inverse transformation distribution at.
parameters (:py:data:typing.Any):
Collection of parameters to ove... | 4.090717 | 3.725384 | 1.098066 |
if (idxi, idxj, idxk) in self.hist:
return self.hist[idxi, idxj, idxk]
if idxi == idxk == 0 or idxi == idxj == 0:
out = 0
elif chaospy.bertran.add(idxi, idxk, self.dim) < idxj \
or chaospy.bertran.add(idxi, idxj, self.dim) < idxk:
ou... | def mom_111(self, idxi, idxj, idxk) | Backend moment for i, j, k == 1, 1, 1. | 2.429499 | 2.405323 | 1.010051 |
rank_ = min(
chaospy.bertran.rank(idxi, self.dim),
chaospy.bertran.rank(idxj, self.dim),
chaospy.bertran.rank(idxk, self.dim)
)
par, axis0 = chaospy.bertran.parent(idxj, self.dim)
gpar, _ = chaospy.bertran.parent(par, self.dim, axis0)
... | def mom_110(self, idxi, idxj, idxk) | Backend moment for i, j, k == 1, 1, 1. | 3.399202 | 3.388896 | 1.003041 |
rank_ = min(
chaospy.bertran.rank(idxi, self.dim),
chaospy.bertran.rank(idxj, self.dim),
chaospy.bertran.rank(idxk, self.dim)
)
par, axis0 = chaospy.bertran.parent(idxk, self.dim)
gpar, _ = chaospy.bertran.parent(par, self.dim, axis0)
... | def mom_recurse(self, idxi, idxj, idxk) | Backend mement main loop. | 2.939461 | 2.914077 | 1.008711 |
assert dist.__class__.__name__ == "Copula"
trans = dist.prm["trans"]
assert trans.__class__.__name__ == "nataf"
vals = numpy.array(vals)
cov = trans.prm["C"]
cov = numpy.dot(cov, cov.T)
marginal = dist.prm["dist"]
dim = len(dist)
orth = chaospy.orthogonal.orth_ttr(order, marg... | def Sens_m_nataf(order, dist, samples, vals, **kws) | Variance-based decomposition through the Nataf distribution.
Generates first order sensitivity indices
Args:
order (int):
Polynomial order used ``orth_ttr``.
dist (Copula):
Assumed to be Nataf with independent components
samples (numpy.ndarray):
Samp... | 3.477565 | 3.419044 | 1.017116 |
order = numpy.array(order)*numpy.ones(len(dist), dtype=int)+1
_, _, coeff1, coeff2 = chaospy.quad.generate_stieltjes(
dist, numpy.max(order), accuracy=accuracy, retall=True, **kws)
dimensions = len(dist)
abscisas, weights = _golbub_welsch(order, coeff1, coeff2)
if dimensions == 1:
... | def quad_golub_welsch(order, dist, accuracy=100, **kws) | Golub-Welsch algorithm for creating quadrature nodes and weights.
Args:
order (int):
Quadrature order
dist (Dist):
Distribution nodes and weights are found for with `dim=len(dist)`
accuracy (int):
Accuracy used in discretized Stieltjes procedure. Will
... | 3.542701 | 3.990164 | 0.887859 |
abscisas, weights = [], []
for dim, order in enumerate(orders):
if order:
bands = numpy.zeros((2, order))
bands[0] = coeff1[dim, :order]
bands[1, :-1] = numpy.sqrt(coeff2[dim, 1:order])
vals, vecs = scipy.linalg.eig_banded(bands, lower=True)
... | def _golbub_welsch(orders, coeff1, coeff2) | Recurrence coefficients to abscisas and weights. | 2.735854 | 2.531318 | 1.080802 |
if isinstance(left, Dist):
if left in cache:
left = cache[left]
else:
left = evaluation.evaluate_bound(left, xloc, cache=cache)
else:
left = (numpy.array(left).T * numpy.ones((2,)+xloc.shape).T).T
if isinstance(right, ... | def _bnd(self, xloc, left, right, cache) | Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Trunc(chaospy.Uniform(), 0.6).range([-2, 0, 2, 4]))
[[0. 0. 0. 0. ]
[0.6 0.6 0.6 0.6]]
>>> pri... | 2.274262 | 2.2921 | 0.992218 |
if isinstance(left, Dist) and left in cache:
left = cache[left]
if isinstance(right, Dist) and right in cache:
right = cache[right]
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
... | def _cdf(self, xloc, left, right, cache) | Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.3, 0.7, 1.2]))
[0. 0.3 0.7 1. ]
>>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).fwd([-0.5, 0.2, 0.8, 1.2]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Trunc(0.6, chaospy.Uni... | 2.537047 | 2.541621 | 0.9982 |
if isinstance(left, Dist) and left in cache:
left = cache[left]
if isinstance(right, Dist) and right in cache:
right = cache[right]
if isinstance(left, Dist):
if isinstance(right, Dist):
raise StochasticallyDependentError(
... | def _ppf(self, q, left, right, cache) | Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9]))
[0.04 0.08 0.36]
>>> print(chaospy.Trunc(0.6, chaospy.Uniform()).inv([0.1, 0.2, 0... | 3.401288 | 3.280346 | 1.036869 |
if isinstance(poly, distributions.Dist):
x = polynomials.variable(len(poly))
poly, dist = x, poly
else:
poly = polynomials.Poly(poly)
if fisher:
adjust = 3
else:
adjust = 0
shape = poly.shape
poly = polynomials.flatten(poly)
m1 = E(poly, dist)
... | def Kurt(poly, dist=None, fisher=True, **kws) | Kurtosis operator.
Element by element 4rd order statistics of a distribution or polynomial.
Args:
poly (Poly, Dist):
Input to take kurtosis on.
dist (Dist):
Defines the space the skewness is taken on. It is ignored if
``poly`` is a distribution.
fish... | 3.144041 | 3.239966 | 0.970393 |
if stop is None:
start, stop = numpy.array(0), start
start = numpy.array(start, dtype=int)
stop = numpy.array(stop, dtype=int)
dim = max(start.size, stop.size, dim)
indices = numpy.array(chaospy.bertran.bindex(
numpy.min(start), 2*numpy.max(stop), dim, sort, cross_truncation))
... | def basis(start, stop=None, dim=1, sort="G", cross_truncation=1.) | Create an N-dimensional unit polynomial basis.
Args:
start (int, numpy.ndarray):
the minimum polynomial to include. If int is provided, set as
lowest total order. If array of int, set as lower order along each
axis.
stop (int, numpy.ndarray):
the max... | 2.988404 | 3.141381 | 0.951302 |
if len(args) == 1:
low, high = 0, args[0]
else:
low, high = args[:2]
core_old = poly.A
core_new = {}
for key in poly.keys:
if low <= numpy.sum(key) < high:
core_new[key] = core_old[key]
return Poly(core_new, poly.dim, poly.shape, poly.dtype) | def cutoff(poly, *args) | Remove polynomial components with order outside a given interval.
Args:
poly (Poly):
Input data.
low (int):
The lowest order that is allowed to be included. Defaults to 0.
high (int):
The upper threshold for the cutoff range.
Returns:
(Poly):... | 3.537257 | 3.744237 | 0.94472 |
P, Q = Poly(P), Poly(Q)
if not chaospy.poly.is_decomposed(Q):
differential(chaospy.poly.decompose(Q)).sum(0)
if Q.shape:
return Poly([differential(P, q) for q in Q])
if Q.dim>P.dim:
P = chaospy.poly.setdim(P, Q.dim)
else:
Q = chaospy.poly.setdim(Q, P.dim)
... | def differential(P, Q) | Polynomial differential operator.
Args:
P (Poly):
Polynomial to be differentiated.
Q (Poly):
Polynomial to differentiate by. Must be decomposed. If polynomial
array, the output is the Jacobian matrix. | 4.384303 | 4.235562 | 1.035117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.