Reference#

Testing#

spicyr.spicy(cells, condition=None, subject=None, covariates=None, image_id='imageID', cell_type='cellType', spatial_coords=('x', 'y'), r=None, from_=None, to=None, method='cell', effect='fraction', k=None, combine='davies', adjust_abundance=False, variance='cr2', ref=None, cores=1, survival=None, table_key='table', image_info=None, cell_weights=None, weight_labels=None, self_variance='sampled', self_variance_cells=50, alpha=0.05, **kwargs)#

Test whether the co-localisation of cell types differs between conditions, or is associated with survival.

Every ordered pair of cell types from_ -> to is tested: are to cells placed near from cells more than other cells are?

In each image, the share of to cells with at least one from cell within r is compared with its exact expectation q if the to cells were a random choice among the cells that are not from cells (random labelling of the observed cells). The effect (effect="fraction", the default) is the fraction of to cells placed next to (or kept away from) from cells. For a pair that attracts (more to cells next to from cells than q over all images together) it is (observed share - q) / (1 - q): if a fraction f of the to cells were moved next to from cells, the effect is f. For a pair that avoids it is (observed share - q) / q: if a fraction f of the to cells that would have a from cell nearby were moved away, the effect is -f. Either way it does not depend on how many from cells there are or how densely they are packed. The side is chosen once per pair from all images with a condition, without the conditions, and is reported in the side column. effect="count" gives the number of extra from cells within r of each to cell instead; it also reflects how many from cells surround a to cell (depth of infiltration), but it grows with how densely the from cells are packed. Images are combined within patients (subject) and patients within conditions by a frailty GEE with a second random effect for the images of a patient (each image is weighted by 1 / (its sampling variance + the between-image variance), so one large image cannot outweigh the patient’s other images), and the difference is tested with a CR2 variance on Satterthwaite degrees of freedom, with patients as the units. The difference is adjusted for any covariates and, with adjust_abundance=True, for the log share of the from type in each image; the unadjusted test is then reported alongside (unadjusted_* columns). When nearly every cell has a from cell within r (q close to 1), there is little room for attraction and an attracting pair’s images carry little information; a smaller r is more informative.

The extra fraction is bounded: an image of an avoiding pair with no to cell next to a from cell has the effect -1, and an image of an attracting pair with every to cell next to one has +1. A patient is informative at a radius when at least one of its images is not at -1 or +1. A radius where one condition has no informative patient is not tested: that condition’s patients all have the same effect, so its spread is exactly 0 and the standard error would rest on the other condition alone. Its p-value is NaN (with adjustment, adjusted_for is "none (no_information)"), and it is left out of the combination over radii. With more than two conditions, a pair where any condition has no informative patient is not tested.

The standard error of the difference is the sum of each condition’s own CR2 variance, on Satterthwaite degrees of freedom; with adjustment, the CR2 variance of the adjusted design. variance="hartung_knapp" keeps its own variance.

Without adjustment, the CR2 t of two conditions is corrected for skewness (a one-term Edgeworth expansion, Hall’s transformation) before its p-value is taken: with conditions of unequal size, right-skewed patient effects make the t of the smaller condition’s mean skewed, with too many small p-values on one side. The skewness comes from the patients’ residuals, pooled over both conditions and weighted as in the test, and is shrunk by its own uncertainty, so that the correction fades out in small studies; it also vanishes for conditions of equal size and weight, and is not applied when a condition has fewer than 3 patients. The difference, standard error and df are unchanged.

For a self-pair (from_ = to) every cell can carry the label, so random labelling moves both the cells counted and their neighbours. Its variance is the random-labelling variance of the self-pair (for the radius graph and for the k nearest neighbours), not the variance of a pair of two types. For the extra fraction this variance depends on how many neighbours each pair of nearby cells shares, which takes time in proportion to the number of cells times the square of the number of neighbours per cell. With a radius, the shared neighbours are by default counted from self_variance_cells randomly chosen cells of each image and scaled up (self_variance="sampled"), an unbiased estimate of the variance; the sample is fixed by the image, so results are reproducible and the same as spicyR’s. "exact" counts them for every cell; "geometric" takes two cells to share their local density times the area where their two discs overlap; "geometricSampled" corrects that with the sampled cells. The count effect and the k nearest neighbours always use the exact variance.

With the extra fraction, an image whose room on the pair’s side (the to cells without a from neighbour expected by chance for an attracting pair, those with one for an avoiding pair) is below one cell is not used: its effect could not show the pair’s side, and could be large in the other direction. The side is chosen first, from every image.

