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 optionalinplace
flag, which ifTrue
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
(float) Duration of TimeSeries
(float) Maximum value of time series
(float) Minimum value of time series
(int) Number of channels (dimension of sample vectors) in this TimeSeries object
(int) Synonymous to
num_channels
(str) Current plotting backend
(ArrayLike[float]) Value of time series at sampled times
(float) Start time of time series
(float) Stop time of time series (final sample)
(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 offsetfrom_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 emptyload
(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.savezset_plotting_backend
(backend[, verbose])Set which plotting backend to use with the
plot
methodstart_at
(t_start[, inplace])Convenience function that calls the
delay
method such thatself.t_start
falls att_start
.start_at_zero
([inplace])Convenience function that calls the
delay
method such thatself.t_start
falls at0
.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 adict
.- __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 ofself
. 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 ist_start
, otherwisetimes[0]
t_stop (Optional[float]) – If not
None
, the series stop time ist_stop
, otherwisetimes[-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
andt_stop
.
- _compatible_shape(other_samples) ndarray [source]
Attempt to make
other_samples
a compatible shape toself.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
, whereN
is the number of channels inself
- _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 TSContinuous
TSContinuous
: 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, ifinclude_stop
is True, att_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 offsetFor 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 intervaldt
. Each sample is assumed to occur at the start of a time bin, such that the first sample occurs att = 0
(ort = t_start
). A continuous time series will be returned, constructed usingsamples
, and filling the timet = 0
tot = N*dt
, witht_start
andt_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]
, whereT
is the number of time bins, andC
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 containingsamples
.
- isempty() bool
Test if this
TimeSeries
object is empty- Return bool:
True
iff theTimeSeries
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 notTimeSeries
.
- 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 inself.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 isnum_first (int) – Shortened version of printout contains samples at first
num_first
points intimes
num_last (int) – Shortened version of printout contains samples at last
num_last
points intimes
limit_shorten (int) – Print shortened version of self if it comprises more than
limit_shorten
time points and iffull
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
- 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 thatself.t_start
falls att_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 thatself.t_start
falls at0
.- 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 leastt_stop
, sampled on a clock defined bydt
. 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 adict
.- Parameters:
- Returns:
Dict with data and attributes of this
TSContinuous
.