timeseries.TSContinuous

class timeseries.TSContinuous(times: ndarray | List | Tuple | None = None, samples: ndarray | List | Tuple | None = None, num_channels: int | None = None, periodic: bool = False, t_start: float | None = None, t_stop: float | None = None, name: str = 'unnamed', units: str | None = None, interp_kind: str = 'previous', fill_value: str = 'extrapolate')[source]

Bases: TimeSeries

Represents a continuously-sampled time series. Mutliple time series can be represented by a single TSContinuous object, and have identical time bases. Temporal periodicity is supported. See Working with time series data for further explanation and examples.

Examples:

Build a linearly-increasing time series that extends from 0 to 1 second

>>> time_base = numpy.linspace(0, 1, 100)
>>> samples = time_base
>>> ts = TSContinuous(time_base, samples)

Build a periodic time series as a sinusoid

>>> time_base = numpy.linspace(0, 2 * numpy.pi, 100)
>>> samples = numpy.sin(time_base)
>>> ts = TSContinuous(time_base, samples, periodic = True)

Build an object containing five random time series

>>> time_base = numpy.linspace(0, 1, 100)
>>> samples = numpy.random.rand((100, 5))
>>> ts = TSContinuous(time_base, samples)

Manipulate time series using standard operators

>>> ts + 5
>>> ts - 3
>>> ts * 2
>>> ts / 7
>>> ts // 3
>>> ts ** 2
>>> ts1 + ts2
...

Manipulate time series data in time

>>> ts.delay(4)
>>> ts.clip(start, stop, [channel1, channel2, channel3])

Combine time series data

>>> ts1.append_t(ts2)    # Appends the second time series, along the time axis
>>> ts1.append_c(ts2)    # Appends the second time series as an extra channel

Note

All TSContinuous manipulation methods return a copy by default. Most methods accept an optional inplace flag, which if True causes the operation to be performed in place.

Resample a time series using functional notation, list notation, or using the resample() method.

>>> ts(0.5)
>>> ts([0, .1, .2, .3])
>>> ts(numpy.array([0, .1, .2, .3]))
>>> ts[0.5]
>>> ts[0, .1, .2, .3]
>>> ts.resample(0.5)
>>> ts.resample([0, .1, .2, .3])

Resample using slice notation

>>> ts[0:.1:1]

Resample and select channels simultaneously

>>> ts[0:.1:1, :3]

Attributes overview

approx_limit_times

beyond_range_exception

duration

(float) Duration of TimeSeries

fill_value

max

(float) Maximum value of time series

min

(float) Minimum value of time series

name

num_channels

(int) Number of channels (dimension of sample vectors) in this TimeSeries object

num_traces

(int) Synonymous to num_channels

plotting_backend

(str) Current plotting backend

samples

(ArrayLike[float]) Value of time series at sampled times

t_start

(float) Start time of time series

t_stop

(float) Stop time of time series (final sample)

times

(ArrayLike[float]) Array of sample times

Methods overview

__init__([times, samples, num_channels, ...])

TSContinuous - Represents a continuously-sample time series, supporting interpolation and periodicity.

append_c(other_series[, inplace])

