Skip to content

Extracellular electrophysiology: cicada_tools.ephys

from cicada_analysis.cicada_tools.ephys.<module> import <function>


ephys.ephys_plots (Raster plotting)

  • render_spikes

render_spikes(ax, spike_nums, frame_times=None, spike_train_format=False, spike_shape='|', cell_spikes_color='white', cells_to_highlight=None, cells_to_highlight_colors=None, ...) -> dict

Draw a spike raster on ax: a binary or float (n_cells, n_frames) raster, or spike trains. About 45 more optional parameters (amplitude colouring, sequence links, highlighted cells, horizontal lines, traces, scales, colours): see the docstring.

Parameter Type Default Description
ax matplotlib Axes Axes to draw on
spike_nums np.ndarray | list (n_cells, n_frames) raster, or one array of spike times per cell with spike_train_format=True
frame_times np.ndarray None Time of each frame in seconds (raster only; frame indices when None)
spike_train_format bool False spike_nums holds spike times
spike_shape str '|' Marker: '\|', '*' or 'o'
cell_spikes_color str 'white' Spike colour
cells_to_highlight array-like None Cells drawn in their own colour
cells_to_highlight_colors list None Colours of the highlighted cells

Returns: dict — min_time, max_time and the sequence link labels (links_labels, links_labels_color, links_labels_y_coord), used to decorate the axes

  • estimate_spike_raster_peak_gb

estimate_spike_raster_peak_gb(n_spikes) -> float

Estimate of the peak memory of drawing n_spikes spikes with render_spikes (spike shape '|'), measured on real files: 1.3 GB + 0.155 GB per million spikes above 500,000 spikes (drawn as one line per unit), 1.35 GB per million below (one segment per spike). An estimate, not a bound.

Parameter Type Description
n_spikes int Number of spikes to draw

Returns: float — estimated peak memory in GB


ephys.psth_utils (Spike-train PSTH)

Counterpart to imaging.psth_utils, operating on spike trains instead of fluorescence traces.

  • compute_psth

compute_psth(spike_times, event_times, window_start, window_end, bin_size) -> (psth, time)

Event-aligned PSTH for a population of units via searchsorted + histogram2d. psth shape (n_events, n_bins, n_units) in Hz; time = right bin edges (avoids activity "predicting" the future).

Parameter Type Description
spike_times list Spike times per unit
event_times np.ndarray Event times
window_start float Start of the window relative to each event, in seconds (negative before the event, e.g. -0.5)
window_end float End of the window relative to each event, in seconds (extended to a whole number of bins)
bin_size float Bin size in seconds

Returns: tuple — (psth, time) where psth is (n_events, n_bins, n_units) in Hz

  • unit_psth_table

unit_psth_table(binned, time, unit_ids, reduction="median", band="percentiles", low_percentile=25, high_percentile=75, baseline_duration=0.0, baseline_correction=False, zscore=False) -> pd.DataFrame

PSTH of each unit over the events of compute_psth's output: line and band over the events (stats.array_line_and_band), then the unit's baseline subtracted (and z-scored) with apply_baseline, the band moved with the line. One row per unit and bin.

Parameter Type Default Description
binned np.ndarray Binned spike counts
time np.ndarray Time values
unit_ids list Unit IDs
reduction str "median" Reduction method
band str "percentiles" Band type
low_percentile float 25 Lower percentile
high_percentile float 75 Upper percentile
baseline_duration float 0.0 Baseline duration
baseline_correction bool False Apply baseline correction
zscore bool False Z-score by baseline

Returns: pd.DataFrame — Unit PSTH table

  • spikes_around_events

spikes_around_events(spikes, event_times, t_before, t_after) -> list

One unit's spikes in [t - t_before, t + t_after) of each event, relative to it (for rasters).

Parameter Type Description
spikes list Spike times
event_times np.ndarray Event times
t_before float Pre-event time
t_after float Post-event time

Returns: list — Spikes relative to events

  • apply_baseline

