2P imaging: cicada_tools.imaging¶
from cicada_analysis.cicada_tools.imaging.<module> import <function>
imaging.calcium_signal_processing (Signal processing)¶
-
norm01¶
norm01(data) -> np.ndarray
Normalize an array to [0, 1] in all dimensions. Returns unchanged if max == min.
| Parameter | Type | Description |
|---|---|---|
data |
np.ndarray | Input array |
Returns: np.ndarray — Normalized array
-
gauss_blur_1d¶
gauss_blur_1d(data, dw, dim) -> np.ndarray
Apply a 1-D Gaussian blur in the Fourier domain along 1 axis.
| Parameter | Type | Description |
|---|---|---|
data |
np.ndarray | Input array |
dw |
float | Gaussian width |
dim |
int | Axis to blur along |
Returns: np.ndarray — Blurred array
-
gauss_blur¶
gauss_blur(data, dw) -> np.ndarray
Apply a 2-D Gaussian filter in the Fourier domain on the two dimensions.
| Parameter | Type | Description |
|---|---|---|
data |
np.ndarray | Input array |
dw |
float | Gaussian width |
Returns: np.ndarray — Blurred array
-
median_normalization¶
median_normalization(traces) -> np.ndarray
Normalize each row of a (n_cells, n_frames) array by its own median: (trace - median) / median. Returns normalized array of same shape.
| Parameter | Type | Description |
|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) array |
Returns: np.ndarray — Normalized traces
-
zscore_normalization¶
zscore_normalization(traces) -> np.ndarray
Normalize each row of a (n_cells, n_frames) array by its own mean and std: (trace - mean) / std. Returns normalized array of same shape.
| Parameter | Type | Description |
|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) array |
Returns: np.ndarray — Normalized traces
-
transient_amplitudes¶
transient_amplitudes(raster, traces, peak_minus_onset=True, max_negative_fraction=0.05) -> tuple
Amplitude of each transient (run of 1s of raster) measured on traces: (cells, onsets, amplitudes), one entry per transient. peak_minus_onset (transients over several frames): trace at the last two frames minus trace at the frame before and the onset, transients at frame 0 left out; otherwise the maximum of the trace over the transient. Negative amplitudes are NaN, with a warning above max_negative_fraction.
| Parameter | Type | Default | Description |
|---|---|---|---|
raster |
np.ndarray | Binary raster | |
traces |
np.ndarray | Fluorescence traces | |
peak_minus_onset |
bool | True | Use peak-minus-onset method |
max_negative_fraction |
float | 0.05 | Warning threshold for negative amplitudes |
Returns: tuple — (cells, onsets, amplitudes)
-
bleaching_correction¶
bleaching_correction(traces) -> np.ndarray
Correct photobleaching by dividing each cell trace by a cubic polynomial fit.
| Parameter | Type | Description |
|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) array |
Returns: np.ndarray — Bleaching-corrected traces
-
savitzky_golay_filt¶
savitzky_golay_filt(traces, sr) -> np.ndarray
Apply a Savitzky-Golay smoothing filter (window = 0.5 s, order 3) along axis 1.
| Parameter | Type | Description |
|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) array |
sr |
float | Sampling rate in Hz |
Returns: np.ndarray — Smoothed traces
-
detect_small_transients¶
detect_small_transients(traces, speed=None, use_speed=False, speed_threshold=None, detection_method='rolling-window', window_size=None, min_small_transient_amp=0, imaging_rate=10, frames_mask=None) -> tuple
Detect small calcium transients (below burst threshold) in fluorescence traces.
| Parameter | Type | Default | Description |
|---|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) array |
|
speed |
np.ndarray | None | Running speed at each frame |
use_speed |
bool | False | Detect only while immobile: 'rolling-window' leaves out frames with a speed above speed_threshold (a NaN speed is kept); 'Find-Peaks' keeps peaks with a speed below it (a NaN speed is left out) |
speed_threshold |
float | None | Speed threshold |
detection_method |
str | 'rolling-window' | Method: 'rolling-window' or 'Find-Peaks' |
window_size |
int | None | Window size, in frames |
min_small_transient_amp |
float | 0 | Minimum amplitude |
imaging_rate |
float | 10 | Imaging rate in Hz |
frames_mask |
np.ndarray | None | Boolean per frame: where transients may be detected (e.g. an epoch), with the speed filter; None: every frame. Each frame is still judged on the full trace |
Returns: tuple — (small_transients_raster, small_transients_activity) where raster is (n_cells, n_frames) binary and activity is a list-of-lists of trace snippets
-
give_unique_id_to_each_transient_of_raster_dur¶
give_unique_id_to_each_transient_of_raster_dur(raster_dur) -> np.ndarray
Assign a unique integer ID to each transient in a binary raster duration array.
Example:
binary raster (input): 0 0 1 1 1 0 0 0 1 1 0 0
labeled raster (output): -1 -1 0 0 0 -1 -1 -1 1 1 -1 -1
| Parameter | Type | Description |
|---|---|---|
raster_dur |
np.ndarray | Binary raster duration array |
Returns: np.ndarray — Labeled raster with unique IDs
-
activity_to_raster¶
activity_to_raster(activity) -> np.ndarray
Binary raster of sparse activity (spike counts, event amplitudes): 1 where the value is above 0, NaN counted as 0.
| Parameter | Type | Description |
|---|---|---|
activity |
np.ndarray | (n_cells, n_frames) |
Returns: np.ndarray — int8, same shape, 0 and 1
-
detect_transients¶
detect_transients(traces) -> np.ndarray
Calcium transients as a binary raster, 1 at each peak frame. Per cell: baseline = median of the trace, noise σ = SD of the samples below the median × √2; peaks at least baseline + 3σ high with a prominence of at least 3σ. A cell with σ = 0 has no transient. No preprocessing: normalize, smooth or detrend beforehand if needed (e.g. median_normalization, savitzky_golay_filt).
| Parameter | Type | Description |
|---|---|---|
traces |
np.ndarray | (n_cells, n_frames) fluorescence traces |
Returns: np.ndarray — int8 (n_cells, n_frames), 1 at the transient peaks
-
raster_dur_to_onsets¶
raster_dur_to_onsets(raster_dur) -> np.ndarray
Onsets of the transients of a raster dur: 1 at the first frame of each run of 1s, 0 elsewhere. Values are cast to int8 and clipped to 0-1, as get_continous_time_periods reads them.
| Parameter | Type | Description |
|---|---|---|
raster_dur |
np.ndarray | (n_cells, n_frames) binary raster, 1 over each transient |
Returns: np.ndarray — float64, same shape
imaging.psth_utils (PSTH)¶
-
build_population_psth¶
build_population_psth(data, epochs, ref_in_epoch, range_value, fcts_to_apply, data_type='traces', cell_reduction='mean') -> tuple
Population-level PSTH (not per-cell). For each epoch, a reference frame is chosen as time zero using ref_in_epoch ("start" → epoch[0], "end" → epoch[-1], "middle" → (start + end) // 2), and a window of ±range_value frames is extracted around it. Activity is then reduced across cells with cell_reduction, and summarised across events with fcts_to_apply.
| Parameter | Type | Default | Description |
|---|---|---|---|
data |
np.ndarray | (n_cells, n_frames) |
|
epochs |
list | List of (start_frame, stop_frame) |
|
ref_in_epoch |
str | 'start' | "start" |
range_value |
int | Half-window in frames (symmetric ±) | |
fcts_to_apply |
list | List of 3 functions [central_fn, low_fn, high_fn] |
|
data_type |
str | 'traces' | 'traces' → mean |
cell_reduction |
str | 'mean' | Reduction method |
Returns: tuple — (frames_indices, psth_values) where psth_values = [central, low, high] (lists, not arrays)
Example:
frames_idx, psth = build_population_psth(
data, epochs, ref_in_epoch="start", range_value=30,
fcts_to_apply=[
np.nanmean,
lambda x: np.nanmean(x) - 2*np.nanstd(x), # absolute lower bound
lambda x: np.nanmean(x) + 2*np.nanstd(x), # absolute upper bound
],
)
time_s = np.array(frames_idx) / sampling_rate
ax.plot(time_s, psth[0])
ax.fill_between(time_s, psth[1], psth[2], alpha=0.3)
-
combine_population_psth¶
combine_population_psth(session_data_list, bins_edges, session_fcts=None) -> tuple
Aggregate build_population_psth results (e.g. from multiple sessions) onto a common time grid.
| Parameter | Type | Default | Description |
|---|---|---|---|
session_data_list |
list | List of (psth_times, psth_values) — direct returns of build_population_psth |
|
bins_edges |
np.ndarray | Common bin edges (seconds) | |
session_fcts |
list | None | [central_fn, low_fn, high_fn] for multi-session |
Returns: tuple — (time_x_values, [central, low, high]). An empty bin (no sample of a session) is NaN.
-
psth_rows_on_grid¶
psth_rows_on_grid(rows, by, bins_edges, time_column="time") -> pd.DataFrame
Each PSTH line of a table on a common time grid (combine_population_psth), so that lines sampled at different rates (e.g. sessions at different frame rates) share their time values and can be reduced together. Edges: core.event_alignment.psth_grid_edges.
| Parameter | Type | Default | Description |
|---|---|---|---|
rows |
pd.DataFrame | One row per line and time: the by columns, time_column, line, low, high, n |
|
by |
list[str] | Columns of one line (without the time column) | |
bins_edges |
np.ndarray | Edges of the common grid, in the unit of time_column |
|
time_column |
str | "time" | Column of the times |
Returns: pd.DataFrame — The same columns, one row per line and bin: the bin centre as time, the mean of the values in the bin (NaN for an empty bin), n the largest of the line
-
build_psth_dataframe¶
build_psth_dataframe(data, event_timestamps, frame_timestamps, window_s, subtract_baseline=False, baseline_event_timestamps=None, roi_indices=None, session_id=None, mouse_id=None, trial_type=None, extra_metadata=None) -> pd.DataFrame
Align calcium activity to a set of events and return a long-format DataFrame where every row is one timepoint × one ROI × one event trial. No averaging is done, only computation is the optional baseline subtraction.
| Parameter | Type | Default | Description |
|---|---|---|---|
data |
np.ndarray | (n_cells, n_frames) |
|
event_timestamps |
np.ndarray | Event timestamps | |
frame_timestamps |
np.ndarray | Frame timestamps | |
window_s |
tuple | (pre_s, post_s) in seconds |
|
subtract_baseline |
bool | False | Subtract baseline |
baseline_event_timestamps |
np.ndarray | None | Baseline event timestamps |
roi_indices |
list | None | Original NWB ROI indices |
session_id |
str | None | Session ID |
mouse_id |
str | None | Mouse ID |
trial_type |
str | None | Trial type |
extra_metadata |
any | None | Extra metadata |
Returns: pd.DataFrame — Long-format DataFrame with columns: activity, time, event, roi + any metadata columns
Example:
df = build_psth_dataframe(
data=rrs,
event_timestamps=trial_table['start_time'].values,
frame_timestamps=rrs_ts,
window_s=(0.5, 1.0),
subtract_baseline=True,
session_id="m01_d01",
trial_type="whisker_hit",
)
-
align_single_cell_to_epochs¶
align_single_cell_to_epochs(cell_data, epochs, ref_in_epoch, range_frames, n_total_frames, filter_consecutive=False, fcts_to_apply=None, low_percentile=25, high_percentile=75, psth_range_in_ms=None, verbose=False, baseline_subtraction=False) -> dict
Align a single cell's 1-D signal to a list of epochs and return per-trial windows plus summary statistics. A trial whose window leaves the recording is dropped.
| Parameter | Type | Default | Description |
|---|---|---|---|
cell_data |
np.ndarray | (n_frames,) — raster (int) or trace (float) |
|
epochs |
list[tuple] | Already-sorted list of (start_frame, stop_frame) pairs |
|
ref_in_epoch |
str | Reference point: "start", "end", or "middle" | |
range_frames |
int | tuple | Window in frames: (before, after) the event, or one value for both |
|
n_total_frames |
int | Total recording length for boundary checking | |
filter_consecutive |
bool | False | Drop a trial whose start is within the window length of the previous kept trial's start |
fcts_to_apply |
list | None | Traces: [center_fn, low_fn, high_fn], each taking (n_trials, n_window_frames) and returning (n_window_frames,); None: median and the two percentiles |
low_percentile |
float | 25 | Lower percentile when fcts_to_apply is None |
high_percentile |
float | 75 | Upper percentile when fcts_to_apply is None |
psth_range_in_ms |
float | None | Window length (ms), only for the verbose message |
verbose |
bool | False | Print filtering messages |
baseline_subtraction |
bool | False | Traces: each trial minus the mean of its frames before the event |
Returns: dict with keys:
- "aligned" — np.ndarray (n_trials_kept, n_window_frames)
- "kept_mask" — list[bool], per-trial keep flag (length = len(epochs))
- "kept_labels" — list[str], e.g. ["Trial_0", "Trial_3", ...]
- "summary" — dict: for int data "sum" and "perc" (sum divided by the number of epochs, kept or not); for float data "center", "low", "high"; each (n_window_frames,). Empty when no trial is kept
-
active_frame_times¶
active_frame_times(aligned, time) -> list
Times of the active frames of each row of a binary aligned raster (one row per trial), e.g. for an event plot.
| Parameter | Type | Description |
|---|---|---|
aligned |
np.ndarray | (n_trials, n_frames) binary (or counts) raster |
time |
np.ndarray | Time of each frame, relative to the event |
Returns: list[np.ndarray] — one array of times per trial
-
align_rolled_cell¶
align_rolled_cell(cell_data, epochs, ref_in_epoch, range_frames, n_total_frames, rolls, baseline_subtraction=False) -> np.ndarray
Surrogates of one cell: its signal rolled (circularly shifted) by each value of rolls, then aligned on the epochs as align_single_cell_to_epochs does. The trials kept are the same for every roll (they depend on the epochs only).
| Parameter | Type | Default | Description |
|---|---|---|---|
cell_data |
np.ndarray | (n_frames,), raster (int) or trace (float) |
|
epochs |
list | As in align_single_cell_to_epochs |
|
ref_in_epoch |
str | As in align_single_cell_to_epochs |
|
range_frames |
int | tuple | As in align_single_cell_to_epochs |
|
n_total_frames |
int | As in align_single_cell_to_epochs |
|
rolls |
list | One shift (frames) per surrogate | |
baseline_subtraction |
bool | False | As in align_single_cell_to_epochs |
Returns: np.ndarray — (n_trials_kept, n_window_frames, n_surrogates)
imaging.images_handling (Image handling)¶
-
read_tiff_movie_frames¶
read_tiff_movie_frames(tiff_filename) -> int
Return the number of frames in a TIFF movie without loading the full stack.
| Parameter | Type | Description |
|---|---|---|
tiff_filename |
str | TIFF file path |
Returns: int — Number of frames
-
load_tiff_movie¶
load_tiff_movie(tiff_file_name, first_frame=None, last_frame=None) -> np.ndarray
Load a TIFF movie stack into memory (or a frame range), with tifffile, Pillow if tifffile cannot read the file. One frame per page of the file, in file order, whatever axes the file declares (the channels or planes of a ScanImage file stay interleaved).
| Parameter | Type | Default | Description |
|---|---|---|---|
tiff_file_name |
str | TIFF file path | |
first_frame |
int | None | First frame to load |
last_frame |
int | None | Frame after the last one loaded (excluded; past the end: to the end) |
Returns: np.ndarray — Movie array (n_frames, H, W), also for a single frame
-
as_sliceable_movie¶
as_sliceable_movie(session_ci_movie_data) -> TiffMovieView | np.ndarray
Normalize a movie source into a sliceable (n_frames, H, W) object without loading the full movie into memory.
| Parameter | Type | Description |
|---|---|---|
session_ci_movie_data |
any | Session movie data |
Returns: TiffMovieView | np.ndarray — Sliceable movie view
Notes:
- str → TiffMovieView wrapping a single TIFF file (lazy, reads on demand)
- list → TiffMovieView over all .tif/.tiff files in the list, concatenated
- np.ndarray or other → returned unchanged (already in memory)
Use movie[start:stop] to extract a frame range; frames are only read from disk when accessed.
-
write_tiff_frames¶
write_tiff_frames(path, movie, start=0, stop=None, chunk_bytes=2**30) -> None
Write frames start to stop (excluded) of a movie to one TIFF file, read chunk_bytes at a time, so that a long movie never has to fit in memory (e.g. 78,000 frames of 512 x 512: 38 GiB). The file is the one tifffile.imwrite writes for the whole array: one series (frames, lines, columns), grey frames, BigTIFF past 4 GB; floats written as float32. Above about 50 MB, the chunk size does not change the writing time; the memory used is about twice the chunk.
| Parameter | Type | Default | Description |
|---|---|---|---|
path |
str | The .tiff file |
|
movie |
sliceable | (frames, lines, columns): an array, a TiffMovieView, an HDF5 dataset |
|
start, stop |
int | 0, None | Frames written (stop None or past the end: to the end) |
chunk_bytes |
int | 2**30 | Bytes read at a time (1 GiB) |
-
TiffMovieView¶
TiffMovieView(paths)
Class. Off-memory sliceable view into one or more TIFF files. Each file is memory-mapped when its frames are uncompressed and all of the same shape: with tifffile.memmap when they are stored back to back, else with a map that skips the header before each frame when they are at a constant distance from each other (raw ScanImage tiffs). Other files (compressed, tiled, headers of varying length) are read with load_tiff_movie, the frames asked only. Exposes .shape (n_frames, H, W) and supports movie[start:stop] slicing.
| Parameter | Type | Description |
|---|---|---|
paths |
str | list[str] | One TIFF file or several, concatenated in this order |
-
get_avg_frames_by_epoch¶
get_avg_frames_by_epoch(data_3d, epoch_frames, subtract_baseline=False, baseline_end_frame=None) -> tuple
Average a 3-D imaging stack across frame epochs. Memory-mapped arrays supported.
| Parameter | Type | Default | Description |
|---|---|---|---|
data_3d |
np.ndarray | (n_frames, H, W) — may be h5py dataset or np.memmap |
|
epoch_frames |
list | List of (frame_start, frame_stop) pairs |
|
subtract_baseline |
bool | False | Subtract baseline |
baseline_end_frame |
int | None | Last frame of pre-event baseline window |
Returns: tuple — (avg_data, center_frame, n_frames_post) — avg_data shape (n_frames_window, H, W)
-
reduce_image_dimensions¶
reduce_image_dimensions(image, factor=2.0, anti_aliasing=True) -> np.ndarray
Downsample a 2-D image (H, W) or image stack (n_frames, H, W) by factor (2 → half resolution) using skimage; same number of dimensions returned. Useful for downsampling widefield frames.
| Parameter | Type | Default | Description |
|---|---|---|---|
image |
np.ndarray | Input image or stack | |
factor |
float | 2.0 | Downsampling factor |
anti_aliasing |
bool | True | Apply anti-aliasing |
Returns: np.ndarray — Downsampled image
-
map_coordinates_to_image¶
map_coordinates_to_image(image_values, coords) -> pd.DataFrame
Map per-ROI values (image_values, one per ROI) to their pixel coordinates (coords: (row, col) per ROI, same order). Returns a DataFrame with columns x (col), y (row) and dff0 (value).
| Parameter | Type | Description |
|---|---|---|
image_values |
list | ROI values |
coords |
list | ROI coordinates |
Returns: pd.DataFrame — DataFrame with x, y, dff0 columns
-
cells_mask¶
cells_mask(pixel_masks, cells, shape) -> np.ndarray
Boolean image of the pixels of some cells. Pixels outside the image are left out.
| Parameter | Type | Description |
|---|---|---|
pixel_masks |
list | Pixel mask of each cell: a sequence of (x, y[, weight]) with x the line (NWB convention, e.g. calcium_imaging.get_pixel_mask); the weight is ignored |
cells |
list | Indices of the cells in pixel_masks |
shape |
tuple | (lines, columns) of the image |
Returns: np.ndarray — bool (lines, columns), True on the pixels of the cells
-
event_clips¶
event_clips(frame_times, event_times, t_before, t_after) -> (clips, n_before)
Frame ranges of the clips from t_before before to t_after after each event, all with the same number of frames (from the median frame interval) so that they can be averaged (e.g. event-triggered movies). An event is skipped when its clip leaves the movie, has a gap (frames more than 1.5 intervals apart, e.g. a movie kept only around trials), or has no frame within one interval of the event.
| Parameter | Type | Description |
|---|---|---|
frame_times |
np.ndarray | Times of the movie frames (s), increasing |
event_times |
np.ndarray | Times to align on (s) |
t_before |
float | Seconds kept before each event |
t_after |
float | Seconds kept after each event |
Returns: tuple — (clips, n_before): clips the [(start, stop)] frame ranges (stop excluded) of the kept events, each n_before + n_after + 1 frames long; n_before the frames before the event's frame in each clip (round(t_before / interval))
-
normalize_clip¶
normalize_clip(clip, n_before, dff=False, subtract_baseline=False) -> np.ndarray
A clip normalized per pixel by its frames before the event: dF/F0 with F0 their 5th percentile (dff), else minus their mean (subtract_baseline), else unchanged. dff takes precedence.
| Parameter | Type | Default | Description |
|---|---|---|---|
clip |
np.ndarray | (frames, lines, columns) frames around one event |
|
n_before |
int | Frames before the event (the baseline); the first frame if 0 | |
dff |
bool | False | (F - F0) / F0 |
subtract_baseline |
bool | False | F - mean of the baseline (when not dff) |
Returns: np.ndarray — the normalized clip, float, same shape
-
time_binned_images¶
time_binned_images(movie, frame_times, bin_duration) -> (images, bins)
Images of a movie averaged over bins of the same number of frames (NaN left out per pixel), e.g. the image series of an event-triggered average movie. Bins are aligned on time 0 (the event): from it forward, and backward from it; only full bins are kept (the frames left over at the ends are not shown).
| Parameter | Type | Description |
|---|---|---|
movie |
np.ndarray | (frames, lines, columns) |
frame_times |
np.ndarray | Time of each frame (s) relative to the event (negative before it), regularly spaced |
bin_duration |
float | Length of each bin (s), rounded to a whole number of frames (at least 1) |
Returns: tuple — (images, bins): images (n_bins, lines, columns); bins the [(start, stop)] of each bin (s): the time of its first frame, plus its number of frames × the frame interval
imaging.detect_population_burst (Population burst detection)¶
-
get_sce_raster_threshold¶
get_sce_raster_threshold(rasterdur, n_surrogates=100, percentile=95, verbose=False, n_jobs=4, seed=0) -> tuple
Estimate the co-activation threshold for synchronous calcium event (SCE) detection using surrogate shuffles. seed (int or np.random.Generator): the same seed gives the same threshold, whatever n_jobs. get_rolling_surrogate_threshold, detect_sce_from_spike_times and detect_sce_rolling take the same seed.
| Parameter | Type | Default | Description |
|---|---|---|---|
rasterdur |
np.ndarray | (n_cells, n_frames) binary raster |
|
n_surrogates |
int | 100 | Number of circular-shift surrogates |
percentile |
float | 95 | Threshold percentile over all surrogate co-activation values |
verbose |
bool | False | Verbose output |
n_jobs |
int | 4 | Number of parallel jobs |
seed |
int | 0 | Random seed |
Returns: tuple — (rnd_rasters, cell_threshold) — surrogate array and scalar threshold
-
detect_sce_raster¶
detect_sce_raster(raster, n_synchronous_frames, sce_n_cells_threshold, sce_min_distance, method="Peaks", frames_mask=None, participation_margin=1) -> (cells_in_sce, sce_windows, sce_n_cells_threshold)
Detect synchronous calcium events (SCEs) from a binary raster with a rolling co-activation score.
For each window i (frames i to i + n_synchronous_frames - 1, every window up to the last one), the score is the number of cells active at least once in it. "Peaks": the peaks of the score at or above sce_n_cells_threshold, at least sce_min_distance frames apart, one SCE each. "All frames": every run of windows at or above the threshold, one SCE each, covering its frames up to the end of its last window. With frames_mask, SCEs start only in the allowed frames and frame numbers stay those of the raster (e.g. an epoch or immobility: no shortened raster).
| Parameter | Type | Default | Description |
|---|---|---|---|
raster |
np.ndarray | (n_cells, n_frames) raster, active where > 0 |
|
n_synchronous_frames |
int | Sliding window width | |
sce_n_cells_threshold |
int | Minimum co-active cells (e.g. from get_sce_raster_threshold) |
|
sce_min_distance |
int | Minimum frame gap between SCEs ("Peaks") | |
method |
str | "Peaks" | "Peaks" or "All frames" |
frames_mask |
np.ndarray | None | Boolean per frame, where SCEs may start; None: every frame |
participation_margin |
int | 1 | "Peaks": a cell is in an SCE if active within this many frames of the peak; "All frames": active in the SCE's frames |
Returns: tuple — (cells_in_sce, sce_windows, sce_n_cells_threshold): (n_cells, n_sce) int array (1 if the cell is in the SCE); [(start, end), ...] inclusive frames of each SCE ((peak, peak) for "Peaks"); the threshold
-
detect_sce_traces¶
detect_sce_traces(raw_traces, speed=None, use_speed=False, speed_threshold=None, sce_n_cells_threshold=5, transient_method='rolling-window', window_size=4, sce_min_distance=4, n_synchronous_frames=2, small_transient_amp=0, imaging_sampling_rate=10, use_median_norm=True, use_bleaching_correction=False, use_savitzky_golay_filt=False, frames_mask=None) -> tuple
Full SCE detection pipeline from raw fluorescence traces. Preprocesses traces, binarises them into a small-transient raster, then calls detect_sce_raster.
Preprocessing (applied in order, all optional):
- use_median_norm: divide each cell's trace by its median
- use_bleaching_correction: fit and subtract a bleaching trend per cell
- use_savitzky_golay_filt: smooth with a Savitzky-Golay filter
Transient detection: with calcium_signal_processing.detect_small_transients
SCE detection (forwarded to detect_sce_raster):
- sce_n_cells_threshold: minimum co-active cells to call an SCE
- sce_min_distance: minimum frame gap between two SCEs
- n_synchronous_frames: sliding window width for co-activation scoring
| Parameter | Type | Default | Description |
|---|---|---|---|
raw_traces |
np.ndarray | Raw fluorescence traces | |
speed |
np.ndarray | None | Running speed |
use_speed |
bool | False | Use speed filtering |
speed_threshold |
float | None | Speed threshold |
sce_n_cells_threshold |
int | 5 | Minimum co-active cells |
transient_method |
str | 'rolling-window' | Transient detection method |
window_size |
int | 4 | Window size |
sce_min_distance |
int | 4 | Minimum frame gap |
n_synchronous_frames |
int | 2 | Sliding window width |
small_transient_amp |
float | 0 | Minimum transient amplitude |
imaging_sampling_rate |
float | 10 | Imaging sampling rate in Hz |
use_median_norm |
bool | True | Apply median normalization |
use_bleaching_correction |
bool | False | Apply bleaching correction |
use_savitzky_golay_filt |
bool | False | Apply Savitzky-Golay filtering |
frames_mask |
np.ndarray | None | Boolean per frame: where transients may be detected and SCEs may start (e.g. an epoch), with the speed filter; None: every frame. Frame indices stay those of the traces |
Returns: tuple — (sce_cells_matrix, sce_loc, raster, small_transients_activity):
- sce_cells_matrix: (n_cells, n_sce) int — cell participation per SCE (active within ±1 frame of the peak)
- sce_loc: 1-D int array of SCE peak frame indices
- raster: (n_cells, n_frames) binary small-transient raster
- small_transients_activity: per cell, the trace snippets around its small transients
imaging.imaging_plots (Imaging plots)¶
-
plot_small_transients¶
plot_small_transients(small_transients, window_size, sampling_rate, title, path_results, filename, save_formats) -> None
Plot a grid of small calcium transient traces per cell (one panel per cell).
| Parameter | Type | Default | Description |
|---|---|---|---|
small_transients |
list | Output of detect_small_transients |
|
window_size |
float | Half-window in seconds — used to compute x-axis time vector | |
sampling_rate |
float | Imaging rate in Hz | |
title |
str | Plot title | |
path_results |
str | Output path | |
filename |
str | Output filename | |
save_formats |
list | Save formats |
Returns: None
-
render_traces¶
render_traces(ax, traces, frame_times, ...) -> float
Draw stacked fluorescence traces onto a matplotlib Axes. Traces are offset vertically by shift_up (median of per-trace maxima) so cell 0 sits at baseline and cell N at N × shift_up.
| Parameter | Type | Description |
|---|---|---|
ax |
Axes | Target axes |
traces |
np.ndarray | (n_cells, n_frames) traces |
frame_times |
np.ndarray | Frame timestamps |
Returns: float — Total vertical offset
-
render_traces_heatmap¶
render_traces_heatmap(raster, ...) -> None
Render a (n_cells, n_times) array as a heatmap split across n_subplots horizontal panels, with an optional speed trace interleaved below each panel.
| Parameter | Type | Description |
|---|---|---|
raster |
np.ndarray | (n_cells, n_times) array |
Returns: None
-
plot_image_series¶
plot_image_series(images, bins, path_results, file_name, title='', cmap='hotcold', vmin=None, vmax=None, image_size=3, save_formats='png', dpi=150, width_inches=None, colorbar_width_mm=None) -> None
One row of images (e.g. time bins of an event-triggered average movie, time_binned_images), with one colour scale and a colour bar, saved with save_figure. The scale is centred on 0 when it spans 0. Text sizes and colours follow the matplotlib settings (figure style of a run).
| Parameter | Type | Default | Description |
|---|---|---|---|
images |
np.ndarray | (n_images, lines, columns) |
|
bins |
list | (start, stop) of each image (s), shown as its title |
|
path_results |
str | Folder of the figure | |
file_name |
str | File name without extension | |
title |
str | '' | Figure title |
cmap |
str | 'hotcold' | Colour map name (display.core_plots.get_colormap, e.g. 'hotcold', 'seismic', 'gray') |
vmin |
float | None | Low end of the scale; None: the 1st percentile of the images |
vmax |
float | None | High end of the scale; None: the 99th percentile |
image_size |
float | 3 | Size of each image (inches), when width_inches is None |
save_formats |
str | list | 'png' | Format(s) of the figure |
dpi |
int | 150 | Resolution |
width_inches |
float | None | Width of the figure, the images sharing it |
colorbar_width_mm |
float | None | Width of the colour bar (mm); None: matplotlib's |
Returns: None — the figure is saved
imaging.imaging_timestamps (Imaging time axis: frame times in seconds)¶
-
imaging_time_axis¶
imaging_time_axis(timestamps, n_frames, imaging_rate=None, verbose=False) -> np.ndarray | None
The frame times (s) of an imaging series, or None if they cannot be known (the x axis then stays in frames). Frame indices stored as timestamps (0, 1, 2, ...) are converted with the imaging rate when one is given. When timestamps and frames differ in number, the first min(n_timestamps, n_frames) are kept: trim the data to the returned length. Prints what it does.
| Parameter | Type | Default | Description |
|---|---|---|---|
timestamps |
np.ndarray | Timestamps of the series (calcium_imaging.get_roi_response_serie_timestamps()) |
|
n_frames |
int | Number of frames of the data | |
imaging_rate |
float | None | None | Imaging rate (Hz), used only when the timestamps are frame indices |
verbose |
bool | False | Print the resulting time range |
Returns: np.ndarray | None — frame times in seconds; None with fewer than 2 timestamps, or frame indices without imaging rate