TimeSeries

class ptsa.data.timeseries.TimeSeries(data: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | DataArray | TimeSeries, coords: Mapping[Any, Any], dims: Sequence[Any] | None = None, name: Hashable | None = None, attrs: Mapping[Any, Any] | None = None, fastpath: bool = False, **kwargs: Any)

A thin wrapper around xr.DataArray for dealing with time series data.

Note that xarray internals prevent us from overriding the constructor which leads to some awkwardness: you must pass coords as a dict with a samplerate entry.

Parameters:
  • data (array-like) – Time series data

  • coords (dict-like) – Coordinate arrays. This must contain at least a samplerate coordinate.

  • dims (array-like) – Dimension labels

  • name (str) – Name of the time series

  • attrs (dict) – Dictionary of arbitrary metadata

  • fastpath (bool) – Not used, but required when subclassing xr.DataArray.

Raises:

AssertionError – When samplerate is not present in coords.

See also

xr.DataArray

Base class

add_mirror_buffer(duration: float, two_sided: bool = True) TimeSeries

Return a time series with mirrored data added to both ends of this time series (up to specified length/duration).

The new series total time duration is:

original duration + 2 * duration * samplerate

Parameters:
  • duration (float) – Buffer duration in seconds.

  • two-sided (bool) – If True, mirror on both sides of the epoch. Otherwise, only mirror on the right side of the epoch

Return type:

New time series with added mirrored buffer.

append(other: TimeSeries, dim: str | None = None) TimeSeries

Append another TimeSeries to this one.

Changed in version 2.0: Appending along a dimension not present will cause that dimension to be created.

Parameters:
  • other (TimeSeries)

  • dim (str or None) – Dimension to concatenate on. If None, attempt to concatenate all data using numpy.concatenate(). If not present, a new dimension will be created with coords [0,1].

Return type:

Appended TimeSeries

astype(**kwargs: Any) TimeSeries

Wraps xarray.DataArray.astype(), returning the result as a TimeSeries.

baseline_corrected(base_range: tuple[float, float]) TimeSeries

Return a baseline corrected timeseries by subtracting the average value in the baseline range from all other time points for each dimension.

Parameters:

base_range ({tuple}) – Tuple specifying the start and end time range (inclusive) for the baseline.

Returns:

ts – A TimeSeries instance with the baseline corrected data.

Return type:

{TimeSeries}

coerce_to(dtype: type[~typing.Any] | ~numpy.dtype[~typing.Any] | ~numpy._typing._dtype_like._HasDType[~numpy.dtype[~typing.Any]] | ~numpy._typing._dtype_like._HasNumPyDType[~numpy.dtype[~typing.Any]] | tuple[~typing.Any, ~typing.Any] | list[~typing.Any] | ~numpy._typing._dtype_like._DTypeDict | str | None=<class 'numpy.float64'>) None

Coerce the data to the specified dtype in place. If dtype is None, this method does nothing. Default: coerce to np.float64.

classmethod create(data: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | DataArray | TimeSeries, samplerate: float | None, coords: dict[Any, Any] | None = None, dims: Sequence[Any] | None = None, name: Hashable | None = None, attrs: Mapping[Any, Any] | None = None) TimeSeries

Factory function for creating a new timeseries object with passing the sample rate as a parameter. See __init__() for parameters.

filter_with(filters: Any | Iterable[Any]) TimeSeries

Filter the time series data using the specified filters in order.

Parameters:

filters (BaseFilter or Iterable[BaseFilter]) – The filter(s) to use.

Returns:

filtered – The resulting data from the filter.

Return type:

TimeSeries

Raises:

TypeError – When filter_class is not a valid filter class.

filtered(freq_range: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], filt_type: str = 'stop', order: int = 4) TimeSeries

Filter the data using a Butterworth filter and return a new TimeSeries instance.

Parameters:
  • freq_range (array-like) – The range of frequencies to filter.

  • filt_type (str) – Filter type (default: 'stop').

  • order (int) – The order of the filter (default: 4).

Returns:

ts – A TimeSeries instance with the filtered data.

Return type:

TimeSeries

classmethod from_hdf(filename: str, engine: str = 'netcdf4', **kwargs: Any) TimeSeries

Load a serialized time series from an HDF5 file. Uses

Parameters:

filename (str) – Path to HDF5 file.

classmethod from_mne_epochs(epochs: Any, event_df: DataFrame) TimeSeries

Create an xarray version of epoch data.

item(*args)

Copy an element of an array to a standard Python scalar and return it.

Parameters:

*args (Arguments (variable number and type)) –

  • none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.

  • int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.

  • tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.

Returns:

z – A copy of the specified element of the array as a suitable Python scalar

Return type:

Standard Python scalar object

Notes

When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.

item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.

Examples

>>> import numpy as np
>>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
       [1, 3, 6],
       [1, 0, 1]])
>>> x.item(3)
1
>>> x.item(7)
0
>>> x.item((0, 1))
2
>>> x.item((2, 2))
1

For an array with object dtype, elements are returned as-is.

>>> a = np.array([np.int64(1)], dtype=object)
>>> a.item() #return np.int64
np.int64(1)
query(**kwargs: Any) TimeSeries

Wraps xarray.DataArray.query(), returning the result as a TimeSeries.

reduce(**kwargs: Any) TimeSeries

Wraps xarray.DataArray.reduce(), returning the result as a TimeSeries.

remove_buffer(duration: float) TimeSeries | None

Return a timeseries with the desired buffer duration (in seconds) removed and the time range reset.

Parameters:

duration (float) – The duration to be removed. The units depend on the samplerate: E.g., if samplerate is specified in Hz (i.e., samples per second), the duration needs to be specified in seconds and if samplerate is specified in kHz (i.e., samples per millisecond), the duration needs to be specified in milliseconds. The specified duration is removed from the beginning and end.

Returns:

ts – A TimeSeries instance with the requested durations removed from the beginning and/or end.

Return type:

TimeSeries

resampled(resampled_rate: float, window: Any = None, loop_axis: Any = None, num_mp_procs: int = 0, pad_to_pow2: bool = False) TimeSeries

Returns a time series Fourier resampled at resampled_rate.

Note that Fourier resampling assumes periodicity, so edge effects can arise. Keeping a buffer of at least 1/f for the lowest frequency of interest guards against this.

Parameters:
  • resampled_rate (float) – New sample rate

  • window – ignored for now - added for legacy reasons

  • loop_axis – ignored for now - added for legacy reasons

  • num_mp_procs – ignored for now - added for legacy reasons

  • pad_to_pow2 – ignored for now - added for legacy reasons

Return type:

Resampled time series

searchsorted(v, side='left', sorter=None)

Find indices where elements of v should be inserted in a to maintain order.

For full documentation, see numpy.searchsorted.

See also

numpy.searchsorted

equivalent function

to_hdf(filename: str, mode: Literal['w', 'a'] = 'w', **kwargs: Any) None

Save to disk using HDF5.

Parameters:
  • filename (str) – Full path to the HDF5 file

  • mode (str) – File mode to use. See the h5py documentation for details. Default: 'w'

  • kwargs (dict) – Keyword arguments to be passed on to to_netcdf() call.

Notes

recarrays/DataFrame fields with “O” dtypes will be assumed to be strings and encoded accordingly.