plotting package

plotting_structure

towbintools.plotting.plotting_structure.build_conditions(conditions_yaml: str | dict) list[source]

Process a conditions YAML file structured in a factorized way. Refer to the documentation for the expected format. The function will return a list of dictionaries, each representing a condition with its parameters.

Parameters:

conditions_yaml (str or dict) – Path to the YAML file or a dictionary containing the conditions.

Returns:

A list of dictionaries, each representing a condition with its parameters.

Return type:

list

Raises:

ValueError – If the conditions YAML file is not structured correctly.

towbintools.plotting.plotting_structure.build_plotting_struct(experiment_dir: str, filemap_path: str, conditions_yaml_path: str | dict, organ_channels: dict[str, str] = {'body': 'ch2', 'pharynx': 'ch1'}, recompute_values_at_molt: bool = False, rescale_n_points: int = 100) tuple[list[dict], list[dict]][source]

Build the plotting structure for a single experiment.

Reads the filemap CSV and the conditions YAML, merges condition metadata into the filemap, and produces a list of condition dicts ready for plotting.

Parameters:
  • experiment_dir (str) – Path to the experiment directory.

  • filemap_path (str) – Path to the CSV filemap file.

  • conditions_yaml_path (str or dict) – Path to the conditions YAML file or an already-parsed conditions dict.

  • organ_channels (dict[str, str]) – Mapping of organ name → filemap channel prefix. Defaults to {"body": "ch2", "pharynx": "ch1"}.

  • recompute_values_at_molt (bool) – If True, recompute at-molt values even when they are already stored in the filemap. Defaults to False.

  • rescale_n_points (int) – Unused; reserved for future use. Defaults to 100.

Returns:

(conditions_struct, conditions_info) where

conditions_struct is the full list of condition dicts sorted by condition_id, and conditions_info contains only the metadata keys from the YAML, also sorted by condition_id.

Return type:

tuple[list[dict], list[dict]]

towbintools.plotting.plotting_structure.combine_experiments(filemap_paths: list[str], config_paths: list[str], experiment_dirs: list[str] | None = None, organ_channels: list[dict] | dict = [{'body': 'ch2', 'pharynx': 'ch1'}], recompute_values_at_molt: bool = False, rescale_n_points: int = 100) list[dict][source]

Build and merge the plotting structure from multiple experiments.

Each experiment is processed independently via build_plotting_struct. Conditions with identical metadata (after removing description and condition_id) are merged by concatenating their numpy arrays along axis 0. Condition IDs in the merged structure are reassigned sequentially.

Parameters:
  • filemap_paths (list[str]) – Paths to the CSV filemap files, one per experiment.

  • config_paths (list[str]) – Paths to the conditions YAML files, one per experiment.

  • experiment_dirs (list[str] or None) – Experiment directories; defaults to the parent directory of each filemap when None.

  • organ_channels (list[dict] or dict) – Organ-to-channel mapping(s). A single dict is broadcast to all experiments; otherwise one dict per experiment is expected. Defaults to [{"body": "ch2", "pharynx": "ch1"}].

  • recompute_values_at_molt (bool) – Passed to build_plotting_struct. Defaults to False.

  • rescale_n_points (int) – Passed to build_plotting_struct. Defaults to 100.

Returns:

Merged conditions_struct with sequential condition IDs.

Return type:

list[dict]

Raises:

ValueError – If the length of organ_channels is neither 1 nor equal to the number of experiments.

towbintools.plotting.plotting_structure.remove_ignored_molts(filemap: DataFrame) DataFrame[source]

Set molt-time columns to null for time points flagged with Ignore=True.

For each ecdysis column, any molt time that coincides with an ignored (Point, Time) pair is replaced with None.

Parameters:

filemap (polars.DataFrame) – Filemap with ecdysis columns and an optional "Ignore" column.

Returns:

Updated filemap; unchanged if "Ignore" is absent.

Return type:

polars.DataFrame

towbintools.plotting.plotting_structure.remove_unwanted_info(conditions_info: list[dict]) list[dict][source]

Remove "description" and "condition_id" from each entry in conditions_info.

Parameters:

conditions_info (list[dict]) – List of condition metadata dicts.

Returns:

The modified list with the two keys removed in place.

Return type:

list[dict]

towbintools.plotting.plotting_structure.separate_column_by_point(filemap: DataFrame, column: str) ndarray[source]

Pivot a long-format filemap column into a 2-D array indexed by point.

Each row of the output corresponds to one imaging point; columns correspond to time frames. Shorter points are right-padded with NaN (numeric) or "error" (string) to the length of the longest point.

Parameters:
  • filemap (polars.DataFrame) – Filemap with at least "Point" and column columns.

  • column (str) – Column to pivot.

Returns:

Array of shape (n_points, max_n_frames) sorted by point.

Return type:

np.ndarray

boxplots

towbintools.plotting.boxplots.boxplot(conditions_struct: list, column: str, conditions_to_plot: list, events_to_plot: list[int] | None = None, log_scale: bool = True, figsize: tuple[float, float] | None = None, colors: list | dict | None = None, plot_significance: bool = False, show_metric: bool = False, significance_pairs: list[tuple] | None = None, significance_test: str = 'Mann-Whitney', legend: dict | None = None, y_axis_label: str | None = None, titles: list[str] | None = None, share_y_axis: bool = False, show_swarm: bool = True, hide_outliers: bool = True, return_data: bool = False) Figure[source]

Create box plots for a per-molt measurement across conditions.

