Package 'cellpaintr'

Title: Perturbation Analysis for Cell Painting Data
Description: cellpaintr tests whether a perturbation, such as a drug, changes the morphology of cells in Cell Painting experiments with few biological replicates, such as patient-derived cells from a handful of donors. It reads the per-cell measurement tables that CellProfiler exports (for example MyExpt_Cells.csv with image metadata columns) into a SingleCellExperiment, removes poor cells and features, transforms and scales the features, and corrects plate row and column effects. It then learns on cells and tests on replicates: a random forest trained on the cells of all other replicates scores the cells of each held-out replicate, and an exact permutation test or a corrected paired t-test compares the scores between conditions, for all features and for feature groups such as measurement types or imaging channels. Unlike profiling pipelines such as pycytominer, which aggregate cells into well-level profiles and compare their similarity, cellpaintr trains on single cells, so it learns the direction of an effect from the data and detects changes in the spread or shape of a feature distribution that leave the means unchanged.
Authors: Christof Seiler [aut, cre] (ORCID: <https://orcid.org/0000-0001-8802-3642>), Phatthamon Laphanuwat [ctb], Caroline Ospelt [ctb], European League Against Rheumatism [fnd], Swiss National Science Foundation [fnd]
Maintainer: Christof Seiler <[email protected]>
License: LGPL-3
Version: 0.99.8
Built: 2026-12-04 21:55:14 UTC
Source: https://github.com/bioc/cellpaintr

Help Index


Test each feature group for a difference between two levels

Description

Average the leave-one-out prediction scores of predictLOO per patient and level, and test in each feature group whether the interest level has higher scores than the reference level.

Usage

calculateStats(
  sce,
  target,
  group,
  assay_type = "tfmfeatures",
  method = c("permutation", "corrected", "nadeau_bengio", "t"),
  n_permutations = 999
)

Arguments

sce

Output of predictLOO

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

assay_type

character(1), name of the assay with the features

method

Either '"permutation"' (default) for a permutation test that relabels whole patients, '"corrected"' for the corrected paired t-test, '"nadeau_bengio"' for the paired t-test with the correction of Nadeau and Bengio, or '"t"' for p-values from the t-distribution

n_permutations

Largest number of relabelings besides the observed labels; if there are more, this many are drawn at random

Details

The test statistic is the one-sided t-statistic for higher mean scores in the interest level. It is paired if every patient ('group') has cells of both levels, and uses a pooled variance otherwise.

With 'method = "permutation"' (the default), the p-value comes from relabeling whole patients: in a paired design, the two levels of a patient are swapped; in an unpaired design, the levels are permuted across patients; and in a mixed design, where only some patients have cells of both levels, the levels of those patients are swapped and the levels of the other patients are permuted among them. For each relabeling, all leave-one-out models are refitted with the settings of the call to predictLOO, and the p-value is the proportion of relabelings, the observed one included, with a statistic at least as large. Exchanging the two levels in all patients at once turns every score into one minus the score and leaves the statistic unchanged, so relabelings come in pairs with the same statistic. Whenever this exchange is itself a relabeling (always in a paired design, and if the patients with one level are split evenly between the two levels otherwise), one patient keeps its labels, which halves the number of relabelings and refits without changing the test. If there are at most 'n_permutations + 1' relabelings (2n−12^{n-1} for nn patients in a paired design), all of them are enumerated and the test is exact; otherwise, 'n_permutations' relabelings are drawn at random. The smallest attainable p-value is one over the number of relabelings, 21−n2^{1-n} in a paired design. Because all models are refitted for every relabeling, the test takes that many times longer than predictLOO. Use set.seed for reproducible results.

With 'method = "corrected"', the p-value comes from a corrected paired t-test, which needs a paired design with at least three patients. Each patient is in the training set of every other patient's model, which makes the score differences of different patients positively correlated, so the t-statistic is too large. If each score difference is a sum of pairwise interactions with the other patients, two score differences have correlation 1/(n−1)1/(n-1) for nn patients, and the t-statistic is too large by the factor 2(n−1)/(n−2)\sqrt{2(n-1)/(n-2)}. The corrected t-test divides the t-statistic by this factor and refers it to the t-distribution with n−1n-1 degrees of freedom. It needs no refits, and its p-values are not limited to multiples of 21−n2^{1-n}, but it is approximate.

With 'method = "nadeau_bengio"', the t-statistic is divided instead by (2n−1)/(n−1)\sqrt{(2n-1)/(n-1)}, the factor of the corrected resampled t-test of Nadeau and Bengio (2003, Machine Learning 52:239-281) for nn splits with one held-out patient each, which assumes a correlation of 1/n1/n instead of 1/(n−1)1/(n-1). It corrects less and therefore has more power, which pays off if part of each score difference is independent of the other patients, for example noise from the random seeds of the forests. If the score differences consist mostly of pairwise interactions, it can exceed the nominal level with four to six patients, where 'method = "corrected"' holds it. It needs a paired design with at least two patients and no refits.

With 'method = "t"', the p-value comes from the t-distribution. This is fast but anti-conservative, because the score differences of different patients are positively correlated.

Value

data.frame with one row per feature group and the columns 'Target' (interest level), 'Feature' (feature group), 'pvalue', and 'log2FoldChange' (log2 ratio of the mean scores of the interest and the reference level). With the permutation test, the attribute 'relabelings' holds the number of relabelings, the observed one included.

References

Laphanuwat P, Ospelt C, Seiler C. cellpaintr: pre-validation with small sample sizes. In preparation; we plan to make the preprint available soon. It derives the corrections and compares the type I error and power of all tests with 4 to 12 patients.

Nadeau C, Bengio Y (2003). Inference for the generalization error. Machine Learning, 52(3), 239-281.

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    n_threads = 1
)

