UncertainScalarArray#
- class named_arrays.UncertainScalarArray(nominal=0, distribution=0)#
Bases:
AbstractUncertainScalarArray,AbstractExplicitScalarArray,Generic[NominalArrayT,DistributionArrayT]A scalar array with uncertainty, represented by a nominal value and a distribution of samples along the axis
_distribution.Each sample of the distribution is one possible realization of the array. Every operation is applied to the nominal value and to each realization separately, which propagates the uncertainty through a calculation.
import numpy as np import named_arrays as na x = na.UncertainScalarArray( nominal=na.ScalarArray(np.array([-1, 0.1, 2]), axes="x"), distribution=na.ScalarArray( ndarray=np.array([ [-1.1, -0.9, -1.0], [-0.2, 0.3, 0.1], [2.1, 1.9, 2.2], ]), axes=("x", "_distribution"), ), )
A mask computed from an uncertain array is uncertain too, and can select a different number of elements in each realization. Indexing with such a mask keeps every element selected by the nominal value or by any sample, and each realization which did not select an element holds NaN there.
print(x[x > 0])
UncertainScalarArray( nominal=ScalarArray( ndarray=[0.1, 2. ], shape={'x': 2}, ), distribution=ScalarArray( ndarray=[[nan, 2.1], [0.3, 1.9], [0.1, 2.2]], shape={'_distribution': 3, 'x': 2}, ), )Reductions which ignore NaN then give the same result as applying the mask to each realization separately.
print(np.nansum(x[x > 0])) print(np.sum(x, where=x > 0))
UncertainScalarArray( nominal=ScalarArray(ndarray=np.float64(2.1), shape={}), distribution=ScalarArray( ndarray=[2.1, 2.2, 2.3], shape={'_distribution': 3}, ), ) UncertainScalarArray( nominal=ScalarArray(ndarray=np.float64(2.1), shape={}), distribution=ScalarArray( ndarray=[2.1, 2.2, 2.3], shape={'_distribution': 3}, ), )A realization which selects nothing holds only NaN, so reductions like
numpy.nanmean()warn about an empty slice for it. Boolean arrays hold False instead of NaN, which leavesnumpy.any()andnumpy.sum()unaffected, but notnumpy.all(), so usenp.all(b, where=m)rather thannp.all(b[m]). Uncertain arrays which can hold neither, such as integer arrays, raise an error, as doesnumpy.nonzero(), since such a mask has no single set of indices. Arrays without a distribution are filled the same way, so they become uncertain, except that those which can hold neither, like the integer component of a vector or the labels of a function’s inputs, keep every selected element and stay certain, since the uncertain arrays which they accompany mark the elements a realization did not select. If every sample of the mask agrees with its nominal value, nothing is filled and arrays without a distribution stay certain. To select using only the nominal value of the mask, index withx[(x > 0).nominal].Assigning through an uncertain mask only changes the elements each realization selected,
y = x.copy() y[y < 0] = 0 print(y)
UncertainScalarArray( nominal=ScalarArray( ndarray=[0. , 0.1, 2. ], shape={'x': 3}, ), distribution=ScalarArray( ndarray=[[0. , 0. , 0. ], [0. , 0.3, 0.1], [2.1, 1.9, 2.2]], shape={'x': 3, '_distribution': 3}, ), )and the NaN values returned by indexing are never written back, so an update like
y[m] = -y[m]changes each realization correctly. If the nominal value or the distribution cannot store the result, because it does not vary along an axis of the mask or the distribution has no sample axis, both are replaced by broadcasted copies, so other arrays which share them are left unchanged. An array without a distribution cannot store a selection which differs between samples, or an uncertain value, so assigning one to it raises an error, except that a vector or function replaces its components, inputs, or outputs which have no distribution with uncertain copies. The arrays they replace are never written to, so other references to them are left unchanged.Similarly,
numpy.sort()sorts the nominal value and each sample separately, andnumpy.argsort()returns indices which differ between samples, so that indexing with them gathers each sample in its own order.Attributes
A
tupleofstrrepresenting the names of each dimension of this array.if this array has multiple components, broadcast them against each other.
Distribution of possible values of the array.
Data type of the array.
Converts this array to an instance of
named_arrays.AbstractExplicitArray.Compute the index of each element of this array.
L2-norm of this array.
Number of dimensions of the array.
The nominal value of the array.
Number samples along
axis_distribution.The number of elements along each axis of the array.
Total number of elements in the array.
The
named_arrays.AbstractArraytype corresponding to this array.The
named_arrays.AbstractExplicitArraytype corresponding to this array.Unit associated with the array.
Similar to
unitbut returnsastropy.units.dimensionless_unscaledifndarrayis not an instance ofastropy.units.Quantity.Returns a new array with its units removed, if they exist.
Methods
__init__([nominal, distribution])add_axes(axes)Add new singleton axes to this array.
all([axis, where])Return
Trueif all of the elements along the given axes areTrue.any([axis, where])Return
Trueif any of the elements along the given axes areTrue.astype(dtype[, order, casting, subok, copy])Copy of the array cast to a specific data type.
broadcast_to(shape[, append])A new view of this array with the specified shape.
cell_centers([axis, random, seed])Convert an array from cell vertices to cell centers.
combine_axes([axes, axis_new])Combine some of the axes of the array into a single new axis.
copy()Create a deep copy of this array.
Create a shallow copy of this array.
debroadcast([axes])Remove redundant axes introduced by broadcasting.
from_scalar_array(a[, like])Constructs a new version of this array using
aas the underlying data.index(value[, axis])index_secant(value[, axis])interp_linear(item)Linearly interpolate this array to find its value at the given fractional index.
isel(**item)Index this array along named axes given as keyword arguments.
matrix_inverse(axis_rows, axis_columns)Compute the inverse of this array, treating it as a matrix with the given row and column axes.
max([axis, initial, where])The maximum value of this array along the given axes.
mean([axis, where])The mean value of this array along the given axes.
mean_trimmed([q, axis])Compute the trimmed mean along the specified axes.
median([axis])The median value of this array along the given axes.
min([axis, initial, where])The minimum value of this array along the given axes.
ndindex([axis_ignored])An iterator that yields the index of each element of this array.
percentile(q[, axis, out, overwrite_input, ...])The requested percentile of this array along the given axes.
ptp([axis])The peak-to-peak value of this array along the given axes.
replace(**changes)A method version of
dataclasses.replace()for named arrays.reshape(shape)Reorganize this array into a new shape.
rms([axis, where])The root-mean-square of this array along the given axes.
std([axis, where])The standard deviation of this array along the given axes.
sum([axis, where])The sum of each element of this array along the given axes.
take_along_axis(indices, axis)Take values from this array by matching
indicesalongaxis.to(unit[, equivalencies, copy])Convert this array to a new unit.
to_string([prefix, multiline])Convert this array instance to a string representation.
to_string_array([format_value, format_unit, ...])Convert to an array of strings where each string has an appropriately-formatted unit attached to the value.
to_value(unit[, equivalencies])The numerical value of this array, possibly in a different unit.
transpose([axes])Reorder the axes of this array to the given sequence.
var([axis, where])The variance of this array along the given axes.
vmr([axis, where])The variance-to-mean ratio of this array along the given axes.
volume_cell(axis)Computes the n-dimensional volume of each cell formed by interpreting this array as a logically-rectangular grid of vertices.
Inheritance Diagram