Log scaling is handled natively by seaborn (unlike violinplot which pre-transforms values). Each column in column (axis 1) corresponds to one molt event subplot.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the per-molt measurement array (shape (n_worms, n_molts)).

  • conditions_to_plot (list) – Ordered condition identifiers.

  • events_to_plot (list[int] or None) – Column indices (molt events) to include. All events are plotted when None. Defaults to None.

  • log_scale (bool) – If True, render y-axis in log scale via set_yscale. Defaults to True.

  • figsize (tuple[float, float] or None) – Figure size; auto-sized when None. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • plot_significance (bool) – If True, add significance brackets. Defaults to False.

  • show_metric (bool) – If True, display summary statistics below the plot. Defaults to False.

  • significance_pairs (list[tuple] or None) – Pairs to annotate; all pairs when None. Defaults to None.

  • significance_test (str) – Statistical test for annotation. Defaults to "Mann-Whitney".

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column. Defaults to None.

  • titles (list[str] or None) – Subplot titles. Defaults to None.

  • share_y_axis (bool) – If True, synchronise y-axis limits. Defaults to False.

  • show_swarm (bool) – If True, overlay a swarm plot on the box plot. Defaults to True.

  • hide_outliers (bool) – If True, hide swarm-plot points beyond ±3 std. Defaults to True.

  • return_data (bool) – If True, also return the intermediate DataFrame. Defaults to False.

Returns:

The generated figure. tuple[matplotlib.figure.Figure, pandas.DataFrame] : Figure and DataFrame if

return_data=True.

Return type:

matplotlib.figure.Figure

towbintools.plotting.boxplots.boxplot_larval_stage(conditions_struct: list, column: str, conditions_to_plot: list, aggregation: str = 'mean', n_points: int = 100, fraction: tuple[float, float] = (0.2, 0.8), log_scale: bool = True, figsize: tuple[float, float] | None = None, colors: list | dict | None = None, plot_significance: bool = False, significance_pairs: list[tuple] | None = None, significance_test: str = 'Mann-Whitney', legend: dict | None = None, y_axis_label: str | None = None, titles: list[str] | None = None, share_y_axis: bool = False, show_metric: bool = False, show_swarm: bool = True, hide_outliers: bool = True) Figure[source]

Create box plots with per-worm values aggregated within a fraction of each larval stage.

Equivalent to violinplot_larval_stage but renders box plots instead of violin plots. If column does not contain "rescaled", the series is first rescaled via rescale_without_flattening.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the measurement series.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • aggregation (str) – Per-worm aggregation within the stage fraction; "mean" or "median". Defaults to "mean".

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

  • fraction (tuple[float, float]) – Start and end fractions of each stage to include in the aggregation. Defaults to (0.2, 0.8).

  • log_scale (bool) – If True, render y-axis in log scale via set_yscale. Defaults to True.

  • figsize (tuple[float, float] or None) – Figure size; auto-sized when None. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • plot_significance (bool) – If True, add significance brackets. Defaults to False.

  • significance_pairs (list[tuple] or None) – Pairs to annotate; all pairs when None. Defaults to None.

  • significance_test (str) – Statistical test for annotation. Defaults to "Mann-Whitney".

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column. Defaults to None.

  • titles (list[str] or None) – Subplot titles. Defaults to None.

  • share_y_axis (bool) – If True, synchronise y-axis limits. Defaults to False.

  • show_metric (bool) – If True, display summary statistics below the plot. Defaults to False.

  • show_swarm (bool) – If True, overlay a swarm plot on the box plot. Defaults to True.

  • hide_outliers (bool) – If True, hide swarm-plot points beyond ±3 std. Defaults to True.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.boxplots.feltz_miller_asymptotic_cv_test(sample1: ndarray, sample2: ndarray) tuple[float, float][source]

Perform the Feltz-Miller asymptotic test for equality of CV on two samples.

Adapted from: https://github.com/benmarwick/cvequality/blob/master/R/functions.R

Parameters:
  • sample1 (array-like) – First sample values.

  • sample2 (array-like) – Second sample values.

Returns:

Test statistic D_AD and two-sided p-value.

Return type:

tuple[float, float]

towbintools.plotting.boxplots.mslr_test(sample1: ndarray, sample2: ndarray, nr: int = 1000) tuple[float, float][source]

Perform the Modified Signed-Likelihood Ratio Test (MSLR) for equality of CVs.

Adapted from: https://github.com/benmarwick/cvequality/blob/master/R/functions.R

Parameters:
  • sample1 (array-like) – First sample values.

  • sample2 (array-like) – Second sample values.

  • nr (int) – Number of parametric bootstrap replicates used to calibrate the test statistic. Defaults to 1000.

Returns:

Modified test statistic statm and two-sided p-value.

Return type:

tuple[float, float]

towbintools.plotting.boxplots.violinplot(conditions_struct: list, column: str, conditions_to_plot: list, events_to_plot: list[int] | None = None, log_scale: bool = True, figsize: tuple[float, float] | None = None, colors: list | dict | None = None, plot_significance: bool = False, show_metric: bool = False, significance_pairs: list[tuple] | None = None, significance_test: str = 'Mann-Whitney', legend: dict | None = None, y_axis_label: str | None = None, titles: list[str] | None = None, share_y_axis: bool = False, show_swarm: bool = True, hide_outliers: bool = True, return_data: bool = False) Figure[source]

Create violin plots for a per-molt measurement across conditions.

