spacr.gene_measurement_compare¶
Compare measurements across annotated gene groups and remaining cells.
Comparisons can use cells, wells, or plates as observations. Statistical test
selection is delegated to spacr.sp_stats, and each result records its
normality, equal-variance, and sample-size evidence. Cell-level tests treat
individual cells as observations and do not account for cells that share a
well; use the well level when wells are the experimental units.
Classes¶
Store one grouped measurement comparison. |
|
Appearance settings for grouped measurement comparisons. |
Functions¶
|
Build the long-form table used for plotting and statistical testing. |
|
Combine one or two measurement columns. |
|
Describe the comparison group and confounding for a contrast. |
|
Resolve the wells occupied by named controls in count data. |
|
Join morphology measurements onto montage object rows. |
|
Return whether object rows contain joined morphology measurements. |
|
Resolve a stable plate/field/object identity for each row. |
|
Draw a grouped measurement comparison. |
|
Render a grouped measurement comparison. |
|
Save a comparison and its supporting data in one folder. |
|
Resolve one well label for each object row. |
|
List the observed wells represented by each annotated group. |
|
Run the applicable statistical test and attach its evidence. |
Module Contents¶
- class spacr.gene_measurement_compare.Comparison[source]¶
Store one grouped measurement comparison.
- Parameters:
measurement – label for the measured value or arithmetic expression.
level – observation level used to build
frame.frame – long-form table containing
group,value, and the observation identifier when available.statistics – statistical-test records added by
with_statistics().note – warning or interpretation text that accompanies the result.
- class spacr.gene_measurement_compare.ComparisonStyle[source]¶
Bases:
spacr.style_base.FigureStyleAppearance settings for grouped measurement comparisons.
Shared axes, typography, grid, legend, page, and background settings are inherited from
spacr.style_base.FigureStyle. This class adds only comparison-specific choices such as plot kind, group filtering, jitter, and count labels.- Parameters:
x_label (str) – Horizontal-axis label; empty leaves the renderer’s category labels.
y_label (str) – Vertical-axis label; empty preserves the measurement name.
title (str) – Optional title drawn above the comparison.
x_scale (str) – Matplotlib horizontal scale inherited for house-style portability.
y_scale (str) – Matplotlib vertical scale applied after the values are drawn.
x_lim (tuple of float, optional) – Explicit horizontal limits, or
Nonefor data-derived limits.y_lim (tuple of float, optional) – Explicit vertical limits, or
Nonefor data-derived limits.invert_x (bool) – Reverse the horizontal axis after applying limits.
invert_y (bool) – Reverse the vertical axis after applying limits.
font_family (str) – Font-family value retained when styles move between figure types; the current comparison renderer does not apply a family override.
font_size (float) – General text size retained for style portability; comparison text uses the specific title, label, and tick sizes below.
title_font_size (float) – Title size in points.
label_font_size (float) – Axis-label size in points.
tick_font_size (float) – Group and value tick-label size in points.
font_weight (str) – Weight applied to the optional title.
figure_width (float) – Live and saved figure width in inches.
figure_height (float) – Live and saved figure height in inches.
dpi (int) – Resolution in dots per inch for raster exports.
grid (bool) – Whether to show the selected grid lines.
grid_axis (str) – Grid direction:
"x","y","both", or"none".grid_color (str) – Matplotlib-compatible grid-line color.
grid_width (float) – Grid-line width in points.
hide_top_right_spines (bool) – Remove the top and right frame lines when true.
legend (bool) – Retained for cross-style compatibility; comparison plots currently create no legend, so this value has no visual effect here.
legend_location (str) – Retained legend position; unused while comparisons have no legend.
background_color (str) – Matplotlib-compatible page and axes background, or
"none".transparent (bool) – Export raster/vector backgrounds transparently when supported.
kind (str) – Plot geometry from
PLOTS: box, jitter, violin, bar, or the default jitter-over-box combination.only (str) – Draw only one named group; stored statistics continue to describe the complete comparison.
rest_color (str) – Color of the
RESTgroup; empty uses the house grey.marker_size (float) – Scatter-marker area in squared typographic points.
jitter_width (float) – Maximum random horizontal displacement on either side of a category.
show_counts (bool) – Append each group’s observation count to its tick label.
- spacr.gene_measurement_compare.build(objects: pandas.DataFrame, measurement: str, *, groups: Dict[str, Sequence[Any]], level: str = 'well', value_column: str | None = None, operator: str = '', second: str = '', contrast: str = '', wells: Sequence[str] | None = None, controls: Sequence[str] | None = None) Comparison[source]¶
Build the long-form table used for plotting and statistical testing.
- Parameters:
objects – per-object rows containing the requested measurements. Well-level comparisons also require
plateID,rowID, andcolumnID; plate-level comparisons requireplateID.measurement – measurement column and default display label.
groups – mapping of group names to object-index values. Objects not listed in any group are assigned to
REST. If an object occurs in more than one group, the last matching mapping entry wins.level –
'cell','well', or'plate'. The default is'well'.value_column – source column to read instead of
measurement.operator – optional arithmetic operator from
OPERATORS.second – second measurement column used with
operator.contrast – which comparison group to build, from
CONTRASTS. The default''keeps every unannotated row, wherever it came from. The other three restrict it to the same well, to the control wells, or to every other well; each is recorded inComparison.notetogether with what it removes.wells – the wells of the annotation to INCLUDE.
Noneincludes all of them. A well left out is dropped from BOTH sides – it is not promoted into the comparison group, because a well excluded for being bad is no more usable as a comparison than as an annotation.controls – the wells the controls occupy, for the
'against_controls'contrast.control_wells()resolves them from the count data.
- Returns:
comparison data and any explanation of rows that could not be used. Missing measurement or identity columns produce an empty comparison with the reason in
Comparison.note.
Well- and plate-level values are means within each observation and group. A well containing both a named and an unassigned cell therefore contributes one row to each group.
- spacr.gene_measurement_compare.combine(objects: pandas.DataFrame, first: str, operator: str, second: str) Tuple[pandas.Series, str, int][source]¶
Combine one or two measurement columns.
- Parameters:
objects – table containing the measurement columns.
first – name of the first measurement column.
operator – one of
'','+','-','*', or'/'. An empty string returnsfirstunchanged.second – name of the second measurement column. Required when
operatoris not empty.
- Returns:
(values, name, dropped).nameis the displayed expression anddroppedcounts zero or non-finite denominators.- Raises:
KeyError – if a requested measurement column is absent.
ValueError – if
operatoris unsupported.
Division by zero or a non-finite denominator produces a missing value; it is never converted to zero or infinity.
- spacr.gene_measurement_compare.contrast_note(contrast: str) str[source]¶
Describe the comparison group and confounding for a contrast.
- Parameters:
contrast (str) – Contrast value from
CONTRASTS.- Returns:
str – User-facing explanation of the selected contrast. Unknown values return an empty string so older saved runs remain readable.
- spacr.gene_measurement_compare.control_wells(counts: pandas.DataFrame, typed, *, guide_column: str = 'grna', gene_column: str = 'gene') Tuple[str, ...][source]¶
Resolve the wells occupied by named controls in count data.
- Parameters:
counts (pandas.DataFrame) – Per-well count table with guide identifiers and recoverable well labels.
typed (str or sequence of str) – Control gene or guide names. Names are resolved through
spacr.control_names, including supported prefixes.guide_column (str, default 'grna') – Column containing guide identifiers.
gene_column (str, default 'gene') – Column containing gene identifiers, when available.
- Returns:
tuple of str – Matching well labels in first-occurrence order. An empty tuple is returned when the table lacks required columns or no control matches.
- spacr.gene_measurement_compare.join_measurements(objects: pandas.DataFrame, databases: Sequence[str], *, keep_uninfected: bool = True, png_list: bool = True) Tuple[pandas.DataFrame, str][source]¶
Join morphology measurements onto montage object rows.
- Parameters:
objects (pandas.DataFrame) – Montage object table. Its index is preserved because group membership is expressed with these index values.
databases (sequence of path-like) –
measurements.dbfiles containing object measurement tables.keep_uninfected (bool, default True) – Preserve cells without a pathogen row when reading joined tables.
png_list (bool, default True) –
Join the crop table as well as the object tables. It carries the classification score and the crop path, neither of which is in any object table – which is why it is on by default and why the panel offers it at all.
THE ARGUMENT EXISTS SO THE BOX CAN MEAN SOMETHING. It was a checkbox that was created, laid out and never read: a control the user can change that changes nothing, which is the failure this codebase writes comments about and shipped anyway.
- Returns:
frame (pandas.DataFrame) – Original rows widened with new numeric measurement columns. Existing columns are never replaced.
note (str) – Empty after a clean join; otherwise a user-facing explanation of files or rows that could not be read or matched.
Notes
Object identities are matched with
object_identity(). Recoverable read and matching failures are reported innoteso callers can still use measurements already present onobjects.
- spacr.gene_measurement_compare.measurements_are_joined(objects: pandas.DataFrame) bool[source]¶
Return whether object rows contain joined morphology measurements.
- Parameters:
objects (pandas.DataFrame) – Object table to inspect.
- Returns:
bool –
Truewhen a non-identifier column uses a cell, nucleus, pathogen, or cytoplasm measurement prefix.
- spacr.gene_measurement_compare.object_identity(frame: pandas.DataFrame) pandas.Series | None[source]¶
Resolve a stable plate/field/object identity for each row.
- Parameters:
frame (pandas.DataFrame) – Object table containing
prcfoor enough component columns to build it from a field key and an object label.- Returns:
pandas.Series or None – String identities aligned to
frame.Noneindicates that no supported object label or field key is available.
Notes
The
prcfokey combines plate, row, column, field, and object label and matches the identity written byspacr.io._read_and_join_tables().
- spacr.gene_measurement_compare.plot(comparison: Comparison, path: str | None = None, *, kind: str = 'jitter_box', title: str = '')[source]¶
Draw a grouped measurement comparison.
- Parameters:
comparison – grouped observations, optionally with statistics.
path – output path for an additional saved copy, or
Noneto keep the figure in memory only.kind – one of
'jitter_box','box','jitter','violin', or'bar'.title – custom title. By default the title reports the observation level, selected test, and P value when available.
- Returns:
a Matplotlib figure, or
Nonewhen no finite values can be drawn.
Named groups use the spaCR highlight palette and
RESTis grey. A bar plot warns on the figure when its smallest group has eight or fewer observations, because individual points show those data more clearly.
- spacr.gene_measurement_compare.render_comparison(comparison: Comparison, style: ComparisonStyle = None, *, figure=None, save_path=None)[source]¶
Render a grouped measurement comparison.
- Parameters:
comparison (Comparison) – Grouped observations returned by
build().style (ComparisonStyle, optional) – Plot appearance. The default style is used when omitted.
figure (matplotlib.figure.Figure, optional) – Existing figure to clear and redraw. Reusing a figure preserves the live-canvas object while restyling.
save_path (path-like, optional) – Also write the completed figure through spaCR’s export pipeline.
- Returns:
figure, axes – Rendered Matplotlib objects, or
(None, None)when no finite observations can be drawn.
- spacr.gene_measurement_compare.save(comparison: Comparison, folder: str, *, kind: str = 'jitter_box', settings: Dict[str, Any] | None = None, images: Dict[str, Sequence[Any]] | None = None, title: str = '') Dict[str, str][source]¶
Save a comparison and its supporting data in one folder.
- Parameters:
comparison – grouped observations, optionally with statistics.
folder – destination directory, created when necessary.
kind – plot type accepted by
plot().settings – regression settings to include in
settings.json.images – mapping from well identifiers to image arrays. Images are written under
cells/<well>/; missing images are allowed.title – optional title passed to
plot().
- Returns:
mapping from artifact type to each successfully written path.
The folder always receives
settings.json. When available, it also receives PDF and PNG figures,data.csv,statistics.csv, and the supplied cell images. The returned mapping lists only artifacts that were written successfully.
- spacr.gene_measurement_compare.well_labels(objects: pandas.DataFrame) pandas.Series | None[source]¶
Resolve one well label for each object row.
- Parameters:
objects (pandas.DataFrame) – Object table containing
montage_well,prc, or the plate, row, and column identifiers inWELL_KEY_COLUMNS.- Returns:
pandas.Series or None – Well labels aligned to
objects.montage_wellis preferred so labels match montage captions, followed byprcand the composite plate/row/column key.Noneindicates that well identity cannot be recovered from the table.
- spacr.gene_measurement_compare.wells_of(objects: pandas.DataFrame, groups: Dict[str, Sequence[Any]]) Dict[str, Tuple[str, ...]][source]¶
List the observed wells represented by each annotated group.
- Parameters:
objects (pandas.DataFrame) – Object rows indexed by the values stored in
groups.groups (dict of str to sequence) – Group names mapped to object-index values.
- Returns:
dict of str to tuple of str – Observed well labels in first-occurrence order. Groups with no matching rows and wells absent from the object table are omitted.
Notes
Wells are derived from the annotated object rows rather than count data, so the result contains only wells represented in the montage.
- spacr.gene_measurement_compare.with_statistics(comparison: Comparison) Comparison[source]¶
Run the applicable statistical test and attach its evidence.
- Parameters:
comparison – grouped observations produced by
build().- Returns:
the same comparison object with
statisticsreplaced.
spacr.sp_stats.perform_statistical_tests()selects among Student’s t-test, Welch’s t-test, Mann-Whitney U, one-way ANOVA, Welch’s ANOVA, and Kruskal-Wallis from the group count and assumption checks. Each result is supplemented with the observation level, measurement, normality result, equal-variance result, and sample size per group. Comparisons with fewer than two groups receive no statistical records.