Skip to content

API reference

infer_cnv

infer_cnv(
    X: SparseMatrix,
    chrom: ArrayLike,
    start: ArrayLike,
    end: ArrayLike,
    reference: ArrayLike,
    *,
    reference_labels: ArrayLike | None = None,
    params: CnvParams | None = None,
    genome: Genome = "hg38",
    n_threads: int | None = None,
    verbose: bool = False,
) -> CnvResult

Copy number inference from single cell expression.

The expression path of numbat: smoothed log-ratio signal against the reference cells, a cell hierarchy, Poisson-lognormal HMMs on pseudobulks, consensus segments, then per-cell segment posteriors and a tumour/normal call per cell.

Genes off chromosomes 1 to 22, or with missing coordinates, are dropped.

Parameters:

Name Type Description Default
X SparseMatrix

Cells x genes raw UMI counts, any scipy sparse format. Not normalised, not log-transformed.

required
chrom ArrayLike

Chromosome per gene (1, "1" or "chr1").

required
start ArrayLike

Gene start in bp per gene.

required
end ArrayLike

Gene end in bp per gene.

required
reference ArrayLike

Normal reference cells as a boolean mask over rows of X or integer row indices; or precomputed profiles, a float (n_genes, R) array of proportions in the gene order of X. Each cell is compared against the profile it correlates best with. Profiles are subset to the kept genes, not renormalised.

required
reference_labels ArrayLike | None

Label per cell (length n_cells), read on the reference cells only. Builds one profile per label instead of pooling all reference cells into one. Not with profiles.

None
params CnvParams | None

Tuning parameters, None for the defaults.

None
genome Genome

Build of the default exclusion intervals (MHC and the IG/TR loci), or "none" to exclude nothing.

'hg38'
n_threads int | None

Threads for this call, None for all cores.

None
verbose bool

Print stage timings to stdout.

False

Returns:

Type Description
CnvResult

The result; see CnvResult.

Raises:

Type Description
ValueError

For malformed inputs.

CnvError

When the core fails, for instance with too few cells per pseudobulk.

infer_cnv_adata

infer_cnv_adata(
    adata: AnnData,
    *,
    reference_key: str,
    reference_cat: str | Sequence[str],
    reference_group_key: str | None = None,
    layer: str | None = None,
    chrom_key: str = "chromosome",
    start_key: str = "start",
    end_key: str = "end",
    key_added: str = "cnv",
    params: CnvParams | None = None,
    genome: Genome = "hg38",
    n_threads: int | None = None,
    verbose: bool = False,
) -> CnvResult

Run infer_cnv on an AnnData and store the result in it.

Writes, with key_added="cnv":

  • obsm["X_cnv"]: smoothed signal, cells x bins.
  • obsm["cnv_p_cnv"]: per-cell posterior of each non-neutral segment.
  • obs["cnv_p_tumour"], obs["cnv_clone"], obs["cnv_leaf"], obs["cnv_reference"] (index into reference_names).
  • uns["cnv"]: chr_pos (first bin per chromosome), bins, segments (columns of CnvResult.segments; multi_state joined with commas, nulls as -1), reference_names, params, genome.

Parameters:

Name Type Description Default
adata AnnData

Cells x genes. Must hold raw counts in layer (or X).

required
reference_key str

obs column that labels the normal cells.

required
reference_cat str | Sequence[str]

Value(s) of reference_key that are normal.

required
reference_group_key str | None

obs column that splits the normal cells into one profile per value, e.g. the cell type. Can be reference_key itself. None pools them into one profile.

None
layer str | None

Layer with raw counts, None for adata.X.

None
chrom_key str

var column with the chromosome per gene.

'chromosome'
start_key str

var column with the gene start.

'start'
end_key str

var column with the gene end.

'end'
key_added str

Prefix of the written slots.

'cnv'
params CnvParams | None

Tuning parameters, None for the defaults.

None
genome Genome

Build of the default exclusion intervals, or "none".

'hg38'
n_threads int | None

Threads for this call, None for all cores.

None
verbose bool

Print stage timings to stdout.

False

Returns:

Type Description
CnvResult

The full CnvResult, which also carries log_odds, clone_prob and

CnvResult

genotypes.

Raises:

Type Description
KeyError

For a missing obs/var column or layer.

ValueError