Each column in column (axis 1) corresponds to one molt event subplot.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the per-molt measurement array (shape (n_worms, n_molts)).

  • conditions_to_plot (list) – Ordered condition identifiers.

  • events_to_plot (list[int] or None) – Column indices (molt events) to include. All events are plotted when None. Defaults to None.

  • log_scale (bool) – If True, render y-axis in log scale via set_yscale. Defaults to True.

  • figsize (tuple[float, float] or None) – Figure size; auto-sized when None. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • plot_significance (bool) – If True, add significance brackets. Defaults to False.

  • show_metric (bool) – If True, display summary statistics below the plot. Defaults to False.

  • significance_pairs (list[tuple] or None) – Pairs to annotate; all pairs when None. Defaults to None.

  • significance_test (str) – Statistical test for annotation. Defaults to "Mann-Whitney".

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column. Defaults to None.

  • titles (list[str] or None) – Subplot titles. Defaults to None.

  • share_y_axis (bool) – If True, synchronise y-axis limits. Defaults to False.

  • show_swarm (bool) – If True, overlay a swarm plot on the violin plot. Defaults to True.

  • hide_outliers (bool) – If True, hide swarm-plot points beyond ±3 std. Defaults to True.

  • return_data (bool) – If True, also return the intermediate DataFrame. Defaults to False.

Returns:

The generated figure. tuple[matplotlib.figure.Figure, pandas.DataFrame] : Figure and DataFrame if

return_data=True.

Return type:

matplotlib.figure.Figure

towbintools.plotting.boxplots.violinplot_larval_stage(conditions_struct: list, column: str, conditions_to_plot: list, aggregation: str = 'mean', n_points: int = 100, fraction: tuple[float, float] = (0.2, 0.8), log_scale: bool = True, figsize: tuple[float, float] | None = None, colors: list | dict | None = None, plot_significance: bool = False, significance_pairs: list[tuple] | None = None, significance_test: str = 'Mann-Whitney', legend: dict | None = None, y_axis_label: str | None = None, titles: list[str] | None = None, share_y_axis: bool = False, show_metric: bool = False, show_swarm: bool = True, hide_outliers: bool = True) Figure[source]

Create violin plots with per-worm values aggregated within a fraction of each larval stage.

If column does not contain "rescaled", the series is first rescaled via rescale_without_flattening to shape (n_worms, 4, n_points). The middle fraction of each stage (controlled by fraction) is averaged per worm before plotting.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the measurement series.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • aggregation (str) – Per-worm aggregation within the stage fraction; "mean" or "median". Defaults to "mean".

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

  • fraction (tuple[float, float]) – Start and end fractions of each stage to include in the aggregation. Defaults to (0.2, 0.8).

  • log_scale (bool) – If True, render y-axis in log scale via set_yscale. Defaults to True.

  • figsize (tuple[float, float] or None) – Figure size; auto-sized when None. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • plot_significance (bool) – If True, add significance brackets. Defaults to False.

  • significance_pairs (list[tuple] or None) – Pairs to annotate; all pairs when None. Defaults to None.

  • significance_test (str) – Statistical test for annotation. Defaults to "Mann-Whitney".

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column. Defaults to None.

  • titles (list[str] or None) – Subplot titles. Defaults to None.

  • share_y_axis (bool) – If True, synchronise y-axis limits. Defaults to False.

  • show_metric (bool) – If True, display summary statistics below the plot. Defaults to False.

  • show_swarm (bool) – If True, overlay a swarm plot on the violin plot. Defaults to True.

  • hide_outliers (bool) – If True, hide swarm-plot points beyond ±3 std. Defaults to True.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

curves

towbintools.plotting.curves.plot_aggregated_series(conditions_struct: list, series_column: str | list[str], conditions_to_plot: list[int], x: str = 'time', experiment_time: bool = True, aggregation: str = 'mean', n_points: int = 100, time_step: int = 10, log_scale: bool = True, colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, xlim: tuple[float, float] | None = None) Figure[source]

Plot the time-rescaled aggregated series with 95% confidence intervals.

Series are rescaled to a common time axis via rescale_and_aggregate, then plotted as a solid line (mean or median) with a shaded 95% CI band. If series_column is a list, all columns are overlaid on the same axes.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_column (str or list[str]) – Key(s) of the measurement series to plot.

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • x (str) – X-axis variable. "time" uses rescaled hours; "percentage" uses development completion (0–100 %). Defaults to "time".

  • experiment_time (bool) – If True, use absolute experiment time (hours); otherwise use time-step index scaled by time_step. Defaults to True.

  • aggregation (str) – Aggregation function; "mean" or "median". Defaults to "mean".

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

  • time_step (int) – Minutes per frame, used to convert time-step indices to hours when experiment_time=False. Defaults to 10.

  • log_scale (bool) – If True, set the y-axis to log scale. Defaults to True.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; auto-generated when None. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to series_column when None. Defaults to None.

  • xlim (tuple[float, float] or None) – X-axis limits (xmin, xmax) used to crop the plotted range. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

Raises:

ValueError – If x is not "time" or "percentage".

towbintools.plotting.curves.plot_growth_curves_individuals(conditions_struct: list, column: str, conditions_to_plot: list[int], share_y_axis: bool, log_scale: bool | tuple | list = True, figsize: tuple[float, float] | None = None, legend: dict | None = None, y_axis_label: str | None = None, cut_after: float | None = None) Figure[source]

Plot smoothed individual-worm growth curves with one subplot per condition.