apply_baseline(peth_matrix, time, baseline_duration, zscore=False) -> (corrected, bl_std)

Subtracts (and optionally z-scores by) the baseline mean/std computed over bins whose right edge falls in [-baseline_duration, 0].

Parameter Type Default Description
peth_matrix np.ndarray PETH matrix
time np.ndarray Time values
baseline_duration float Baseline duration
zscore bool False Z-score by baseline

Returns: tuple — (corrected, bl_std)


ephys.anatomy_utils (CCF anatomy lookups)

Loads ephys/structures.json (the Allen CCF brain-structure list) at import time to build bidirectional acronym/name lookup maps and a custom coarse area-group taxonomy: the constants AREA_GROUPS ({group name: [CCF acronyms]}) and AREA_GROUP_COLORS ({group name: color}, for consistent plotting).

  • map_to_area_groups

map_to_area_groups(series: pd.Series) -> pd.Series

Map a Series of CCF acronyms/names to their coarse area group.

Parameter Type Description
series pd.Series Series of CCF acronyms/names

Returns: pd.Series — Mapped area groups

  • select_units_by_area

select_units_by_area(unit_areas, items) -> list

Units whose area, or the area group of their area (map_to_area_groups), is one of items. Areas outside every group map to 'Other', so the item 'Other' selects them.

Parameter Type Description
unit_areas dict {unit id: area}, the area as a CCF acronym or full structure name
items list Areas and / or area group names (keys of AREA_GROUPS)

Returns: list — unit ids, in the order of unit_areas


ephys.ccf_plot_utils (Unit positions in the brain atlas)

  • resolve_unit_positions

resolve_unit_positions(coords_df, units_df, unit_ids) -> dict

Positions of the units, from the first source available for every unit of unit_ids: 1. CCF atlas coordinates (ccf_atlas_ap, ccf_atlas_ml, ccf_atlas_dv), 2. raw electrode coordinates (x, y, z), 3. probe depth (depth or probe_depth column of units_df) and electrode group, for a schematic layout. A source is skipped when a unit is missing from coords_df or has a NaN coordinate.

Parameter Type Description
coords_df pd.DataFrame | None Indexed by unit id, with the CCF and / or raw coordinate columns (e.g. electrophysiology.get_units_coordinates)
units_df pd.DataFrame | None Units table indexed by unit id, for the depth source only
unit_ids list Units to place, in the order of the returned lists

Returns: dict — {'kind': 'ccf', 'a': ap, 'b': ml, 'c': dv} (DV negated, so dorsal is up), {'kind': 'raw', 'a': x, 'b': y, 'c': z}, {'kind': 'depth', 'depths': [...], 'probe_names': [...]} ('probe' without electrode group), or {'kind': None}; lists of floats in the order of unit_ids


ephys.ephys_signal_processing (Filtering, spike binning, smoothing and artifact removal)

  • butterworth_filter

butterworth_filter(values, rate, low_hz=None, high_hz=None, order=4, axis=-1) -> np.ndarray

Zero-phase Butterworth filter (forward-backward, scipy.signal.sosfiltfilt) for sampled signals (LFP, ECoG...): band-pass with both cutoffs, high-pass with low_hz only, low-pass with high_hz only. NaN gaps are kept: each finite stretch is filtered on its own, and a stretch too short for the filter's edge padding becomes NaN. Without NaN, exactly sosfiltfilt on the whole signal.

Parameter Type Default Description
values np.ndarray Signal(s), filtered along axis
rate float Sampling rate (Hz)
low_hz float None Lower cutoff (Hz): frequencies below are removed
high_hz float None Upper cutoff (Hz): frequencies above are removed
order int 4 Filter order (the forward-backward pass doubles it)
axis int -1 Time axis

Returns: np.ndarray — filtered signal, same shape; same dtype if floating, else float64

Raises: ValueError — no cutoff given, a cutoff not between 0 and rate / 2, or low_hz >= high_hz

  • replace_artifact_spikes

