---
title: "Getting Started with conformeR"
author: "Justine Leclerc and Christof Seiler"
output:
BiocStyle::html_document:
toc: true
toc_float: true
number_sections: true
vignette: >
%\VignetteIndexEntry{Getting Started with conformeR}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r options, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
dev = "png",
fig.width = 12,
fig.height = 7,
out.width = "100%",
warning = FALSE,
message = FALSE
)
```
```{css, echo = FALSE}
.callout {
border-left: 4px solid #4472A8;
background-color: #F2F6FA;
padding: 0.6em 1em;
margin: 1em 0;
border-radius: 2px;
}
.callout p {
margin: 0.3em 0;
}
```
# Introduction
## Overview
LEMUR fits a low-dimensional embedding and assigns cells to neighborhoods
based on similar responses to a given contrast and gene.
Because these neighborhood assignments are themselves derived from a fitted
model, they are subject to sampling variability: refitting the model on a
different sample of cells can shift the neighborhood boundaries.
conformeR quantifies this uncertainty by wrapping the neighborhood
construction step in a conformal prediction framework. It is designed to
integrate naturally into existing Bioconductor workflows for single-cell
data analysis, operating downstream of SingleCellExperiment-based
preprocessing and LEMUR analyses to provide uncertainty-aware inference for
neighborhood assignments.
It provides two complementary views of that uncertainty:
- **Conformal selection** asks, for a given gene, *which cells can we
confidently say belong to the affected neighborhood?* It returns a
subset of neighborhood cells with a guaranteed bound on the
proportion of false inclusions.
- **Conformal clustering** asks, *for each
cell, how uncertain are we about its neighborhood assignment?* It
returns a prediction *set* of plausible neighborhoods per cell,
which can contain zero, one, or several labels.
**Why this matters.** A single LEMUR fit gives you one particular
neighborhood assignment, with no way to tell how much of it would
survive resampling. `conformeR` turns that single assignment into a
statement with a formal, finite-sample coverage guarantee.
# Installation
`conformeR` is distributed through [Bioconductor](https://bioconductor.org).
Install it with `BiocManager`:
```{r installation, eval=FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager")
}
BiocManager::install("conformeR")
```
```{r setup and theme}
library(conformeR)
library(SingleCellExperiment)
library(BiocParallel)
library(dplyr)
library(ggplot2)
library(tibble)
library(knitr)
theme_set(
theme_minimal(base_size = 13) +
theme(
panel.grid.minor = element_blank(),
plot.title = element_text(face = "bold"),
legend.position = "bottom"
)
)
conformer_palette <- c(
"inside" = "#4472A8",
"outside" = "#D9822B",
"none" = "#B0B0B0"
)
```
# Use-case of conformeR
## Example dataset
This vignette runs `conformeR` on a reduced version of the single-cell
RNA-seq dataset from Zhao, Dovas, Spinazzi, et al. (2021),
*"Deconvolution of cell type-specific drug responses in human tumor
tissue with single-cell RNA-seq,"* published in *Genome Medicine*
(GEO accession `GSE148842`). As with any input to `conformeR`, the
data have already been preprocessed and quality-checked upstream.
```{r load-data}
data("sce_reduced")
sce_reduced
rownames(sce_reduced) <- rowData(sce_reduced)$gene
head(colData(sce_reduced))
```
We restrict the analysis to three genes with distinct expected
behavior, to illustrate a range of neighborhood sizes and
uncertainty patterns: `HIST3H2A`, `PTPRZ1`, and `HBEGF`.
```{r genes-of-interest}
pan_affect_genes <- rowData(sce_reduced) |>
as_tibble() |>
dplyr::select(gid, gene) |>
filter(gene %in% c("HIST3H2A", "PTPRZ1", "HBEGF"))
kable(pan_affect_genes, caption = "Genes of interest for this vignette")
```
## Running conformeR
`conformeR()` fits `LEMUR` and layers both conformal procedures on
top of it in one call. The key arguments are:
- `design_lemur` — the LEMUR design formula; here we adjust for
`patient_id` and estimate the effect of `condition`.
- `contrast_column` — which column of the design defines the
contrast of interest.
- `genes_of_interest` — restrict the (more expensive) conformal
layers to a gene subset; LEMUR itself is still fit genome-wide.
- `what` — which conformal procedure(s) to run: `"conf_selection"`,
`"conf_clustering"`, or both.
By default the data are split 50% training / 50% test, with the
calibration set taking 25% of the training set (`cp_train_frac` and
`cp_cal_frac` set these proportions). The split is stratified on the
variables of `design_lemur`.
Gene chunks are processed in parallel with the
[BiocParallel](https://bioconductor.org/packages/BiocParallel) back-end
given in `BPPARAM` (serial by default). Use, for instance,
`MulticoreParam(workers = 4)` on Linux and macOS or
`SnowParam(workers = 4)` on Windows.
## Interpretation of `cp_alpha`
`cp_alpha` is an *error* level; the corresponding confidence (or
coverage) level is `1 - cp_alpha`. With the default `cp_alpha = 0.05`:
- **Conformal selection**: `cp_alpha` is the target **false discovery
rate**. Among the cells selected as belonging to a gene's neighborhood,
the expected proportion of cells that are actually outside the
neighborhood is at most 5%.
- **Conformal clustering**: `cp_alpha` is the **miscoverage level** of
the prediction sets. For a new cell, the prediction set contains the
cell's true neighborhood label with probability at least 95%.
Lowering `cp_alpha` makes both procedures more conservative: fewer
cells are selected and more prediction sets are ambiguous.
```{r run-conformer}
set.seed(2002)
sce_res <- conformeR(
sce_reduced,
design_lemur = ~ patient_id + condition,
contrast_column = "condition",
genes_of_interest = pan_affect_genes$gene,
what = c("conf_selection", "conf_clustering"),
cp_alpha = 0.05,
BPPARAM = SerialParam(),
verbose = TRUE
)
```
## Structure of the output
`conformeR()` returns the input `SingleCellExperiment`, with all its
original assays and annotations, enriched with the results.
```{r output}
sce_res
```
- `colData(sce_res)$conformeR_split` records whether each cell was used
for conformal training (`"train"`), calibration (`"cal"`) or testing
(`"test"`). Conformal results are reported for the test cells only.
- `reducedDim(sce_res, "LEMUR")` holds the aligned LEMUR embedding, and
`"LEMUR_UMAP"` / `"LEMUR_aligned_UMAP"` its UMAPs before and after
Harmony alignment.
- `altExp(sce_res, "conformeR")` has one row per gene of interest and one
column per cell. Its assays contain the LEMUR predicted differential
expression (`DE`), the LEMUR neighborhood membership
(`lemur_neighborhood`), the conformal selection (`conf_selection`), and
the conformal clustering prediction sets (`conf_clustering_inside`,
`conf_clustering_outside`, `conf_set_size`). Non-test cells are `NA`.
- `metadata(sce_res)$conformeR` stores the analysis parameters.
```{r output-altexp}
conf <- altExp(sce_res, "conformeR")
conf
table(sce_res$conformeR_split)
```
The `rowData` of the alternative experiment gathers per-gene results:
the LEMUR neighborhood statistics (prefixed with `lemur_`), the number
of test cells in the LEMUR neighborhood, the number of conformally
selected cells, and the conformal clustering score quantile.
```{r output-rowdata}
rowData(conf)
```
## Conformal selection
For each gene, conformal selection returns the set of cells flagged
as belonging to the neighborhood affected by `condition`, with the
false discovery rate controlled at `cp_alpha`. The table below reports
both the raw neighborhood size and its share of all cells in the test set.
```{r selection-summary}
test_cells <- sce_res$conformeR_split == "test"
selected <- assay(conf, "conf_selection")[, test_cells]
selection_summary <- tibble(
gene = rownames(conf),
`Neighborhood size` = rowSums(selected),
`% of cells` = round(rowMeans(selected) * 100)
)
kable(selection_summary,
caption =
"Conformal selection: neighborhood size per gene (test cells)"
)
```
## Conformal clustering
Conformal clustering instead reports, per cell, a *prediction set*:
the neighborhoods that cell could plausibly belong to, with coverage
`1 - cp_alpha`. A prediction set of size zero or two means the procedure
could not confidently assign that cell to any neighborhood. It is
ambiguous.
```{r clustering-summary}
inside <- assay(conf, "conf_clustering_inside")[, test_cells]
outside <- assay(conf, "conf_clustering_outside")[, test_cells]
set_size <- assay(conf, "conf_set_size")[, test_cells]
clustering_summary <- tibble(
gene = rownames(conf),
`Prediction set = inside` = rowSums(set_size == 1 & inside),
`Prediction set = outside` = rowSums(set_size == 1 & outside),
`Prediction set size 2 or empty` = rowSums(set_size != 1)
)
kable(clustering_summary,
caption =
"Conformal clustering: prediction set composition per gene"
)
```
## Visualizing results on the LEMUR embedding
### Conformal selection
```{r plot-selection, fig.cap = "Conformal selection overlaid on LEMUR"}
plotter_conformal_selection(sce_res, pan_affect_genes$gene)
```
Cells shaded as part of the selected neighborhood are those the
procedure can confidently attribute to the condition effect for that
gene; unshaded cells fall outside the selection at the chosen false
discovery rate.
### Conformal clustering
```{r plot-clustering, fig.cap = "Conformal prediction sets overlaid on LEMUR"}
plotter_conformal_clustering(sce_res, pan_affect_genes$gene)
```
Here color reflects the prediction set itself rather than a single
hard assignment, making it easy to spot the boundary regions where
neighborhood membership is genuinely uncertain versus the core
regions where every resampling agrees.
# Session info
```{r session-info}
sessionInfo()
```