# permutation test; by default, it enumerates all 64 relabelings of the
# six patients, here 9 random relabelings keep the example fast
calculateStats(sce_single,
    target = "Drug", group = "Patient",
    n_permutations = 9
)

# corrected t-test: no refits
calculateStats(sce_single,
    target = "Drug", group = "Patient",
    method = "corrected"
)

# correction of Nadeau and Bengio: no refits, corrects less
calculateStats(sce_single,
    target = "Drug", group = "Patient",
    method = "nadeau_bengio"
)

# p-values from the t-distribution: fast but anti-conservative
calculateStats(sce_single,
    target = "Drug", group = "Patient",
    method = "t"
)

Simulate CellProfiler data and write to a temporary file

Description

Simulate CellProfiler data and write to a temporary file

Usage

generateData()

Value

path to csv file

Examples

set.seed(23)
generateData()

Load cell painting data from file and convert to a SingleCellExperiment

Description

Reads a per-cell table exported by CellProfiler's ExportToSpreadsheet module, for example MyExpt_Cells.csv, with one row per cell. The table needs the column ImageNumber, at least one image metadata column whose name starts with Metadata_ (CellProfiler adds them with the option "Add image metadata columns to your object data file"), and numeric measurement columns such as AreaShape_Area or Intensity_MeanIntensity_DNA. Metadata columns become the column data of the cells, without the Metadata_ prefix, together with ImageNumber, ObjectNumber, and Location_Center_X, _Y, and _Z; all other columns become the features in the assay "features".

Usage

loadData(cell_file, ...)

Arguments

cell_file

character(1), path to a csv file from CellProfiler, e.g., MyExpt_Cells.csv; compressed files such as .csv.gz work

...

Further arguments to read_csv, for example num_threads to limit the threads used to read large files

Value

SingleCellExperiment object with features as rows and cells as columns

Examples

set.seed(23)
cell_file <- generateData()
loadData(cell_file)

Plot AUC comparison

Description

Plot AUC comparison

Usage

plotAUC(sce, target, group, assay_type = "tfmfeatures")

Arguments

sce

SingleCellExperiment object

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

assay_type

character(1), name of the assay with the features

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")
types <- c("AreaShape", "Intensity", "Texture")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    types = types,
    n_threads = 1
)

plotAUC(sce_single, target = "Drug", group = "Patient")

Plot number of cells per image

Description

Plot number of cells per image

Usage

plotCellsPerImage(sce, bins = 100)

Arguments

sce

SingleCellExperiment object

bins

numeric(1), number of histogram bins

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
plotCellsPerImage(sce)

Plot predicted leave-one-out probabilities

Description

Plot predicted leave-one-out probabilities