replace_artifact_spikes(spike_times, event_times, artifact_window=(-0.01, 0.005), baseline_window=(-0.5, -0.01), seed=None) -> list[numpy.ndarray]

Remove the spikes in [event + start, event + end) of artifact_window around each event (stimulation artifacts), and insert surrogates instead: per unit and event, a Poisson number of spikes with the unit's rate in that event's baseline_window, spread uniformly in the artifact window. Works on the spike times before binning. With no event, copies of spike_times are returned.

Parameter Type Default Description
spike_times list[np.ndarray] Sorted spike times (s), one array per unit
event_times np.ndarray Event times (s)
artifact_window tuple (-0.01, 0.005) (start, end) relative to each event (s)
baseline_window tuple (-0.5, -0.01) (start, end) relative to each event (s), for the rate
seed int None Seed of np.random.default_rng

Returns: list[numpy.ndarray] — sorted spike times, one array per unit, in the order of spike_times

  • compute_rolling_binned_activity

compute_rolling_binned_activity(spike_times_list, bin_size_ms, step_ms, duration_s) -> (binned, time_axis_s)

Rolling/overlapping-window spike counts per unit via compute_psth at step resolution + cumsum rolling sum.

Parameter Type Description
spike_times_list list Spike times per unit
bin_size_ms float Bin size in milliseconds
step_ms float Step size in milliseconds
duration_s float Duration in seconds

Returns: tuple — (binned, time_axis_s)

  • binarize_activity

binarize_activity(binned_activity, threshold=0) -> np.ndarray

Thresholds any numeric activity array to binary presence/absence.

Parameter Type Default Description
binned_activity np.ndarray Binned activity
threshold float 0 Threshold value

Returns: np.ndarray — Binary activity

  • smooth_causal_half_gaussian

smooth_causal_half_gaussian(x, sigma, dt, axis=1) -> np.ndarray

Causal (one-sided) half-Gaussian smoothing along axis, so post-event activity can't leak into the baseline.

Parameter Type Default Description
x np.ndarray Input array
sigma float Sigma parameter
dt float Time step
axis int 1 Axis to smooth along

Returns: np.ndarray — Smoothed array


ephys.signal_psth (PSTH of continuous signals: LFP, ECoG)

Channels and frequency bands of a continuous signal, the band's signal (filtered, amplitude envelope or power) in time bins around each event, and the line and band over the events of a channel group. Constants: FREQUENCY_BANDS ({name: (low_hz, high_hz)}: delta 1-4, theta 4-8, alpha 8-12, beta 12-30, low gamma 30-60, high gamma 60-100 Hz) and BAND_MEASURES ('filtered signal', 'amplitude envelope', 'power').

The steps of the PSTH, as in the PSTH ephys - electrical series plugin: band_measure on the whole signal, window_bins once, bin_window for each event, then channels_psth on the stacked windows of a channel group.

  • band_labels

band_labels() -> list[str]

Labels of FREQUENCY_BANDS, e.g. 'theta (4-8 Hz)', read back by parse_frequency_band.

Returns: list[str] — one label per band

  • parse_frequency_band

parse_frequency_band(text) -> tuple | None

The band of a text: the first low-high in it (decimals and spaces allowed), e.g. '4-8', '4 - 8 Hz' or a label 'theta (4-8 Hz)'.

Parameter Type Description
text str Band as typed or as a label

Returns: tuple | None — (low_hz, high_hz) floats; None without low-high, or unless 0 < low < high

  • group_band

group_band(items) -> tuple | None

The band covered by a group of bands: from the lowest to the highest frequency of its items (parse_frequency_band of each).

Parameter Type Description
items list Bands, typed or as labels

Returns: tuple | None — (low_hz, high_hz); None when the group is empty or an item is not a band

  • edge_padding

edge_padding(cutoffs_hz, n_cycles=3) -> float

Time read on each side of a window so that filtering it has no edge effect inside: n_cycles periods of the lowest cutoff. None and 0 cutoffs are ignored.