Each worm’s series is smoothed via smooth_series_classified and plotted from hatch time. Worms without a detected hatch event are skipped.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the raw measurement series.

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • share_y_axis (bool) – If True, all subplots share the same y-axis range.

  • log_scale (bool or tuple or list) – Scale spec passed to set_scale. Defaults to True (log y-axis only).

  • figsize (tuple[float, float] or None) – Figure size (width, height) in inches. Defaults to (n_conditions * 8, 10).

  • legend (dict or None) – Legend spec used to generate subplot titles. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column when None. Defaults to None.

  • cut_after (float or None) – Truncate worm traces at this experiment time (hours after hatch). None keeps full traces. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

heterogeneity

towbintools.plotting.heterogeneity.plot_cv_at_ecdysis(conditions_struct: dict, column: str, conditions_to_plot: list[int], remove_hatch: bool = True, legend: dict | None = None, colors: list | dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, exclude_arrests: bool = False) Figure[source]

Plot the coefficient of variation (CV) of a measurement at each molt event.

One line per condition; x-axis ticks are labelled M1–M4 (or Hatch–M4 when remove_hatch=False).

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the per-molt measurement array (shape (n_worms, n_molts)).

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • remove_hatch (bool) – If True, drop the hatch (first) column before computing CV. Defaults to True.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • x_axis_label (str or None) – X-axis label. Defaults to None.

  • y_axis_label (str or None) – Y-axis label. Defaults to None.

  • exclude_arrests (bool) – If True, remove arrested worms before computing CV via exclude_arrests_from_series_at_ecdysis. Defaults to False.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.heterogeneity.plot_cv_development_percentage(conditions_struct: dict, column: str, conditions_to_plot: list[int], percentages: ndarray = array([0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]), legend: dict | None = None, colors: list | dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None) Figure[source]

Plot the coefficient of variation (CV) of a rescaled series at specific development percentages.

column must be a pre-rescaled series of shape (n_worms, total_n_points). Values at the requested percentages are extracted by linear index into the rescaled time axis.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the rescaled measurement array.

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • percentages (np.ndarray) – Fractional development positions (0–1) at which to compute CV. Defaults to np.linspace(0, 1, 11).

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • x_axis_label (str or None) – X-axis label. Defaults to None.

  • y_axis_label (str or None) – Y-axis label. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.heterogeneity.plot_cv_rescaled_data(conditions_struct: dict, column: str, conditions_to_plot: list[int], smooth: bool = False, legend: dict | None = None, colors: list | dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None) Figure[source]

Plot the coefficient of variation (CV) across the full rescaled time axis.

One line per condition plotted against the resampled index. An optional median filter (window = 7) can be applied to the CV trace.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the rescaled measurement array (shape (n_worms, n_points)).

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • smooth (bool) – If True, apply a median filter (window = 7) to each CV trace. Defaults to False.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • x_axis_label (str or None) – X-axis label. Defaults to None.

  • y_axis_label (str or None) – Y-axis label. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.heterogeneity.plot_std_at_ecdysis(conditions_struct: dict, column: str, conditions_to_plot: list[int], remove_hatch: bool = True, legend: dict | None = None, colors: list | dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, exclude_arrests: bool = False) Figure[source]

Plot the standard deviation of a measurement at each molt event.

One line per condition; x-axis ticks are labelled M1–M4 (or Hatch–M4 when remove_hatch=False).

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the per-molt measurement array (shape (n_worms, n_molts)).

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • remove_hatch (bool) – If True, drop the hatch (first) column before computing std. Defaults to True.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • x_axis_label (str or None) – X-axis label. Defaults to None.

  • y_axis_label (str or None) – Y-axis label. Defaults to None.

  • exclude_arrests (bool) – If True, remove arrested worms before computing std via exclude_arrests_from_series_at_ecdysis. Defaults to False.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

images

towbintools.plotting.images.filter_non_worm_data(data: ndarray, qc: ndarray) ndarray[source]

Set data points to NaN where the quality-control label is not "worm".

Parameters:
  • data (np.ndarray) – Measurement array; any shape.

  • qc (np.ndarray) – Quality-control string array; same shape as data.

Returns:

Copy of data with non-worm entries replaced by np.nan.

Return type:

np.ndarray

towbintools.plotting.images.get_condition_filemaps_images(condition_dict: dict) dict[str, Any][source]

Load the CSV filemaps for a condition, retaining only image-related columns.

Reads each unique filemap CSV referenced by condition_dict["filemap_path"] and keeps the "Time", "Point", and any column starting with "raw" or containing "analysis".

Parameters:

condition_dict (dict) – A single condition dict containing a "filemap_path" key with an array of CSV file paths.

Returns:

Mapping of filemap path → filtered DataFrame.

Return type:

dict[str, polars.DataFrame]

towbintools.plotting.images.get_image_paths_of_time_point(point: int, time: int, filemap: DataFrame, image_columns: list[str] | str) list[source]

Retrieve image file paths for a specific imaging point and time step.

Parameters:
  • point (int) – Microscope point identifier.

  • time (int) – Time-step index.

  • filemap (polars.DataFrame) – Filemap DataFrame containing "Point", "Time", and the requested image columns.

  • image_columns (list[str] or str) – Column name(s) to retrieve.

Returns:

Image path(s) for the requested point/time, squeezed to a flat list.

Return type:

list

towbintools.plotting.images.get_images_ecdysis(conditions_struct: dict, column: str, img_dir: str, criterion: str, conditions_to_plot: list[int], nb_per_condition: int = 1, molts_to_plot: list[int] = ['M1', 'M2', 'M3', 'M4'], channels: list[int] | None = None, dpi: int = 100, scale: float = 1.0, pixelsize: float = 0.65, cmaps: list[str] | None = None, show_scalebar: bool = True, scalebar_size: float = 100, scalebar_thickness: float = 0.02, scalebar_font_size: int = 12, scalebar_location: str = 'lower right', projection_type: str = 'max')[source]