Usage

plotLOO(sce, target, group, assay_type = "tfmfeatures")

Arguments

sce

SingleCellExperiment object

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

assay_type

character(1), name of the assay with the features

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")
types <- c("AreaShape", "Intensity", "Texture")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    types = types,
    n_threads = 1
)

plotLOO(sce_single, target = "Drug", group = "Patient")

Plot correlations between features and principal components

Description

Computes the Pearson correlation of every feature with the first principal components in reducedDim(sce, "PCA") and shows the features most correlated with one of them.

Usage

plotPCACor(
  sce,
  filter_by = 1,
  top = 20,
  pcs = seq(5),
  assay_type = "tfmfeatures"
)

Arguments

sce

SingleCellExperiment object

filter_by

numeric(1), principal component used to select features

top

numeric(1), number of features to show

pcs

integer vector, principal components to show

assay_type

character(1), name of the assay with the features

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce, robust = TRUE)
sce <- scater::runPCA(sce, exprs_values = "tfmfeatures", ncomponents = 10)
plotPCACor(sce, filter_by = 1)

Plot ROC curves

Description

Plot ROC curves

Usage

plotROC(sce, target, group, assay_type = "tfmfeatures")

Arguments

sce

SingleCellExperiment object

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

assay_type

character(1), name of the assay with the features

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")
types <- c("AreaShape", "Intensity", "Texture")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    types = types,
    n_threads = 1
)

plotROC(sce_single, target = "Drug", group = "Patient")

Predict target from features

Description

Predict target from features

Usage

predictLOO(
  sce,
  target,
  group,
  interest_level,
  reference_level,
  types = NULL,
  channels = NULL,
  weights = NULL,
  n_threads = 1,
  assay_type = "tfmfeatures",
  progress = TRUE
)

Arguments

sce

SingleCellExperiment object

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

interest_level

character(1), level of 'target' compared with the reference, such as a drug

reference_level

character(1), level of 'target' used as the reference, such as the control

types

NULL or character vector of CellProfiler measurement types, such as "Intensity"; each type is a feature group of the features whose names start with it

channels

NULL or character vector of imaging channels, such as "DNA" or "Mito"; each channel is a feature group of the features whose names contain it

weights

NULL or character(1), name of the column of colData(sce) with case weights, for example cell counts when cells are aggregated to images

n_threads

numeric(1), number of threads of each random forest fit

assay_type

character(1), name of the assay with the features

progress

logical(1), show a progress bar while fitting the models of feature types and channels

Value

SingleCellExperiment object with the cells of the two levels, the leave-one-out prediction scores in reducedDim(sce, "prevalidated"), and the settings of this call in metadata(sce)$predictLOO, which calculateStats uses to refit the models in its permutation test

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")
types <- c("AreaShape", "Intensity", "Texture")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    types = types,
    n_threads = 1
)

Filter low variance features

Description

Filter low variance features

Usage

removeLowVariance(sce, threshold = 0, robust = FALSE, assay_type = "features")

Arguments

sce

SingleCellExperiment object

threshold

numeric(1), keep features whose spread exceeds it

robust

logical(1), if TRUE the spread is the median absolute deviation, otherwise the variance

assay_type

character(1), name of the assay with the features

Value

SingleCellExperiment object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- removeLowVariance(sce)

Remove cells with missing features

Description

Remove cells with missing features

Usage

removeNAs(sce, assay_type = "features")

Arguments

sce

SingleCellExperiment object

assay_type

character(1), name of the assay with the features

Value

SingleCellExperiment object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- removeNAs(sce)

Remove cells if not enough or too many in one image

Description

Remove cells if not enough or too many in one image

Usage

removeOutliers(sce, min, max)

Arguments

sce

SingleCellExperiment object

min

numeric(1), remove the cells of images with fewer cells

max

numeric(1), remove the cells of images with more cells

Value

SingleCellExperiment object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- removeOutliers(sce, min = 0, max = 300)

Remove row and column effect using the median polish procedure

Description