Every requested pair has a row in cell_results: not_tested gives why a pair (or, in radius_results, a radius) was not tested ("one_patient_per_group", "no_information", "few_effective_units", "no_variation" or "too_few_df"; for a continuous condition also "too_few_units" or "design_not_full_rank"; for survival also "no_deaths", "no_survivors" or "too_few_units"; None when it was), and its p-value is then NaN and not counted in the BH adjustment. A test (of any condition, and the overall test) is not done when its Satterthwaite degrees of freedom are below 1 or not finite ("too_few_df").

An adjustment that differs between a patient’s images (the from type’s share, or an image-level covariate) can relate to the effect differently within a patient than between patients. Each such column therefore gets a second column, its plain average over the patient’s images: the conditions are compared at equal patient averages, and the reported effect of the adjustment (<column>_effect) is its slope within patients. The between-image variance is then estimated within patients from what the adjustments leave (tau2_image), and the patient variance (tau2) from the patients’ average effects and adjustments, each by Paule-Mandel. An adjustment with one value per patient (for example age) gets no second column.

With more than two conditions, the pairs called by the overall test (overall_p_adj at most alpha) are followed up: every two levels are compared, each by the two-condition test on the patients of those two levels, Bonferroni-corrected within the pair at the Benjamini-Bogomolov level (follow_up_results; see SpicyResults.top_follow_ups()).

With a survival outcome, a null Cox model of the outcome on the covariates (an image-level covariate as its average over the patient’s images) gives each patient’s martingale residual M, and the effect is regressed on M (with the covariates and, with adjust_abundance=True, the log share of the from type) by the same frailty model, CR2 variance and Satterthwaite df: the score test (p_value). Patients with no outcome (or with a covariate missing in all their images) are left out before anything else. A pair is tested when, among its informative patients (an outcome and an image row for the pair), there is a death (else "no_deaths") and a survivor ("no_survivors"), and at least q + 2 patients ("too_few_units"; q = 2, plus one per covariate column, plus one per column that varies between a patient’s images); n_deaths counts their deaths. The hazard ratio (hazard_ratio_sd, per SD of the shrunken effect) comes from a Cox model with the covariates; its standard error log_hr_se is model-based and approximate, so the score test’s p_value is a pair’s only p-value. One radius.

A patient’s weight within its condition grows with the information of its images, so one or two patients can carry nearly all of a condition’s weight. A radius where a condition’s effective patients (Kish’s (sum w)^2 / sum w^2 of the patients’ weights w) fall below the smaller of 3 and half the number of its patients that contribute at that radius is not tested: its p-value is NaN (with adjustment, adjusted_for is "none (few_effective_units)"), and it is left out of the combination over radii. A condition of 3 patients with equal weights can therefore be tested. With more than two conditions, a pair where any condition falls below this is not tested.

Images with a missing condition are left out of every step: the choice of the side, the between-image variance and the tests.

from is spelled from_ because from is a Python keyword (**{"from": ...} also works).