Select representative worms at each molt event and display their images.

For each condition and molt, the worm(s) whose measurement is closest to the population-level criterion statistic are selected and their TIFF images are loaded and rendered with a scale bar via microfilm.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column (str) – Key of the per-molt measurement used for worm selection (shape (n_worms, n_molts)).

  • img_dir (str) – Filemap column name pointing to the raw image files.

  • criterion (str) – Statistic used to pick representative worms. Supported values: "mean", "median", "min", "max".

  • conditions_to_plot (list[int]) – Indices of conditions to include.

  • nb_per_condition (int) – Number of worms to display per condition per molt. Defaults to 1.

  • molts_to_plot (list[str]) – Molt event labels to display. Defaults to ["M1", "M2", "M3", "M4"].

  • channels (list[int] or None) – Image channels to load. None loads all channels. Defaults to None.

  • dpi (int) – Figure DPI. Defaults to 100.

  • scale (float) – Scaling factor applied to the figure size. Defaults to 1.0.

  • pixelsize (float) – Physical pixel size in µm for the scale bar. Defaults to 0.65.

  • cmaps (list[str] or None) – Colormaps for each channel. None uses the microfilm defaults. Defaults to None.

  • show_scalebar (bool) – Whether to overlay a scale bar. Defaults to True.

  • scalebar_size (float) – Scale bar length in µm. Defaults to 100.

  • scalebar_thickness (float) – Scale bar thickness as a fraction of image height. Defaults to 0.02.

  • scalebar_font_size (int) – Font size for the scale bar label. Defaults to 12.

  • scalebar_location (str) – Location of the scale bar (matplotlib legend loc string). Defaults to "lower right".

  • projection_type (str) – Z-projection type passed to microfilm. Defaults to "max".

Returns:

Images are displayed inline; no figure object is returned.

Return type:

None

towbintools.plotting.images.get_indices_from_percentages(percentages: ndarray, ecdysis: ndarray) ndarray[source]

Convert fractional development percentages to raw time-step indices.

Development is divided into four equal segments (L1–L4). For each percentage, the stage is determined and the index is interpolated linearly between the bounding ecdysis events. Edge cases 0 and 1 map to the first and last ecdysis columns, respectively.

Parameters:
  • percentages (array-like) – Fractional positions in development (0–1).

  • ecdysis (np.ndarray) – Ecdysis time-step array of shape (n_worms, 5) (columns: Hatch, M1, M2, M3, M4).

Returns:

Index array of shape (n_worms, len(percentages)).

Return type:

np.ndarray

proportions

towbintools.plotting.proportions.compute_deviation_from_each_model_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, output_column_name: str, remove_hatch: bool = True, deviations_as_percentage: bool = True, poly_degree: int = 2, remove_outliers_fitting: bool = True) list[source]

Fit a separate model per condition and store each condition’s self-deviation.

Unlike compute_deviation_from_model_at_ecdysis, the model is refitted independently for each condition using that condition’s own data.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement (per-molt array).

  • column_two (str) – Key of the Y measurement (per-molt array).

  • output_column_name (str) – Key under which deviations are stored.

  • remove_hatch (bool) – If True, drop the hatch column (index 0) before fitting. Defaults to True.

  • deviations_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

Returns:

The modified conditions_struct with deviations added in place.

Return type:

list

towbintools.plotting.proportions.compute_deviation_from_model_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, control_condition: int, output_column_name: str, remove_hatch: bool = True, deviations_as_percentage: bool = True, poly_degree: int = 2, remove_outliers_fitting: bool = True) list[source]

Compute per-worm deviations from a control-fitted model and store them in conditions_struct.

A polynomial model is fitted on the control condition; deviations for all conditions (including control) are stored under output_column_name.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement (per-molt array).

  • column_two (str) – Key of the Y measurement (per-molt array).

  • control_condition (int) – Index of the control condition used to fit the model.

  • output_column_name (str) – Key under which deviations are stored.

  • remove_hatch (bool) – If True, drop the hatch column (index 0) before fitting and computing deviations. Defaults to True.

  • deviations_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

Returns:

The modified conditions_struct with deviations added in place.

Return type:

list

towbintools.plotting.proportions.compute_deviation_from_model_development_percentage(conditions_struct: list, column_one: str, column_two: str, control_condition: int, percentages: ndarray, output_column_name: str, deviations_as_percentage: bool = True, poly_degree: int = 2, remove_outliers_fitting: bool = True) list[source]

Compute per-worm deviations from a control model sampled at development percentages.

The model is fitted on the control condition at the sampled indices; deviations for all conditions are stored under output_column_name.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the rescaled X measurement series.

  • column_two (str) – Key of the rescaled Y measurement series.

  • control_condition (int) – Index of the control condition used to fit the model.

  • percentages (np.ndarray) – Fractional development positions (0–1) at which to sample and fit the model.

  • output_column_name (str) – Key under which deviations are stored.

  • deviations_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

Returns:

The modified conditions_struct with deviations added in place.

Return type:

list

towbintools.plotting.proportions.get_deviation_from_model(series_one_values: ndarray, series_two_values: ndarray, model: Any, percentage: bool = True) ndarray[source]

Compute per-worm deviations from a proportion model at each molt event.

