brainbox.plot
Plots metrics that assess quality of single units. Some functions here generate plots for the output of functions in the brainbox single_units.py module.
Run the following to set-up the workspace to run the docstring examples: >>> from brainbox import processing >>> import one.alf.io as alfio >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import ibllib.ephys.spikes as e_spks # (*Note, if there is no ‘alf’ directory, make ‘alf’ directory from ‘ks2’ output directory): >>> e_spks.ks2_to_alf(path_to_ks_out, path_to_alf_out) # Load the alf spikes bunch and clusters bunch, and get a units bunch. >>> spks_b = alfio.load_object(path_to_alf_out, ‘spikes’) >>> clstrs_b = alfio.load_object(path_to_alf_out, ‘clusters’) >>> units_b = processing.get_units_bunch(spks_b) # may take a few mins to compute
Functions
Plots a heatmap of the normalized voltage values over time and space for given timestamps and channels, after (optionally) common-average-referencing. |
|
Plots the values of a spike feature array (y-axis) over time (x-axis). |
|
Plots the driftmap of a session or a trial |
|
Plots the coefficients of variation of a particular spike feature for all units as a bar plot, where each bar is color-coded corresponding to the depth of the max amplitude channel of the respective unit. |
|
Plots the instantaneous firing rate of for given spike timestamps over time, and optionally overlays the value of the coefficient of variation of the firing rate for a specified number of bins. |
|
Plots the pdf of an estimated symmetric spike feature distribution, with a vertical cutoff line that indicates the approximate fraction of spikes missing from the distribution, assuming the true distribution is symmetric. |
|
Plot peri-event time histograms, with the meaning firing rate of units centered on a given series of events. |
|
Plots the presence ratio of spike counts: the number of bins where there is at least one spike, over the total number of bins, given a specified bin width. |
|
Plots two different sets of waveforms across specified channels after (optionally) common-average-referencing. |
- feat_vars(units_b, units=None, feat_name='amps', dist='norm', test='ks', cmap_name='coolwarm', ax=None)[source]
Plots the coefficients of variation of a particular spike feature for all units as a bar plot, where each bar is color-coded corresponding to the depth of the max amplitude channel of the respective unit.
- Parameters:
units_b (bunch) – A units bunch containing fields with spike information (e.g. cluster IDs, times, features, etc.) for all units.
units (array-like (optional)) – A subset of all units for which to create the bar plot. (If None, all units are used)
feat_name (string (optional)) – The spike feature to plot.
dist (string (optional)) – The type of hypothetical null distribution from which the empirical spike feature distributions are presumed to belong to.
test (string (optional)) – The statistical test used to calculate the probability that the empirical spike feature distributions come from dist.
cmap_name (string (optional)) – The name of the colormap associated with the plot.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
cv_vals (ndarray) – The coefficients of variation of feat_name for each unit.
p_vals (ndarray) – The probabilites that the distribution for feat_name for each unit comes from a dist distribution based on the test statistical test.
See also
metrics.unit_stability
Examples
- Create a bar plot of the coefficients of variation of the spike amplitudes for all units.
>>> fig, var_vals, p_vals = bb.plot.feat_vars(units_b)
- missed_spikes_est(feat, feat_name, spks_per_bin=20, sigma=5, min_num_bins=50, ax=None)[source]
Plots the pdf of an estimated symmetric spike feature distribution, with a vertical cutoff line that indicates the approximate fraction of spikes missing from the distribution, assuming the true distribution is symmetric.
- Parameters:
feat (ndarray) – The spikes’ feature values.
feat_name (string) – The spike feature to plot.
spks_per_bin (int (optional)) – The number of spikes per bin from which to compute the spike feature histogram.
sigma (int (optional)) – The standard deviation for the gaussian kernel used to compute the pdf from the spike feature histogram.
min_num_bins (int (optional)) – The minimum number of bins used to compute the spike feature histogram.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
fraction_missing – The fraction of missing spikes (0-0.5). *Note: If more than 50% of spikes are missing, an accurate estimate isn’t possible.
- Return type:
float
See also
single_units.feature_cutoff
Examples
1) Plot cutoff line indicating the fraction of spikes missing from a unit based on the recorded unit’s spike amplitudes, assuming the distribution of the unit’s spike amplitudes is symmetric.
>>> feat = units_b['amps']['1'] >>> fraction_missing = bb.plot.missed_spikes_est(feat, feat_name='amps', unit=1)
- wf_comp(ephys_file, ts1, ts2, ch, sr=30000, n_ch_probe=385, dtype='int16', car=True, col=['b', 'r'], ax=None)[source]
Plots two different sets of waveforms across specified channels after (optionally) common-average-referencing. In this way, waveforms can be compared to see if there is, e.g. drift during the recording, or if two units should be merged, or one unit should be split.
- Parameters:
ephys_file (string) – The file path to the binary ephys data.
ts1 (array_like) – A set of timestamps for which to compare waveforms with ts2.
ts2 (array_like) – A set of timestamps for which to compare waveforms with ts1.
ch (array-like) – The channels to use for extracting and plotting the waveforms.
sr (int (optional)) – The sampling rate (in hz) that the ephys data was acquired at.
n_ch_probe (int (optional)) – The number of channels of the recording.
dtype (str (optional)) – The datatype represented by the bytes in ephys_file.
car (bool (optional)) – A flag for whether or not to perform common-average-referencing before extracting waveforms
col (list of strings or float arrays (optional)) – Two elements in the list, where each specifies the color the ts1 and ts2 waveforms will be plotted in, respectively.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
wf1 (ndarray) – The waveforms for the spikes in ts1: an array of shape (#spikes, #samples, #channels).
wf2 (ndarray) – The waveforms for the spikes in ts2: an array of shape (#spikes, #samples, #channels).
s (float) – The similarity score between the two sets of waveforms, calculated by single_units.wf_similarity
See also
io.extract_waveforms
,single_units.wf_similarity
Examples
1) Compare first and last 100 spike waveforms for unit1, across 20 channels around the channel of max amplitude, and compare the waveforms in the first minute to the waveforms in the fourth minutes for unit2, across 10 channels around the mean.
# Get first and last 100 spikes, and 20 channels around channel of max amp for unit 1: >>> ts1 = units_b[‘times’][‘1’][:100] >>> ts2 = units_b[‘times’][‘1’][-100:] >>> max_ch = clstrs_b[‘channels’][1] >>> if max_ch < n_c_ch: # take only channels greater than max_ch. >>> ch = np.arange(max_ch, max_ch + 20) >>> elif (max_ch + n_c_ch) > n_ch_probe: # take only channels less than max_ch. >>> ch = np.arange(max_ch - 20, max_ch) >>> else: # take n_c_ch around max_ch. >>> ch = np.arange(max_ch - 10, max_ch + 10) >>> wf1, wf2, s = bb.plot.wf_comp(path_to_ephys_file, ts1, ts2, ch) # Plot waveforms for unit2 from the first and fourth minutes across 10 channels. >>> ts = units_b[‘times’][‘2’] >>> ts1_2 = ts[np.where(ts<60)[0]] >>> ts2_2 = ts[np.where(ts>180)[0][:len(ts1)]] >>> max_ch = clstrs_b[‘channels’][2] >>> if max_ch < n_c_ch: # take only channels greater than max_ch. >>> ch = np.arange(max_ch, max_ch + 10) >>> elif (max_ch + n_c_ch) > n_ch_probe: # take only channels less than max_ch. >>> ch = np.arange(max_ch - 10, max_ch) >>> else: # take n_c_ch around max_ch. >>> ch = np.arange(max_ch - 5, max_ch + 5) >>> wf1_2, wf2_2, s_2 = bb.plot.wf_comp(path_to_ephys_file, ts1_2, ts2_2, ch)
- amp_heatmap(ephys_file, ts, ch, sr=30000, n_ch_probe=385, dtype='int16', cmap_name='RdBu', car=True, ax=None)[source]
Plots a heatmap of the normalized voltage values over time and space for given timestamps and channels, after (optionally) common-average-referencing.
- Parameters:
ephys_file (string) – The file path to the binary ephys data.
ts (array_like) – A set of timestamps for which to get the voltage values.
ch (array-like) – The channels to use for extracting the voltage values.
sr (int (optional)) – The sampling rate (in hz) that the ephys data was acquired at.
n_ch_probe (int (optional)) – The number of channels of the recording.
dtype (str (optional)) – The datatype represented by the bytes in ephys_file.
cmap_name (string (optional)) – The name of the colormap associated with the plot.
car (bool (optional)) – A flag for whether or not to perform common-average-referencing before extracting waveforms
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
v_vals – The voltage values.
- Return type:
ndarray
Examples
1) Plot a heatmap of the spike amplitudes across 20 channels around the channel of max amplitude for all spikes in unit 1.
>>> ts = units_b['times']['1'] >>> max_ch = clstrs_b['channels'][1] >>> if max_ch < n_c_ch: # take only channels greater than `max_ch`. >>> ch = np.arange(max_ch, max_ch + 20) >>> elif (max_ch + n_c_ch) > n_ch_probe: # take only channels less than `max_ch`. >>> ch = np.arange(max_ch - 20, max_ch) >>> else: # take `n_c_ch` around `max_ch`. >>> ch = np.arange(max_ch - 10, max_ch + 10) >>> bb.plot.amp_heatmap(path_to_ephys_file, ts, ch)
- firing_rate(ts, hist_win=0.01, fr_win=0.5, n_bins=10, show_fr_cv=True, ax=None)[source]
Plots the instantaneous firing rate of for given spike timestamps over time, and optionally overlays the value of the coefficient of variation of the firing rate for a specified number of bins.
- Parameters:
ts (ndarray) – The spike timestamps from which to compute the firing rate.
hist_win (float (optional)) – The time window (in s) to use for computing spike counts.
fr_win (float (optional)) – The time window (in s) to use as a moving slider to compute the instantaneous firing rate.
n_bins (int (optional)) – The number of bins in which to compute coefficients of variation of the firing rate.
show_fr_cv (bool (optional)) – A flag for whether or not to compute and show the coefficients of variation of the firing rate for n_bins.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
fr (ndarray) – The instantaneous firing rate over time (in hz).
cv (float) – The mean coefficient of variation of the firing rate of the n_bins number of coefficients computed. Can only be returned if show_fr_cv is True.
cvs (ndarray) – The coefficients of variation of the firing for each bin of n_bins. Can only be returned if show_fr_cv is True.
See also
single_units.firing_rate_cv
,singecell.firing_rate
Examples
1) Plot the firing rate for unit 1 from the time of its first to last spike, showing the cv of the firing rate for 10 evenly spaced bins.
>>> ts = units_b['times']['1'] >>> fr, cv, cvs = bb.plot.firing_rate(ts)
- peri_event_time_histogram(spike_times, spike_clusters, events, cluster_id, t_before=0.2, t_after=0.5, bin_size=0.025, smoothing=0.025, as_rate=True, include_raster=False, n_rasters=None, error_bars='std', ax=None, pethline_kwargs={'color': 'blue', 'lw': 2}, errbar_kwargs={'alpha': 0.5, 'color': 'blue'}, eventline_kwargs={'alpha': 0.5, 'color': 'black'}, raster_kwargs={'color': 'black', 'lw': 0.5}, **kwargs)[source]
Plot peri-event time histograms, with the meaning firing rate of units centered on a given series of events. Can optionally add a raster underneath the PETH plot of individual spike trains about the events.
- Parameters:
spike_times (array_like) – Spike times (in seconds)
spike_clusters (array-like) – Cluster identities for each element of spikes
events (array-like) – Times to align the histogram(s) to
cluster_id (int) – Identity of the cluster for which to plot a PETH
t_before (float, optional) – Time before event to plot (default: 0.2s)
t_after (float, optional) – Time after event to plot (default: 0.5s)
bin_size (float, optional) – Width of bin for histograms (default: 0.025s)
smoothing (float, optional) – Sigma of gaussian smoothing to use in histograms. (default: 0.025s)
as_rate (bool, optional) – Whether to use spike counts or rates in the plot (default: True, uses rates)
include_raster (bool, optional) – Whether to put a raster below the PETH of individual spike trains (default: False)
n_rasters (int, optional) – If include_raster is True, the number of rasters to include. If None will default to plotting rasters around all provided events. (default: None)
error_bars ({'std', 'sem', 'none'}, optional) – Defines which type of error bars to plot. Options are: – ‘std’ for 1 standard deviation – ‘sem’ for standard error of the mean – ‘none’ for only plotting the mean value (default: ‘std’)
ax (matplotlib axes, optional) – If passed, the function will plot on the passed axes. Note: current behavior causes whatever was on the axes to be cleared before plotting! (default: None)
pethline_kwargs (dict, optional) – Dict containing line properties to define PETH plot line. Default is a blue line with weight of 2. Needs to have color. See matplotlib plot documentation for more options. (default: {‘color’: ‘blue’, ‘lw’: 2})
errbar_kwargs (dict, optional) – Dict containing fill-between properties to define PETH error bars. Default is a blue fill with 50 percent opacity.. Needs to have color. See matplotlib fill_between documentation for more options. (default: {‘color’: ‘blue’, ‘alpha’: 0.5})
eventline_kwargs (dict, optional) – Dict containing fill-between properties to define line at event. Default is a black line with 50 percent opacity.. Needs to have color. See matplotlib vlines documentation for more options. (default: {‘color’: ‘black’, ‘alpha’: 0.5})
raster_kwargs (dict, optional) – Dict containing properties defining lines in the raster plot. Default is black lines with line width of 0.5. See matplotlib vlines for more options. (default: {‘color’: ‘black’, ‘lw’: 0.5})
- Returns:
ax – Axes with all of the plots requested.
- Return type:
matplotlib axes
- driftmap(ts, feat, ax=None, plot_style='bincount', t_bin=0.01, d_bin=20, weights=None, vmax=None, **kwargs)[source]
Plots the values of a spike feature array (y-axis) over time (x-axis). Two arguments can be given for the plot_style of the drift map: - ‘scatter’ : whereby each value is plotted as a marker (up to 100’000 data point) - ‘bincount’ : whereby the values are binned (optimised to represent spike raster)
- Parameters:
feat (ndarray) – The spikes’ feature values.
ts (ndarray) – The spike timestamps from which to compute the firing rate.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
t_bin (time bin used when plot_style='bincount')
d_bin (depth bin used when plot_style='bincount')
plot_style ('scatter', 'bincount')
**kwargs (matplotlib.imshow arguments)
- Returns:
cd (float) – The cumulative drift of feat.
md (float) – The maximum drift of feat.
See also
metrics.cum_drift
,metrics.max_drift
Examples
- Plot the amplitude driftmap for unit 1.
>>> ts = units_b['times']['1'] >>> amps = units_b['amps']['1'] >>> ax = bb.plot.driftmap(ts, amps)
- Plot the depth driftmap for unit 1.
>>> ts = units_b['times']['1'] >>> depths = units_b['depths']['1'] >>> ax = bb.plot.driftmap(ts, depths)
- pres_ratio(ts, hist_win=10, ax=None)[source]
Plots the presence ratio of spike counts: the number of bins where there is at least one spike, over the total number of bins, given a specified bin width.
- Parameters:
ts (ndarray) – The spike timestamps from which to compute the presence ratio.
hist_win (float) – The time window (in s) to use for computing the presence ratio.
ax (axessubplot (optional)) – The axis handle to plot the histogram on. (if None, a new figure and axis is created)
- Returns:
pr (float) – The presence ratio.
spks_bins (ndarray) – The number of spks in each bin.
See also
metrics.pres_ratio
Examples
- Plot the presence ratio for unit 1, given a window of 10 s.
>>> ts = units_b['times']['1'] >>> pr, pr_bins = bb.plot.pres_ratio(ts)
- driftmap_color(clusters_depths, spikes_times, spikes_amps, spikes_depths, spikes_clusters, ax=None, axesoff=False, return_lims=False)[source]
Plots the driftmap of a session or a trial
The plot shows the spike times vs spike depths. Each dot is a spike, whose color indicates the cluster and opacity indicates the spike amplitude.
- Parameters:
clusters_depths (ndarray) – depths of all clusters
spikes_times (ndarray) – spike times of all clusters
spikes_amps (ndarray) – amplitude of each spike
spikes_depths (ndarray) – depth of each spike
spikes_clusters (ndarray) – cluster idx of each spike
ax (matplotlib.axes.Axes object (optional)) – The axis object to plot the driftmap on (if None, a new figure and axis is created)
- Returns:
ax (matplotlib.axes.Axes object) – The axis object with driftmap plotted
x_lim (list of two elements) – range of x axis
y_lim (list of two elements) – range of y axis