Parameters:
  • cells – A pandas DataFrame (one row per cell), an AnnData object (cells as observations; coordinates in obsm["spatial"] or obs columns), a SpatialData object (its annotation table table_key), or the path of a SpatialData store (.zarr) or of an AnnData zarr store. A store is read lazily: the image and cell-type columns are loaded once as integer codes, the coordinates (obsm["spatial"], or the obs columns spatial_coords) a batch of whole images at a time, and the condition, subject and covariates once per image, so the data never need to fit in memory. Reading is fastest when the rows are grouped by image (as spatialdata writes a table sorted by region); categorical image and cell-type columns keep the codes small.

  • condition – Column of the image-level condition: two groups; more than two groups (each level against the reference, and an overall test of all of them); or a number with more than two values, taken as continuous (the slope of the effect on it). Make a numeric column categorical to compare its values as groups.

  • subject – Column of the patient of each image. Images of one patient are combined; by default each image is a patient.

  • covariates – Image- or patient-level columns to adjust for. The effect of each is reported as <column>_effect and <column>_p_value (one column per level after the first for a categorical covariate); for an image-level one, its slope within patients (see above). With survival, they enter both the null Cox model and the model of the effect.

  • r – Radius, or several radii combined by combine (two conditions only; a survival outcome takes one radius): “davies” (the default: Davies’ upper bound on the max-T p-value, a closed form that is never smaller than the exact p-value and takes microseconds for any number of radii; slightly conservative), “maxT” (the exact max-T p-value) or “cauchy”. Default 50. The max-T p-value is the multivariate normal probability that the largest absolute z over the radii is at least the one observed, computed as a sum of first-exceedance terms by the quasi-Monte Carlo method of Genz and Bretz to a relative error of about 0.1% (by quadrature for two radii); the same inputs always give the same value. A radius whose correlation with a smaller kept radius exceeds 0.995 is left out. cell_results then has maxT_converged: True when the pair’s p-value met the error target. Choose one radius from the relationship of interest when you can; when the scale is unknown, we recommend about 4 radii spanning the range of interest, none below about one cell diameter: many closely spaced radii add little information, cost some power and, with max-T, are slower.

  • from_ – Cell types to test (all ordered pairs by default).

  • to – Cell types to test (all ordered pairs by default).

  • method – “cell” (spicyR v2). The image-level method of spicyR (spicyR v1) is not yet available in Python.

  • effect – “fraction” (default): the extra fraction of to cells moved next to (or away from) from cells within r; “count”: the number of extra from cells within r of each to cell. “allocation”, the earlier name of “fraction”, is also accepted. With k, “within r” means among the cell’s k nearest neighbours.

  • k – Use the k nearest neighbours instead of a radius.

  • adjust_abundance – Adjust the test for the log share of the from type in each image (default False). Its effect is reported as abundance_effect. It does not separate more from cells from more densely packed ones, and it removes real effects when the share tracks the condition.

  • variance – “cr2” (default: each condition’s CR2 variance, on Satterthwaite df, see above) or “hartung_knapp” (the model-based variance, scaled by the Pearson statistic when that exceeds its df and never below CR2, on m - 2 df). The variance used is in .variance of the result.

  • survival – A survival outcome: (time_column, event_column), one value per patient (the R package’s Surv(time, event)). Leave condition empty. (Older form: condition=time_column, survival=event_column.)

  • image_id – Columns of the image, the cell type and the coordinates. For SpatialData, images are the table’s regions (its region_key column) unless image_id names another column.

  • cell_type – Columns of the image, the cell type and the coordinates. For SpatialData, images are the table’s regions (its region_key column) unless image_id names another column.

  • spatial_coords – Columns of the image, the cell type and the coordinates. For SpatialData, images are the table’s regions (its region_key column) unless image_id names another column.

  • cores – Threads. Batches of whole images are read and summarised in parallel; results do not depend on it.

  • table_key – The annotation table of a SpatialData object or store.

  • image_info – A table with one row per image, for condition, subject, covariates or the survival columns that are not columns of the cell table: a DataFrame, an AnnData object (its obs), or the key of a table of the SpatialData object or store. Its image_id column, or else its index, gives the image IDs. Every image of the cells needs a row, and every row an image.

  • cell_weights – Optional cell weights in [0, 1], in the order of the cells: a 1-D array with one weight per cell for its own cell type (for example a quality score), or a cells x labels matrix of soft cell type membership (for example a classifier’s confidence; a DataFrame, whose columns are the labels, or a numpy array or scipy sparse matrix with weight_labels). A 1-D array (numpy array, list or pandas Series, taken by position) is the same as the cells x cell types matrix with each cell’s weight in its own type’s column. With a matrix, from_ and to name labels, and labels may overlap (a group and its subtypes). A to cell counts with its weight, and its score is the chance that it has a from neighbour within r if labels were drawn from the weights (fraction), or the summed from weight of its neighbours (count). The null shuffles the to weights over the cells whose from weight is below 1, whose exact mean and variance replace those of random labelling; 0/1 weights give the results of the cell types. The abundance share is the from label’s summed weight over the image’s cells. A label with itself, and a pair where some to cells have from weight 1 (for example a group and one of its subtypes), are tested instead under random labelling of all the image’s cells, each cell keeping its pair of from and to weights and never its own neighbour, with the mean and variance of the score under that permutation (fraction: by default from a closed form that corrects every pair of cells exactly for sampling without replacement, exact for up to two cells and second order in 1 / cells; self_variance="exact" computes them exactly, at a cost of cells x neighbourhood size^2 per image; count: exact) (for the count effect, as for a self-pair of cell types, the expected score is a share of the summed from weight around all the cells, the share that gives the difference a mean of 0). With 0/1 weights a label with itself gives the self-pair of that cell type (fraction: with the variance of self_variance). One cell with from weight 1 and a to weight above 0 in any image is enough to test a pair this way in every image. One radius, cells in memory.

  • weight_labels – The labels of the columns of cell_weights when it is a 2-D numpy array or sparse matrix.

  • self_variance – Cell method, extra fraction with a radius: how a self-pair’s variance counts the neighbours shared by nearby cells: "sampled" (the default), "exact", "geometricSampled" or "geometric" (see above). With soft cell_weights, "exact" gives the exact moments of the pairs tested under random labelling of all cells, and any other value the closed form described under cell_weights.

  • self_variance_cells – The number of cells sampled in each image for "sampled" or "geometricSampled" (every cell when an image has no more).

  • alpha – More than two conditions: the level of the gate for the follow-up comparisons (pairs whose overall_p_adj is at most alpha are followed up; see SpicyResults.top_follow_ups()). Default 0.05.

