cmomy.CentralMoments#
- class cmomy.CentralMoments(data, *, mom_ndim=1, copy=None, order=None, dtype=None, fastpath=False)[source]#
Bases:
CentralMomentsABC
[FloatT
,ndarray
[Any
,dtype
[FloatT
]]],Generic
[FloatT
]Wrapper of
numpy.ndarray
based central moments data.- Parameters:
data (
numpy.ndarray
) – Central moments array.mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
).copy (
bool
, optional) – If True, copy the data. If None or False, attempt to use view. Note thatFalse
values will be converted toNone
for numpy versions>2.0
. This will be changed to reflect the new behavior of thecopy
parameter tonumpy.array()
when the minimum numpy version>2.0
.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.fastpath (
bool
) – For internal use.
Notes
Base data has the form
\[\begin{split}{\rm data}[..., i, j] = \begin{cases} \text{weight} & i = j = 0 \\ \langle x \rangle & i = 1, j = 0 \\ \langle (x - \langle x \rangle^i) (y - \langle y \rangle^j) \rangle & i + j > 0 \end{cases}\end{split}\]Methods
assign_weight
(weight[, copy])Create object with updated weights
astype
(dtype, *[, order, casting, subok, copy])Underlying data cast to specified type
block
(block_size, *[, axis, order, parallel])Block average reduction.
cmom
()Central moments.
copy
()Create a new object with copy of data.
fill
([value])Fill data with value.
from_raw
(raw, *, mom_ndim)Create object from raw moment data.
from_resample_vals
(x, *y, mom, freq[, axis, ...])Create from resample observations/values.
from_vals
(x, *y, mom[, axis, weight, order, ...])Create from observations/values.
mean
()Mean (first moment).
moments_to_comoments
(*, mom)Convert moments (mom_ndim=1) to comoments (mom_ndim=2).
moveaxis
(source, destination)Move axis from source to destination.
new_like
([data, copy, order, verify, dtype])Create new object like self, with new data.
pipe
(func_or_method, *args[, _reorder, ...])Apply func_or_method to underlying data and wrap results in class:cmomy.xCentralMoments object.
push_data
(data, *[, order, parallel])Push data object to moments.
push_datas
(datas, *[, axis, order, parallel])Push and reduce multiple average central moments.
push_val
(x, *y[, weight, order, parallel])Push single sample to central moments.
push_vals
(x, *y[, axis, weight, order, parallel])Push multiple samples to central moments.
randsamp_freq
(*[, axis, nrep, nsamp, ...])Interface to
resample.randsamp_freq()
reduce
(*[, axis, by, order, parallel])Create new object reduce along axis.
resample
(indices, *[, axis, last, order])Create a new object sampled from index.
resample_and_reduce
(*, freq[, axis, ...])Bootstrap resample and reduce.
reshape
(shape, *[, order])Create a new object with reshaped data.
rmom
()Raw moments.
set_values
(values)Set values.
std
()Standard deviation.
to_dataarray
(*[, dims, attrs, coords, name, ...])Create a
xarray.DataArray
representation of underlying data.to_numpy
()Access to numpy array underlying class.
to_raw
(*[, weight])Raw moments accumulation array.
Access underlying values
to_x
(*[, dims, attrs, coords, name, ...])Alias to
to_xcentralmoments()
.to_xcentralmoments
(*[, dims, attrs, coords, ...])Create an
xarray.DataArray
representation of underlying data.var
()Variance (second central moment).
weight
()Weight data.
zero
()Zero out underlying data.
zeros
(*, mom[, val_shape, dtype, order])Create a new base object.
Create new empty object like self.
Attributes
Accessor to numpy array underlying data.
self.data.dtype.
Number of moments.
Length of moments.
Shape of moments part.
self.data.ndim.
self.data.shape.
Number of value dimensions.
Shape of values dimensions.
Access underlying central moments array.
Dunder Methods
__add__
(b)Add objects to new object.
__getitem__
(key)Get new object by indexing.
__iadd__
(b)Self adder.
__imul__
(scale)Inplace multiply.
__isub__
(b)Inplace subtraction.
__mul__
(scale)New object with weight scaled by scale.
__sub__
(b)Subtract objects.
- new_like(data=None, *, copy=None, order=None, verify=False, dtype=None)[source]#
Create new object like self, with new data.
- Parameters:
data (
numpy.ndarray
) – data for new objectcopy (
bool
, optional) – If True, copy the data. If None or False, attempt to use view. Note thatFalse
values will be converted toNone
for numpy versions>2.0
. This will be changed to reflect the new behavior of thecopy
parameter tonumpy.array()
when the minimum numpy version>2.0
.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.verify (
bool
) – If True, make sure data is c-contiguous.
- Returns:
CentralMoments
– New CentralMoments object with zerod out data.
Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> da = CentralMoments.from_vals(rng.random(10), mom=3, axis=0) >>> da <CentralMoments(val_shape=(), mom=(3,))> array([10. , 0.5505, 0.1014, -0.0178])
>>> da2 = da.new_like().zero() >>> da2 <CentralMoments(val_shape=(), mom=(3,))> array([0., 0., 0., 0.])
>>> da <CentralMoments(val_shape=(), mom=(3,))> array([10. , 0.5505, 0.1014, -0.0178])
- astype(dtype, *, order=None, casting=None, subok=None, copy=False)[source]#
Underlying data cast to specified type
- Parameters:
dtype (
str
ordtype
) – Typecode of data-type to cast the array data. Note that a value of None will upcast tonp.float64
. This is the same behaviour asasarray()
.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
, optional) –Controls what kind of data casting may occur.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ (default) means any data conversions may be done.
subok (
bool
, optional) – If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array.copy (
bool
, optional) – By default, astype always returns a newly allocated array. If this is set to False and the dtype requirement is satisfied, the input array is returned insteadof a copy.
Notes
Only
numpy.float32
andnumpy.float64
dtypes are supported.See also
- to_dataarray(*, dims=None, attrs=None, coords=None, name=None, indexes=None, mom_dims=None, template=None, copy=False)[source]#
Create a
xarray.DataArray
representation of underlying data.- Parameters:
dims (hashable or sequence of hashable) –
Dimension of resulting
xarray.DataArray
.If
len(dims) == self.ndim
, then dims specifies all dimensions.If
len(dims) == self.val_ndim
,dims = dims + mom_dims
Default to
('dim_0', 'dim_1', ...)
attrs (mapping) – Attributes of output
coords (mapping) – Coordinates of output
name (hashable) – Name of output
indexes (
Any
) – indexes attribute. This is ignored.template (
DataArray
) – If present, output will have attributes of template. Overrides other options.copy (
bool
) – IfTrue
, copy the data. If False, return a view if possible.
- Returns:
output (
DataArray
)
Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> da = CentralMoments.from_vals(rng.random((10, 1, 2)), axis=0, mom=2) >>> da <CentralMoments(val_shape=(1, 2), mom=(2,))> array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]])
Default constructor
>>> da.to_dataarray() <xarray.DataArray (dim_0: 1, dim_1: 2, mom_0: 3)> Size: 48B array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]]) Dimensions without coordinates: dim_0, dim_1, mom_0
Setting attributes
>>> da.to_dataarray() <xarray.DataArray (dim_0: 1, dim_1: 2, mom_0: 3)> Size: 48B array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]]) Dimensions without coordinates: dim_0, dim_1, mom_0 >>> da <CentralMoments(val_shape=(1, 2), mom=(2,))> array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]])
- to_xcentralmoments(*, dims=None, attrs=None, coords=None, name=None, indexes=None, mom_dims=None, template=None, copy=False)[source]#
Create an
xarray.DataArray
representation of underlying data.- Parameters:
dims (hashable or sequence of hashable) –
Dimension of resulting
xarray.DataArray
.If
len(dims) == self.ndim
, then dims specifies all dimensions.If
len(dims) == self.val_ndim
,dims = dims + mom_dims
Default to
('dim_0', 'dim_1', ...)
attrs (mapping) – Attributes of output
coords (mapping) – Coordinates of output
name (hashable) – Name of output
indexes (
Any
) – indexes attribute. This is ignored.template (
DataArray
) – If present, output will have attributes of template. Overrides other options.copy (
bool
) – IfTrue
, copy the data. If False, return a view if possible.
- Returns:
output (
xCentralMoments
)
See also
Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> da = CentralMoments.from_vals(rng.random((10, 1, 2)), axis=0, mom=2) >>> da <CentralMoments(val_shape=(1, 2), mom=(2,))> array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]])
Default constructor
>>> da.to_xcentralmoments() <xCentralMoments(val_shape=(1, 2), mom=(2,))> <xarray.DataArray (dim_0: 1, dim_1: 2, mom_0: 3)> Size: 48B array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]]) Dimensions without coordinates: dim_0, dim_1, mom_0
Setting attributes
>>> da.to_xcentralmoments() <xCentralMoments(val_shape=(1, 2), mom=(2,))> <xarray.DataArray (dim_0: 1, dim_1: 2, mom_0: 3)> Size: 48B array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]]) Dimensions without coordinates: dim_0, dim_1, mom_0 >>> da <CentralMoments(val_shape=(1, 2), mom=(2,))> array([[[10. , 0.6207, 0.0647], [10. , 0.404 , 0.1185]]])
- to_x(*, dims=None, attrs=None, coords=None, name=None, indexes=None, mom_dims=None, template=None, copy=False)[source]#
Alias to
to_xcentralmoments()
.
- push_data(data, *, order=None, parallel=False)[source]#
Push data object to moments.
- Parameters:
data (array-like) – Accumulation array of same form as
self.data
order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – Same object with pushed data.
Examples
>>> import cmomy >>> rng = cmomy.random.default_rng(0) >>> xs = rng.random((2, 10)) >>> datas = [cmomy.reduce_vals(x, mom=2, axis=0) for x in xs] >>> da = CentralMoments(datas[0], mom_ndim=1) >>> da <CentralMoments(val_shape=(), mom=(2,))> array([10. , 0.5505, 0.1014])
>>> da.push_data(datas[1]) <CentralMoments(val_shape=(), mom=(2,))> array([20. , 0.5124, 0.1033])
Which is equivalent to
>>> CentralMoments.from_vals(xs.reshape(-1), mom=2, axis=0) <CentralMoments(val_shape=(), mom=(2,))> array([20. , 0.5124, 0.1033])
- push_datas(datas, *, axis=-1, order=None, parallel=None)[source]#
Push and reduce multiple average central moments.
- Parameters:
datas (array-like,
numpy.ndarray
) – Collection of accumulation arrays to push ontoself
. This should have shape like (nrec,) + self.shape if axis=0, where nrec is the number of data objects to sum.axis (
int
, optional) – Axis to reduce along. Note that negative values are relative todata.ndim - mom_ndim
. It is assumed that the last dimensions are for moments. For example, ifdata.shape == (1,2,3)
withmom_ndim=1
,axis = -1 `` would be equivalent to ``axis = 1
. Defaults toaxis=-1
.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – Same object with pushed data.
Examples
>>> import cmomy >>> rng = cmomy.random.default_rng(0) >>> xs = rng.random((2, 10)) >>> datas = cmomy.reduce_vals(xs, axis=1, mom=2) >>> da = CentralMoments.zeros(mom=2) >>> da.push_datas(datas, axis=0) <CentralMoments(val_shape=(), mom=(2,))> array([20. , 0.5124, 0.1033])
Which is equivalent to
>>> CentralMoments.from_vals(xs.reshape(-1), mom=2, axis=0) <CentralMoments(val_shape=(), mom=(2,))> array([20. , 0.5124, 0.1033])
- push_val(x, *y, weight=None, order=None, parallel=False)[source]#
Push single sample to central moments.
- Parameters:
x (array) – Values to push onto
self
.*y (array-like, optional) – Additional Values (needed if
mom_ndim > 1
)weight (
int
,float
, array-like, optional) – Weight of each sample. If scalar, broadcast w.shape to x0.shape.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – Same object with pushed data.
Notes
Array x0 should have same shape as self.val_shape.
Examples
>>> import cmomy >>> rng = cmomy.random.default_rng(0) >>> x = rng.random((10, 2)) >>> y = rng.random(10) >>> w = rng.random(10)
>>> da = CentralMoments.zeros(val_shape=(2,), mom=(2, 2)) >>> for xx, yy, ww in zip(x, y, w): ... _ = da.push_val(xx, yy, weight=ww)
>>> da <CentralMoments(val_shape=(2,), mom=(2, 2))> array([[[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 6.4741e-01, 3.3791e-02, -5.1117e-03], [ 5.0888e-02, -1.0060e-02, 7.0290e-03]], [[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 3.9793e-01, 6.3224e-03, -2.2669e-02], [ 9.3979e-02, 9.9433e-04, 6.5765e-03]]])
Which is the same as
>>> CentralMoments.from_vals(x, y, weight=w, mom=(2, 2), axis=0) <CentralMoments(val_shape=(2,), mom=(2, 2))> array([[[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 6.4741e-01, 3.3791e-02, -5.1117e-03], [ 5.0888e-02, -1.0060e-02, 7.0290e-03]], [[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 3.9793e-01, 6.3224e-03, -2.2669e-02], [ 9.3979e-02, 9.9433e-04, 6.5765e-03]]])
- push_vals(x, *y, axis=-1, weight=None, order=None, parallel=None)[source]#
Push multiple samples to central moments.
- Parameters:
x (array) – Value to reduce.
*y (array-like) – Additional array (if
self.mom_ndim == 2
).axis (
int
) – Axis to reduce along.weight (
int
,float
, array-like, optional) – Weight of each sample. If scalar, broadcast to x0.shapeorder (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – Same object with pushed data.
Examples
>>> import cmomy >>> rng = cmomy.random.default_rng(0) >>> x = rng.random((10, 2)) >>> y = rng.random(10) >>> w = rng.random(10)
>>> da = CentralMoments.zeros(val_shape=(2,), mom=(2, 2)) >>> da.push_vals(x, y, weight=w, axis=0) <CentralMoments(val_shape=(2,), mom=(2, 2))> array([[[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 6.4741e-01, 3.3791e-02, -5.1117e-03], [ 5.0888e-02, -1.0060e-02, 7.0290e-03]], [[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 3.9793e-01, 6.3224e-03, -2.2669e-02], [ 9.3979e-02, 9.9433e-04, 6.5765e-03]]])
Which is the same as
>>> CentralMoments.from_vals(x, y, weight=w, mom=(2, 2), axis=0) <CentralMoments(val_shape=(2,), mom=(2, 2))> array([[[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 6.4741e-01, 3.3791e-02, -5.1117e-03], [ 5.0888e-02, -1.0060e-02, 7.0290e-03]], [[ 5.4367e+00, 6.0656e-01, 9.9896e-02], [ 3.9793e-01, 6.3224e-03, -2.2669e-02], [ 9.3979e-02, 9.9433e-04, 6.5765e-03]]])
- __getitem__(key)[source]#
Get new object by indexing.
Note that only objects with the same moment(s) shape are allowed.
If you want to extract data in general, use self.to_values()[….].
- assign_weight(weight, copy=True)[source]#
Create object with updated weights
- Parameters:
weight (array-like, optional) – Optional weights. Can be scalar, 1d array of length
args[0].shape[axis]
or array of same form asargs[0]
.copy (
bool
, defaultTrue
) – IfTrue
(default), copy the underlying moments data before update. Otherwise, update weights in in place.
- Returns:
output (
object
) – Same type asself
- cmom()[source]#
Central moments.
Strict central moments of the form
\[\text{cmom[..., n, m]} = \langle (x - \langle x \rangle)^n (y - \langle y \rangle)^m \rangle\]where
\[\langle x \rangle = \sum_i w_i x_i / \sum_i w_i\]
- copy()[source]#
Create a new object with copy of data.
- Parameters:
**copy_kws – passed to parameter
copy_kws
in methodnew_like()
- Returns:
output (
object
) – Same type as calling class. Object with same attributes as caller, but with new underlying data.
See also
- property data#
Accessor to numpy array underlying data.
By convention data has the following meaning for the moments indexes
data[…,i=0,j=0], weight
data[…,i=1,j=0]], if only one moment index is one and all others zero, then this is the average value of the variable with unit index.
all other cases, the central moments <(x0-<x0>)**i0 * (x1 - <x1>)**i1 * …>
- property dtype#
self.data.dtype.
- property mom#
Number of moments.
- property mom_ndim#
Length of moments.
if mom_ndim == 1, then single variable moments if mom_ndim == 2, then co-moments.
- property mom_shape#
Shape of moments part.
- moments_to_comoments(*, mom)[source]#
Convert moments (mom_ndim=1) to comoments (mom_ndim=2).
- Parameters:
mom (
tuple
ofint
) – Moments for comoments array. Pass a negative value for one of the moments to fill all available moments for that dimensions. For example, if original array has moments m (i.e.,values.shape=(..., m + 1)
), and pass inmom = (2, -1)
, then this will be transformed tomom = (2, m - 2)
.
See also
- property ndim#
self.data.ndim.
- pipe(func_or_method, *args, _reorder=True, _copy=None, _order=None, _verify=False, **kwargs)[source]#
Apply func_or_method to underlying data and wrap results in class:cmomy.xCentralMoments object.
This is useful for calling any not implemented methods on
numpy.ndarray
orxarray.DataArray
data.Note that a
ValueError
will be raised if last dimension(s) do not have the same shape asself.mom_shape
.- Parameters:
func_or_method (
str
orcallable()
) – If callable, then applyvalues = func_or_method(self.to_values(), *args, **kwargs)
. If string is passed, thenvalues = getattr(self.to_values(), func_or_method)(*args, **kwargs)
.*args (
Any
) – Extra positional arguments to func_or_method_reorder (
bool
, defaultTrue
) – If True, reorder the data such thatmom_dims
are last. Only applicable forDataArray
like underlying data._copy (
bool
, defaultFalse
) – If True, copy the resulting data. Otherwise, try to use a view._order (
str
, optional) – Array order to apply to output.**kwargs (
Any
) – Extra keyword arguments to func_or_method
- Returns:
output (
object
) – New object after func_or_method is applies to self.to_values()
Notes
Use leading underscore for _order, _copy, etc to avoid possible name clashes with
func_or_method
.
- randsamp_freq(*, axis=-1, nrep=None, nsamp=None, indices=None, freq=None, check=False, rng=None)[source]#
Interface to
resample.randsamp_freq()
- resample_and_reduce(*, freq, axis=-1, parallel=None, order=None)[source]#
Bootstrap resample and reduce.
- Parameters:
freq (array of
int
) – Array of shape(nrep, size)
where nrep is the number of replicates andsize = self.shape[axis]
. freq is the weight that each sample contributes to resamples values. Seerandsamp_freq()
axis (
int
, optional) – Axis to reduce along. Note that negative values are relative todata.ndim - mom_ndim
. It is assumed that the last dimensions are for moments. For example, ifdata.shape == (1,2,3)
withmom_ndim=1
,axis = -1 `` would be equivalent to ``axis = 1
. Defaults toaxis=-1
.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
object
) – Instance of calling class. Note that new object will have(...,shape[axis-1], shape[axis+1], ..., nrep, mom0, ...)
, wherenrep = freq.shape[0]
.
See also
randsamp_freq
random frequency sample
freq_to_indices
convert frequency sample to index sample
indices_to_freq
convert index sample to frequency sample
resample_data
method to perform resampling
- rmom()[source]#
Raw moments.
\[\text{rmom[..., n, m]} = \langle x^n y^m \rangle\]where
\[\langle x \rangle = \sum_i w_i x_i / \sum_i w_i\]See also
- property shape#
self.data.shape.
- to_raw(*, weight=None)[source]#
Raw moments accumulation array.
\[\begin{split}\text{raw[..., n, m]} = \begin{cases} \text{weight} & n = m = 0 \\ \langle x^n y ^m \rangle & \text{otherwise} \end{cases}\end{split}\]where
\[\langle x \rangle = \sum_i w_i x_i / \sum_i w_i\]See also
- property val_ndim#
Number of value dimensions.
- property val_shape#
Shape of values dimensions.
That is shape less moments dimensions.
- property values#
Access underlying central moments array.
- zero()[source]#
Zero out underlying data.
- Returns:
self (
object
) – Same type as calling class. Same object with data filled with zeros.
See also
- zeros_like()[source]#
Create new empty object like self.
- Returns:
output (
object
) – Object with same attributes as caller, but with data set to zero.
See also
- reduce(*, axis=-1, by=None, order=None, parallel=None)[source]#
Create new object reduce along axis.
- Parameters:
axis (
int
, optional) – Axis to reduce along. Note that negative values are relative todata.ndim - mom_ndim
. It is assumed that the last dimensions are for moments. For example, ifdata.shape == (1,2,3)
withmom_ndim=1
,axis = -1 `` would be equivalent to ``axis = 1
. Defaults toaxis=-1
.by (array-like of
int
) – Groupby values of same length asdata
along sampled dimension. Negative values indicate no group (i.e., skip this index).order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – Ifby
isNone
, reduce all samples alongaxis
. Otherwise, reduce for each unique value ofby
. In this case, output will have shape(..., shape[axis-1], shape[axis+1], ..., ngroup, mom0, ...)
wherengroups = np.max(by) + 1
is the number of unique positive values inby
.
See also
- resample(indices, *, axis=-1, last=True, order=None)[source]#
Create a new object sampled from index.
- Parameters:
indices (array of
int
) – Array of shape(nrep, size)
. If passed, create freq from indices. Seerandsamp_freq()
.axis (
int
, optional) – Axis to reduce along. Note that negative values are relative todata.ndim - mom_ndim
. It is assumed that the last dimensions are for moments. For example, ifdata.shape == (1,2,3)
withmom_ndim=1
,axis = -1 `` would be equivalent to ``axis = 1
. Defaults toaxis=-1
.last (
bool
, defaultTrue
) – IfTrue
, and axis != -1, move the axis to last position before moments. This makes results similar to resample and reduce If last False, then resampled array can have odd shapeorder (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
object
) – Instance of calling class. The new object will have shape(..., shape[axis-1], nrep, nsamp, shape[axis+1], ...)
, (iflast=False
) or shape(..., shape[axis-1], shape[axis+1], ..., nrep, nsamp, mom_0, ...)
(iflast=True
), whereshape=self.data
andnrep, nsamp = indices.shape
.
- block(block_size, *, axis=-1, order=None, parallel=None)[source]#
Block average reduction.
- Parameters:
- Returns:
output (
object
) – Block averaged data of shape(..., shape[axis-1],shape[axis+1], ..., nblock, mom_0, ...)
Whereshape=self.shape
. That is, the blocked coordinates are last.
Notes
The block averaged axis will be moved to the front of the output data.
See also
- reshape(shape, *, order=None)[source]#
Create a new object with reshaped data.
- Parameters:
shape (
tuple
) – shape of values part of data.order (
{"C", "F", "A"}
, optional) – Parameter tonumpy.reshape()
. Note that this parameter has nothing to do with the output data order. Rather, it is how the data is read for the reshape.
- Returns:
output (
CentralMoments
) – Output object with reshaped data. This will be a view if possilble; otherwise, it will be copy.
See also
Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> da = CentralMoments.from_vals(rng.random((10, 2, 3)), mom=2, axis=0) >>> da <CentralMoments(val_shape=(2, 3), mom=(2,))> array([[[10. , 0.5205, 0.0452], [10. , 0.4438, 0.0734], [10. , 0.5038, 0.1153]], [[10. , 0.5238, 0.1272], [10. , 0.628 , 0.0524], [10. , 0.412 , 0.0865]]])
>>> da.reshape(shape=(-1,)) <CentralMoments(val_shape=(6,), mom=(2,))> array([[10. , 0.5205, 0.0452], [10. , 0.4438, 0.0734], [10. , 0.5038, 0.1153], [10. , 0.5238, 0.1272], [10. , 0.628 , 0.0524], [10. , 0.412 , 0.0865]])
- moveaxis(source, destination)[source]#
Move axis from source to destination.
- Parameters:
- Returns:
result (
CentralMoments
) – CentralMoments object with with moved axes. This array is a view of the input array.
Notes
Both
source
anddestination
are relative toself.val_shape
. So the moment dimensions will always remain as the last dimensions.Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> da = CentralMoments.from_vals(rng.random((10, 1, 2, 3)), axis=0, mom=2) >>> da.moveaxis((2, 1), (0, 2)) <CentralMoments(val_shape=(3, 1, 2), mom=(2,))> array([[[[10. , 0.5205, 0.0452], [10. , 0.5238, 0.1272]]], [[[10. , 0.4438, 0.0734], [10. , 0.628 , 0.0524]]], [[[10. , 0.5038, 0.1153], [10. , 0.412 , 0.0865]]]])
- classmethod zeros(*, mom, val_shape=None, dtype=None, order=None)[source]#
Create a new base object.
- Parameters:
mom (
int
ortuple
ofint
) – Order or moments. If integer or length one tuple, then moments are for a single variable. If length 2 tuple, then comoments of two variablesval_shape (
tuple
) – Shape of values part of data. That is, the non-moment dimensions.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
) – New instance with zero values.
See also
- classmethod from_vals(x, *y, mom, axis=-1, weight=None, order=None, parallel=None, dtype=None)[source]#
Create from observations/values.
- Parameters:
x (
ndarray
) – Values to reduce.*y (array-like) – Additional values (needed if
len(mom)==2
).weight (scalar or array-like, optional) – Optional weight. If scalar or array, attempt to broadcast to x0.shape
axis (
int
) – Axis to reduce along.mom (
int
ortuple
ofint
) – Order or moments. If integer or length one tuple, then moments are for a single variable. If length 2 tuple, then comoments of two variablesorder (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
CentralMoments
)
See also
Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> x = rng.random((100, 3)) >>> da = CentralMoments.from_vals(x, axis=0, mom=2) >>> da <CentralMoments(val_shape=(3,), mom=(2,))> array([[1.0000e+02, 5.5313e-01, 8.8593e-02], [1.0000e+02, 5.5355e-01, 7.1942e-02], [1.0000e+02, 5.1413e-01, 1.0407e-01]])
- classmethod from_resample_vals(x, *y, mom, freq, axis=-1, weight=None, order=None, parallel=None, dtype=None)[source]#
Create from resample observations/values.
This effectively resamples x.
- Parameters:
x (array) – For moments, pass single array-like objects x=x0. For comoments, pass tuple of array-like objects x=(x0, x1).
*y (array-like) – Additional values (needed if
len(mom) > 1
).mom (
int
ortuple
ofint
) – Order or moments. If integer or length one tuple, then moments are for a single variable. If length 2 tuple, then comoments of two variablesfreq (array of
int
) – Array of shape(nrep, size)
where nrep is the number of replicates andsize = self.shape[axis]
. freq is the weight that each sample contributes to resamples values. Seerandsamp_freq()
weight (array-like, optional) – Optional weights. Can be scalar, 1d array of length
args[0].shape[axis]
or array of same form asargs[0]
.axis (
int
) – Axis to reduce along.full_output (
bool
) – If True, also returnfreq
arrayorder (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
out (
CentralMoments
) – Instance of calling class
See also
cmomy.resample.resample_vals
,cmomy.resample.randsamp_freq
,cmomy.resample.freq_to_indices
,cmomy.resample.indices_to_freq
Examples
>>> from cmomy.random import default_rng >>> from cmomy.resample import random_freq >>> rng = default_rng(0) >>> ndat, nrep = 10, 3 >>> x = rng.random(ndat) >>> freq = random_freq(nrep=nrep, ndat=ndat) >>> da = CentralMoments.from_resample_vals(x, freq=freq, axis=0, mom=2) >>> da <CentralMoments(val_shape=(3,), mom=(2,))> array([[10. , 0.5397, 0.0757], [10. , 0.5848, 0.0618], [10. , 0.5768, 0.0564]])
Note that this is equivalent to (though in general faster than)
>>> from cmomy.resample import freq_to_indices >>> indices = freq_to_indices(freq) >>> x_resamp = np.take(x, indices, axis=0) >>> da = CentralMoments.from_vals(x_resamp, axis=1, mom=2) >>> da <CentralMoments(val_shape=(3,), mom=(2,))> array([[10. , 0.5397, 0.0757], [10. , 0.5848, 0.0618], [10. , 0.5768, 0.0564]])
- classmethod from_raw(raw, *, mom_ndim)[source]#
Create object from raw moment data.
raw[…, i, j] = <x**i y**j>. raw[…, 0, 0] = weight
- Parameters:
raw (
numpy.ndarray
) – Raw moment array.mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
).
- Returns:
output (
CentralMoments
)
See also
Notes
Weights are taken from
raw[...,0, 0]
. Using raw moments can result in numerical issues, especially for higher moments. Use with care.Examples
>>> from cmomy.random import default_rng >>> rng = default_rng(0) >>> x = rng.random(10) >>> raw_x = (x[:, None] ** np.arange(5)).mean(axis=0)
>>> dx_raw = CentralMoments.from_raw(raw_x, mom_ndim=1) >>> print(dx_raw.mean()) 0.5505105129032412 >>> dx_raw.cmom() array([ 1. , 0. , 0.1014, -0.0178, 0.02 ])
Which is equivalent to creating raw moments from values >>> dx_cen = CentralMoments.from_vals(x, axis=0, mom=4) >>> print(dx_cen.mean()) 0.5505105129032413 >>> dx_cen.cmom() array([ 1. , 0. , 0.1014, -0.0178, 0.02 ])
But note that calculating using from_raw can lead to numerical issues. For example
>>> y = x + 10000 >>> raw_y = (y[:, None] ** np.arange(5)).mean(axis=0) >>> dy_raw = CentralMoments.from_raw(raw_y, mom_ndim=1) >>> print(dy_raw.mean() - 10000) 0.5505105129050207
Note that the central moments don’t match!
>>> np.isclose(dy_raw.cmom(), dx_raw.cmom()) array([ True, True, True, False, False])
>>> dy_cen = CentralMoments.from_vals(y, axis=0, mom=4) >>> print(dy_cen.mean() - 10000) 0.5505105129032017 >>> dy_cen.cmom() # this matches above array([ 1. , 0. , 0.1014, -0.0178, 0.02 ])