Fits Tukey's median polish to the per-well medians of each feature and subtracts the overall, row, and column effects from every cell, similar to the B-score of high-throughput screening. The column data need the factors Row and Col with the plate position of each cell. Row and column effects differ between plates, so with several plates, pass the column with the plate (or batch) of each cell as 'plate'; the median polish is then fitted to each plate separately. Wells without cells are left out of the fit. Because the median polish removes everything that varies with rows or columns, it also removes the part of a treatment effect that is confounded with them, so the conditions should be spread over the rows and columns of each plate.

Usage

removeRowColEffect(sce, assay_type = "tfmfeatures", plate = NULL)

Arguments

sce

SingleCellExperiment object

assay_type

character(1), name of the assay with the features

plate

NULL or character(1), name of the column of colData(sce) with the plate or batch of each cell; if NULL, all cells come from one plate

Value

SingleCellExperiment object with the corrected features in the new assay "corrected"

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)
row <- substr(sce$Well, 1, 1)
row <- factor(row, levels = sort(unique(row)))
col <- substr(sce$Well, 2, 3)
col <- factor(as.numeric(col))
sce$Row <- row
sce$Col <- col
sce <- removeRowColEffect(sce)

# several plates: one median polish per plate
sce$Plate <- ifelse(sce$Patient %in% c("P1", "P2", "P3"),
    "plate1", "plate2"
)
sce <- removeRowColEffect(sce, plate = "Plate")

Remove zero-inflated features

Description

Remove zero-inflated features

Usage

removeZeroInflation(sce, proportion = 0.2, assay_type = "features")

Arguments

sce

SingleCellExperiment object

proportion

numeric(1) between 0 and 1, remove features with a larger proportion of zeros

assay_type

character(1), name of the assay with the features

Value

SingleCellExperiment object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- removeZeroInflation(sce)

Transform, center, and scale features

Description

Transforms each family of CellProfiler features to an approximately unbounded, symmetric scale (logarithm for intensities and dispersion-type texture measures, Fisher's z for correlations, logit for proportions, and a rank-based inverse normal transformation for thresholded colocalization coefficients), caps infinite values at the finite extremes of each feature, and standardizes every feature.

Usage

transformScale(sce, robust = FALSE, assay_type = "features")

Arguments

sce

SingleCellExperiment object

robust

logical(1), if TRUE robust z-scores (median and median absolute deviation), otherwise standard z-scores

assay_type

character(1), name of the assay with the features

Value

SingleCellExperiment object with the transformed features in the new assay "tfmfeatures"

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

Plot predicted leave-one-out probabilities

Description

Plot predicted leave-one-out probabilities

Usage

volcanoPlot(
  sce,
  target,
  group,
  p_cutoff = NULL,
  fc_cutoff = 1,
  assay_type = "tfmfeatures",
  stats = NULL,
  ...
)

Arguments

sce

SingleCellExperiment object

target

character(1), name of the column of colData(sce) with the condition of each cell, such as the drug

group

character(1), name of the column of colData(sce) with the replicate of each cell, such as the patient; the replicates are the folds of the leave-one-out cross-validation

p_cutoff

Cut-off for statistical significance. A horizontal line will be drawn at -log10(p_cutoff). Defaults to 0.01 divided by the number of feature groups. With few patients, permutation p-values cannot fall below this default, because the smallest attainable p-value is one over the number of relabelings.

fc_cutoff

Cut-off for absolute log2 fold-change. A vertical lines will be drawn at fc_cutoff.

assay_type

character(1), name of the assay with the features

stats

Output of calculateStats; if 'NULL', it is computed from 'sce'

...

Further arguments to calculateStats, such as 'method' or 'n_permutations'

Value

ggplot2 object

Examples

set.seed(23)
cell_file <- generateData()
sce <- loadData(cell_file)
sce <- transformScale(sce)

sce$Drug <- as.factor(sce$Drug)
sce$Drug <- relevel(sce$Drug, ref = "D1")
types <- c("AreaShape", "Intensity", "Texture")

sce_single <- predictLOO(
    sce,
    target = "Drug", group = "Patient",
    interest_level = "D7", reference_level = "D1",
    types = types,
    n_threads = 1
)

# p-values from the t-distribution keep the example fast; the default
# permutation test refits all models for every relabeling of the patients
volcanoPlot(sce_single,
    target = "Drug", group = "Patient",
    p_cutoff = 0.05, fc_cutoff = 0.5, method = "t"
)