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_ -> tois tested: aretocells placed nearfromcells more than other cells are?In each image, the share of
tocells with at least onefromcell withinris compared with its exact expectation q if thetocells were a random choice among the cells that are notfromcells (random labelling of the observed cells). The effect (effect="fraction", the default) is the fraction oftocells placed next to (or kept away from)fromcells. For a pair that attracts (moretocells next tofromcells than q over all images together) it is (observed share - q) / (1 - q): if a fraction f of thetocells were moved next tofromcells, the effect is f. For a pair that avoids it is (observed share - q) / q: if a fraction f of thetocells that would have afromcell nearby were moved away, the effect is -f. Either way it does not depend on how manyfromcells 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 thesidecolumn.effect="count"gives the number of extrafromcells withinrof eachtocell instead; it also reflects how manyfromcells surround atocell (depth of infiltration), but it grows with how densely thefromcells 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 anycovariatesand, withadjust_abundance=True, for the log share of thefromtype in each image; the unadjusted test is then reported alongside (unadjusted_*columns). When nearly every cell has afromcell withinr(q close to 1), there is little room for attraction and an attracting pair’s images carry little information; a smallerris more informative.The extra fraction is bounded: an image of an avoiding pair with no
tocell next to afromcell has the effect -1, and an image of an attracting pair with everytocell 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_foris"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 fromself_variance_cellsrandomly 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
tocells without afromneighbour 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_testedgives why a pair (or, inradius_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
fromtype’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_adjat mostalpha) 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; seeSpicyResults.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, withadjust_abundance=True, the log share of thefromtype) 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_deathscounts their deaths. The hazard ratio (hazard_ratio_sd, per SD of the shrunken effect) comes from a Cox model with the covariates; its standard errorlog_hr_seis model-based and approximate, so the score test’sp_valueis 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_foris"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.
fromis spelledfrom_becausefromis 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 tabletable_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 columnsspatial_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>_effectand<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_resultsthen hasmaxT_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
tocells moved next to (or away from)fromcells withinr; “count”: the number of extrafromcells withinrof eachtocell. “allocation”, the earlier name of “fraction”, is also accepted. Withk, “withinr” means among the cell’sknearest neighbours.k – Use the
knearest neighbours instead of a radius.adjust_abundance – Adjust the test for the log share of the
fromtype in each image (defaultFalse). Its effect is reported asabundance_effect. It does not separate morefromcells 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
.varianceof the result.survival – A survival outcome:
(time_column, event_column), one value per patient (the R package’sSurv(time, event)). Leaveconditionempty. (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_idnames 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_idnames 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_idnames 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. Itsimage_idcolumn, 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_andtoname labels, and labels may overlap (a group and its subtypes). Atocell counts with its weight, and its score is the chance that it has afromneighbour withinrif labels were drawn from the weights (fraction), or the summedfromweight of its neighbours (count). The null shuffles thetoweights over the cells whosefromweight 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 thefromlabel’s summed weight over the image’s cells. A label with itself, and a pair where sometocells havefromweight 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 offromandtoweights 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 summedfromweight 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 ofself_variance). One cell withfromweight 1 and atoweight 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_weightswhen 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 softcell_weights,"exact"gives the exact moments of the pairs tested under random labelling of all cells, and any other value the closed form described undercell_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_adjis at mostalphaare followed up; seeSpicyResults.top_follow_ups()). Default 0.05.
- Return type:
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 runsspicyr.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 asr,cell_typeorcovariates.
- Returns:
A
SpicyCalibration, a DataFrame with one row per shuffle and threshold:shuffle,thresholdandpercent, the percentage of pairs whose p-value is below the threshold. Itssummary()gives the average percentage over the shuffles at each threshold, with the expected one, andplot()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, andplot()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) andpercent, 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), whichspicy()reads a block of rows at a time andspatialdata.read_zarr()reads as a SpatialData object. The coordinates become theobsmarray"spatial"and the other columns the table’sobs(categorical columns stay categorical). An AnnData object is written whole:X,layers,var,obsm,varm,obsp,varpandunsas anndata writes them (chunked), and itsobsas 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 ofchunk_rowsrows compressed with zstd, one chunk at a time, so writing needs little memory beyond that ofcells, however many cells it has.- Parameters:
cells – A pandas DataFrame with one row per cell, or an AnnData object (cells as observations; its
obsis written, with the coordinates from the obs columnsspatial_coordsor else fromobsm["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 tableinfo_key. Itsimage_idcolumn, 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_resultsis the full table, one row per pair (and per level when there are more than two conditions): for the extra fraction the pair’sside(“attract” or “avoid”, which sets its scale), the effect (effect: “fraction”, the extra fraction oftocells moved next to or away fromfromcells withinr, or “count”, the extrafromcells pertocell) 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 variancetau2, 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_weightsgives, for every pair, each image’s share of its condition’s information, and with two conditionscondition_informationgives that information for each pair (pairs x conditions: the sum of the patients’ weights; seetest_correlation()). With adjustment or several radii,pairwise_assoc,image_weightsandcondition_informationare 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_Fonoverall_df1andoverall_df2df,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;conditionholds 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 levelalpha(seetop_follow_ups()). With several radii andcombine="maxT",maxT_convergedsays whether a pair’s max-T p-value met its error target (about 0.1%). For survival,log_hr_seis model-based and approximate,n_deathscounts the deaths among the informative patients, and every requested pair has a row, withnot_testedgiving 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"(onlypairif given). Withfrom_andto, a table of that pair alone, with its effect in a columneffectand each image’sweightin the test, to look up the images behind one pair.NaNwhere 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=Truethe 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 withspicyr.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_andtochoose 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, withfdr=True, the BH-adjusted p) belowcutoff.breaksis(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 patientsn_permutationstimes; 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, asspicyr.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) andvariance="cr2".- Parameters:
method (
str) –"cr2"(the default) or"permutation".n_permutations (
int) – The number of permutations formethod="permutation".cores (
int) – The number of threads formethod="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 ofspicyr.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’ssidestays 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 issignificantwhenp_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_refis the reference of the comparison,level_compthe other level):excess_ref,excess_comp,excess_difference,se,df,p_value,p_threshold,significant, the pair’soverall_p_valueandoverall_p_adj,n_comparisons,tau2andnot_tested;sideandtau2_imagefor the extra fraction; with adjustment,adjusted_forand 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
fromandtocell types (fromalso works as a keyword).to – Only the pairs with these
fromandtocell types (fromalso works as a keyword).significant (
bool) – Only the significant comparisons.figures (
int|None) – Round tofiguressignificant figures, as R’ssignif().
- 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_refandexcess_comp(the average effect in the reference and the comparison group),excess_difference,p_valueandp_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=Truegives every column ofcell_results.- Parameters:
n (
int|None) – The number of pairs to list (10 by default).Nonelists every pair, as does leavingnout whencutoffis 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 mostcutoff.figures (
int|None) – Round tofiguressignificant figures, as R’ssignif().from_ – Only the pairs with these
fromandtocell types (one or several;fromalso works as a keyword).to – Only the pairs with these
fromandtocell types (one or several;fromalso 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 |
|---|---|
|
every column of the test (what |
|
with more than two conditions, the follow-up comparisons of two levels for the pairs called by the overall test at level |
|
with several radii, one row per pair and radius (what |
|
the effect of every pair in every image (what |
|
the weight of every image in the test of every pair: its share of its group’s information (the point sizes of |
|
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 |
|
the groups, images and settings of the analysis ( |
Proportions#
- spicyr.get_prop(cells, feature='cellType', image_id='imageID')#
The proportion of each level of
featurein each image, as spicyR’sgetProp().- 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(). Withfeaturegiven,dfis instead a table of cells (a DataFrame or an AnnData object), and the proportions offeaturein eachimage_idare 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 ofdfis matched to the rows by name (rows without a condition are left out); otherwise the condition is taken in the row order ofdf. Withfeature, 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_andtocells of a pair.Without
from_andto, every cell is shown, coloured by its cell type, with the same colour for a cell type in every image ofcells. With them, the density of all cells is shown in blue, with thefrom_cells (gold) andtocells (dark red) on top. Withr, a circle of radiusris drawn around eachtocell: thefrom_cells inside the circles are those thatspicyr.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_idcolumn), or a list of several.from_ – The two cell types (
fromalso works as a keyword). Optional, together.to – The two cell types (
fromalso works as a keyword). Optional, together.r – Optional radius of the circles around the
tocells, 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 therds2pypackage (pip install "spicyr[data]").With
as_anndata=Truethe cells are returned as an AnnData object: the table asobsand the coordinates inobsm["spatial"](needsanndata).
- 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 asspe_Schurch_2020of the R package SpatialDatasets (82 MB), and cached as formetabric_ali2020().as_anndataas formetabric_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().