timeseries.TSEvent
- class timeseries.TSEvent(times: Optional[Union[numpy.ndarray, List, Tuple]] = None, channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, periodic: bool = False, t_start: Optional[float] = None, t_stop: Optional[float] = None, name: Optional[str] = None, num_channels: Optional[int] = None)[source]
Bases:
timeseries.TimeSeries
Represents a discrete time series, composed of binary events (present or absent). This class is primarily used to represent spike trains or event trains to communicate with spiking neuron layers, or to communicate with event-based computing systems. See Working with time series data for further explanation and examples.
TSEvent
supports multiple channels of event time series encapsulated by a single object, as well as periodic time series.- Examples
Build a series of several random event times
>>> times = numpy.cumsum(numpy.random.rand(10)) >>> ts = TSEvent(times)
- __init__(times: Optional[Union[numpy.ndarray, List, Tuple]] = None, channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, periodic: bool = False, t_start: Optional[float] = None, t_stop: Optional[float] = None, name: Optional[str] = None, num_channels: Optional[int] = None)[source]
Represent discrete events in time
- Parameters
times (Optional[ArrayLike[float]]) –
Tx1
vector of event timeschannels (Optional[ArrayLike[int]]) –
Tx1
vector of event channels (Default: all events are in channel 0)periodic (bool) – Is this a periodic TimeSeries (Default: False; non-periodic)
t_start (float) – Explicitly specify the start time of this series. If
None
, thentimes[0]
is taken to be the start timet_stop (float) – Explicitly specify the stop time of this series. If
None
, thentimes[-1]
is taken to be the stop timename (Optional[str]) – Name of the time series (Default: None)
num_channels (Optional[int]) – Total number of channels in the data source. If
None
, the total channel number is taken to bemax(channels)
Attributes overview
(ArrayLike[int]) Event channel indices.
(float) Duration of TimeSeries
(int) The maximum number of channels represented by this
TSEvent
(str) Current plotting backend
(float) Start time of time series
(float) Stop time of time series (final sample)
(ArrayLike[float]) Array of sample times
Methods overview
__init__
([times, channels, periodic, ...])Represent discrete events in time
append_c
(other_series[, inplace])Append another time series to
self
along the channels axisappend_t
(other_series[, offset, ...])Append another time series to this one along the time axis
clip
([t_start, t_stop, channels, ...])Return a
TSEvent
which is restricted to given time limits and only contains events of selected channelsconcatenate_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_raster
(raster[, dt, t_start, t_stop, ...])Create a
TSEvent
object from a raster arrayisempty
()Test if this
TimeSeries
object is emptyload
(path[, expected_type])Load TimeSeries object from file.
merge
(other_series[, delay, ...])Merge another
TSEvent
into this one so that they may overlap in timeplot
([time_limits, target, channels])Visualise this time series on a scatter plot
print
([full, num_first, num_last, limit_shorten])Print an overview of the time series and its values
raster
(dt[, t_start, t_stop, num_timesteps, ...])Return a rasterized version of the time series data, where each data point represents a time step
remap_channels
(channel_map[, inplace])Renumber channels in the
TSEvent
save
(path[, verbose, dtype_times, ...])Save this
TSEvent
as annpz
file usingnp.savez()
set_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_dict
([dtype_times, dtype_channels])Store data and attributes of this
TSEvent
in aDict
.xraster
(dt[, t_start, t_stop, ...])Generator which
yield
s a rasterized time series data, where each data point represents a time step- __init__(times: Optional[Union[numpy.ndarray, List, Tuple]] = None, channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, periodic: bool = False, t_start: Optional[float] = None, t_stop: Optional[float] = None, name: Optional[str] = None, num_channels: Optional[int] = None)[source]
Represent discrete events in time
- Parameters
times (Optional[ArrayLike[float]]) –
Tx1
vector of event timeschannels (Optional[ArrayLike[int]]) –
Tx1
vector of event channels (Default: all events are in channel 0)periodic (bool) – Is this a periodic TimeSeries (Default: False; non-periodic)
t_start (float) – Explicitly specify the start time of this series. If
None
, thentimes[0]
is taken to be the start timet_stop (float) – Explicitly specify the stop time of this series. If
None
, thentimes[-1]
is taken to be the stop timename (Optional[str]) – Name of the time series (Default: None)
num_channels (Optional[int]) – Total number of channels in the data source. If
None
, the total channel number is taken to bemax(channels)
- _matching_channels(channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, event_channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None) numpy.ndarray [source]
Return boolean array of which events match a given channel selection
- Parameters
channels (ArrayLike[int]) – Channels of which events are to be indicated
True
. Default:None
, use all channels- Params ArrayLike[int] event_channels
Channel IDs for each event. If not provided (Default:
None
), then use self._channels- Return ArrayLike[bool]
A matrix
TxC
indicating which events match the requested channels
- _modulo_period(times: Union[numpy.ndarray, List, Tuple, float, int]) Union[numpy.ndarray, List, Tuple, float, int]
_modulo_period - Calculate provided times modulo
self.duration
- append_c(other_series: timeseries.TSEvent, inplace: bool = False) timeseries.TSEvent [source]
Append another time series to
self
along the channels axisThe channel IDs in
other_series
are shifted byself.num_channels
. Event times remain the same.
- append_t(other_series: Union[timeseries.TimeSeries, Iterable[timeseries.TimeSeries]], offset: Optional[Union[float, Iterable[Optional[float]]]] = None, remove_duplicates: bool = False, inplace: bool = False) timeseries.TSEvent [source]
Append another time series to this one along the time axis
t_start
fromother_series
is shifted toself.t_stop + offset
.- Parameters
other_series (TSEvent) –
TSEvent
or list ofTSEvent
that will be appended toself
along the time axisoffset (Optional[float]) – Scalar or iterable with at least the same number of elements as
other_series
. If scalar, use same value for all timeseries. Event times fromother_series
will be shifted byself.t_stop + offset
. Default: 0remove_duplicates (bool) – If
True
, duplicate events will be removed from the resulting timeseries. Duplicates can occur ifoffset
is negative. Default:False
, do not remove duplicate events.inplace (bool) – If
True
, conduct operation in-place (Default:False
; return a copy)
- Return TSEvent
TSEvent
containing events fromself
, with other TS appended in time
- property channels
(ArrayLike[int]) Event channel indices. A
Tx1
vector, where each elementt
corresponds to the event time inself.times[t]
.
- clip(t_start: Optional[float] = None, t_stop: Optional[float] = None, channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, remap_channels: bool = False, inplace: bool = False) timeseries.TSEvent [source]
Return a
TSEvent
which is restricted to given time limits and only contains events of selected channelsIf time limits are provided,
t_start
andt_stop
attributes of the new time series will correspond to those. Ifremap_channels
isTrue
, channels IDs will be mapped to a continuous sequence of integers starting from 0 (e.g. [1, 3, 6]->[0, 1, 2]). In this casenum_channels
will be set to the number of different channels inchannels
. Otherwisenum_channels
will keep its original values, which is also the case for all other attributes. Ifinplace
is True, modifyself
accordingly.- Parameters
t_start (Optional[float]) – Time from which on events are returned. Default:
t_start
t_stop (Optional[float]) – Time until which events are returned. Default:
t_stop
channels (Optional[ArrayLike[int]]) – Channels of which events are returned. Default: All channels
remap_channels (bool) – Map channel IDs to continuous sequence starting from 0. Set
num_channels
to largest new ID + 1. Default:False
, do not remap channelsinplace (bool) – Iff
True
, the operation is performed in place (Default: False)
- Return TSEvent
TSEvent
TSEvent
containing events from the requested channels
- classmethod concatenate_t(series: Iterable[timeseries.TS], offset: Optional[Union[float, Iterable[Optional[float]]]] = None) timeseries.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: Union[int, float, numpy.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() timeseries.TS
Return a deep copy of this time series
- Return TimeSeries
copy of
self
- delay(offset: Union[int, float], inplace: bool = False) timeseries.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
- static from_raster(raster: numpy.ndarray, dt: float = 1.0, t_start: float = 0.0, t_stop: Optional[float] = None, name: Optional[str] = None, periodic: bool = False, num_channels: Optional[int] = None, spikes_at_bin_start: bool = False) timeseries.TSEvent [source]
Create a
TSEvent
object from a raster arrayGiven a rasterised event time series, with dimensions [TxC],
from_raster
will generate a event time series as aTSEvent
object.Example
The following code will generate a Poisson event train with 200 time steps of 1ms each, and 20 channels, with a spiking probability of 10% per time bin:
T = 200 C = 20 dt = 1e-3 spike_prob = 0.1 raster = np.random.rand((T, C)) > spike_prob spikes_ts = TSEvent.from_raster(raster, dt)
- Parameters
raster (np.ndarray) – An array of events
(T, C)
. Each row corresponds to a clocked time step ofdt
duration. Each bin contains the number of spikes present in that bindt (float) – Duration of each time bin in seconds
t_start (float) – The start time of the first bin in
raster
. Default:0.
t_stop (float) – The stop time of the time series. Default: the total duration of the provided raster
name (Optional[str]) – The name of the returned time series. Default:
None
periodic (bool) – The
periodic
flag passed to the new time seriesnum_channels (Optional[int]) – The
num_channels
argument passed to the new time series. Default:None
, use the number of channelsC
inraster
spikes_at_bin_start (bool) – Iff
True
, then spikes inraster
are considered to occur at the start of the time bin. IfFalse
, then spikes occur half-way through each time bin. Default:False
, spikes occur half-way through each time bin.
- Return TSEvent
A new
TSEvent
containing the events inraster
- isempty() bool
Test if this
TimeSeries
object is empty- Return bool
True
iff theTimeSeries
object contains no samples
- classmethod load(path: Union[str, pathlib.Path], expected_type: Optional[str] = None) timeseries.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
.
- merge(other_series: Union[timeseries.TimeSeries, Iterable[timeseries.TimeSeries]], delay: Union[float, Iterable[float]] = 0, remove_duplicates: bool = False, inplace: bool = False) timeseries.TSEvent [source]
Merge another
TSEvent
into this one so that they may overlap in time- Parameters
other_series (TSEvent) –
TSEvent
or list ofTSEvent
to merge intoself
delay (Union[float, Iterable[float]]) – Scalar or iterable with at least the number of elements as other_series. If scalar, use same value for all timeseries. Delay
other_series
series by this value before merging.remove_duplicates (bool) – If
True
, remove duplicate events in resulting timeseries. Default:False
, do not remove duplicates.inplace (bool) – If
True
, operation will be performed in place (Default:False
, return a copy)
- Return TSEvent
self
with new samples included
- property name: str
- plot(time_limits: Optional[Tuple[Optional[float], Optional[float]]] = None, target: Optional[Union[mpl.axes.Axes, hv.Scatter, hv.Overlay]] = None, channels: Optional[Union[numpy.ndarray, List, Tuple, int]] = None, *args, **kwargs)[source]
Visualise this time series on a scatter plot
- Parameters
time_limits (Optional[float, float]) – Tuple with times between which to plot. Default: plot all times
target (Optional[axis]) – Object to which plot will be added. Default: new plot
channels (ArrayLike[int]) – Channels that are to be plotted. Default: plot all channels
kwargs (args,) – Optional arguments to pass to plotting function
- 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. Default:False
limit_shorten (int) – Print shortened version of
self
if it comprises more thanlimit_shorten
time points andfull
isFalse
. Default: 4num_first (int) – Shortened version of printout contains samples at first
num_first
points inself.times
. Default: 4num_last (int) – Shortened version of printout contains samples at last
num_last
points inself.times
. Default: 4
- raster(dt: float, t_start: Optional[float] = None, t_stop: Optional[float] = None, num_timesteps: Optional[int] = None, channels: Optional[numpy.ndarray] = None, add_events: bool = False) numpy.ndarray [source]
Return a rasterized version of the time series data, where each data point represents a time step
Events are represented in a boolean matrix, where the first axis corresponds to time, the second axis to the channel. Events that happen between time steps are projected to the preceding step. If two events happen during one time step within a single channel, they are counted as one, unless
add_events
isTrue
.Time bins for the raster extend
[t, t+dt)
, that is explicitly excluding events that occur att+dt
. Such events would be included in the following time bin.To generate a time trace that corresponds to the raster, you can use
numpy.arange()
as follows:num_timesteps = np.ceil((t_stop - t_start) / dt) bin_starts = np.arange(num_timesteps) * dt + t_start bin_stops = bin_starts + dt bin_mid = bin_starts + dt/2
Note that the modulo computation is numerically unstable as expressed above. Internally we use a numerically more stable version, with:
def mod(num, div): return (num - div * np.floor(num/div)) num_timesteps = int(np.ceil((t_stop - t_start) / dt)
- Parameters
dt (float) – Duration of single time step in raster
t_start (Optional[float]) – Time where to start raster. Default: None (use
self.t_start
)t_stop (Optional[float]) – Time where to stop raster. This time point is not included in the raster. Default:
None
(useself.t_stop
. Ifnum_timesteps
is provided,t_stop
is ignored.num_timesteps (Optional[int]) – Specify number of time steps directly, instead of providing
t_stop
. Default:None
(uset_start
,t_stop
anddt
to determine raster size)channels (Optional[ArrayLike[int]]) – Channels from which data is to be used. Default:
None
(use all channels)add_events (bool) – If
True
, return an integer raster containing number of events for each time step and channel. Default:False
, merge simultaneous events in a single channel, and return a boolean rasterendpoint (bool) – If
True
, an extra time bin is added to the raster aftert_stop
, to ensure that any events occurring att_stop
are included in the raster. Default:False
, do not include events occurring att_stop
.
- Return ArrayLike
event_raster Boolean matrix with
True
indicating presence of events for each time step and channel. Ifadd_events == True
, the raster consists of integers indicating the number of events per time step and channel. First axis corresponds to time, second axis to channel.
- remap_channels(channel_map: Union[numpy.ndarray, List, Tuple], inplace: bool = False) timeseries.TSEvent [source]
Renumber channels in the
TSEvent
Maps channels 0..``self.num_channels-1`` to the channels in
channel_map
.- Parameters
channel_map (ArrayLike[int]) – List of channels that existing channels should be mapped to, in order. Must be of size
self.num_channels
.inplace (bool) – Specify whether operation should be performed in place (Default:
False
, a copy is returned)
- save(path: Union[str, pathlib.Path], verbose: bool = False, dtype_times: Union[None, str, type, numpy.dtype] = None, dtype_channels: Union[None, str, type, numpy.dtype] = None)[source]
Save this
TSEvent
as annpz
file usingnp.savez()
- Parameters
path (str) – Path to save file
verbose (bool) – Print path information after successfully saving.
dtype_times (Union[None, str, type, np.dtype]) – Data type in which
times
are to be stored, for example to save space.dtype_channels (Union[None, str, type, np.dtype]) – Data type in which
channels
are to be stored, for example to save space.
- set_plotting_backend(backend: Optional[str], 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) timeseries.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) timeseries.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_dict(dtype_times: Union[None, str, type, numpy.dtype] = None, dtype_channels: Union[None, str, type, numpy.dtype] = None) Dict [source]
Store data and attributes of this
TSEvent
in aDict
.- Parameters
dtype_times (Union[None, str, type, np.dtype]) – Data type in which
times
are to be returned, for example to save space.dtype_channels (Union[None, str, type, np.dtype]) – Data type in which
channels
are to be returned, for example to save space.
- Returns
Dict with data and attributes of this
TSEvent
.
- xraster(dt: float, t_start: Optional[float] = None, t_stop: Optional[float] = None, num_timesteps: Optional[int] = None, channels: Optional[numpy.ndarray] = None, add_events: Optional[bool] = None, endpoint: Optional[bool] = None) numpy.ndarray [source]
Generator which
yield
s a rasterized time series data, where each data point represents a time stepEvents are represented in a boolean matrix, where the first axis corresponds to time, the second axis to the channel. Events that happen between time steps are projected to the preceding one. If two events happen during one time step within a single channel, they are counted as one.
- Parameters
dt (float) – Duration of single time step in raster
t_start (Optional[float]) – Time where to start raster. Default:
None
(useself.t_start
)t_stop (Optional[float]) – Time where to stop raster. This time point is not included in the raster. Default:
None
(useself.t_stop
. Ifnum_timesteps
is provided,t_stop
is ignored.num_timesteps (Optional[int]) – Specify number of time steps directly, instead of providing
t_stop
. Default:None
(uset_start
,t_stop
anddt
to determine raster size.channels (Optional[ArrayLike[int]]) – Channels from which data is to be used. Default:
None
(use all channels)add_events (Optional[bool]) – If
True
, return an integer raster containing number of events for each time step and channel. Default:False
, merge simultaneous events in a single channel, and return a boolean rasterendpoint (Optional[bool]) – If
True
, an extra time bin is added to the raster aftert_stop
, to ensure that any events occurring att_stop
are included in the raster. Default:False
, do not include events occurring att_stop
.
- Yields ArrayLike
event_raster - Boolean matrix with
True
indicating presence of events for each time step and channel. Ifadd_events == True
, the raster consists of integers indicating the number of events per time step and channel. First axis corresponds to time, second axis to channel.