Return type:

SpicyResults

Checking calibration#

spicyr.calibration_check(cells, condition=None, subject=None, survival=None, n_shuffles=10, thresholds=(0.05, 0.01), rng=None, image_id='imageID', **kwargs)#

Check that spicyr.spicy() is calibrated on your data by shuffling the condition.

The condition may be groups, a number (continuous) or a survival outcome.

Shuffles the condition across patients (or across images, without subject), which removes any real difference between the groups while keeping everything else about the study, and runs spicyr.spicy() on each shuffle. If the test is calibrated, about 5% of pairs have p < 0.05 and about 1% p < 0.01 in each shuffle. Pairs share cells, so the percentage moves by a few points from one shuffle to the next; look at the average over shuffles. Patients without a condition keep it missing.

Parameters:
  • cells – A pandas DataFrame or AnnData object, as for spicyr.spicy() (not a store).

  • condition – The column of the condition to shuffle.

  • subject – The column of the patient. Each patient keeps one condition, moved as a whole; without it, the condition is shuffled across images.

  • survival – Instead of condition: a survival outcome (time_column, event_column), whose time and event are shuffled together.

  • n_shuffles – The number of shuffles.

  • thresholds – The p-value thresholds to report.

  • rng – A numpy.random.Generator, or a seed for one.

  • image_id – The column of the image.

  • **kwargs – Other arguments of spicyr.spicy(), such as r, cell_type or covariates.

Returns:

A SpicyCalibration, a DataFrame with one row per shuffle and threshold: shuffle, threshold and percent, the percentage of pairs whose p-value is below the threshold. Its summary() gives the average percentage over the shuffles at each threshold, with the expected one, and plot() shows each shuffle against the expected percentage.

Examples

>>> import spicyr
>>> cells = spicyr.datasets.example_cells()
>>> shuffles = spicyr.calibration_check(cells, condition="condition", subject="patient", r=30, n_shuffles=2, rng=1)
>>> shuffles.summary()
>>> shuffles.plot()
class spicyr.SpicyCalibration(data=None, index=None, columns=None, dtype=None, copy=None)#

The result of calibration_check(): a DataFrame with one row per shuffle and threshold.

summary() gives the average percentage over the shuffles at each threshold, with the expected one, and plot() shows each shuffle against the expected percentage.

plot(ax=None)#

Each shuffle’s percentage of pairs below each threshold (points), with the expected percentage (red).

Returns:

The matplotlib axes.

summary()#

The average percentage of pairs below each threshold over the shuffles, with the expected percentage.

Return type:

DataFrame

Returns:

A DataFrame with one row per threshold, the largest first: threshold, expected (100 times the threshold) and percent, the mean over the shuffles.

Writing a store#

spicyr.write_cell_store(cells, path, image_id='imageID', spatial_coords=('x', 'y'), table_key='table', image_info=None, info_key='images', chunk_rows=1048576, points=True)#

Write cells as a SpatialData Zarr store.

The store holds the cells as an AnnData table under tables/ (Zarr v3), which spicy() reads a block of rows at a time and spatialdata.read_zarr() reads as a SpatialData object. The coordinates become the obsm array "spatial" and the other columns the table’s obs (categorical columns stay categorical). An AnnData object is written whole: X, layers, var, obsm, varm, obsp, varp and uns as anndata writes them (chunked), and its obs as described here. The cells of each image also become a points element named after the image (x, y and the "instance_id" that links each point to its row of the table), so the table annotates elements of the store. The image column is the table’s region key: a categorical column whose categories are the images in order of first appearance, unless it is categorical already. A column "instance_id" numbers the cells from 0 (unsigned integers of 16 bits at least). A table with one row per image can be added as a second table. Every array of the length of the table is written in chunks of chunk_rows rows compressed with zstd, one chunk at a time, so writing needs little memory beyond that of cells, however many cells it has.