For each event (axis 1), the model is evaluated on log(series_one) to predict log(series_two). The deviation is exp(log(actual) - log(predicted)) - 1, optionally multiplied by 100 for percentages.

Parameters:
  • series_one_values (np.ndarray) – X values of shape (n_worms, n_molts).

  • series_two_values (np.ndarray) – Y values of shape (n_worms, n_molts).

  • model – Fitted model with a predict method (sklearn Pipeline) or a callable (LOWESS spline) accepting log-transformed X values.

  • percentage (bool) – If True, express deviations as percentages. Defaults to True.

Returns:

Deviations of shape (n_worms, n_molts); NaN where either

input value is NaN.

Return type:

np.ndarray

towbintools.plotting.proportions.plot_continuous_deviation_from_model(conditions_struct: list, rescaled_column_one: str, rescaled_column_two: str, control_condition_id: int, conditions_to_plot: list, deviation_as_percentage: bool = True, colors: list | dict | None = None, log_scale: tuple[bool, bool] | bool = (True, False), legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, sort_values: bool = False) Figure[source]

Plot the deviation from a LOWESS model as a continuous line across the rescaled axis.

A LOWESS model is fitted on the control condition’s log-log data; all conditions (including the control) are then plotted as mean ± 95% CI of their per-worm deviations from that model.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • rescaled_column_one (str) – Key of the rescaled X series.

  • rescaled_column_two (str) – Key of the rescaled Y series.

  • control_condition_id (int) – Index of the control condition used to fit the model.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • deviation_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • log_scale (tuple[bool, bool] or bool) – Scale spec passed to set_scale. Defaults to (True, False).

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to rescaled_column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; auto-generated when None. Defaults to None.

  • sort_values (bool) – If True, sort both the x and residual arrays by x before averaging. Defaults to False.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_correlation(conditions_struct: list, column_one: str, column_two: str, conditions_to_plot: list, log_scale: bool | tuple | list = True, colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None) Figure[source]

Plot the correlation between two measurements as aggregated rescaled series.

Each condition is first rescaled and aggregated via rescale_and_aggregate; the resulting mean traces are plotted against each other sorted by the x value.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement series.

  • column_two (str) – Key of the Y measurement series.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • log_scale (bool or tuple or list) – Scale spec passed to set_scale. Defaults to True.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column_two. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_correlation_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, conditions_to_plot: list, remove_hatch: bool = True, log_scale: bool | tuple | list = True, colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None) Figure[source]

Plot the mean ± std of two measurements at each molt event as error-bar scatter.

Each point on the plot represents one molt event; x and y error bars show the cross-worm standard deviation.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement (per-molt array).

  • column_two (str) – Key of the Y measurement (per-molt array).

  • conditions_to_plot (list) – Ordered condition identifiers.

  • remove_hatch (bool) – If True, drop the hatch column (index 0). Defaults to True.

  • log_scale (bool or tuple or list) – Scale spec passed to set_scale. Defaults to True.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column_two. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_deviation_from_model_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, control_condition_id: int, conditions_to_plot: list, remove_hatch: bool = False, deviation_as_percentage: bool = True, log_scale: tuple[bool, bool] | bool = (True, False), colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, poly_degree: int = 2, remove_outliers_fitting: bool = True) Figure[source]

Plot the per-condition deviation from a polynomial model at each molt event.

A polynomial OLS model is fitted on the control condition; for each other condition, the mean deviation and its standard error are plotted as a line with error bars over the mean X values at each molt.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement (per-molt array).

  • column_two (str) – Key of the Y measurement (per-molt array).

  • control_condition_id (int) – Index of the control condition used to fit the model.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • remove_hatch (bool) – If True, drop the hatch column (index 0). Defaults to False.

  • deviation_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • log_scale (tuple[bool, bool] or bool) – Scale spec passed to set_scale. Defaults to (True, False).

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; auto-generated when None. Defaults to None.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_deviation_from_model_development_percentage(conditions_struct: list, column_one: str, column_two: str, control_condition_id: int, conditions_to_plot: list, percentages: ndarray, deviation_as_percentage: bool = True, log_scale: tuple[bool, bool] | bool = (True, False), colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, poly_degree: int = 2, remove_outliers_fitting: bool = True) Figure[source]

Plot the deviation from a polynomial model at specified development percentages.

A polynomial OLS model is fitted on the control condition at the sampled percentages; for each other condition, the mean deviation and its standard error are plotted with error bars over the mean X values at those percentages.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the rescaled X measurement series.

  • column_two (str) – Key of the rescaled Y measurement series.

  • control_condition_id (int) – Index of the control condition used to fit the model.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • percentages (np.ndarray) – Fractional development positions (0–1) at which to sample and fit the model.

  • deviation_as_percentage (bool) – If True, express deviations as percentages. Defaults to True.

  • log_scale (tuple[bool, bool] or bool) – Scale spec passed to set_scale. Defaults to (True, False).

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; auto-generated when None. Defaults to None.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_model_comparison_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, conditions_to_plot: list, remove_hatch: bool = True, poly_degree: int = 2, remove_outliers_fitting: bool = True, log_scale: tuple[bool, bool] | bool = (True, False), colors: list | dict | None = None, legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None, single_plot: bool = True) Figure[source]

Scatter-plot the log-log relationship between two columns at molt events with fitted models.

