Interface to utility functions (cmomy.utils
)#
Functions:
|
Get new integer order for transpose corresponding to moveaxis parameters. |
|
Generalized moveaxis for moments arrays. |
|
Get indexer for moments |
|
Select specific moments for a central moments array. |
|
Update weights of moments array. |
|
Convert values to central moments array. |
- cmomy.utils.moveaxis_order(x, axis=MISSING, dest=MISSING, *, dim=MISSING, dest_dim=MISSING, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, axes_to_end=False, allow_select_mom_axes=False)[source]#
Get new integer order for transpose corresponding to moveaxis parameters.
- cmomy.utils.moveaxis(x, axis=MISSING, dest=MISSING, *, dim=MISSING, dest_dim=MISSING, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, axes_to_end=False, allow_select_mom_axes=False)[source]#
Generalized moveaxis for moments arrays.
- Parameters:
axis (
complex
or sequence ofcomplex
) – Original positions of axes to move. Complex values wrapped relative tomom_ndim
.dest (
complex
or sequence ofcomplex
) – Destination positions for each original axes.dim (
str
or sequence of hashable) – Original dimensions to move (for DataArray).dest_dim (
str
or sequence of hashable) – Destination of each original dimension.mom_ndim (
{1, 2}
, optional) – Ifmom_ndim
is notNone
, then wrap axis relative tomom_ndim
. For Example, with mom_ndim=``2``,axis = -1
will be transformed toaxis = -3
. Ifmom_dims
is passed and data is anxarray
object, infermom_n=ndim
frommom_dims
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.axes_to_end (
bool
) – IfTrue
, place sampled dimension (if exists in output) and moment dimensions at end of output. Otherwise, place sampled dimension (if exists in output) at same position as inputaxis
and moment dimensions at same position as input (if input does not contain moment dimensions, place them at end of array).allow_select_mom_axes (
bool
, defaultFalse
) – If True, allow moving moment axes. Otherwise, raiseValueError
if try to movemom_axes
.
- Returns:
out (
ndarray
orDataArray
) – Same type asx
with moved axis.
Notes
Must specify either
axis
ordim
and eitherdest
ordest_dim
.See also
Examples
>>> x = np.zeros((2, 3, 4, 5)) >>> moveaxis(x, 0, -1).shape (3, 4, 5, 2)
Specifying
mom_ndim
will result in negative complex axis relative to the moments dimensions.>>> moveaxis(x, 0, -1j, mom_ndim=1).shape (3, 4, 2, 5)
Note that if
mom_ndim
is not specified, then complex axis are equivalent to integer axis.>>> moveaxis(x, 0, -1j).shape (3, 4, 5, 2)
Multiple axes can also be specified.
>>> moveaxis(x, (1, 0), (-2j, -1j), mom_ndim=1).shape (4, 3, 2, 5)
This also works with dataarrays
>>> dx = xr.DataArray(x, dims=["a", "b", "c", "mom_0"]) >>> moveaxis(dx, dim="a", dest=-1j, mom_ndim=1).dims ('b', 'c', 'a', 'mom_0')
All the routines in
cmomy
accept moment dimensions in arbitrary locations. However, it is often easiest to work with these dimensions as the last dimensions in an array. You can easily achieve this withmoveaxis
with the parameteraxes_to_end=True
. For example:>>> moveaxis(x, mom_axes=(0, 1), axes_to_end=True).shape (4, 5, 2, 3)
>>> moveaxis(x, axis=-1, mom_axes=(1, 2), axes_to_end=True).shape (2, 5, 3, 4)
>>> moveaxis(x, axis=-2j, mom_ndim=2, axes_to_end=True).shape (3, 2, 4, 5)
- cmomy.utils.moment_indexer(name, mom_ndim, squeeze=True)[source]#
Get indexer for moments
- Parameters:
moment (
{"weight", "ave", "var", "cov", "xave", "xvar", "yave", "yvar", "xmom_0", "xmom_1", "ymom_0", "ymom_1"}
) –Name of moment(s) to select.
"weight"
: weights"ave"
: Averages."var"
: Variance."cov"
: Covariance ifmom_ndim == 2
, or variace ifmom_ndim == 1
."xave"
: Average of first variable."xvar"
: Variance of first variable."yave"
: Average of second variable (ifmom_ndim == 2
)."yvar"
: Variace of second variable (ifmom_ndim == 2
)."all"
: All values.
Names
"weight", "xave", "yave", "xvar", "yvar", "cov"
imply shapedata.shape[:-mom_ndim]
. Names"ave", "var"
imply shape(*data.shape[:-mom_ndim], mom_ndim)
, unlessmom_ndim == 1
andsqueeze = True
.mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
). Defaults tomom_ndim=1
.squeeze (
bool
, defaultFalse
) – If True, squeeze last dimension ifname
is one ofave
orvar
andmom_ndim == 1
.
- Returns:
indexer (
tuple
)
- cmomy.utils.select_moment(data, name, *, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, squeeze=True, dim_combined='variable', coords_combined=None, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Select specific moments for a central moments array.
- Parameters:
mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
). Defaults tomom_ndim=1
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.moment (
{"weight", "ave", "var", "cov", "xave", "xvar", "yave", "yvar", "xmom_0", "xmom_1", "ymom_0", "ymom_1"}
) –Name of moment(s) to select.
"weight"
: weights"ave"
: Averages."var"
: Variance."cov"
: Covariance ifmom_ndim == 2
, or variace ifmom_ndim == 1
."xave"
: Average of first variable."xvar"
: Variance of first variable."yave"
: Average of second variable (ifmom_ndim == 2
)."yvar"
: Variace of second variable (ifmom_ndim == 2
)."all"
: All values.
Names
"weight", "xave", "yave", "xvar", "yvar", "cov"
imply shapedata.shape[:-mom_ndim]
. Names"ave", "var"
imply shape(*data.shape[:-mom_ndim], mom_ndim)
, unlessmom_ndim == 1
andsqueeze = True
.squeeze (
bool
, defaultFalse
) – If True, squeeze last dimension ifname
is one ofave
orvar
andmom_ndim == 1
.dim_combined (
str
, optional) – Name of dimension for options that produce multiple values (e.g.,name="ave"
).coords_combined (
str
or sequence ofstr
, optional) – Coordates to assign todim_combined
. Defaults to names of moments dimension(s)keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
output (
ndarray
orDataArray
orDataset
) – Same type asdata
. Ifname
isave
orvar
, the last dimensions ofoutput
has shapemom_ndim
with each element corresponding to the ith variable. Ifsqueeze=True
and mom_ndim==1, this last dimension is removed. For all othername
options, output has shape of input with moment dimensions removed. In all cases,mom_dims
ormom_axes
are first moved to the last dimensions.
Examples
>>> data = np.arange(2 * 3).reshape(2, 3) >>> data array([[0, 1, 2], [3, 4, 5]]) >>> select_moment(data, "weight", mom_ndim=1) array([0, 3]) >>> select_moment(data, "ave", mom_ndim=1) array([1, 4])
Note that with
squeeze = False ``, selecting ``ave
andvar
will result in the last dimension having sizemom_ndim
. Ifsqueeze = True
(the default) andmom_ndim==1
, this dimension will be removed>>> select_moment(data, "ave", mom_ndim=1, squeeze=False) array([[1], [4]])
>>> select_moment(data, "xave", mom_ndim=2) array(3) >>> select_moment(data, "cov", mom_ndim=2) array(4)
Use options
"xmom_0"
, to select all values with first moment equal0
, etc>>> select_moment(data, "xmom_0", mom_ndim=2) array([0, 1, 2]) >>> select_moment(data, "ymom_1", mom_ndim=2) array([1, 4])
- cmomy.utils.assign_moment(data, moment=None, *, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, squeeze=True, copy=True, dim_combined=None, keep_attrs=None, apply_ufunc_kwargs=None, **moment_kwargs)[source]#
Update weights of moments array.
- Parameters:
moment (mapping of
str
to array-like) –Mapping from moment name to new value. Allowed moment names are:
"weight"
: weights"ave"
: Averages."var"
: Variance."cov"
: Covariance ifmom_ndim == 2
, or variace ifmom_ndim == 1
."xave"
: Average of first variable."xvar"
: Variance of first variable."yave"
: Average of second variable (ifmom_ndim == 2
)."yvar"
: Variace of second variable (ifmom_ndim == 2
)."xmom_n", "ymom_n"
: All values with first (second) variable moment == n."all"
: All values.
Names
"weight", "xave", "yave", "xvar", "yvar", "cov"
imply shapedata.shape[:-mom_ndim]
. Names"ave", "var"
imply shape(*data.shape[:-mom_ndim], mom_ndim)
, unlessmom_ndim == 1
andsqueeze = True
.mom_ndim (
{1, 2}
) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
). Defaults tomom_ndim=1
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.squeeze (
bool
, defaultFalse
) – If True, squeeze last dimension ifname
is one ofave
orvar
andmom_ndim == 1
.copy (
bool
, defaultTrue
) – IfTrue
(the default), return new array with updated weights. Otherwise, return the original array with weights updated inplace. Note that a copy is always created for adask
backed object.dim_combined (
str
, optional) – Name of dimensions for multiple values. Must supply if passing in multiple values forname="ave"
etc.keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.**moment_kwargs (ArrayLike | xr.DataArray | xr.Dataset) – Keyword argument form of
moment
. Must provide eithermoment
ormoment_kwargs
.
- Returns:
output (
ndarray
orDataArray
) – Same type asdata
with momentname
updated tovalue
.
See also
Examples
>>> data = np.arange(3) >>> data array([0, 1, 2])
>>> assign_moment(data, weight=-1, mom_ndim=1) array([-1, 1, 2])
>>> assign_moment(data, ave=-1, mom_ndim=1) array([ 0, -1, 2])
>>> assign_moment(data, var=-1, mom_ndim=1) array([ 0, 1, -1])
Note that you can chain these together. Note that the order of evaluation is the order values are passed.
>>> assign_moment(data, weight=-1, ave=-2, mom_ndim=1) array([-1, -2, 2])
For multidimensional data, the passed
value
must conform to the selected data>>> data = np.arange(2 * 3).reshape(2, 3)
Selecting
ave
for this data withmom_ndim=1
andsqueeze=False
would have shape(2, 1)
.>>> assign_moment(data, ave=np.ones((2, 1)), mom_ndim=1, squeeze=False) array([[0, 1, 2], [3, 1, 5]])
The
squeeze
parameter has the same meaning as forselect_moment()
>>> assign_moment(data, ave=np.ones(2), mom_ndim=1, squeeze=True) array([[0, 1, 2], [3, 1, 5]])
- cmomy.utils.vals_to_data(x, *y, mom, weight=None, mom_dims=None, mom_params=None, dtype=None, out=None, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Convert values to central moments array.
This allows passing values based observations to data routines. See examples below for more details
- Parameters:
x (array-like or
DataArray
) – First value.*y (array-like or
DataArray
) – Secondary value (if comoments).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 variablesweight (array-like, optional) – Optional weights. Can be scalar, 1d array of length
args[0].shape[axis]
or array of same form asargs[0]
.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. Defaults to("mom_0",)
formom_ndim==1
and(mom_0, mom_1)
formom_ndim==2
mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.out (
ndarray
) – Optional output array. If specified, output will be a reference to this array. Note that if the output if method returns aDataset
, then this option is ignored.keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
Notes
Values
x
,y
andweight
must be broadcastable.Note that if input data is a chunked dask array, then
out
is ignored, and a new array is always created.Also, broadcasting is different here then
reduce_vals()
,resample_vals()
, etc. For these reduction functions, you can, for example, pass a 1-D` array fory
with N-Dx
regardless if the axis is not the last axis. This is because those reduction functions have aaxis
parameter that can be used to infer the intended shape ofy
(andweight
). In this function, you have to specifyy
andweight
such that they broadcast tox
.Examples
>>> w = np.full((2), 0.1) >>> x = np.full((1, 2), 0.2) >>> out = vals_to_data(x, weight=w, mom=2) >>> out.shape (1, 2, 3) >>> print(out[..., 0]) [[0.1 0.1]] >>> print(out[..., 1]) [[0.2 0.2]] >>> y = np.full((2, 1, 2), 0.3) >>> out = vals_to_data(x, y, weight=w, mom=(2, 2)) >>> out.shape (2, 1, 2, 3, 3) >>> print(out[..., 0, 0]) [[[0.1 0.1]] [[0.1 0.1]]] >>> print(out[..., 1, 0]) [[[0.2 0.2]] [[0.2 0.2]]] >>> print(out[..., 0, 1]) [[[0.3 0.3]] [[0.3 0.3]]]