Base Classes#
- class cmomy._central_abc.CentralMomentsABC(data, *, mom_ndim=1, copy=None, order=None, dtype=None, fastpath=False)[source]#
Bases:
ABC
,Generic
[FloatT
,ArrayT
]Wrapper to calculate central moments.
- Parameters:
data (
numpy.ndarray
orxarray.DataArray
) – 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}\]Attributes:
Access underlying central moments array.
Accessor to numpy array underlying data.
self.data.shape.
self.data.ndim.
self.data.dtype.
Length of moments.
Shape of moments part.
Number of moments.
Shape of values dimensions.
Number of value dimensions.
Methods:
set_values
(values)Set values.
Access underlying values
to_numpy
()Access to numpy array underlying class.
new_like
([data, copy, order, verify, dtype])Create new object like self, with new data.
astype
(dtype, *[, order, casting, subok, copy])Underlying data cast to specified type
Create new empty object like self.
copy
()Create a new object with copy of data.
moments_to_comoments
(*, mom)Convert moments (mom_ndim=1) to comoments (mom_ndim=2).
assign_weight
(weight[, copy])Create object with updated weights
weight
()Weight data.
mean
()Mean (first moment).
var
()Variance (second central moment).
std
()Standard deviation.
cmom
()Central moments.
to_raw
(*[, weight])Raw moments accumulation array.
rmom
()Raw moments.
fill
([value])Fill data with value.
zero
()Zero out underlying data.
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()
resample_and_reduce
(*, freq[, axis, ...])Bootstrap resample and reduce.
reduce
(*[, axis, by, order, parallel])Create new object reduce along axis.
pipe
(func_or_method, *args[, _reorder, ...])Apply func_or_method to underlying data and wrap results in class:cmomy.xCentralMoments object.
zeros
(*, mom[, val_shape, dtype, order])Create a new base object.
from_vals
(x, *y, mom[, axis, weight, order, ...])Create from observations/values.
from_resample_vals
(x, *y, mom, freq[, axis, ...])Create from resample observations/values.
from_raw
(raw, *, mom_ndim)Create object from raw moment data.
- property values#
Access underlying central moments array.
- 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 shape#
self.data.shape.
- property ndim#
self.data.ndim.
- property dtype#
self.data.dtype.
- 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.
- property mom#
Number of moments.
- property val_shape#
Shape of values dimensions.
That is shape less moments dimensions.
- property val_ndim#
Number of value dimensions.
- abstract 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
orxarray.DataArray
) – 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:
object
– New object object with zerod out data.
- 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
- 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
- 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
- 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
- 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\]
- 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
- 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
- zero()[source]#
Zero out underlying data.
- Returns:
self (
object
) – Same type as calling class. Same object with data filled with zeros.
See also
- abstract 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 (
object
) – Same object with pushed data.
- abstract push_datas(datas, *, axis=-1, order=None, parallel=None)[source]#
Push and reduce multiple average central moments.
- Parameters:
datas (array-like,
numpy.ndarray
orxarray.DataArray
) – 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 (
object
) – Same object with pushed data.
- abstract 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 (
object
) – Same object with pushed data.
Notes
Array x0 should have same shape as self.val_shape.
- abstract 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
).weight (
int
,float
, array-like, optional) – Weight of each sample. If scalar, broadcast to x0.shapeaxis (
int
) – Axis to reduce along.order (
{"C", "F", "A", "K"}
, optional) – Order argument tonumpy.asarray()
.
- Returns:
output (
object
) – Same object with pushed data.
- randsamp_freq(*, axis=-1, nrep=None, nsamp=None, indices=None, freq=None, check=False, rng=None)[source]#
Interface to
resample.randsamp_freq()
- abstract 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
- abstract 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 (
object
) – 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
- 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
.
- abstract 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 (
object
) – New instance with zero values.
See also
- abstract 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 (
object
)
See also
- abstract 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 (
object
) – Instance of calling class
- 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
orxarray.DataArray
) – Raw moment array.mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
).
- Returns:
output (
object
)
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.