One polynomial model is fitted per condition. A shared R² annotation is added to the legend. Outliers are shown as open circles; inliers as filled markers.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the X measurement (per-molt array).

  • column_two (str) – Key of the Y measurement (per-molt array).

  • conditions_to_plot (list) – Ordered condition identifiers.

  • remove_hatch (bool) – If True, drop the hatch column (index 0). Defaults to True.

  • poly_degree (int) – Polynomial degree for model fitting. Defaults to 2.

  • remove_outliers_fitting (bool) – If True, use IsolationForest to remove outliers before fitting. Defaults to True.

  • log_scale (tuple[bool, bool] or bool) – Scale spec passed to set_scale. Defaults to (True, False).

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; falls back to column_two. Defaults to None.

  • single_plot (bool) – If True, overlay all conditions on one axes; otherwise create one subplot per condition. Defaults to True.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

towbintools.plotting.proportions.plot_normalized_proportions_at_ecdysis(conditions_struct: list, column_one: str, column_two: str, control_condition_id: int, conditions_to_plot: list, colors: list | dict | None = None, aggregation: str = 'mean', log_scale: tuple[bool, bool] | bool = (True, False), legend: dict | None = None, x_axis_label: str | None = None, y_axis_label: str | None = None) Figure[source]

Plot the column_two/column_one ratio normalised to the control at each molt event.

The control proportion (mean ratio across worms) is computed first; each condition’s ratio is divided by the control proportion before averaging.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • column_one (str) – Key of the denominator measurement (per-molt array).

  • column_two (str) – Key of the numerator measurement (per-molt array).

  • control_condition_id (int) – Index of the control condition used for normalisation.

  • conditions_to_plot (list) – Ordered condition identifiers.

  • colors (list or dict or None) – Color spec passed to get_colors. Defaults to None.

  • aggregation (str) – Aggregation function; currently only "mean" is used. Defaults to "mean".

  • log_scale (tuple[bool, bool] or bool) – Scale spec passed to set_scale. Defaults to (True, False).

  • legend (dict or None) – Legend spec passed to build_legend. Defaults to None.

  • x_axis_label (str or None) – X-axis label; falls back to column_one. Defaults to None.

  • y_axis_label (str or None) – Y-axis label; auto-generated when None. Defaults to None.

Returns:

The generated figure.

Return type:

matplotlib.figure.Figure

utils_data_processing

towbintools.plotting.utils_data_processing.combine_series(conditions_struct: list, series_one: str, series_two: str, operation: str, new_series_name: str) list[source]

Combine two series in every condition dict via an elementwise arithmetic operation.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_one (str) – Key of the first operand series.

  • series_two (str) – Key of the second operand series.

  • operation (str) – Arithmetic operation to apply. Supported values: "add", "subtract", "multiply", "divide". Division adds a small epsilon (1e-8) to the denominator to avoid division by zero.

  • new_series_name (str) – Key under which the result is stored in each condition dict.

Returns:

The modified conditions_struct with the new series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.compute_growth_rate(conditions_struct: list, series_name: str, gr_series_name: str, experiment_time: bool = True, lmbda: float = 0.0075, order: int = 2, medfilt_window: int = 5) list[source]

Compute the instantaneous growth rate for each worm in every condition.

The quality-control column is detected automatically by matching series_name against all keys containing "qc".

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_name (str) – Key of the measurement series (e.g. body length).

  • gr_series_name (str) – Key under which the growth-rate series is stored.

  • experiment_time (bool) – If True, use "experiment_time_hours"; otherwise use "time". Defaults to True.

  • lmbda (float) – Regularisation parameter for the Whittaker smoother used internally. Defaults to 0.0075.

  • order (int) – Polynomial order for smoothing. Defaults to 2.

  • medfilt_window (int) – Median-filter window size applied before differentiation. Defaults to 5.

Returns:

The modified conditions_struct with the growth-rate series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.detrend_rescaled_series_population_mean(conditions_struct: list, rescaled_series: str) list[source]

Remove the population mean trend from a rescaled series in every condition.

The population mean is computed across worms within each condition independently. The detrended result is stored under f"{rescaled_series}_detrended".

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • rescaled_series (str) – Key of the rescaled series to detrend.

Returns:

The modified conditions_struct with the detrended series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.exclude_arrests_from_series_at_ecdysis(series_at_ecdysis: ndarray) ndarray[source]

Remove arrested worms from a per-molt measurement array.

A worm is considered arrested at molt i if its value at molt i+1 is NaN. The value at that molt is set to NaN in the output. The last molt event is always kept regardless.

Parameters:

series_at_ecdysis (np.ndarray) – Per-worm, per-molt values. Shape (n_molts,) for a single worm or (n_worms, n_molts) for multiple worms.

Returns:

Copy of series_at_ecdysis with arrested molt values replaced by NaN.

Return type:

np.ndarray

towbintools.plotting.utils_data_processing.rescale(conditions_struct: list, series_name: str, rescaled_series_name: str, experiment_time: bool = True, n_points: int = 100) list[source]

Rescale a series to a fixed number of points per larval stage and flatten the stage axis.

Each worm’s series is resampled to n_points per larval stage via rescale_series, yielding shape (n_worms, 4, n_points), which is then reshaped to (n_worms, 4 * n_points).

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_name (str) – Key of the raw series to rescale.

  • rescaled_series_name (str) – Key under which the rescaled series is stored.

  • experiment_time (bool) – If True, use "experiment_time"; otherwise use "time". Defaults to True.

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

Returns:

The modified conditions_struct with the rescaled series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.rescale_without_flattening(conditions_struct: list, series_name: str, rescaled_series_name: str, experiment_time: bool = True, n_points: int = 100) list[source]

Rescale a series to a fixed number of points per larval stage, retaining the stage axis.