For a reference that matches no cell, or a normal cell without a reference_group_key value.

CnvParams dataclass

CnvParams(
    window: int = 101,
    cap: float = 3.0,
    bin_size: int = 100,
    init_k: int = 3,
    min_cells: int = 50,
    t: float = 1e-05,
    logphi_min: float = 0.25,
    min_genes: int = 10,
    min_llr: float = 5.0,
    min_overlap: float = 0.45,
    max_entropy: float = 0.5,
    p_multi: float = 1.0 - 0.0001,
)

Tuning parameters. Defaults are numbat's (run_numbat), plus the binning, which is ours.

Parameters:

Name Type Description Default
window int

Running-mean window of the smoothed signal, in genes.

101
cap float

Symmetric cap on the per-gene log-ratio before smoothing.

3.0
bin_size int

Kept genes per bin of the smoothed signal.

100
init_k int

Leaf clusters cut from the cell hierarchy.

3
min_cells int

A pseudobulk needs more than this many cells.

50
t float

HMM transition probability between copy number states.

1e-05
logphi_min float

log2 fold change of a single-copy event.

0.25
min_genes int

Segments up to this many genes are smoothed away.

10
min_llr float

Segments with a lower log-likelihood ratio count as neutral.

5.0
min_overlap float

Overlap fraction that links two segments in the consensus.

0.45
max_entropy float

Segments with a higher mean p_cnv entropy are not confident.

0.5
p_multi float

Probability threshold of the multi-state test.

1.0 - 0.0001

CnvResult dataclass

CnvResult(
    used: ndarray,
    bins: ndarray,
    bin_table: DataFrame,
    leaf: ndarray,
    segments: DataFrame,
    p_cnv: ndarray,
    log_odds: ndarray,
    mu: ndarray,
    sigma: ndarray,
    p_tumour: ndarray,
    clone: ndarray,
    clone_prob: ndarray,
    genotypes: list[list[tuple[int, str | None]]],
    reference: ndarray,
    reference_names: list[str],
    params: CnvParams,
    genome: str,
)

Output of infer_cnv.

Per-cell arrays have one row per input cell. Cells the core dropped (zero counts, or no usable reference) have used == False, NaN in float arrays and -1 in integer ones. Posterior and clone arrays are NaN for every cell when no consensus segment is non-neutral.

Parameters:

Name Type Description Default
used ndarray

Cells that went through the pipeline, (n_cells,) bool.

required
bins ndarray

Smoothed log-ratio signal, (n_cells, n_bins) float32.

required
bin_table DataFrame

One row per bin: chrom, start, end (bp), n_genes.

required
leaf ndarray

Leaf cluster of the cell hierarchy per cell, -1 for none.

required
segments DataFrame

One row per consensus segment. state is the HMM label, state_post the retest call (neu, amp, del, loh), p_* the retest posteriors, post_col the column in p_cnv (null for neutral segments), confident whether it passed the entropy and LLR filters.

required
p_cnv ndarray

Per-cell posterior probability of each non-neutral segment, (n_cells, n_post).

required
log_odds ndarray

Per-cell log-odds against neutral, (n_cells, n_post, 4); the last axis is LOG_ODDS_COLUMNS (pooled log Bayes factor, LOH, deletion, gain).

required
mu ndarray

Per-cell baseline mu of the Poisson-lognormal fit.

required
sigma ndarray

Per-cell baseline sigma.

required
p_tumour ndarray

1 - p(normal genotype) per cell.

required
clone ndarray

Most probable genotype per cell, 0 is normal.

required
clone_prob ndarray

Genotype posterior, (n_cells, n_genotypes).

required
genotypes list[list[tuple[int, str | None]]]

Per genotype, its events as (segment row, state); state is None unless the segment is multi-state. Genotype 0 is the empty, normal one.

required
reference ndarray

Reference profile each cell correlates best with, an index into reference_names, -1 for dropped cells.

required
reference_names list[str]

Name per reference profile: the label with reference_labels, otherwise its column index ("0" for pooled reference cells).

required
params CnvParams

Parameters the run used.

required
genome str

Exclusion intervals the run used.

required

LOG_ODDS_COLUMNS module-attribute

LOG_ODDS_COLUMNS: tuple[str, ...] = (
    "logbf",
    "loh",
    "del",
    "amp",
)

CnvError

Bases: Exception