- Parameters:
nominal (NominalArrayT)
distribution (DistributionArrayT)
- classmethod from_scalar_array(a, like=None)#
Constructs a new version of this array using
aas the underlying data.- Parameters:
a (float | Quantity | AbstractScalarArray) – Anything that can be coerced into an instance of
named_arrays.AbstractScalarArray.like (None | Self) – Optional reference object. If provided, the result will be defined by this object.
- Return type:
- add_axes(axes)#
Add new singleton axes to this array.
- Parameters:
axes (str | Sequence[str]) – Either a single axis name or a sequence of axis names add to this array.
- Return type:
See also
named_arrays.add_axes()A functional version of this method.
- all(axis=None, where=<no value>)#
Return
Trueif all of the elements along the given axes areTrue.- Parameters:
- Return type:
See also
numpy.all()A functional version of this method.
- any(axis=None, where=<no value>)#
Return
Trueif any of the elements along the given axes areTrue.- Parameters:
- Return type:
See also
numpy.any()A functional version of this method.
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)#
Copy of the array cast to a specific data type.
Equivalent to
numpy.ndarray.astype().
- broadcast_to(shape, append=False)#
A new view of this array with the specified shape.
- Parameters:
- Return type:
See also
named_arrays.broadcast_to()A functional version of this method.
- cell_centers(axis=None, random=False, seed=None)#
Convert an array from cell vertices to cell centers.
- Parameters:
axis (None | str | Sequence[str]) – The axes of the array to average over.
random (bool) – If true, select a random point within each cell instead of the geometric center.
seed (None | int) – The seed of the random sampling, which has an effect only where
randomis true. IfNone(the default), the sampling differs from one call to the next, and anything computed from it cannot be reproduced.
- Return type:
- combine_axes(axes=None, axis_new=None)#
Combine some of the axes of the array into a single new axis.
- debroadcast(axes=None)#
Remove redundant axes introduced by broadcasting.
- Parameters:
- Return type:
See also
named_arrays.debroadcast()A functional version of this method.
- index(value, axis=None)#
- index_secant(value, axis=None)#
- interp_linear(item)#
Linearly interpolate this array to find its value at the given fractional index.
- isel(**item)#
Index this array along named axes given as keyword arguments.
This is a convenience wrapper around
__getitem__():a.isel(x=0)is equivalent toa[dict(x=0)].Since keyword-argument names must be valid Python identifiers, axes whose names are not valid identifiers can only be indexed using the
dictform,a[{...}].- Parameters:
item (int | slice | AbstractArray) – The index to apply along each named axis.
self (Self)
- Return type:
- matrix_inverse(axis_rows, axis_columns)#
Compute the inverse of this array, treating it as a matrix with the given row and column axes.
The nominal value and every sample of the distribution are inverted separately, since the distribution axis is independent of the axes of the matrix.
- Parameters:
- Return type:
- max(axis=None, initial=<no value>, where=<no value>)#
The maximum value of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.max()A functional version of this method.
- mean(axis=None, where=<no value>)#
The mean value of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.mean()A functional version of this method.
- mean_trimmed(q=0.25, axis=None)#
Compute the trimmed mean along the specified axes.
- Parameters:
q (float) – The fraction of the largest and smallest elements to remove. Must be between 0 and 1/2. If the specified fraction does not result in an integer number of elements, the number of elements to trim is rounded down.
axis (None | str | Sequence[str]) – The axis or axes along which to compute the trimmed mean.
- Return type:
See also
- median(axis=None)#
The median value of this array along the given axes.
- Parameters:
axis (None | str | Sequence[str]) – The logical axis or axes along which the operation is computed.
See also
numpy.median()A functional version of this method.
- min(axis=None, initial=<no value>, where=<no value>)#
The minimum value of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.min()A functional version of this method.
- ndindex(axis_ignored=None)#
An iterator that yields the index of each element of this array.
- Parameters:
- Return type:
See also
named_arrays.ndindex()A functional version of this method.
- percentile(q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False)#
The requested percentile of this array along the given axes.
- Parameters:
q (int | float | Quantity | Self) – The percentile to compute.
axis (None | str | Sequence[str]) – The logical axis or axes along which the operation is computed.
out (None | Self) – An optional output array in which to place the result.
overwrite_input (bool) – Whether to overwrite the input array.
method (str) – How to interpolate the result.
keepdims (bool) – A boolean flag indicating whether to keep the reduced dimensions.
self (Self)
See also
numpy.percentile()A functional version of this method.
- ptp(axis=None)#
The peak-to-peak value of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.ptp()A functional version of this method.
- replace(**changes)#
A method version of
dataclasses.replace()for named arrays.- Parameters:
changes – The fields of the dataclass to be overwritten
- Return type:
- reshape(shape)#
Reorganize this array into a new shape.
- rms(axis=None, where=<no value>)#
The root-mean-square of this array along the given axes.
- std(axis=None, where=<no value>)#
The standard deviation of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.std()A functional version of this method.
- sum(axis=None, where=<no value>)#
The sum of each element of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.sum()A functional version of this method.
- take_along_axis(indices, axis)#
Take values from this array by matching
indicesalongaxis.- Parameters:
indices (AbstractArray) – The integer indices to take along
axis.axis (str) – The axis of this array along which the values are taken.
self (Self)
- Return type:
See also
named_arrays.take_along_axis()A functional version of this method.
- to(unit, equivalencies=None, copy=True)#
Convert this array to a new unit.
Equivalent to
astropy.units.Quantity.to().
- to_string(prefix=None, multiline=None)#
Convert this array instance to a string representation.
- to_string_array(format_value='%.2f', format_unit='latex_inline', pad_unit='$\\,$')#
Convert to an array of strings where each string has an appropriately-formatted unit attached to the value.
- Parameters:
- Return type:
- to_value(unit, equivalencies=None)#
The numerical value of this array, possibly in a different unit.
Equivalent to
astropy.units.Quantity.to_value().
- transpose(axes=None)#
Reorder the axes of this array to the given sequence.
- Parameters:
- Return type:
See also
numpy.transpose()The
numpyversion of this method.
- var(axis=None, where=<no value>)#
The variance of this array along the given axes.
- Parameters:
- Return type:
See also
numpy.var()A functional version of this method.
- vmr(axis=None, where=<no value>)#
The variance-to-mean ratio of this array along the given axes.
- volume_cell(axis)#
Computes the n-dimensional volume of each cell formed by interpreting this array as a logically-rectangular grid of vertices.
Note that this method is usually only used for sorted arrays.
If self is a scalar, this method computes the length of each edge, and is equivalent to
numpy.diff(). If self is a 2d vector, this method computes the area of each quadrilateral, and if self is a 3d vector, this method computes the volume of each cuboid.
- property axes: tuple[str, ...]#
A
tupleofstrrepresenting the names of each dimension of this array.Must have the same length as the number of dimensions of this array.
- property axes_flattened: str#
Combine
axesinto a singlestr.This is useful for functions like
numpy.flatten()which returns an array with only one dimension.
- property broadcasted: AbstractExplicitArray#
if this array has multiple components, broadcast them against each other.
Equivalent to
a.broadcast_to(a.shape).
- distribution: DistributionArrayT = 0#
Distribution of possible values of the array.
- property dtype: dtype#
Data type of the array. Equivalent to
numpy.ndarray.dtype
- property explicit: Self#
Converts this array to an instance of
named_arrays.AbstractExplicitArray.
- property indices: dict[str, ScalarArrayRange]#
Compute the index of each element of this array.
See also
named_arrays.indices()A functional version of this method.
- property length: AbstractScalar#
L2-norm of this array.
- property ndim: int#
Number of dimensions of the array. Equivalent to
numpy.ndarray.ndim.
- nominal: NominalArrayT = 0#
The nominal value of the array.
- property num_distribution: int#
Number samples along
axis_distribution.
- property shape: dict[str, int]#
The number of elements along each axis of the array. Analogous to
numpy.ndarray.shapebut represented as adictwhere the keys are the axis names and the values are the axis sizes.
- property size: int#
Total number of elements in the array. Equivalent to
numpy.ndarray.size
- property type_abstract: Type[AbstractUncertainScalarArray]#
The
named_arrays.AbstractArraytype corresponding to this array.
- property type_explicit: Type[UncertainScalarArray]#
The
named_arrays.AbstractExplicitArraytype corresponding to this array.
- property unit: None | UnitBase#
Unit associated with the array.
If
ndarrayis an instance ofastropy.units.Quantity, returnastropy.units.Quantity.unit, otherwise returnNone.
- property unit_normalized: UnitBase#
Similar to
unitbut returnsastropy.units.dimensionless_unscaledifndarrayis not an instance ofastropy.units.Quantity.
- property value: UncertainScalarArray#
Returns a new array with its units removed, if they exist.
The family is preserved, so a vector returns a vector and a function array returns a function array, but the result is always explicit: an implicit array materializes into its family’s explicit type.