spacr.timelapse¶
Workflow inputs and outputs¶
Motility Assay¶
Inspect track speed and infection-related measurements with an explicit frame interval and pixel calibration.
Open: Measure → Motility Assay.
Inputs and outputs below include conditional alternatives. The guidance and handoff notes say which route applies.
Inputs
Linked time-series objects — Tracked labels and frame/object associations from the time-series project, with frame interval and units.
Measured objects — measurements/measurements.db; object tables depend on the enabled cell, nucleus, pathogen and organelle masks. Relevant tables, depending on the route:
cell,nucleus,pathogen,cytoplasm. Relevant columns, depending on the route:plateID,rowID,columnID,fieldID.
Outputs
Assay results — Assay-specific result tables and figures in the configured destination, preserving well and condition identities.
Figures and table exports — The output location chosen by the tool; exports describe the selected data and filters.
Before this module
Timelapse: Supply frame interval and pixel calibration.
Measure: Combine measured objects with matching tracks.
Time-series tracking, motility analysis, and trajectory utilities.
Functions¶
|
Detect and summarise per-cell calcium oscillation peaks from a measurements DB. |
|
End-to-end merged-npy pipeline for cell/pathogen motility and infection QC. |
Create the standard 3-panel QC results figure layout. |
|
|
Return |
|
Plot per-well mean |
|
Match labels between two consecutive frames using IoU and Hungarian assignment. |
|
Plot |
|
Aggregate a per-parasite table to one row per host cell with a parasite count. |
|
Save |
|
Save |
|
Aggregate per-object peak details to one summary row per well. |
|
Aggregate per-object peak details per well, split by infection status. |
Module Contents¶
- spacr.timelapse.analyze_calcium_oscillations(db_loc, measurement='cell_channel_1_mean_intensity', size_filter='cell_area', fluctuation_threshold=0.25, num_lines=None, peak_height=0.01, pathogen=None, cytoplasm=None, remove_transient=True, verbose=False, transience_threshold=0.9, *, bleach_correction='legacy')[source]¶
Detect and summarise per-cell calcium oscillation peaks from a measurements DB.
Loads the
cell(and optionallypathogen/cytoplasm) tables, filters transient tracks, detects peaks on the chosen intensity trace, and writes the per-peak, per-cell and per-well tables to CSV in aresultsfolder beside the database.- Parameters:
db_loc – path to the measurements SQLite database.
measurement – intensity column analysed for oscillations.
size_filter – object-size column used for gating.
fluctuation_threshold – maximum coefficient of variation (std / mean) of
size_filterwithin a track; more variable tracks are dropped.num_lines – cap on the number of traces to plot; plots all when
None.peak_height – minimum absolute peak height, passed to
scipy.find_peaks(height=...)on the delta trace.pathogen – optional pathogen table name to join for infection status.
cytoplasm – optional cytoplasm table name to join.
remove_transient – drop tracks shorter than the transience threshold.
verbose – print diagnostic information.
transience_threshold – fraction of timepoints a track must span to be retained.
bleach_correction –
legacypreserves the original global decay fit. Opt-inratio,exponentialorhistogramuses Measure’s per-field correction once on the original table. Raw intensities remain unchanged;bleach_corrected_<measurement>stores absolute corrected levels.corrected_<measurement>is dimensionless: corrected signal above the measured outside ring divided by that field’s positive, finite initial median signal. Integrated levels subtract ring times area. Missing background or an invalid initial baseline remains NaN; missing intervals are not bridged for peak detection. The actual method, background and baseline accompany traces;bleach_correction_fits.csvrecords field fits. Histogram matching can erase population changes.
- Returns:
tuple
(result_df, peak_details_df, fig)– the photobleach-corrected per-cell traces, the per-peak details and the summary matplotlib Figure. The per-well summaries are only written to CSV. ReturnsNonewhen the database has no time axis, the decay legacy fit fails, or no cells pass the filters.- Raises:
ValueError – an unknown correction method, an unsupported intensity column for an explicit shared method, or ambiguous field/time/object identities.
- spacr.timelapse.automated_motility_assay(settings)[source]¶
End-to-end merged-npy pipeline for cell/pathogen motility and infection QC.
Reads
merged/*.npyframes, builds per-cell measurements, cleans and persists them to SQLite, computes per-track velocities, generates intensity + motility QC panels (mask-based and, optionally, XGBoost / histogram / PCA / UMAP / t-SNE adjusted labels), and writes a well-level motility summary.- Parameters:
settings – dict of assay settings; see
get_automated_motility_assay_default_settingsfor keys includingsrc,db_table_name,n_jobs,max_displacement,track_outlier_zscore,infection_intensity_qc,infection_intensity_strategy,infection_intensity_mode,infection_xgb_drop_ambiguous,infection_xgb_ambiguous_low,infection_xgb_ambiguous_high,infection_xgb_proba_column,infection_hist_percentile,make_mask_panel,make_adjusted_panel,motility_xlim,motility_ylim,motility_origin_xlim,motility_origin_ylim, andreuse_existing_measurements. Optionalbleach_correctiondefaults tonone;ratio,exponentialorhistogramcorrect each field/channel and object role before child aggregation and infection QC, using a five-pixel label-zero background ring (missing rings give NaN). Histogram matching can erase biological changes. Opt-in runs require recomputation rather than reuse of cached measurement rows. Original intensity measurements remain raw; separate tables with_bleach_correctedand_bleach_fitssuffixes and a fits CSV record the corrected levels, source filenames and method.- Returns:
the per-cell measurements DataFrame carrying the final (QC-adjusted) labels. Measurements and summary tables are also written to
measurements/measurements.dband the QC panels saved undersrc.- Raises:
ValueError – when
settings['db_table_name']names a spaCR-owned table; see_validate_db_table_name().
Pre-QC corrected values are persisted separately; the cached originals stay raw.
- spacr.timelapse.create_results_figure()[source]¶
Create the standard 3-panel QC results figure layout.
Arrangement is PCA (top-left), XGBoost (top-right) and Histogram (bottom spanning both columns).
- Returns:
tuple
(fig, ax_pca, ax_xgb, ax_hist).
- spacr.timelapse.exponential_decay(x, a, b, c)[source]¶
Return
a * exp(-b * x) + cfor curve fitting.The photobleaching model
analyze_calcium_oscillations()fits withscipy.optimize.curve_fit, which reads the three arguments afterxas the free parameters to solve for.- Parameters:
x – time points, as a scalar or a NumPy array / pandas Series; a
Seriescomes back as aSerieson the same index, which is what lets the caller’sdf[measurement] / exponential_decay(...)align by label.a – amplitude of the decaying term. At
x == 0the result isa + c, nota;a == 0flattens the curve to the constantc.b – decay rate. The sign is not checked – a negative
bgrows instead of decaying, and a large-b * xoverflows toinfwith aRuntimeWarningrather than raising.c – additive offset, and the asymptote as
xgrows. Nothing keeps the curve positive, so a fit withc < 0crosses zero and the caller’s division by this curve flips sign across the crossing.
- Returns:
numpy.float64for scalarx, otherwise the array type ofx.- Raises:
TypeError – when
xis a plain list andbis a float, because-b * xis then list arithmetic. An integerbdoes not raise: it silently returns an empty array forb >= 0.
- spacr.timelapse.infected_vs_noninfected(result_df, measurement)[source]¶
Plot per-well mean
delta_<measurement>for infected vs uninfected cell groups.- Parameters:
result_df – per-cell/time DataFrame keyed by the composed
plate_row_column_field_objectcolumn, withtime,parasite_countand thedelta_<measurement>column.measurement – base measurement column name to plot (the
delta_variant is drawn).
- Returns:
None.
- spacr.timelapse.link_by_iou(mask_prev, mask_next, iou_threshold=0.1)[source]¶
Match labels between two consecutive frames using IoU and Hungarian assignment.
- Parameters:
mask_prev – labelled mask from the previous frame.
mask_next – labelled mask from the next frame.
iou_threshold – minimum IoU required to accept a match. Default
0.1.
- Returns:
list of
(label_prev, label_next)matches above the threshold.
- spacr.timelapse.plot_data(measurement, group, ax, label, marker='o', linestyle='-')[source]¶
Plot
delta_<measurement>vstimefor one grouped subset ontoax.- Parameters:
measurement – base measurement name; the
delta_prefix is added when reading the column.group – DataFrame subset for a single group.
ax – matplotlib axis to draw onto.
label – legend label for this series.
marker – matplotlib marker. Default
'o'.linestyle – matplotlib line style. Default
'-'.
- Returns:
None.
- spacr.timelapse.preprocess_pathogen_data(pathogen_df)[source]¶
Aggregate a per-parasite table to one row per host cell with a parasite count.
Keys on the column names the measurement writer actually emits:
columnID(notcolumn_name),timeID(nottimeid, and absent altogether outside a timelapse run) andcell_id– the child table’s link to its host cell – notpathogen_cell_id, which no writer has ever produced. Under the old names every call died withKeyError.- Parameters:
pathogen_df – per-parasite measurements DataFrame with plate/well/field/time/cell identifiers.
- Returns:
DataFrame aggregated to (plate, row, column, field, time, host cell) with a
parasite_countcolumn.
- spacr.timelapse.save_figure(fig, src, figure_number)[source]¶
Save
figasfigure_<figure_number>inside a siblingresultsfolder.The
.pdfextension built here is only a proposal:spacr.plot.save_figure()rewrites it to the configured figure format. That preference defaults topdf, so the file on disk isfigure_1.pdfunless another format has been selected.- Parameters:
fig – matplotlib Figure to persist.
src – reference path used to derive the parent directory.
figure_number – integer/string suffix embedded in the filename.
- Returns:
None; the written path is printed.
- spacr.timelapse.save_results_dataframe(df, src, results_name)[source]¶
Save
dfas<results_name>.csvinside a siblingresultsfolder.- Parameters:
df – DataFrame to write.
src – reference path used to derive the parent directory.
results_name – filename stem (no extension).
- Returns:
None.
- spacr.timelapse.summarize_per_well(peak_details_df)[source]¶
Aggregate per-object peak details to one summary row per well.
- Parameters:
peak_details_df – per-object peak DataFrame with an
IDcolumn encodingplate_row_column_field_objectand peak metrics.- Returns:
DataFrame with one row per well including peak counts, unique cell counts, and per-well means of the numeric metrics.
- Raises:
spacr.schema.KeyParseError – when an
IDis not an object key.
- spacr.timelapse.summarize_per_well_inf_non_inf(peak_details_df)[source]¶
Aggregate per-object peak details per well, split by infection status.
- Parameters:
peak_details_df – per-object peak DataFrame with an
IDcolumn encodingplate_row_column_field_object, peak metrics, and aninfectedcolumn whose positive values mark infected objects.- Returns:
DataFrame with one row per well and infection status (so one row for a well seen in a single status) of peak counts, cell counts, and per-well means of numeric metrics.
- Raises:
spacr.schema.KeyParseError – when an
IDis not an object key.KeyError – when the frame has no
infectedcolumn; the pathogen count must be carried under exactly that name.
Nested helpers¶
- _event_network._EventNet.__init__(self)¶
Build temporal features and the optional per-frame crop encoder.
spacr/timelapse.py:1939
- _event_network._EventNet.forward(self, inputs, crops=None, video=None)¶
Class scores for a batch of windows.
spacr/timelapse.py:1955
- _event_partner_columns.count(points, x, y)¶
Number of
pointswithinradiusof(x, y).spacr/timelapse.py:1837
- _feature_velocity_correlations._corr_subset(mask, label)¶
Return correlations for at least five finite-velocity rows, else
None.spacr/timelapse.py:7345
- _infection_qc_pca_clustering._evaluate_embedding(coords, cluster_labels, y_orig, gt_uninf, gt_inf)¶
- Compute:
infected/uninfected cluster mapping using GT sets
GT separation score
silhouette score
centroid distance between the two clusters
original infected fractions in each cluster
overall score = centroid_distance * GT separation
spacr/timelapse.py:6085
- _infection_qc_pca_clustering._search_tsne(X_scaled, y_orig, gt_uninf, gt_inf, settings_local)¶
Return coordinates, labels, statistics, and parameters from t-SNE.
spacr/timelapse.py:6215
- _infection_qc_pca_clustering._search_tsne._run_tsne(perplexity, learning_rate)¶
Return coordinates, labels, and statistics for one t-SNE pair.
spacr/timelapse.py:6222
- _infection_qc_pca_clustering._search_umap(X_scaled, y_orig, gt_uninf, gt_inf, settings_local)¶
Return coordinates, labels, statistics, and parameters from UMAP.
spacr/timelapse.py:6149
- _make_intensity_motility_panel._plot_all_tracks(ax)¶
Plot tracks on
axin absolute pixel or calibrated coordinates; returnNone.spacr/timelapse.py:4426
- _make_intensity_motility_panel._plot_hist_qc(ax, source)¶
Draw infected vs uninfected intensity histogram.
sourcecan be:- a dict payload (settings[‘infection_hist_data’]) with keys:
‘intensities_inf’, ‘intensities_uninf’, ‘bin_edges’, ‘thr_val’ (optional), ‘intensity_col’ (optional)
- or a DataFrame (df_well), in which case the histogram
is computed on the fly using a reasonable intensity column and
infection_intensity_n_bins.
spacr/timelapse.py:4008
- _make_intensity_motility_panel._plot_inf_uninf_bar(ax, df_vals, value_col, title, ylabel)¶
Helper to plot infected vs uninfected distributions for the given column, using violin plots (with mean markers) instead of barplots.
spacr/timelapse.py:4242
- _make_intensity_motility_panel._plot_origin(ax, want_infected: bool)¶
Plot the selected group on
axrelative to its origins; returnNone.spacr/timelapse.py:4495
- _make_intensity_motility_panel._plot_pca_qc(ax, pdata)¶
Plot
pdata’s 2-D embedding onax, or hide it, then returnNone.spacr/timelapse.py:4106
- _make_intensity_motility_panel._plot_xgb_importance_qc(ax, xdata)¶
Plot
xdataimportances onax, or hide it, then returnNone.spacr/timelapse.py:4151
- _make_intensity_motility_panel._plot_xgb_prob_qc(ax, df_prob)¶
Per-cell probability distribution by adjusted infection label.
Uses settings[‘infection_xgb_proba_column’] if available, otherwise falls back through a few common column names.
spacr/timelapse.py:4173
- _make_motility_plots._apply_axis_limits(ax, xlim, ylim)¶
Apply valid two-value limits to
axand returnNone.spacr/timelapse.py:7552
- _make_motility_plots._fmt_vel(val)¶
Return finite
valto two decimals, orn/awhen non-finite.spacr/timelapse.py:7548
- _masks_to_gif._display_gif(path)¶
Read
pathinto an IPython image, display it, and returnNone.spacr/timelapse.py:198