8.7.6. pymodaq_data.data module
Created the 28/10/2022
@author: Sebastien Weber
- exception pymodaq_data.data.DataDimError[source]
Bases:
ExceptionRaised when the dimension of data is not the expected one
- exception pymodaq_data.data.DataDimWarning[source]
Bases:
WarningWarning about an unexpected dimension of data
- exception pymodaq_data.data.DataIndexWarning[source]
Bases:
WarningWarning about an invalid index in a data object
- exception pymodaq_data.data.DataLengthError[source]
Bases:
ExceptionRaised when the lengths of data arrays or lists are not compatible
- exception pymodaq_data.data.DataShapeError[source]
Bases:
ExceptionRaised when the shapes of data arrays are not compatible
- exception pymodaq_data.data.DataSizeWarning[source]
Bases:
WarningWarning about an unexpected size of data
- exception pymodaq_data.data.DataTypeWarning[source]
Bases:
WarningWarning about an unexpected type of data
- exception pymodaq_data.data.DataUnitError[source]
Bases:
ExceptionRaised when units are not compatible
- pymodaq_data.data.warning
alias of
DataSizeWarning
- class pymodaq_data.data.Averaging(*values)[source]
Bases:
StrEnumKeywords to describe averaging in Data objects
- AVERAGED = 'averaged'
- N_AVERAGED = 'n_averaged'
- class pymodaq_data.data.AxesManagerBase(data_shape, axes, nav_indexes=None, sig_indexes=None, **kwargs)[source]
Bases:
object- Attributes:
- axes
- nav_axes
- nav_indexes
- nav_shape
- shape
- sig_indexes
- sig_shape
Methods
append_axis(axis)Append an axis to the axes and check that the resulting axes are valid
Get the index list from the axis objects
get_axis_from_index_spread(index, spread_order)Only valid for Spread data
Get the navigation axes corresponding to the data
get_shape_from_index(index)Get the data shape at the given index
Get the signal axes (axes whose index is not a navigation one) of size larger than 1
get_sorted_index([axis_index, spread_index])Get the index to sort the specified axis
is_axis_navigation(axis)Check if an axis is a navigation one (its index is a navigation index)
is_axis_signal(axis)Check if an axis is a signal one (its index is not a navigation index)
compute_shape_from_axes
compute_sig_indexes
get_axis_from_index
- get_axis_from_index_spread(index, spread_order)[source]
Only valid for Spread data
In spread mode, different nav axes have the same index (but not the same spread_order integer value)
Get the navigation axes corresponding to the data
Use get_axis_from_index for all index in self.nav_indexes, but in spread distribution, one index may correspond to multiple nav axes, see Spread data distribution
- abstractmethod get_shape_from_index(index)[source]
Get the data shape at the given index
- Return type:
- get_signal_axes()[source]
Get the signal axes (axes whose index is not a navigation one) of size larger than 1
- abstractmethod get_sorted_index(axis_index=0, spread_index=0)[source]
Get the index to sort the specified axis
- Parameters:
- Return type:
- Returns:
np.ndarray (
the sorted index from the specified axis)tupleofindexes (arraysandEllipsis)– used to slice the underlying dataBoth are None if the axis is absent
Check if an axis is a navigation one (its index is a navigation index)
- Return type:
- is_axis_signal(axis)[source]
Check if an axis is a signal one (its index is not a navigation index)
- Return type:
- class pymodaq_data.data.AxesManagerSpread(*args, **kwargs)[source]
Bases:
AxesManagerBaseFor this particular data category, some explanation is needed, see example below:
Examples
One take images data (20x30) as a function of 2 parameters, say xaxis and yaxis non-linearly spaced on a regular grid.
data.shape = (150, 20, 30) data.nav_indexes = (0,)
The first dimension (150) corresponds to the navigation (there are 150 non uniform data points taken) The second and third could correspond to signal data, here an image of size (20x30) so: * nav_indexes is (0, ) * sig_indexes are (1, 2)
xaxis = Axis(name=xaxis, index=0, data…) length 150 yaxis = Axis(name=yaxis, index=0, data…) length 150
In fact from such a data shape the number of navigation axes in unknown . In our example, they are 2. To somehow keep track of some ordering in these navigation axes, one adds an attribute to the Axis object: the spread_order xaxis = Axis(name=xaxis, index=0, spread_order=0, data…) length 150 yaxis = Axis(name=yaxis, index=0, spread_order=1, data…) length 150
Methods
Get data shape from axes
get_axis_from_index(index[, create])in spread mode, different nav axes have the same index (but not the same spread_order integer value) so may return multiple axis
get_axis_from_index_spread(index, spread_order)in spread mode, different nav axes have the same index (but not the same spread_order integer value)
get_shape_from_index(index)Get the data shape at the given index
get_sorted_index([axis_index, spread_index])Get the index to sort the specified axis
- compute_shape_from_axes()[source]
Get data shape from axes
First get the nav length from one of the navigation axes Then check for signal axes
- get_axis_from_index(index, create=False)[source]
in spread mode, different nav axes have the same index (but not the same spread_order integer value) so may return multiple axis
No possible “linear” creation in this mode except if the index is a signal index
- get_axis_from_index_spread(index, spread_order)[source]
in spread mode, different nav axes have the same index (but not the same spread_order integer value)
- class pymodaq_data.data.AxesManagerUniform(*args, **kwargs)[source]
Bases:
AxesManagerBaseMethods
get_axis_from_index(index[, create])Get the axis referred by a given data dimensionality index
get_axis_from_index_spread(index, spread_order)in spread mode, different nav axes have the same index (but not the same spread_order integer value)
get_shape_from_index(index)Get the data shape at the given index
get_sorted_index([axis_index, spread_index])Get the index to sort the specified axis
compute_shape_from_axes
- get_axis_from_index(index, create=False)[source]
Get the axis referred by a given data dimensionality index
If the axis is absent, create a linear one to fit the data shape if parameter create is True
- Parameters:
- Returns:
List[Axis] or None
- Return type:
See also
- get_axis_from_index_spread(index, spread_order)[source]
in spread mode, different nav axes have the same index (but not the same spread_order integer value)
- class pymodaq_data.data.Axis(*args, **kwargs)[source]
Bases:
SerializableBaseObject holding info and data about physical axis of some data
In case the axis’s data is linear, store the info as a scale and offset else store the data
- Parameters:
label (
str) – The label of the axis, for instance ‘time’ for a temporal axisunits (
str) – The units of the data in the object, for instance ‘s’ for secondsdata (
ndarray) – A 1D ndarray holding the data of the axisindex (
int) – an integer representing the index of the Data object this axis is related toscaling (
float) – The scaling to apply to a linspace version in order to obtain the proper scalingoffset (
float) – The offset to apply to a linspace/scaled version in order to obtain the proper axissize (
int) – The size of the axis array (to be specified if data is None)spread_order (
int) – An integer needed in the case where data has a spread DataDistribution. It refers to the index along the data’s spread_index dimension
Examples
>>> axis = Axis('myaxis', units='seconds', data=np.array([1,2,3,4,5]), index=0)
- Attributes:
axis_widthget the width of the axis in axis unit
datanp.ndarray: get/set the data of Axis (None if the axis is linear, see
get_data())indexint: get/set the index this axis corresponds to in a DataWithAxis object
labelstr: get/set the label of this axis
- offset
- scaling
sizeint: get/set the size/length of the 1D ndarray
unitsstr: get/set the units for this axis without conversion (equivalent to
Methods
as_dwa([set_itself_as_axis])Convert this axis to a DataRaw whose data are the axis values
copy()Return a shallow copy of this axis
create_linear_data(nsteps)replace the axis data with a linear version using scaling and offset
create_simple_linear_data(nsteps)Return the array [0, 1, ..., nsteps-1]
deserialize(bytes_str)Convert bytes into an Axis object
find_index(threshold)find the index of the threshold value within the axis
find_indexes(thresholds)Find the indexes of several values within the axis, see
find_index()flip()flip the direction of the axis
force_units(units)Change immediately the units to whatever else.
from_quantity(quantity[, label, index])Create an Axis whose data and units are those of a pint Quantity
get_data()Convenience method to obtain the axis data (usually None because scaling and offset are used)
get_data_at(indexes)Get data at specified indexes
Convenience method to obtain the numerical data as a quantity array
get_scale_offset_from_data([data])Get the scaling and offset from the axis's data
is_axis_linear([data])Check if the axis values are linearly spaced
max()Maximum value of the axis
mean()Mean value of the axis (for linear axes, the value at the middle of the axis)
min()Minimum value of the axis
serialize(axis)Convert an Axis object into a bytes message together with the info to convert it back
to_base_units([inplace])Convert the axis to pint base units
to_reduced_units([inplace])Convert the axis to reduced units (see
dimensionless_aware_reduce_units())units_as(units[, inplace, context])Convert the axis to other units, optionally using a pint context
- static deserialize(bytes_str)[source]
Convert bytes into an Axis object
Convert the first bytes into an Axis reading first information about the Axis
- static from_quantity(quantity, label='axis', index=0)[source]
Create an Axis whose data and units are those of a pint Quantity
- Return type:
- static serialize(axis)[source]
Convert an Axis object into a bytes message together with the info to convert it back
- Parameters:
axis (
Axis)- Returns:
bytes
- Return type:
the total bytes messagetoserialize the Axis
Notes
The bytes sequence is constructed as:
serialize the axis label
serialize the axis units
serialize the axis array
serialize the axis
serialize the axis spread_order
- as_dwa(set_itself_as_axis=False)[source]
Convert this axis to a DataRaw whose data are the axis values
If set_itself_as_axis is False, the axes of the returned object are created with default values.
- Return type:
- create_linear_data(nsteps)[source]
replace the axis data with a linear version using scaling and offset
- find_indexes(thresholds)[source]
Find the indexes of several values within the axis, see
find_index()
- get_data()[source]
Convenience method to obtain the axis data (usually None because scaling and offset are used)
- Return type:
- get_quantity()[source]
Convenience method to obtain the numerical data as a quantity array
- Return type:
Quantity
- get_scale_offset_from_data(data=None)[source]
Get the scaling and offset from the axis’s data
If data is not None, extract the scaling and offset
- is_axis_linear(data=None)[source]
Check if the axis values are linearly spaced
Uses data if given, else the axis data. Returns False if there is no data.
- to_base_units(inplace=False)[source]
Convert the axis to pint base units
If inplace is True the axis is modified and None is returned, else a new Axis is returned.
- to_reduced_units(inplace=False)[source]
Convert the axis to reduced units (see
dimensionless_aware_reduce_units())If inplace is True the axis is modified and None is returned, else a new Axis is returned.
- units_as(units, inplace=True, context=None, **context_kwargs)[source]
Convert the axis to other units, optionally using a pint context
If inplace is True the axis is modified and None is returned, else a new Axis is returned.
- property axis_width: Quantity
get the width of the axis in axis unit
That is the difference between the max value and the min value of the axis
- base_type = 'Axis'
- property data: ndarray | None
get/set the data of Axis (None if the axis is linear, see
get_data())- Type:
np.ndarray
- iaxis: SpecialSlicersData
- property units: str
get/set the units for this axis without conversion (equivalent to force_units)
- Type:
- vaxis: SpecialSlicersData
- class pymodaq_data.data.DataBase(*args, **kwargs)[source]
Bases:
DataLowLevel,NDArrayOperatorsMixinBase object to store homogeneous data and metadata generated by pymodaq’s objects.
To be inherited for real data
- Parameters:
name (
str) – the identifier of these datasource (
DataSourceorstr) – Enum specifying if data are raw or processed (for instance from roi)distribution (
DataDistributionorstr) – The distribution type of the data: uniform if distributed on a regular grid or spread if on specific unordered pointsdata (
listofndarrayorQuantities) – The data the object is storing. In case of Quantities, the object units attribute will be forced to the unit of this quantity, ignoring the units argument.origin (
str) – An identifier of the element where the data originated, for instance the DAQ_Viewer’s name. Used when appending DataToExport in DAQ_Scan to disintricate from which origin data comes from when scanning multiple detectors.units (
str) – A unit string identifier as specified in the UnitRegistry of the pint modulekwargs (
named parameters) – All other parameters are stored dynamically using the name/value pair. The name of these extra parameters are added into the extra_attributes attribute
- Variables:
name (
str) – the identifier of these datasource (
DataSourceorstr) – Enum specifying if data are raw or processed (for instance from roi)distribution (
DataDistributionorstr) – The distribution type of the data: uniform if distributed on a regular grid or spread if on specific unordered pointsdata (
listofndarray) – The data the object is storingorigin (
str) – An identifier of the element where the data originated, for instance the DAQ_Viewer’s name. Used when appending DataToExport in DAQ_Scan to disintricate from which origin data comes from when scanning multiple detectors.shape (
Tuple[int,]) – The shape of the underlying datasize (
int) – The size of the ndarrays stored in the objectlength (
int) – The number of ndarrays stored in the objectextra_attributes (
List[str]) – list of string giving identifiers of the attributes added dynamically at the initialization (for instance to save extra metadata using the DataSaverLoader
See also
DataWithAxes,DataFromPlugins,DataRaw,DataSaverLoaderExamples
>>> import numpy as np >>> from pymodaq.utils.data import DataBase, DataSource, DataDim, DataDistribution >>> data = DataBase('mydata', source=DataSource['raw'], dim=DataDim['Data1D'], distribution=DataDistribution.uniform, data=[np.array([1.,2.,3.]), np.array([4.,5.,6.])], labels=['channel1', 'channel2'], origin='docutils code') >>> data.dim <DataDim.Data1D: 1> >>> data.source <DataSource.raw: 0> >>> data.shape (3,) >>> data.length 2 >>> data.size 3
- Attributes:
averagedGet/Set a boolean depending if self is the result of an average operation
dataList[np.ndarray]: get/set (and check) the data the object is storing
dimDataDim: the enum representing the dimensionality of the stored data
distributionDataDistribution: the enum representing the distribution of the stored data
- labels
lengthThe length of data.
n_averagedGet/set the number of averaging that resulted in this data
quantitiesGet the arrays as pint quantities (with units)
shapeThe shape of the nd-arrays
sizeThe size of the nd-arrays
sourceDataSource: the enum representing the source of the data
- units
Methods
abs()Take the absolute value of itself
angle()Take the phase value of itself
append(data)Append data content if the underlying arrays have the same shape and compatible units
as_dte([name])Convenience method to wrap the DataWithAxes object into a DataToExport
average(other, weight)Compute the weighted average between self and other DataBase
check_shape_from_data(data)Set the shape of the object from the first array of data
deepcopy()Return a deep copy of this object
equal_to(other, epsilon)Check if two data object are equal within epsilon
fliplr()Reverse the order of elements along axis 1 (left/right)
flipud()Reverse the order of elements along axis 0 (up/down)
force_units(units)Change immediately the units to whatever else.
get_data_index([index])Get the data by its index in the list, same as self[index]
get_dim_from_data(data)Get the dimensionality DataDim from data
Get the data ful name including the origin attribute into the returned value
get_origin_name_from_full_name(full_name)Standardize the obtention of the origin and name from the full name expression
imag()Take the imaginary part of itself
pop(index)Returns a copy of self but with data taken at the specified index
real()Take the real part of itself
set_dim(dim)Addhoc modification of dim independantly of the real data shape, should be used with extra care
split_as_dte([name])Convenience method to split each ndarray into a DataWithAxes object
stack_as_array([axis, dtype])Stack all data arrays in a single numpy array
to_dB()Get a new data object in decibels
to_dict()Get the data arrays into dictionary whose keys are the labels
units_as(units[, inplace, context])Set the object units to the new one (if possible)
unwrap()unwrap the underlying array (should be angles otherwise meaningless)
value([units])Returns the underlying float value (of the first elt in the data list) if this data holds only a float otherwise returns a mean of the underlying data
values([units])Returns the underlying float value (for each data array in the data list) if this data holds only a float otherwise returns a mean of the underlying data
add_extra_attribute
to_base_units
- static get_origin_name_from_full_name(full_name)[source]
Standardize the obtention of the origin and name from the full name expression
Origin is always the first bit before the first ‘/’ character while the name will be the remaining characters
- append(data)[source]
Append data content if the underlying arrays have the same shape and compatible units
- as_dte(name='mydte')[source]
Convenience method to wrap the DataWithAxes object into a DataToExport
- Return type:
- get_data_index(index=0)[source]
Get the data by its index in the list, same as self[index]
- Return type:
- get_full_name()[source]
Get the data ful name including the origin attribute into the returned value
- Returns:
str
- Return type:
Examples
d0 = DataBase(name=’datafromdet0’, origin=’det0’)
- set_dim(dim)[source]
Addhoc modification of dim independantly of the real data shape, should be used with extra care
- split_as_dte(name='mydte')[source]
Convenience method to split each ndarray into a DataWithAxes object
- Return type:
- stack_as_array(axis=0, dtype=None)[source]
Stack all data arrays in a single numpy array
- Parameters:
- Return type:
See also
np.stack()
- units_as(units, inplace=True, context=None, **context_kwargs)[source]
Set the object units to the new one (if possible)
- value(units=None)[source]
Returns the underlying float value (of the first elt in the data list) if this data holds only a float otherwise returns a mean of the underlying data
- values(units=None)[source]
Returns the underlying float value (for each data array in the data list) if this data holds only a float otherwise returns a mean of the underlying data
- property averaged: bool
Get/Set a boolean depending if self is the result of an average operation
See also
- base_type = 'Data'
- property data: List[ndarray]
get/set (and check) the data the object is storing
- Type:
List[np.ndarray]
- property distribution
the enum representing the distribution of the stored data
- Type:
- property length
The length of data. This is the length of the list containing the nd-arrays
- property shape
The shape of the nd-arrays
- property size
The size of the nd-arrays
- property source
the enum representing the source of the data
- Type:
- Setter accepts:
- class pymodaq_data.data.DataCalculated(name, dim=None, distribution=DataDistribution.uniform, data=None, labels=None, origin='', units='', axes=[], nav_indexes=(), errors=None, **kwargs)[source]
Bases:
DataWithAxesSpecialized DataWithAxes set with source as ‘calculated’. To be used for processed/calculated data
- class pymodaq_data.data.DataDim(*values)[source]
Bases:
BaseEnumEnum for dimensionality representation of data
- static from_data_array(data_array)[source]
Get the DataDim corresponding to the shape of a numpy array
A 1D array of size 1 is Data0D, other 1D arrays are Data1D, 2D arrays are Data2D and any array with more dimensions is DataND.
- Data0D = 0
- Data1D = 1
- Data2D = 2
- DataND = 3
- class pymodaq_data.data.DataDistribution(*values)[source]
Bases:
BaseEnumEnum for distribution of data
- spread = 1
- uniform = 0
- class pymodaq_data.data.DataFromRoi(name, dim=None, distribution=DataDistribution.uniform, data=None, labels=None, origin='', units='', axes=[], nav_indexes=(), errors=None, **kwargs)[source]
Bases:
DataCalculatedSpecialized DataWithAxes set with source as ‘calculated’. To be used for processed data from region of interest
- class pymodaq_data.data.DataLowLevel(name)[source]
Bases:
objectAbstract object for all Data Object
- Parameters:
name (
str) – the identifier of the data- Variables:
- Attributes:
- class pymodaq_data.data.DataRaw(name, dim=None, distribution=DataDistribution.uniform, data=None, labels=None, origin='', units='', axes=[], nav_indexes=(), errors=None, **kwargs)[source]
Bases:
DataWithAxesSpecialized DataWithAxes set with source as ‘raw’. To be used for raw data
- class pymodaq_data.data.DataSource(*values)[source]
Bases:
BaseEnumEnum for source of data
- calculated = 1
- raw = 0
- class pymodaq_data.data.DataToExport(*args, **kwargs)[source]
Bases:
DataLowLevel,SerializableBaseObject to store all raw and calculated DataWithAxes data for later exporting, saving, sending signal…
Includes methods to retrieve data from dim, source… Stored data have a unique identifier their name. If some data is appended with an existing name, it will replace the existing data. So if you want to append data that has the same name
- Parameters:
name (
str) – The identifier of the exporting objectdata (
listofDataWithAxes) – All the raw and calculated data to be exported
- Variables:
name
timestamp
data
- Attributes:
dataList[DataWithAxes]: get the data contained in the object
Methods
accumulate(other, weight)Same as
average()but the standard error of the mean is also set as theerrorsof each averaged DataWithAxes, seeDataWithAxes.accumulate()Affect self.name to all DataWithAxes children's attribute origin if this origin is not defined
average(other, weight)Compute the weighted average between self and other DataToExport and attributes it to self
deepcopy()Return a deep copy of this object, named 'Copy', with deep copies of its data
deserialize(bytes_str)Convert bytes into a DataToExport object
from_xarray(dt[, name])Construct a DataToExport from an xarray.DataTree or a dict of Datasets.
get_data_from_Naxes(Naxes[, deepcopy])Get the data matching the given number of axes
get_data_from_attribute(attribute, ...[, ...])Get the data matching a given attribute value
get_data_from_dim(dim[, deepcopy, sort_by_name])Get the data matching the given DataDim
get_data_from_dims(dims[, deepcopy, ...])Get the data matching the given DataDim
get_data_from_full_name(full_name[, deepcopy])Get the DataWithAxes with matching full name
get_data_from_full_names(full_names[, deepcopy])Get the data matching the given full names (see
get_data_from_full_name()) as a new DataToExportget_data_from_missing_attribute(attribute[, ...])Get the data matching a given attribute value
get_data_from_name(name)Get the data matching the given name
get_data_from_name_origin(name[, origin])Get the data matching the given name and the given origin
get_data_from_names(names)Get the data whose name is in names as a new DataToExport
get_data_from_origins(origins)Get the data whose origin is in origins as a new DataToExport
get_data_from_sig_axes(Naxes[, deepcopy])Get the data matching the given number of signal axes
get_data_from_source(source[, deepcopy, ...])Get the data matching the given DataSource
get_data_with_naxes_lower_than([n_axes, ...])Get the data with n axes lower than the given number
Get the names of the dimensions (Data0D, Data1D, ...) for which at least one data is present
get_full_names([dim])Get the ful names including the origin attribute into the returned value, eventually filtered by dim
get_names([dim])Get the names of the stored DataWithAxes, eventually filtered by dim
get_origins([dim])Get the origins of the underlying data into the returned value, eventually filtered by dim
index(data)Here use a comparison to assert data is equal to one element in the list
index_from_name_origin(name[, origin])Get the index of a given DataWithAxes within the list of data
mean_with_errors([axis])Apply
DataWithAxes.mean_with_errors()to each DataWithAxes: the mean onaxisof a buffer of acquisitions given at once, with the standard error of the mean aserrorsmerge_as_dwa(dim[, name])attempt to merge filtered dwa into one
plot([plotter_backend])Call a plotter factory and its plot method over the actual data
pop(index)return and remove the DataWithAxes referred by its index
remove(dwa)Use the DataWithAxes object comparison __eq__ to retrieve the elt to remove
serialize(dte)Convert a DataToExport into a bytes string
Convert this DataToExport to an xarray.DataTree.
add_extra_attribute
append
- classmethod deserialize(bytes_str)[source]
Convert bytes into a DataToExport object
Convert the first bytes into a DataToExport reading first information about the underlying data
- Return type:
- Returns:
DataToExport (
the decoded DataToExport)bytes (
the remaining bytes if any)
- classmethod from_xarray(dt, name=None)[source]
Construct a DataToExport from an xarray.DataTree or a dict of Datasets.
- Parameters:
- Return type:
- Raises:
ImportError – If xarray is not installed.
- static serialize(dte)[source]
Convert a DataToExport into a bytes string
- Parameters:
dte (
DataToExport)- Returns:
bytes
- Return type:
the total bytes messagetoserialize the DataToExport
Notes
The bytes sequence is constructed as:
serialize the string type: ‘DataToExport’
serialize the timestamp: float
serialize the name
serialize the list of DataWithAxes
- accumulate(other, weight)[source]
Same as
average()but the standard error of the mean is also set as theerrorsof each averaged DataWithAxes, seeDataWithAxes.accumulate()- Parameters:
other (
DataToExport) – The average of theweightprevious acquisitionsweight (
int) – The weight the ‘other_data’ holds with respect to self
- Return type:
- affect_name_to_origin_if_none()[source]
Affect self.name to all DataWithAxes children’s attribute origin if this origin is not defined
- average(other, weight)[source]
Compute the weighted average between self and other DataToExport and attributes it to self
- Parameters:
other (
DataToExport)weight (
int) – The weight the ‘other_data’ holds with respect to self
- Return type:
- get_data_from_Naxes(Naxes, deepcopy=False)[source]
Get the data matching the given number of axes
- Parameters:
Naxes (
int) – Number of axes in the DataWithAxes objects- Returns:
DataToExport
- Return type:
- get_data_from_attribute(attribute, attribute_value, deepcopy=False, sort_by_name=False)[source]
Get the data matching a given attribute value
- Parameters:
- Returns:
DataToExport
- Return type:
- get_data_from_dim(dim, deepcopy=False, sort_by_name=False)[source]
Get the data matching the given DataDim
- Returns:
DataToExport
- Return type:
- get_data_from_dims(dims, deepcopy=False, sort_by_name=False)[source]
Get the data matching the given DataDim
- Returns:
DataToExport
- Return type:
- get_data_from_full_name(full_name, deepcopy=False)[source]
Get the DataWithAxes with matching full name
- Return type:
- get_data_from_full_names(full_names, deepcopy=False)[source]
Get the data matching the given full names (see
get_data_from_full_name()) as a new DataToExport- Return type:
- get_data_from_missing_attribute(attribute, deepcopy=False)[source]
Get the data matching a given attribute value
- Parameters:
- Returns:
DataToExport
- Return type:
- get_data_from_name_origin(name, origin='')[source]
Get the data matching the given name and the given origin
- Return type:
- get_data_from_names(names)[source]
Get the data whose name is in names as a new DataToExport
- Return type:
- get_data_from_origins(origins)[source]
Get the data whose origin is in origins as a new DataToExport
- Return type:
- get_data_from_sig_axes(Naxes, deepcopy=False)[source]
Get the data matching the given number of signal axes
- Parameters:
Naxes (
int) – Number of signal axes in the DataWithAxes objects- Returns:
DataToExport
- Return type:
- get_data_from_source(source, deepcopy=False, sort_by_name=False)[source]
Get the data matching the given DataSource
- Returns:
DataToExport
- Return type:
- get_data_with_naxes_lower_than(n_axes=2, deepcopy=False)[source]
Get the data with n axes lower than the given number
- Parameters:
Naxes (
int) – Number of axes in the DataWithAxes objects- Returns:
DataToExport
- Return type:
- get_dim_presents()[source]
Get the names of the dimensions (Data0D, Data1D, …) for which at least one data is present
- get_full_names(dim=None)[source]
Get the ful names including the origin attribute into the returned value, eventually filtered by dim
- Parameters:
- Returns:
list of str
- Return type:
the namesof the (filtered) DataWithAxes data constructed as :origin/name
Examples
d0 = DataWithAxes(name=’datafromdet0’, origin=’det0’)
- get_origins(dim=None)[source]
Get the origins of the underlying data into the returned value, eventually filtered by dim
- Parameters:
- Returns:
list of str
- Return type:
the originsofthe (filtered) DataWithAxes data
Examples
d0 = DataWithAxes(name=’datafromdet0’, origin=’det0’)
- index(data)[source]
Here use a comparison to assert data is equal to one element in the list
But the __eq__ method is not checking the name while it is the main issue for elt finding Hence here I’m doing both checks
- index_from_name_origin(name, origin='')[source]
Get the index of a given DataWithAxes within the list of data
- Return type:
- mean_with_errors(axis=0)[source]
Apply
DataWithAxes.mean_with_errors()to each DataWithAxes: the mean onaxisof a buffer of acquisitions given at once, with the standard error of the mean aserrorsThe acquisitions have to be stacked on the same
axisin all the DataWithAxes.- Parameters:
axis (
int) – The axis of the acquisitions- Return type:
- merge_as_dwa(dim, name=None)[source]
attempt to merge filtered dwa into one
Only possible if all filtered dwa and underlying data have same shape
- plot(plotter_backend='matplotlib', *args, **kwargs)[source]
Call a plotter factory and its plot method over the actual data
- pop(index)[source]
return and remove the DataWithAxes referred by its index
- Parameters:
index (
int) – index as returned by self.index_from_name_origin- Return type:
See also
- remove(dwa)[source]
Use the DataWithAxes object comparison __eq__ to retrieve the elt to remove
- Parameters:
dwa (
DataWithAxes) – The da to remove from the list
- to_xarray()[source]
Convert this DataToExport to an xarray.DataTree.
The root node carries
pymodaq_namein its attrs. Each DataWithAxes becomes a child node whose dataset is produced byDataWithAxes.to_xarray().- Return type:
xr.DataTree- Raises:
ImportError – If xarray is not installed.
- append
Dispatch methods based on type signature
See also
Dispatcher
- property data: List[DataWithAxes]
get the data contained in the object
- Type:
List[DataWithAxes]
- class pymodaq_data.data.DataWithAxes(*args, **kwargs)[source]
Bases:
DataBase,SerializableBaseData object with Axis objects corresponding to underlying data nd-arrays
- Parameters:
axes (
listofAxis) – the list of Axis object for proper plotting, calibration …nav_indexes (
tupleofint) – highlight which Axis in axes is Signal or Navigation axis depending on the content: For instance, nav_indexes = (2,), means that the axis with index 2 in a at least 3D ndarray data is the first navigation axis For instance, nav_indexes = (3,2), means that the axis with index 3 in a at least 4D ndarray data is the first navigation axis while the axis with index 2 is the second navigation Axis. Axes with index 0 and 1 are signal axes of 2D ndarray dataerrors (
listofndarray.) – The list should match the length of the data attribute while the ndarrays should match the data ndarray
- Attributes:
axesconvenience property to fetch attribute from axis_manager
errorsGet/Set the errors bar values as a list of np.ndarray
n_axesGet the number of axes (even if not specified)
nav_indexesconvenience property to fetch attribute from axis_manager
sig_indexesconvenience property to fetch attribute from axis_manager
Methods
accumulate(other, weight)Compute the weighted average as
average()does, and set the standard error of the mean as theerrorsof the resultaxes_limits([axes_indexes])Get the limits of specified axes (all if axes_indexes is None)
check_axes_linear([axes])Check if any axis may be non linear
combine_with_errors(other)Combine two measurements of the same quantity, each carrying its own
errors, with an inverse-variance weighted meanCheck if given the data shape, some axes are missing to properly define the data (especially for plotting)
deepcopy_with_new_data([data, ...])deepcopy without copying the initial data (saving memory)
deserialize(bytes_str)Convert bytes into a DataWithAxes object
Get a dwa from self replacing the data content with the error attribute (if not None)
find_peaks([height, threshold])Apply the scipy find_peaks method to 1D data
fit(function, initial_guess[, data_index, ...])Apply 1D curve fitting using the scipy optimization package
from_xarray(ds)Construct a DataWithAxes from an xarray Dataset (or DataArray).
ft([axis, axis_label, axis_units, labels])Process the Fourier Transform of the data on the specified axis and returns the new data
Get the width (as a pint Quantity) of each axis, creating the missing axes if needed
get_axis_from_label(label)Get the axis referred by a given label
Get all present different axis indexes
get_data_as_dwa([index])Get the underlying data selected from the list at index, returned as a DataWithAxes
Get the string describing the dimensions of the data, e.g. (nav0, nav1|sig0).
Get the dimensionality DataDim from data taking into account nav indexes
get_error(index)Get a particular error ndarray at the given index in the list
Get the data's navigation axes making sure there is data in the data field
ift([axis, axis_label, axis_units, labels])Process the inverse Fourier Transform of the data on the specified axis and returns the new data
interp(new_axis_data, **kwargs)Performs linear interpolation for 1D data only.
mean([axis])Process the mean of the data on the specified axis and returns the new data
mean_with_errors([axis])Process the mean of the data on the specified axis, as
mean()does, and set the standard error of the mean as theerrorsof the resultmoment()returns the two first moments of the data over the axis
pad(pad_width, **kwargs)Pad the data arrays using the numpy pad function
plot([plotter_backend, viewer])Call a plotter factory and its plot method over the actual data
rot90([k, axes])Rotate an array by 90 degrees in the plane specified by axes.
serialize(dwa)Convert a DataWithAxes into a bytes string
set_axes_manager(data_shape, axes, ...)Create the axes manager (uniform or spread, depending on the distribution) of this object
sort_data([axis_index, spread_index, inplace])Sort data along a given axis, default is 0
sum([axis])Process the sum of the data on the specified axis and returns the new data
Convert this DataWithAxes to an xarray.Dataset.
replace the data by their transposed version
check_squeeze
crop_at_along
get_axis_from_index
get_axis_from_index_spread
get_nav_axes
get_sig_index
- classmethod deserialize(bytes_str)[source]
Convert bytes into a DataWithAxes object
Convert the first bytes into a DataWithAxes reading first information about the underlying data
- Return type:
- Returns:
DataWithAxes (
the decoded DataWithAxes)bytes (
the remaining bytes string if any)
- classmethod from_xarray(ds)[source]
Construct a DataWithAxes from an xarray Dataset (or DataArray).
- Parameters:
ds (
xr.Datasetorxr.DataArray)- Return type:
- Raises:
ImportError – If xarray is not installed.
- static serialize(dwa)[source]
Convert a DataWithAxes into a bytes string
- Parameters:
dwa (
DataWithAxes)- Returns:
bytes
- Return type:
the total bytes messagetoserialize the DataWithAxes
Notes
The bytes sequence is constructed as:
serialize the timestamp: float
serialize the name
serialize the source enum as a string
serialize the dim enum as a string
serialize the distribution enum as a string
serialize the list of numpy arrays
serialize the list of labels
serialize the origin
serialize the nav_index tuple as a list of int
serialize the list of axis
serialize the errors attributes (None or list(np.ndarray))
serialize the list of names of extra attributes
serialize the extra attributes
- accumulate(other, weight)[source]
Compute the weighted average as
average()does, and set the standard error of the mean as theerrorsof the resultIt is meant to be used to average step by step N acquisitions,
selfbeing the new acquisition andotherthe average of theweightprevious ones, as returned by this method (the first acquisition is just a copy of itself). The standard error of the mean is updated from the one ofother(Welford’s algorithm), so no more than the averaged data is needed to follow the statistics.- Parameters:
other (
DataWithAxes) – The average of theweightprevious acquisitions. Ifweightis larger than 1, it should carry theerrorsset by the previous call, else the result has noerrors. Theerrorsof the first acquisition (weightequal to 1) are not taken into account.weight (
int) – The number of acquisitions averaged inother
- Returns:
DataWithAxes
- Return type:
See also
averageNotes
The update of the sum of squared deviations from the mean is Welford’s online algorithm [1] [2], with
S_N = S_(N-1) + (x_N - mean_(N-1)) * (x_N - mean_N)(complex conjugate on the second factor for complex data). The errors are thensqrt(S_N / (N (N - 1))), i.e. the sample standard deviation (ddof=1) divided bysqrt(N).selfis taken as a single acquisition without errors (weight one). To combine two measurements that each carry an error (inverse-variance weighting), seecombine_with_errors().References
- axes_limits(axes_indexes=None)[source]
Get the limits of specified axes (all if axes_indexes is None)
- check_axes_linear(axes=None)[source]
Check if any axis may be non linear
Should trigger a spread like distribution except id dim is Data1D, in which cas, it doesn’t matter
- Return type:
- combine_with_errors(other)[source]
Combine two measurements of the same quantity, each carrying its own
errors, with an inverse-variance weighted meanWith
w_i = 1 / e_i**2, the result is, for each point of each array:mean = (w_1 * x_1 + w_2 * x_2) / (w_1 + w_2) = (x_1 * e_2**2 + x_2 * e_1**2) / (e_1**2 + e_2**2) error = 1 / sqrt(w_1 + w_2) = e_1 * e_2 / sqrt(e_1**2 + e_2**2)
Use
accumulate()instead to average successive acquisitions into a running mean and its standard error.- Parameters:
other (
DataWithAxes) – The other measurement, with the same shape, units and number of arrays asself- Returns:
DataWithAxes
- Return type:
- Raises:
ValueError – If one of the two objects has no
errorsor if some of them are not strictly positiveDataUnitError – If the units of
selfandotherdifferDataShapeError – If the arrays of
selfandotherhave different shapes
Notes
The errors are taken as the standard deviations of independent, normally distributed measurements. The weights are the inverse of their variances, the minimum-variance unbiased estimator [1] [2].
References
- create_missing_axes()[source]
Check if given the data shape, some axes are missing to properly define the data (especially for plotting)
- deepcopy_with_new_data(data=None, remove_axes_index=None, source=DataSource.calculated, keep_dim=False, errors=None)[source]
deepcopy without copying the initial data (saving memory)
The new data, may have some axes stripped as specified in remove_axes_index
- Parameters:
remove_axes_index (
Union[int,integer,List[Union[int,integer]],Tuple[Union[int,integer],...],None]) – indexes of the axis to be removedsource (
Union[DataSource,str])keep_dim (
bool) – if False (the default) will calculate the new dim based on the data shape else keep the same (be aware it could lead to issues)errors (
Optional[List[ndarray]]) – The new errors corresponding to the new data
- Return type:
- errors_as_dwa()[source]
Get a dwa from self replacing the data content with the error attribute (if not None)
New in 4.2.0
- find_peaks(height=None, threshold=None, **kwargs)[source]
Apply the scipy find_peaks method to 1D data
- Parameters:
height (
numberorndarrayorsequence, optional)threshold (
numberorndarrayorsequence, optional)kwargs (
dict) – extra named parameters applied to the find_peaks scipy method
- Return type:
See also
find_peaks()
- fit(function, initial_guess, data_index=None, axis_index=0, **kwargs)[source]
Apply 1D curve fitting using the scipy optimization package
- Parameters:
function (
Callable) – a callable to be used for the fitinitial_guess (
Iterable) – The initial parameters for the fitdata_index (
Optional[int]) – The index of the data over which to do the fit, if None apply the fit to allaxis_index (
int) – the axis index to use for the fit (if multiple) but there should be only onekwargs (
dict) – extra named parameters applied to the curve_fit scipy method
- Return type:
See also
curve_fit()
- ft(axis=0, axis_label=None, axis_units=None, labels=None)[source]
Process the Fourier Transform of the data on the specified axis and returns the new data
- Parameters:
- Return type:
See also
ft(),fft()
- get_axes_sizes()[source]
Get the width (as a pint Quantity) of each axis, creating the missing axes if needed
- Return type:
Iterable[Quantity]
- get_data_as_dwa(index=0)[source]
Get the underlying data selected from the list at index, returned as a DataWithAxes
- Return type:
- get_data_dimension()[source]
Get the string describing the dimensions of the data, e.g. (nav0, nav1|sig0)
- Return type:
- get_dim_from_data_axes()[source]
Get the dimensionality DataDim from data taking into account nav indexes
- Return type:
- get_error(index)[source]
Get a particular error ndarray at the given index in the list
new in 4.2.0
- ift(axis=0, axis_label=None, axis_units=None, labels=None)[source]
Process the inverse Fourier Transform of the data on the specified axis and returns the new data
- Parameters:
- Return type:
See also
ift(),ifft()
- interp(new_axis_data, **kwargs)[source]
Performs linear interpolation for 1D data only.
For more complex ones, see
scipy.interpolate()- Parameters:
- Return type:
See also
interp(),interpolate()
- mean(axis=0)[source]
Process the mean of the data on the specified axis and returns the new data
- Parameters:
axis (
int)- Return type:
- mean_with_errors(axis=0)[source]
Process the mean of the data on the specified axis, as
mean()does, and set the standard error of the mean as theerrorsof the resultIt is meant for a buffer that gives a series of N acquisitions at once (as the first axis of the data, a navigation axis for instance), when
accumulate()which averages them one after the other is not needed. The errors are the sample standard deviation (ddof=1) divided bysqrt(N), asaccumulate()gives.- Parameters:
axis (
int) – The axis of the acquisitions- Returns:
DataWithAxes
- Return type:
See also
- moment()[source]
returns the two first moments of the data over the axis
only valid for Data1D data
- Return type:
- Returns:
DataCalculated (
containing the momentoforder 0 (mean))DataCalculated (
containing the momentoforder 1 (std))
- pad(pad_width, **kwargs)[source]
Pad the data arrays using the numpy pad function
The accepted pad_witdh type is the same than the numpy pad function
see numpy.pad method for the signature and possible named arguments
- plot(plotter_backend='matplotlib', *args, viewer=None, **kwargs)[source]
Call a plotter factory and its plot method over the actual data
- rot90(k=1, axes=(0, 1))[source]
Rotate an array by 90 degrees in the plane specified by axes.
Valid only for 2D data
- set_axes_manager(data_shape, axes, nav_indexes, **kwargs)[source]
Create the axes manager (uniform or spread, depending on the distribution) of this object
- sort_data(axis_index=0, spread_index=0, inplace=False)[source]
Sort data along a given axis, default is 0
- Parameters:
- Return type:
- sum(axis=0)[source]
Process the sum of the data on the specified axis and returns the new data
- Parameters:
axis (
int)- Return type:
- to_xarray()[source]
Convert this DataWithAxes to an xarray.Dataset.
Each array in self.data becomes a data variable (keyed by its label). Each Axis becomes a coordinate on the corresponding dimension. Error arrays (if present) are stored as
<label>_errordata variables.- Return type:
xr.Dataset- Raises:
ImportError – If xarray is not installed.
- property errors: Sequence[ndarray] | None
Get/Set the errors bar values as a list of np.ndarray
new in 4.2.0
- property n_axes
Get the number of axes (even if not specified)
convenience property to fetch attribute from axis_manager
- property sig_indexes
convenience property to fetch attribute from axis_manager
- class pymodaq_data.data.DwaType(*values)[source]
Bases:
BaseEnumDifferent types of DataWithAxes.
- DataActuator = 2
- DataCalculated = 4
- DataFromPlugins = 3
- DataRaw = 1
- DataWithAxes = 0
Bases:
Axis
- pymodaq_data.data.check_units(units)[source]
Return units if it is defined in the pint registry, else log a warning and return ‘’ (dimensionless)
- pymodaq_data.data.dimensionless_aware_reduce_units(q)[source]
Take a quantity q and converts it to its reduced units. For dimensionless units it compact them
- Parameters:
q (
Quantity)- Return type:
Quantity