Parameters:
  • cells – A pandas DataFrame with one row per cell, or an AnnData object (cells as observations; its obs is written, with the coordinates from the obs columns spatial_coords or else from obsm["spatial"]). Columns are categorical, strings, integers, floats or booleans (pandas’ nullable types included).

  • path – The directory of the store (replaced if it exists).

  • image_id – The column of the image.

  • spatial_coords – The two columns of the coordinates. They are written as float64 (float32 coordinates stay float32).

  • table_key – The name of the cell table.

  • image_info – Optional: a DataFrame (or an AnnData object, its obs) with one row per image, written as the table info_key. Its image_id column, or else its index, gives the image IDs.

  • info_key – The name of the per-image table.

  • chunk_rows – Rows per chunk of every array of the length of a table.

  • points – Whether to write the cells as points, one points element per image (needs pyarrow). Image IDs must then be valid element names (letters, digits, _, - and .); otherwise no points are written, with a warning.

Returns:

The path of the store.

Examples

>>> import numpy as np, pandas as pd
>>> rng = np.random.default_rng(1)
>>> cells = pd.DataFrame({"imageID": pd.Categorical(np.repeat(["a", "b"], 50)),
...                       "cellType": pd.Categorical(np.tile(["T", "B"], 50)),
...                       "x": rng.uniform(0, 100, 100), "y": rng.uniform(0, 100, 100)})
>>> path = write_cell_store(cells, "cells.zarr")

Results#

class spicyr.SpicyResults(cell_results, levels, survival, radius_results=None, image_ids=list(), condition=None, subject=None, pairwise_assoc=dict(), image_weights=dict(), r=None, k=None, method='cell', effect='fraction', variance=None, continuous=False, follow_up_results=None, alpha=None, condition_information=None)#

Results of spicyr.spicy().

cell_results is the full table, one row per pair (and per level when there are more than two conditions): for the extra fraction the pair’s side (“attract” or “avoid”, which sets its scale), the effect (effect: “fraction”, the extra fraction of to cells moved next to or away from from cells within r, or “count”, the extra from cells per to cell) in the reference condition (excess_ref) and the comparison condition, the difference, its standard error, Satterthwaite df, p-value and BH-adjusted p-value, the frailty variance tau2, what the test was adjusted for (adjusted_for), the effect and p-value of each adjustment (abundance_effect, <covariate>_effect, …) and the unadjusted test (unadjusted_*). image_weights gives, for every pair, each image’s share of its condition’s information, and with two conditions condition_information gives that information for each pair (pairs x conditions: the sum of the patients’ weights; see test_correlation()). With adjustment or several radii, pairwise_assoc, image_weights and condition_information are those of the unadjusted test at the radius nearest the median. For survival: the score test (score_coefficient, p_value) and the hazard ratio per SD of the shrunken excess.

With more than two conditions each pair also has its overall test (overall_F on overall_df1 and overall_df2 df, overall_p_value, overall_p_adj: the CR2 Wald test of every level equal to the reference, with the HTZ small-sample F of Tipton and Pustejovsky). With a continuous condition (continuous), one row per pair: the effect at the condition’s mean (excess_mean) and its slope per unit of the condition (excess_slope), with its CR2 standard error and Satterthwaite df; condition holds each image’s value. follow_up_results (more than two conditions) holds the follow-up comparisons of two levels for the pairs called by the overall test at level alpha (see top_follow_ups()). With several radii and combine="maxT", maxT_converged says whether a pair’s max-T p-value met its error target (about 0.1%). For survival, log_hr_se is model-based and approximate, n_deaths counts the deaths among the informative patients, and every requested pair has a row, with not_tested giving why a pair was not tested.

bind(pair=None, from_=None, to=None, parent=None, **kwargs)#

The per-image values of every pair, or of one pair, as spicyR’s bind().

One row per image, with the image IDs as index: imageID, condition, subject (if given) and one column per pair, named "from__to" (only pair if given). With from_ and to, a table of that pair alone, with its effect in a column effect and each image’s weight in the test, to look up the images behind one pair. NaN where the pair could not be measured in an image.

Return type:

DataFrame

box_plot(from_, to, ax=None, interactive=False)#

Per-image excess of one pair by condition, with a point per image behind each box.

The Python version of spicyR’s spicyBoxPlot().

Each point is sized by how much the image contributes to the test (its weight in the frailty model, relative to the average image of its condition). With interactive=True the result is a plotly figure: hover over a point to see its image, patient, excess and weight, which helps to find images worth looking at with spicyr.plot_image(). Images in which the pair was not tested are not shown.