Append another time series to this one, along the samples axis (i.e.

append_t(other_series[, offset, inplace])

Append another time series to this one, along the time axis

clip([t_start, t_stop, channels, ...])

Return a TSContinuous which is restricted to given time limits and only contains events of selected channels

concatenate_t(series[, offset])

Append multiple TimeSeries objects in time to a new series

contains(times)

Does the time series contain the time range specified in the given time trace? Always true for periodic series

copy()

Return a deep copy of this time series

delay(offset[, inplace])

Return a copy of self that is delayed by an offset

from_clocked(samples, dt[, t_start, ...])

Convenience method to create a new continuous time series from a clocked sample.

isempty()

Test if this TimeSeries object is empty

load(path[, expected_type])

Load TimeSeries object from file.

merge(other_series[, remove_duplicates, inplace])

Merge other time series to this one, by interleaving in time.

plot([times, target, channels, stagger, ...])

Visualise a time series on a line plot

print([full, num_first, num_last, limit_shorten])

Print an overview of the time series and its values

resample(times[, channels, inplace])

Return a new time series sampled to the supplied time base

save(path[, verbose, dtype_times, dtype_samples])

Save this time series as an npz file using np.savez

set_plotting_backend(backend[, verbose])

Set which plotting backend to use with the plot method

start_at(t_start[, inplace])

Convenience function that calls the delay method such that self.t_start falls at t_start.

start_at_zero([inplace])

Convenience function that calls the delay method such that self.t_start falls at 0.

to_clocked(dt)

Resample this time series to a synchronous clock and return the samples

to_dict([dtype_times, dtype_samples])

Store data and attributes of this TSContinuous in a dict.

__init__(times: ndarray | List | Tuple | None = None, samples: ndarray | List | Tuple | None = None, num_channels: int | None = None, periodic: bool = False, t_start: float | None = None, t_stop: float | None = None, name: str = 'unnamed', units: str | None = None, interp_kind: str = 'previous', fill_value: str = 'extrapolate')[source]

TSContinuous - Represents a continuously-sample time series, supporting interpolation and periodicity.

Parameters:
  • times (ArrayLike) – [Tx1] vector of time samples

  • samples (ArrayLike) – [TxM] matrix of values corresponding to each time sample

  • num_channels (Optional[in]) – If samples is None, determines the number of channels of self. Otherwise it has no effect at all.

  • periodic (bool) – Treat the time series as periodic around the end points. Default: False

  • t_start (Optional[float]) – If not None, the series start time is t_start, otherwise times[0]

  • t_stop (Optional[float]) – If not None, the series stop time is t_stop, otherwise times[-1]

  • name (str) – Name of the TSContinuous object. Default: "unnamed"

  • units (Optional[str]) – Units of the TSContinuous object. Default: None

  • interp_kind (str) – Specify the interpolation type. Default: "previous"

  • fill_value (str) – Specify the method to fill values outside sample times. Default: "extrapolate". Sampling beyond `.t_stop` is still not permitted

If the time series is not periodic (the default), then NaNs will be returned for any values outside t_start and t_stop.

_compatible_shape(other_samples) ndarray[source]

Attempt to make other_samples a compatible shape to self.samples.

Parameters:

other_samples (ArrayLike) – Samples to convert

Return np.ndarray:

Array the same shape as self.samples

Raises:

ValueError if broadcast fails

_create_interpolator()[source]

Build an interpolator for the samples in this TimeSeries.

Replaces the current interpolator.

_interpolate(times: int | float | ndarray | List | Tuple) ndarray[source]

Interpolate the time series to the provided time points

Parameters:

times (ArrayLike) – Array of T desired interpolated time points

Return np.ndarray:

Array of interpolated values. Will have the shape TxN, where N is the number of channels in self

static _mask_duplicate_time_points(series0, series1, use_points1)[source]
_modulo_period(times: ndarray | List | Tuple | float | int) ndarray | List | Tuple | float | int

_modulo_period - Calculate provided times modulo self.duration

_samples = []
append_c(other_series: TSContinuous, inplace: bool = False) TSContinuous[source]

Append another time series to this one, along the samples axis (i.e. add new channels)

Parameters:
  • other_series (TSContinuous) – Another time series. Will be resampled to the time base of self

  • inplace (bool) – Conduct operation in-place (Default: False; create a copy)

Return TSContinuousTSContinuous:

Current time series, with new channels appended

append_t(other_series: TSContinuous | Iterable[TSContinuous], offset: float | Iterable[float | None] | None = None, inplace: bool = False) TSContinuous[source]

Append another time series to this one, along the time axis

Parameters:
  • other_series (Union["TSContinuous", Iterable[TSContinuous]]) – Time series to be tacked on to the end of the called series object. These series must have the same number of channels as self or be empty.

  • offset (Union[float, Iterable[float], Iterable[None], None]) – If not None, defines distance between last sample of one series and first sample of the next. Otherwise the offset will be the median of all timestep sizes of the first of the two series, or 0 if that series has len < 2.

  • inplace (bool) – Conduct operation in-place (Default: False; create a copy)

Return TSContinuous:

Time series containing data from self, with the other series appended in time

property approx_limit_times
property beyond_range_exception
clip(t_start: float | None = None, t_stop: float | None = None, channels: ndarray | List | Tuple | int | None = None, include_stop: bool = True, sample_limits: bool = True, inplace: bool = False) TSContinuous[source]

Return a TSContinuous which is restricted to given time limits and only contains events of selected channels

Parameters:
  • t_start (float) – Time from which on events are returned

  • t_stop (float) – Time until which events are returned

  • channels (ArrayLike) – Channels of which events are returned

  • include_stop (bool) – True -> If there are events with time t_stop include them. False -> Exclude these samples. Default: True.

  • sample_limits (bool) – If True, make sure that a sample exists at t_start and, if include_stop is True, at t_stop, as long as not both are None.

  • inplace (bool) – Conduct operation in-place (Default: False; create a copy)

Return TSContinuous:

clipped_series: New TSContinuous clipped to bounds

classmethod concatenate_t(series: Iterable[TS], offset: float | Iterable[float | None] | None = None) TS

Append multiple TimeSeries objects in time to a new series

Parameters:
  • series (Iterable) – Time series to be tacked at the end of each other. These series must have the same number of channels.

  • offset (Union[None, float, Iterable]) – Offset to be introduced between time traces. First value corresponds to delay of first time series.

Return TimeSeries:

Time series with data from series in series

contains(times: int | float | ndarray | List | Tuple) bool

Does the time series contain the time range specified in the given time trace? Always true for periodic series

Parameters:

times (ArrayLike) – Array-like containing time points

Return bool:

True iff all specified time points are contained within this time series

copy() TS

Return a deep copy of this time series

Return TimeSeries:

copy of self

delay(offset: int | float, inplace: bool = False) TS

Return a copy of self that is delayed by an offset

For delaying self, use the inplace argument, or .times += ... instead.

Parameters:
  • Offset (float) – Time by which to offset this time series

  • inplace (bool) – If True, conduct operation in-place (Default: False; create a copy)

Return TimeSeries:

New TimeSeries, delayed

property duration: float

(float) Duration of TimeSeries

property fill_value
static from_clocked(samples: ndarray, dt: float, t_start: float = 0.0, periodic: bool = False, name: str | None = None, interp_kind: str = 'previous') TSContinuous[source]

Convenience method to create a new continuous time series from a clocked sample.

samples is an array of clocked samples, sampled at a regular interval dt. Each sample is assumed to occur at the start of a time bin, such that the first sample occurs at t = 0 (or t = t_start). A continuous time series will be returned, constructed using samples, and filling the time t = 0 to t = N*dt, with t_start and t_stop set appropriately.

Parameters:
  • samples (np.ndarray) – A clocked set of contiguous-time samples, with a sample interval of dt. samples must be of shape [T, C], where T is the number of time bins, and C is the number of channels.

  • dt (float) – The sample interval for samples

  • t_start (float) – The time of the first sample.

  • periodic (bool) – Flag specifying whether or not the time series will be generated as a periodic series. Default:False, do not generate a periodic time series.

  • name (Optional[str]) – Optional string to set as the name for this time series. Default: None

  • interp_kind (str) – String specifying the interpolation method to be used for the returned time series. Any string accepted by scipy.interp1d is accepted. Default: "previous", sample-and-hold interpolation.

:return TSContinuous : A continuous time series containing samples.

isempty() bool

Test if this TimeSeries object is empty

Return bool:

True iff the TimeSeries object contains no samples

classmethod load(path: str | Path, expected_type: str | None = None) TS

Load TimeSeries object from file. If called from a subclass of :py:class’TimeSeries`, the type of the stored object must match that of the method class.

Parameters:
  • path (Union[str, Path]) – Path to load from.

  • expected_type (Optional[str]) – Specify expected type of timeseires (TSContinuous or py:class:TSEvent). Can only be set if method is called from py:class:TimeSeries class. Default: None, use whichever type is loaded.

Return TimeSeries:

Loaded time series object

Raises:
  • TypeError – Unsupported or unexpected type

  • TypeError – Argument expected_type is defined if class is not TimeSeries.

property max

(float) Maximum value of time series

merge(other_series: TSContinuous | Iterable[TSContinuous], remove_duplicates: bool = True, inplace: bool = False) TSContinuous[source]

Merge other time series to this one, by interleaving in time. Maintain each time series’ time values and channel IDs.

Parameters:
  • other_series (Union["TSContinuous", Iterable["TSContinuous"]]) – time series that is merged to self or iterable thereof to merge multiple series

  • remove_duplicates (bool) – If True, time points in other series that are also in self.times are discarded. Otherwise they are included in the new time trace and come after the corresponding points of self.times.

  • inplace (bool) – Conduct operation in-place (Default: False; create a copy)

Return TSContinuous:

The merged time series

property min

(float) Minimum value of time series

property name: str
property num_channels

(int) Number of channels (dimension of sample vectors) in this TimeSeries object

property num_traces

(int) Synonymous to num_channels

plot(times: int | float | ndarray | List | Tuple | None = None, target: mpl.axes.Axes | hv.Curve | hv.Overlay | None = None, channels: ndarray | List | Tuple | int | None = None, stagger: float | int | None = None, skip: int | None = None, dt: float | None = None, *args, **kwargs)[source]

Visualise a time series on a line plot

Parameters:
  • times (Optional[ArrayLike]) – Time base on which to plot. Default: time base of time series

  • target (Optional) – Axes (or other) object to which plot will be added.

  • channels (Optional[ArrayLike]) – Channels of the time series to be plotted.

  • stagger (Optional[float]) – Stagger to use to separate each series when plotting multiple series. (Default: None, no stagger)

  • skip (Optional[int]) – Skip several series when plotting multiple series

  • dt (Optiona[float]) – Resample time series to this timestep before plotting

Returns:

Plot object. Either holoviews Layout, or matplotlib plot

property plotting_backend

(str) Current plotting backend

print(full: bool = False, num_first: int = 4, num_last: int = 4, limit_shorten: int = 10)[source]

Print an overview of the time series and its values

Parameters:
  • full (bool) – Print all samples of self, no matter how long it is

  • num_first (int) – Shortened version of printout contains samples at first num_first points in times

  • num_last (int) – Shortened version of printout contains samples at last num_last points in times

  • limit_shorten (int) – Print shortened version of self if it comprises more than limit_shorten time points and if full is False

resample(times: int | float | ndarray | List | Tuple, channels: int | float | ndarray | List | Tuple | None = None, inplace: bool = False) TSContinuous[source]

Return a new time series sampled to the supplied time base

Parameters:
  • times (ArrayLike) – T desired time points to resample

  • channels (Optional[ArrayLike]) – Channels to be used. Default: None (use all channels)

  • inplace (bool) – True -> Conduct operation in-place (Default: False; create a copy)

Return TSContinuous:

Time series resampled to new time base and with desired channels.

property samples

(ArrayLike[float]) Value of time series at sampled times

save(path: str | Path, verbose: bool = False, dtype_times: None | str | type | dtype = None, dtype_samples: None | str | type | dtype = None)[source]

Save this time series as an npz file using np.savez

Parameters:
  • path (str) – Path to save file

  • dtype_times (Union[None, str, type, np.dtype]) – Data type in which times are to be stored, for example to save space.

  • dtype_samples (Union[None, str, type, np.dtype]) – Data type in which samples are to be stored, for example to save space.

set_plotting_backend(backend: str | None, verbose: bool = True)

Set which plotting backend to use with the plot method

Parameters:
  • backend (str) – Specify a backend to use. Supported: {“holoviews”, “matplotlib”}

  • verbose (bool) – If True, print feedback about which backend has been set

start_at(t_start: float, inplace: bool = False) TS

Convenience function that calls the delay method such that self.t_start falls at t_start.

Parameters:
  • t_start (float) – Time to which self.t_start should be shifted;

  • inplace (bool) – If True, conduct operation in-place (Default: False; create a copy)

Return TimeSeries:

New TimeSeries, delayed

start_at_zero(inplace: bool = False) TS

Convenience function that calls the delay method such that self.t_start falls at 0.

Return TimeSeries:

New TimeSeries, with t_start at 0

property t_start: float

(float) Start time of time series

property t_stop: float

(float) Stop time of time series (final sample)

property times

(ArrayLike[float]) Array of sample times

to_clocked(dt: float) ndarray[source]

Resample this time series to a synchronous clock and return the samples

This method will generate a time base that begins at t_start and extends to at least t_stop, sampled on a clock defined by dt. The time series will be resampled to that time base, using the defined interpolation method, and the clocked samples will be returned as a raster.

Parameters:

dt (float) – The desired clock time step, in seconds

Returns:

The samples from the clocked time series

Return type:

np.ndarray

to_dict(dtype_times: None | str | type | dtype = None, dtype_samples: None | str | type | dtype = None) Dict[source]

Store data and attributes of this TSContinuous in a dict.

Parameters:
  • dtype_times (Union[None, str, type, np.dtype]) – Data type in which times are to be returned, for example to save space.

  • dtype_samples (Union[None, str, type, np.dtype]) – Data type in which samples are to be returned, for example to save space.

Returns:

Dict with data and attributes of this TSContinuous.