spacr.timelapse
===============

.. py:module:: spacr.timelapse




Module Contents
---------------

.. py:function:: link_by_iou(mask_prev, mask_next, iou_threshold=0.1)

   Match labels between two consecutive frames using IoU and Hungarian assignment.

   :param mask_prev: labelled mask from the previous frame.
   :param mask_next: labelled mask from the next frame.
   :param iou_threshold: minimum IoU required to accept a match. Default ``0.1``.
   :returns: list of ``(label_prev, label_next)`` matches above the threshold.


.. py:function:: exponential_decay(x, a, b, c)

   Return ``a * exp(-b * x) + c`` for curve fitting.


.. py:function:: preprocess_pathogen_data(pathogen_df)

   Aggregate a per-parasite table to one row per host cell with a parasite count.

   :param 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_count`` column.


.. py:function:: plot_data(measurement, group, ax, label, marker='o', linestyle='-')

   Plot ``delta_<measurement>`` vs ``time`` for one grouped subset onto ``ax``.

   :param measurement: base measurement name; the ``delta_`` prefix is added when reading the column.
   :param group: DataFrame subset for a single group.
   :param ax: matplotlib axis to draw onto.
   :param label: legend label for this series.
   :param marker: matplotlib marker. Default ``'o'``.
   :param linestyle: matplotlib line style. Default ``'-'``.
   :returns: None.


.. py:function:: infected_vs_noninfected(result_df, measurement)

   Plot per-well mean ``delta_<measurement>`` for infected vs uninfected cell groups.

   :param result_df: per-cell/time DataFrame with plate/row/column/field/object identifiers, ``parasite_count`` and the target measurement.
   :param measurement: base measurement column name to plot (the ``delta_`` variant is drawn).
   :returns: None.


.. py:function:: save_figure(fig, src, figure_number)

   Save ``fig`` as ``figure_<figure_number>.pdf`` inside a sibling ``results`` folder.

   :param fig: matplotlib Figure to persist.
   :param src: reference path used to derive the parent directory.
   :param figure_number: integer/string suffix embedded in the filename.
   :returns: None.


.. py:function:: save_results_dataframe(df, src, results_name)

   Save ``df`` as ``<results_name>.csv`` inside a sibling ``results`` folder.

   :param df: DataFrame to write.
   :param src: reference path used to derive the parent directory.
   :param results_name: filename stem (no extension).
   :returns: None.


.. py:function:: summarize_per_well(peak_details_df)

   Aggregate per-object peak details to one summary row per well.

   :param peak_details_df: per-object peak DataFrame with an ``ID`` column
       encoding ``plate_row_column_field_object`` and peak metrics.
   :returns: DataFrame with one row per well including peak counts, unique
       cell counts, and per-well means of the numeric metrics.


.. py:function:: summarize_per_well_inf_non_inf(peak_details_df)

   Aggregate per-object peak details per well, split by infection status.

   :param peak_details_df: per-object peak DataFrame with an ``ID`` column
       encoding ``plate_row_column_field_object``, peak metrics, and
       pathogen counts used to infer infection.
   :returns: DataFrame with two rows per well (infected/uninfected) of
       peak counts, cell counts, and per-well means of numeric metrics.


.. py:function:: 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)

   Detect and summarise per-cell calcium oscillation peaks from a measurements DB.

   Loads the ``cell`` (and optionally ``pathogen``/``cytoplasm``) tables,
   filters transient tracks, detects peaks on the chosen intensity trace,
   and returns both per-peak details and per-well summaries.

   :param db_loc: path to the measurements SQLite database.
   :param measurement: intensity column analysed for oscillations.
   :param size_filter: object-size column used for gating.
   :param fluctuation_threshold: minimum normalised fluctuation to keep a trace.
   :param num_lines: cap on the number of traces to plot; plots all when ``None``.
   :param peak_height: minimum peak prominence for ``scipy.find_peaks``.
   :param pathogen: optional pathogen table name to join for infection status.
   :param cytoplasm: optional cytoplasm table name to join.
   :param remove_transient: drop tracks shorter than the transience threshold.
   :param verbose: print diagnostic information.
   :param transience_threshold: fraction of timepoints a track must span to be retained.
   :returns: tuple of per-peak DataFrame and per-well summary DataFrame(s).


.. py:function:: create_results_figure()

   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)``.


.. py:function:: automated_motility_assay(settings)

   End-to-end merged-npy pipeline for cell/pathogen motility and infection QC.

   Reads ``merged/*.npy`` frames, 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.

   :param settings: dict of assay settings; see
       ``get_automated_motility_assay_default_settings`` for keys
       including ``src``, ``db_table_name``, ``n_jobs``,
       ``max_displacement``, ``zscore_thresh``, ``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``, and
       ``reuse_existing_measurements``.
   :returns: None. Writes measurements and summary tables to
       ``measurements/measurements.db`` and saves panel PDFs under ``src``.