radius_plot(from_=None, to=None, ax=None, **kwargs)#

The evidence for pairs at each radius, as spicyR’s radiusPlot().

For a result with several radii, plots -log10 of the p-value of each chosen pair at every radius, one line per pair, to show the scale at which the evidence is strongest. The combined p-value over the radii is in top_pairs(). from_ and to choose the pairs (one or several cell types each; every pair between them).

Returns:

The matplotlib axes.

signif_plot(fdr=False, breaks=None, comparison_group=None, colours=('#4575B4', 'white', '#D73027'), marks_to_plot=None, cutoff=0.05, ax=None)#

Bubble plot of every pair, as spicyR’s signifPlot().

Each pair is a disc at (to, from). Its left half is coloured by the excess in the reference condition and its right half by the excess in the comparison condition (for a continuous condition, one SD across images below and above the condition’s mean); the radius grows with -log10 p (the BH-adjusted p with fdr=True), and a black ring marks p (or, with fdr=True, the BH-adjusted p) below cutoff. breaks is (low, high, step) for the colour scale. For survival results each disc is one colour: the log hazard ratio per SD.

test_correlation(method='cr2', n_permutations=1000, cores=1)#

The correlation between the tests of the pairs.

The tests of pairs that share a cell type, or that are nested (a cell type and a group containing it), are correlated through the patients they share. This estimates the correlation between every two pairs’ tests from the one fit, for a correction for multiple testing that uses it in place of independence.

Each pair’s difference between conditions is a weighted mean over patients: a patient’s summary is the weighted mean of its images’ effects (pairwise_assoc) with the images’ weights (image_weights), and its weight is the sum of its images’ weights times its condition’s information (condition_information).

method="cr2": each patient’s CR2 influence on the difference, psi = h (summary - its condition’s mean) / sqrt(1 - h) with h the patient’s share of its condition’s weight, negated in the reference condition. Its squares sum to the test’s squared standard error, and the cross-products of two pairs’ influences, divided by the two standard errors, estimate the correlation of their differences. It is noisy when a few patients carry most of a pair’s weight and one condition is small.

method="permutation": the conditions are permuted over the patients n_permutations times; for each permutation every test is recomputed in closed form from the patients’ summaries and weights (each condition’s weighted mean, its CR2 variance and Satterthwaite df, as spicyr.spicy() computes them; the between-patient variance is held at the fit’s, and of spicy()’s rules for not testing a pair only the need for two patients in each condition is applied), and its p-value is turned into a z with the sign of its (skewness-corrected) t (0 when a condition has fewer than two of the pair’s patients). The correlation of the tests’ z over the permutations is returned. The permutations come from a fixed seed, so a result always gives the same matrix, in Python and in R.

Needs two conditions, one radius (or k), no adjustment (no covariates, adjust_abundance=False) and variance="cr2".

Parameters:
  • method (str) – "cr2" (the default) or "permutation".

  • n_permutations (int) – The number of permutations for method="permutation".

  • cores (int) – The number of threads for method="permutation".

Return type:

DataFrame

Returns:

A symmetric DataFrame with one row and one column per row of cell_results (the same index): the estimated correlation between the pairs’ tests. The diagonal is 1, and rows and columns of pairs not tested (or, by permutation, whose z is the same in every permutation) are NaN.

top_follow_ups(n=None, from_=None, to=None, significant=False, figures=None, **kwargs)#

The follow-up comparisons of two levels, for more than two conditions, as spicyR’s topFollowUps().

With more than two conditions, each pair is first tested by the overall test (are all the levels equal?). The pairs it calls, by BH at level alpha (the argument of spicyr.spicy(), 0.05 by default), are followed up: every two levels are compared, each by the two-condition test on the patients of those two levels only, with their own between-image and between-patient variances, the same rules for not testing and the same adjustments; the pair’s side stays the one chosen from every image. Within a pair the comparisons are Bonferroni-corrected at the Benjamini-Bogomolov level alpha R / m (R the pairs called, m the pairs with an overall test): a comparison is significant when p_value <= p_threshold, p_threshold = alpha R / (m K) with K the comparisons tested in the pair (n_comparisons).

One row per called pair and comparison (level_ref is the reference of the comparison, level_comp the other level): excess_ref, excess_comp, excess_difference, se, df, p_value, p_threshold, significant, the pair’s overall_p_value and overall_p_adj, n_comparisons, tau2 and not_tested; side and tau2_image for the extra fraction; with adjustment, adjusted_for and the unadjusted difference and p-value. Sorted by the overall p-value, then the comparison’s p-value.