Parameter Type Default Description
cutoffs_hz list Cutoffs (Hz) of the filter
n_cycles int 3 Periods of the lowest cutoff

Returns: float — padding in seconds; 0.0 without cutoff

  • channel_labels

channel_labels(electrode_groups, locations, n_channels) -> list[tuple]

The names a channel group can use for each channel of a series: its electrode group, its location and its own name ('channel 3 (shank1)', or 'channel 3' without group).

Parameter Type Description
electrode_groups list | None Electrode group of each channel
locations list | None Location of each channel
n_channels int Number of channels of the series

Returns: list[tuple] — (electrode group, location, own name) per channel; None where not given

  • select_channels

select_channels(items, channel_labels, n_channels) -> np.ndarray

Positions of the channels of a group, in the group's order, each once: for each item, the channels having it among their labels; when none has it, the item is read as typed indices ('0-7 12') and those below n_channels are kept.

Parameter Type Description
items list | None Electrode groups, locations, channel names or typed indices; None: every channel
channel_labels list Labels of each channel (channel_labels)
n_channels int Number of channels of the series

Returns: np.ndarray — int positions of the channels in the series

  • band_measure

band_measure(values, rate, band=None, measure="filtered signal", order=4) -> np.ndarray

One frequency band of signals: zero-phase Butterworth band-pass (butterworth_filter), then the measure: 'filtered signal', 'amplitude envelope' (modulus of the analytic signal, Hilbert) or 'power' (envelope squared; any other value gives the power too). NaN gaps are kept: each finite stretch on its own.

Parameter Type Default Description
values np.ndarray (n_channels, n_times)
rate float Sampling rate (Hz)
band tuple None (low_hz, high_hz); None: not filtered
measure str "filtered signal" One of BAND_MEASURES
order int 4 Filter order

Returns: np.ndarray — (n_channels, n_times)

  • window_bins

window_bins(t_before, t_after, bin_size) -> np.ndarray

Edges of the time bins around an event, from -t_before, bin_size wide: round((t_before + t_after) / bin_size) bins (at least one), so the last edge can differ slightly from t_after.

Parameter Type Description
t_before float Time before the event (s)
t_after float Time after the event (s)
bin_size float Bin width (s)

Returns: np.ndarray — n_bins + 1 edges (s, relative to the event)

  • bin_window

bin_window(values, times, event_time, edges) -> np.ndarray

Signals around one event in time bins: the mean of the finite samples of each channel in each bin [edges[i], edges[i + 1]) of the times relative to event_time.

Parameter Type Description
values np.ndarray (n_channels, n_times)
times np.ndarray Time of each sample (s)
event_time float Event time (s)
edges np.ndarray Bin edges (window_bins)

Returns: np.ndarray — (n_channels, n_bins); NaN for a bin without sample

  • channels_psth

channels_psth(aligned, time, channel_reduction="mean", baseline="none", t_before=None, reduction="median", band="percentiles", low_percentile=25, high_percentile=75) -> (line, low, high)

PSTH of a group of channels: the channels reduced at each event and bin (NaN ignored); each event against its own baseline, the bins whose centre is in [-t_before, 0] (apply_baseline); then the line and band over the events (stats.array_line_and_band).

Parameter Type Default Description
aligned np.ndarray (n_events, n_channels, n_bins): bin_window of each event
time np.ndarray (n_bins,) bin centres (s)
channel_reduction str "mean" 'mean' or 'median' over the channels
baseline str "none" 'none', 'subtract' (the baseline mean) or 'z-score'
t_before float None Baseline duration (s); needed with a baseline
reduction str "median" Line over the events: 'median' or 'mean'
band str "percentiles" Band over the events: 'SD', 'SEM', '95% CI', 'percentiles' or 'none'
low_percentile float 25 Lower percentile (band 'percentiles')
high_percentile float 75 Upper percentile (band 'percentiles')

Returns: tuple — (line, low, high), each (n_bins,)

Raises: ValueError — with a baseline, when no bin centre falls in [-t_before, 0] (apply_baseline)