Like rescale, but the output shape is (n_worms, 4, n_points) rather than being flattened. Useful when per-stage statistics are required downstream.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_name (str) – Key of the raw series to rescale.

  • rescaled_series_name (str) – Key under which the rescaled series is stored.

  • experiment_time (bool) – If True, use "experiment_time"; otherwise use "time". Defaults to True.

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

Returns:

The modified conditions_struct with the rescaled series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.smooth_and_rescale_series(conditions_struct: list, series_name: str, smoothed_series_name: str, experiment_time: bool = True, lmbda: float = 0.0075, order: int = 2, medfilt_window: int = 5, n_points: int = 100, flatten: bool = True) list[source]

Smooth a series and rescale it to a fixed number of points per larval stage.

After smoothing, the QC classification is discarded (all frames are treated as "worm") before resampling. Two new keys are written to each condition dict: smoothed_series_name (the smoothed but not rescaled series) and f"{smoothed_series_name}_rescaled" (the rescaled result).

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_name (str) – Key of the raw series.

  • smoothed_series_name (str) – Base key for the output series.

  • experiment_time (bool) – If True, use "experiment_time_hours"; otherwise use "time". Defaults to True.

  • lmbda (float) – Regularisation parameter for the Whittaker smoother. Defaults to 0.0075.

  • order (int) – Polynomial order for smoothing. Defaults to 2.

  • medfilt_window (int) – Median-filter window size applied before the smoother. Defaults to 5.

  • n_points (int) – Number of resampled points per larval stage. Defaults to 100.

  • flatten (bool) – If True, reshape the rescaled array from (n_worms, 4, n_points) to (n_worms, 4 * n_points). Defaults to True.

Returns:

The modified conditions_struct with the smoothed and rescaled series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.smooth_series(conditions_struct: list, series_name: str, smoothed_series_name: str, experiment_time: bool = True, lmbda: float = 0.0075, order: int = 2, medfilt_window: int = 5) list[source]

Smooth a measurement series for each worm in every condition using a classified smoother.

Short smoothed series are right-padded with NaN to match the original length.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series_name (str) – Key of the raw series to smooth.

  • smoothed_series_name (str) – Key under which the smoothed series is stored.

  • experiment_time (bool) – If True, use "experiment_time_hours"; otherwise use "time". Defaults to True.

  • lmbda (float) – Regularisation parameter for the Whittaker smoother. Defaults to 0.0075.

  • order (int) – Polynomial order for smoothing. Defaults to 2.

  • medfilt_window (int) – Median-filter window size applied before the smoother. Defaults to 5.

Returns:

The modified conditions_struct with the smoothed series added in place.

Return type:

list

towbintools.plotting.utils_data_processing.transform_series(conditions_struct: list, series: str, operation: str, new_series_name: str) list[source]

Apply a pointwise mathematical transformation to a series in every condition dict.

Parameters:
  • conditions_struct (list) – List of condition dicts.

  • series (str) – Key of the series to transform.

  • operation (str) – Transformation to apply. Supported values: "log" (natural log), "exp", "sqrt".

  • new_series_name (str) – Key under which the transformed series is stored.

Returns:

The modified conditions_struct with the transformed series added in place.

Return type:

list

utils_plotting

towbintools.plotting.utils_plotting.build_legend(single_condition_dict: dict, legend: dict | None) str[source]

Build a legend label string for a single condition.

Parameters:
  • single_condition_dict (dict) – Condition dict containing metadata fields.

  • legend (dict or None) – Mapping of condition dict keys to unit/suffix strings. Each key whose value is truthy is appended as "<value> <unit>"; a falsy value appends only "<value>". If None, the label defaults to "Condition <condition_id>".

Returns:

Legend label for the condition.

Return type:

str

towbintools.plotting.utils_plotting.get_colors(conditions_to_plot: list, colors: list | dict | None, base_palette: str = 'colorblind') list[source]

Return a list of colors, one per condition, validating user-supplied values.

Parameters:
  • conditions_to_plot (list) – Ordered list of condition identifiers.

  • colors (list or dict or None) –

    Color specification. - None: a seaborn base_palette palette is generated automatically. - list: must have the same length as conditions_to_plot. - dict: must contain a key for every entry in conditions_to_plot;

    values are returned in the same order.

  • base_palette (str) – Seaborn palette name used when colors is None. Defaults to "colorblind".

Returns:

Colors in the same order as conditions_to_plot.

Return type:

list

Raises:

AssertionError – If a list colors has a different length than conditions_to_plot, or if a dict colors is missing entries for any condition.

towbintools.plotting.utils_plotting.save_figure(fig: Figure, name: str, directory: str, format: str = 'svg', dpi: int = 300, transparent: bool = True) None[source]

Save a given matplotlib figure to the specified directory with the given name, in the chose format.

Parameters:
  • fig (matplotlib.figure.Figure) – Figure to save

  • name (str) – Name of the file (without extension)

  • directory (str) – Directory to save the file in

  • format (str) – File format to save the figure in

  • dpi (int) – Resolution of the saved figure

  • transparent (bool) – Whether to save the figure with a transparent background

Returns:

Full path to the saved file

Return type:

str

towbintools.plotting.utils_plotting.set_scale(ax: Axes, log_scale: bool | tuple | list) None[source]

Set the x- and/or y-axis scale of a matplotlib Axes object.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes to configure.

  • log_scale (bool or tuple or list) – Scale specification. - bool: applies to the y-axis only (True → log, False → linear). - tuple or list of two bools (x_log, y_log): sets both axes independently.

Returns:

None