Parameters:
  • n (int | None) – The number of rows to list (all by default).

  • from_ – Only the pairs with these from and to cell types (from also works as a keyword).

  • to – Only the pairs with these from and to cell types (from also works as a keyword).

  • significant (bool) – Only the significant comparisons.

  • figures (int | None) – Round to figures significant figures, as R’s signif().

Return type:

DataFrame

top_pairs(n=<object object>, coef=None, adj='fdr', cutoff=None, figures=None, from_=None, to=None, full=False, **kwargs)#

The most significant pairs, or the results of chosen pairs, as spicyR’s topPairs().

One row per pair (and per level with more than two conditions), most significant first, with the pair ("from__to") as index. The columns are those of the test: from, to, side, excess_ref and excess_comp (the average effect in the reference and the comparison group), excess_difference, p_value and p_adj; with several radii, r, the radius with the strongest evidence; with covariates, the effect and p-value of each (<covariate>_effect, <covariate>_p_value); for survival, hazard_ratio_sd. full=True gives every column of cell_results.

Parameters:
  • n (int | None) – The number of pairs to list (10 by default). None lists every pair, as does leaving n out when cutoff is given.

  • coef (str | None) – With more than two conditions, the level to list ("III" or "conditionIII").

  • adj (str) – The p-value adjustment: "fdr" (or "BH"), Benjamini-Hochberg across all pairs.

  • cutoff (float | None) – List only the pairs whose adjusted p-value is at most cutoff.

  • figures (int | None) – Round to figures significant figures, as R’s signif().

  • from_ – Only the pairs with these from and to cell types (one or several; from also works as a keyword).

  • to – Only the pairs with these from and to cell types (one or several; from also works as a keyword).

  • full (bool) – Every column of the test, not only the main ones.

Return type:

DataFrame

The attributes of a results object:

Attribute

Contents

cell_results

every column of the test (what top_pairs(n=None, full=True) lists, unsorted): one row per pair (and per group with more than two groups): excess_ref, excess_comp, excess_difference, se, df, p_value, p_adj, tau2; with covariates or adjust_abundance=True, what the test was adjusted for (adjusted_for), the effect and p-value of each adjustment (<covariate>_effect, <covariate>_p_value, abundance_effect) and the unadjusted test (unadjusted_difference, unadjusted_se, unadjusted_df, unadjusted_p_value, unadjusted_p_adj). For survival: score_coefficient, p_value, p_adj, hazard_ratio_sd, log_hr_se (model-based and approximate), n_deaths, not_tested and, with adjust_abundance=True, the p-value and hazard ratio without it. With several radii: r and p_value_best_radius; with combine="maxT", maxT_converged (whether the max-T p-value met its error target of about 0.1%)

follow_up_results, alpha

with more than two conditions, the follow-up comparisons of two levels for the pairs called by the overall test at level alpha (what top_follow_ups() lists)

radius_results

with several radii, one row per pair and radius (what radius_plot() shows)

pairwise_assoc

the effect of every pair in every image (what bind() returns)

image_weights

the weight of every image in the test of every pair: its share of its group’s information (the point sizes of box_plot(), and the weight column of bind(from_=, to=))

condition_information

with two conditions, each condition’s information in the test of every pair (one row per pair, one column per group: the sum of its patients’ weights); an image’s weight times it is the image’s weight on the scale of the model (what test_correlation() uses)

levels, image_ids, condition, subject, r, k, effect

the groups, images and settings of the analysis (effect: “fraction” or “count”)

Proportions#

spicyr.get_prop(cells, feature='cellType', image_id='imageID')#

The proportion of each level of feature in each image, as spicyR’s getProp().

Parameters:
  • cells – A pandas DataFrame or an AnnData object with one row per cell.

  • feature – The column whose proportions are computed, e.g. cell types or regions.

  • image_id – The column of the units: images, or patients to pool the images of each patient.

Return type:

DataFrame

Returns:

A DataFrame with one row per unit and one column per level of feature; each row sums to one.

spicyr.col_test(df, condition, type=None, feature=None, image_id='imageID', subject=None)#

Test each column of a table, such as proportions per image, as spicyR’s colTest().

Each column is tested for a difference between two groups (Wilcoxon or Welch t-test) or for an association with survival (Cox model).

