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 (
complexor sequence ofcomplex) – Original positions of axes to move. Complex values wrapped relative tomom_ndim.dest (
complexor sequence ofcomplex) – Destination positions for each original axes.dim (
stror sequence of hashable) – Original dimensions to move (for DataArray).dest_dim (
stror sequence of hashable) – Destination of each original dimension.mom_ndim (
{1, 2}, optional) – Ifmom_ndimis notNone, then wrap axis relative tomom_ndim. For Example, with mom_ndim=``2``,axis = -1will be transformed toaxis = -3. Ifmom_dimsis passed and data is anxarrayobject, infermom_n=ndimfrommom_dims.mom_axes (
intortupleofint, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...). If specified andmom_ndimis None, setmom_ndimtolen(mom_axes). Note that ifmom_axesis specified, negative values are relative to the end of the array. This is also the case foraxesifmom_axesis specified.mom_dims (hashable or
tupleof hashable) – Name of moment dimensions. If specified, infermom_ndimfrommom_dims. If also passmom_ndim, check thatmom_dimsis consistent withmom_dims. If not specified, defaults todata.dims[-mom_ndim:]. This is primarily used ifdatais aDataset, or ifmom_dimsare not the last dimensions.mom_params (
MomParamsorMomParamsDictordict, optional) – Moment parameters. You can set moment parametersaxesanddimsusing this option. For example, passingmom_params={"dim": ("a", "b")}is equivalent to passingmom_dims=("a", "b"). You can also pass as aMomParamsobject 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 inputaxisand 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, raiseValueErrorif try to movemom_axes.
- Returns:
out (
ndarrayorDataArray) – Same type asxwith moved axis.
Notes
Must specify either
axisordimand eitherdestordest_dim.See also
Examples
>>> x = np.zeros((2, 3, 4, 5)) >>> moveaxis(x, 0, -1).shape (3, 4, 5, 2)
Specifying
mom_ndimwill 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_ndimis 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
cmomyaccept 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 withmoveaxiswith 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 variance ifmom_ndim == 1."xave": Average of first variable."xvar": Variance of first variable."yave": Average of second variable (ifmom_ndim == 2)."yvar": Variance 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 == 1andsqueeze = 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 ifnameis one ofaveorvarandmom_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 (
intortupleofint, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...). If specified andmom_ndimis None, setmom_ndimtolen(mom_axes). Note that ifmom_axesis specified, negative values are relative to the end of the array. This is also the case foraxesifmom_axesis specified.mom_dims (hashable or
tupleof hashable) – Name of moment dimensions. If specified, infermom_ndimfrommom_dims. If also passmom_ndim, check thatmom_dimsis consistent withmom_dims. If not specified, defaults todata.dims[-mom_ndim:]. This is primarily used ifdatais aDataset, or ifmom_dimsare not the last dimensions.mom_params (
MomParamsorMomParamsDictordict, optional) – Moment parameters. You can set moment parametersaxesanddimsusing this option. For example, passingmom_params={"dim": ("a", "b")}is equivalent to passingmom_dims=("a", "b"). You can also pass as aMomParamsobject 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 variance ifmom_ndim == 1."xave": Average of first variable."xvar": Variance of first variable."yave": Average of second variable (ifmom_ndim == 2)."yvar": Variance 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 == 1andsqueeze = True.squeeze (
bool, defaultFalse) – If True, squeeze last dimension ifnameis one ofaveorvarandmom_ndim == 1.dim_combined (
str, optional) – Name of dimension for options that produce multiple values (e.g.,name="ave").coords_combined (
stror sequence ofstr, optional) – Coordinates 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 aDatasetmissing core dimensions. Other options arejoin,dataset_join,dataset_fill_value, anddask_gufunc_kwargs. Unlisted options are handled internally.
- Returns:
output (
ndarrayorDataArrayorDataset) – Same type asdata. Ifnameisaveorvar, the last dimensions ofoutputhas shapemom_ndimwith each element corresponding to the ith variable. Ifsqueeze=Trueand mom_ndim==1, this last dimension is removed. For all othernameoptions, output has shape of input with moment dimensions removed. In all cases,mom_dimsormom_axesare 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 ``aveandvarwill 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
strto 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 variance ifmom_ndim == 1."xave": Average of first variable."xvar": Variance of first variable."yave": Average of second variable (ifmom_ndim == 2)."yvar": Variance 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 == 1andsqueeze = True.mom_ndim (
{1, 2}) – Value indicates if moments (mom_ndim = 1) or comoments (mom_ndim=2). Defaults tomom_ndim=1.mom_axes (
intortupleofint, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...). If specified andmom_ndimis None, setmom_ndimtolen(mom_axes). Note that ifmom_axesis specified, negative values are relative to the end of the array. This is also the case foraxesifmom_axesis specified.mom_dims (hashable or
tupleof hashable) – Name of moment dimensions. If specified, infermom_ndimfrommom_dims. If also passmom_ndim, check thatmom_dimsis consistent withmom_dims. If not specified, defaults todata.dims[-mom_ndim:]. This is primarily used ifdatais aDataset, or ifmom_dimsare not the last dimensions.mom_params (
MomParamsorMomParamsDictordict, optional) – Moment parameters. You can set moment parametersaxesanddimsusing this option. For example, passingmom_params={"dim": ("a", "b")}is equivalent to passingmom_dims=("a", "b"). You can also pass as aMomParamsobject withmom_params=cmomy.MomParams(dims=("a", "b")).squeeze (
bool, defaultFalse) – If True, squeeze last dimension ifnameis one ofaveorvarandmom_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 adaskbacked 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 aDatasetmissing core dimensions. Other options arejoin,dataset_join,dataset_fill_value, anddask_gufunc_kwargs. Unlisted options are handled internally.**moment_kwargs (
Union[Buffer,_SupportsArray[dtype[Any]],_NestedSequence[_SupportsArray[dtype[Any]]],complex,bytes,str,_NestedSequence[complex|bytes|str],DataArray,Dataset]) – Keyword argument form ofmoment. Must provide eithermomentormoment_kwargs.
- Returns:
output (
ndarrayorDataArray) – Same type asdatawith momentnameupdated 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
valuemust conform to the selected data>>> data = np.arange(2 * 3).reshape(2, 3)
Selecting
avefor this data withmom_ndim=1andsqueeze=Falsewould 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
squeezeparameter 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 (
intortupleofint) – 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
tupleof hashable) – Name of moment dimensions. Defaults to("mom_0",)formom_ndim==1and(mom_0, mom_1)formom_ndim==2mom_params (
MomParamsorMomParamsDictordict, optional) – Moment parameters. You can set moment parametersaxesanddimsusing this option. For example, passingmom_params={"dim": ("a", "b")}is equivalent to passingmom_dims=("a", "b"). You can also pass as aMomParamsobject 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 aDatasetmissing core dimensions. Other options arejoin,dataset_join,dataset_fill_value, anddask_gufunc_kwargs. Unlisted options are handled internally.
- Returns:
Notes
Values
x,yandweightmust be broadcastable.Note that if input data is a chunked dask array, then
outis 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 forywith N-Dxregardless if the axis is not the last axis. This is because those reduction functions have aaxisparameter that can be used to infer the intended shape ofy(andweight). In this function, you have to specifyyandweightsuch 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]]]