Parameters:
  • df – A DataFrame with one row per image (or patient) and one column per feature, such as the output of get_prop(). With feature given, df is instead a table of cells (a DataFrame or an AnnData object), and the proportions of feature in each image_id are computed first.

  • condition – The group of each row of df, or two columns (time, event) for survival. A Series or DataFrame whose index holds row names of df is matched to the rows by name (rows without a condition are left out); otherwise the condition is taken in the row order of df. With feature, the name of the cells’ group column.

  • type – "wilcox", "ttest" or "survival"; by default "ttest" for one condition and "survival" for two columns.

  • feature – The column of the cells whose proportions are tested, e.g. cell types or regions.

  • image_id – With feature: the column of the images.

  • subject – With feature, optional: the column of the patient. The proportions are then those of each patient’s cells, all images pooled, and each patient is one unit of the test.

Return type:

DataFrame

Returns:

A DataFrame with one row per column of df, ordered by p-value: the group means (t-test) or medians (Wilcoxon test), the test statistic (tval.W, tval.t) or the Cox coefficient and its standard error (survival), the p-value (pval), the Benjamini-Hochberg adjusted p-value (adjPval) and the column name (cluster), all rounded to two significant digits as in R.

Plotting an image#

spicyr.plot_image(cells, image, from_=None, to=None, r=None, image_id='imageID', cell_type='cellType', spatial_coords=('x', 'y'), table_key='table', ax=None, **kwargs)#

Plot images, showing their cell types or the from_ and to cells of a pair.

Without from_ and to, every cell is shown, coloured by its cell type, with the same colour for a cell type in every image of cells. With them, the density of all cells is shown in blue, with the from_ cells (gold) and to cells (dark red) on top. With r, a circle of radius r is drawn around each to cell: the from_ cells inside the circles are those that spicyr.spicy() counts. Several images are drawn side by side, in the order given, on the same scale.

Parameters:
  • cells – A pandas DataFrame, AnnData or SpatialData object, as for spicyr.spicy().

  • image – The image to plot (a value of the image_id column), or a list of several.

  • from_ – The two cell types (from also works as a keyword). Optional, together.

  • to – The two cell types (from also works as a keyword). Optional, together.

  • r – Optional radius of the circles around the to cells, in the units of the coordinates.

  • ax – One image: the matplotlib axes to draw on.

Returns:

One image: the matplotlib axes. Several: the matplotlib figure, with a panel per image.

Data#

spicyr.datasets.metabric_ali2020(path=None, as_anndata=False)#

Imaging mass cytometry of 483 breast tumours from the METABRIC cohort (Ali et al., Nature Cancer 2020).

One row per cell (433,001 cells): the core (file_id), the patient (metabricId), the cell type assigned by the authors (description), the coordinates in micrometres (x, y) and the patient’s clinical data, including ER status (ER.Status) and relapse-free survival (timeRFS, eventRFS).

The file (130 MB) is downloaded once from Bioconductor’s ExperimentHub, where the R package SpatialDatasets gets it (spe_Ali_2020), and cached in ~/.cache/spicyr (or $SPICYR_CACHE). Reading it needs the rds2py package (pip install "spicyr[data]").

With as_anndata=True the cells are returned as an AnnData object: the table as obs and the coordinates in obsm["spatial"] (needs anndata).

spicyr.datasets.schurch2020(path=None, as_anndata=False)#

CODEX imaging of colorectal cancer (Schürch et al., Cell 2020): 35 patients, four tissue cores each.

One row per cell (258,385 cells) with the core (imageID), the patient (patient), the cell type (cellType), the coordinates (x, y) and the patient group (group: 1 = Crohn’s-like reaction, 2 = diffuse inflammatory infiltration). Downloaded from ExperimentHub as spe_Schurch_2020 of the R package SpatialDatasets (82 MB), and cached as for metabric_ali2020(). as_anndata as for metabric_ali2020().

spicyr.datasets.example_cells()#

A small simulated data set: 14 patients (7 per condition, A and B), two images each, six cell types.

In condition B, about a third of the T cells were moved next to tumour cells. Both directions change; tumour -> T (are T cells placed near tumour cells? tumour cells counted around each T cell, the recruited type at the centre) is the direction whose excess does not depend on how common tumour cells are.

Return type:

DataFrame

spicyr.format_data(cells, image_id='imageID', cell_type='cellType', spatial_coords=('x', 'y'), table_key='table')#

One row per cell with columns imageID, cellType, x, y, and every other column kept.

Rows are ordered by image in order of first appearance, as spicyR’s .format_data().