Skip to content

Preprocessing

This module contains various methods that can be included in the preprocessing workflow, e.g. creation of reference profiles, simulation of bulks,

Reference profiles

hide_deconv.preprocessing.create_reference(adata, celltype_col='cell_type')

Create archetypal cell type references from a given AnnData object.

The function creates reference profiles from a given AnnData object by averaging over the gene expression profiles of each cell type. The used cell types are determined by the given cell type observation name.

Parameters:

Name Type Description Default
adata AnnData

Input expression data.

required
celltype_col str

Column in adata.obs containing the cell type labels used for averaging over the gene expressions.

"cell_type"

Returns:

Type Description
DataFrame

A gene x cell type pandas DataFrame containing the archetypal gene expression profiles of each cell type.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def create_reference(
    adata: ad.AnnData, celltype_col: str = "cell_type"
) -> pd.DataFrame:
    """
    Create archetypal cell type references from a given AnnData object.

    The function creates reference profiles from a given AnnData object by
    averaging over the gene expression profiles of each cell type.
    The used cell types are determined by the given cell type observation name.

    Parameters
    ----------
    adata : anndata.AnnData
        Input expression data.
    celltype_col : str, default="cell_type"
        Column in adata.obs containing the cell type labels used for averaging over the gene expressions.

    Returns
    -------
    pd.DataFrame
        A gene x cell type pandas DataFrame containing the archetypal gene expression profiles of each cell type.

    """

    celltypes = adata.obs[celltype_col].astype(str).values

    X = adata.X
    if sp.issparse(X):
        X = X.tocsr()
    else:
        X = np.asarray(X)

    unique_ct = np.array(sorted(pd.unique(celltypes)))
    ref = np.zeros((adata.n_vars, len(unique_ct)), dtype=np.float64)

    for j, ct in enumerate(unique_ct):
        mask = celltypes == ct
        if mask.sum() == 0:
            continue
        if sp.issparse(X):
            ref[:, j] = np.asarray(X[mask].mean(axis=0)).ravel()
        else:
            ref[:, j] = X[mask].mean(axis=0)

    return pd.DataFrame(ref, index=adata.var_names, columns=unique_ct)

Simulated bulk data

hide_deconv.preprocessing.create_bulks(adata, n_bulks, n_cells_per_bulk, celltype_col='cell_type', seed=42, norm=False)

Generate in silico bulk expression samples and their cell type compositions.

The function draws cells with replacement from the input AnnData object to create n_bulks bulk samples. For each bulk, expression counts are summed across the sampled cells and the corresponding cell type counts are tracked. Optionally, bulk expression is normalized to counts per million (CPM).

Parameters:

Name Type Description Default
adata AnnData

Input AnnData object.

required
n_bulks int

Number of bulks samples to simulate.

required
n_cells_per_bulk int

Number of cells sampled per simulated bulk.

required
celltype_col str

Column in adata.obs containing cell type labels.

"cell_type"
seed int

Random seed for reproducible simulations.

42
norm bool

If True each bulk is normalized to CPM.

False

Returns:

Type Description
tuple[DataFrame, DataFrame]

Y : gene x bulk expression profiles. C : celltype x bulk composition matrix

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def create_bulks(
    adata: ad.AnnData,
    n_bulks: int,
    n_cells_per_bulk: int,
    celltype_col: str = "cell_type",
    seed: int = 42,
    norm: bool = False,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """
    Generate in silico bulk expression samples and their cell type compositions.

    The function draws cells with replacement from the input AnnData object to create
    n_bulks bulk samples. For each bulk, expression counts are summed across the
    sampled cells and the corresponding cell type counts are tracked. Optionally, bulk
    expression is normalized to counts per million (CPM).

    Parameters
    ----------
    adata : ad.AnnData
        Input AnnData object.
    n_bulks : int
        Number of bulks samples to simulate.
    n_cells_per_bulk : int
        Number of cells sampled per simulated bulk.
    celltype_col : str, default="cell_type"
        Column in adata.obs containing cell type labels.
    seed : int, default=42
        Random seed for reproducible simulations.
    norm : bool, default=False
        If True each bulk is normalized to CPM.

    Returns
    -------
    tuple[pd.DataFrame, pd.DataFrame]
        Y : gene x bulk expression profiles.
        C : celltype x bulk composition matrix
    """

    rng = np.random.default_rng(seed)

    celltypes = adata.obs[celltype_col].astype(str).values
    if hasattr(adata.X, "toarray"):
        expr = adata.X.toarray()
    elif hasattr(adata.X, "todense"):
        expr = adata.X.todense()
    else:
        expr = np.array(adata.X[:])

    n_cells, n_genes = expr.shape

    unique_celltypes = sorted(pd.unique(celltypes))
    n_celltypes = len(unique_celltypes)
    celltype_to_idx = {ct: i for i, ct in enumerate(unique_celltypes)}

    Y = np.zeros((n_genes, n_bulks), dtype=np.float32)
    C = np.zeros((n_celltypes, n_bulks), dtype=np.float32)

    for b in range(n_bulks):
        idx = rng.choice(n_cells, size=n_cells_per_bulk, replace=True)
        sampled_expr = expr[idx]
        sampled_celltypes = celltypes[idx]

        Y[:, b] = sampled_expr.sum(axis=0)

        for ct in sampled_celltypes:
            C[celltype_to_idx[ct], b] += 1

    if norm:
        Y = (Y * 1e6) / Y.sum(axis=0)  # cpm

    Y = pd.DataFrame(
        Y, index=adata.var_names, columns=[f"bulk_{i}" for i in range(n_bulks)]
    )
    C = pd.DataFrame(
        C, index=unique_celltypes, columns=[f"bulk_{i}" for i in range(n_bulks)]
    )
    C = C / C.sum(axis=0)

    return Y, C

Domain transfer

hide_deconv.preprocessing.get_domain_transfer_factor(df1, df2)

Calculate the domain transfer factor to align two bulks

Parameters:

Name Type Description Default
df1 DataFrame

First dataframe

required
df2 DataFrame

Second dataframe

required

Returns:

Type Description
Series

Series containing the conversion factors for each gene

Source code in src/hide_deconv/preprocessing/bulk_preprocessing.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def get_domain_transfer_factor(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.Series:
    """
    Calculate the domain transfer factor to align two bulks

    Parameters
    ----------
    df1 : pd.DataFrame
        First dataframe
    df2 : pd.DataFrame
        Second dataframe

    Returns
    -------
    pd.Series
        Series containing the conversion factors for each gene
    """
    # \sum_g df1_g = \alpha \sum_g df2_g

    mean_df1 = df1.median(axis=1)
    mean_df2 = df2.median(axis=1)

    alpha = mean_df1 / mean_df2

    return alpha

Gene and bulk utilities

hide_deconv.preprocessing.get_common_genes(adata, bulk, remove_zero_median=True)

Return genes present in both single-cell and bulk expression data.

The function computes the intersection between gene names in adata.var_names and the bulk expressions.

Additionally remove genes, which have a median of 0 in the bulk, as these can influence domain transfer.

Gene Symbols that are duplicate will be added together (Preferentably to use EnsemblIDs).

Parameters:

Name Type Description Default
adata AnnData

AnnData object containing single-cell expression data. Gene names are taken from adata.var_names

required
bulk DataFrame

Bulk expression profiles with genes as index and samples as columns

required
remove_zero_median bool = True

Remove genes that have a median expression of zero

True

Returns:

Type Description
list[str]

List of shared gene names

Source code in src/hide_deconv/preprocessing/bulk_preprocessing.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def get_common_genes(
    adata: ad.AnnData, bulk: pd.DataFrame, remove_zero_median=True
) -> list[str]:
    """
    Return genes present in both single-cell and bulk expression data.

    The function computes the intersection between gene names in adata.var_names
    and the bulk expressions.

    Additionally remove genes, which have a median of 0 in the bulk, as these can influence domain transfer.

    Gene Symbols that are duplicate will be added together (Preferentably to use EnsemblIDs).

    Parameters
    ----------
    adata : ad.AnnData
        AnnData object containing single-cell expression data.
        Gene names are taken from adata.var_names

    bulk : pd.DataFrame
        Bulk expression profiles with genes as index and samples as columns

    remove_zero_median : bool = True
        Remove genes that have a median expression of zero

    Returns
    -------
    list[str]
        List of shared gene names

    """

    # Handle duplicate Gene Symbols, appear sometimes after converting from EnsemblIDs to GeneSymbol
    if bulk.index.has_duplicates:
        bulk = bulk.groupby(level=0).sum()

    if remove_zero_median:
        bulk_med = bulk.median(axis=1)
        zero_genes = bulk_med[bulk_med == 0].index
        if len(zero_genes) > 0:
            bulk = bulk.drop(index=zero_genes)

    genes_sc = set(adata.var_names)
    genes_bulk = set(bulk.index)
    common_genes = list(genes_sc.intersection(genes_bulk))

    return common_genes

hide_deconv.preprocessing.combine_bulk_dataframes(data_frames)

Combines a list of bulk RNA seq dataframes and corrects for batch effects.

Parameters:

Name Type Description Default
data_frames list[DataFrame]

List of bulk RNA seq dataframes that should be combined.

required

Returns:

Type Description
tuple[DataFrame, DataFrame]

DataFrame, containing the bulk labels as columns and the merged genes as rows and DataFrame containing assignment to original batches.

Source code in src/hide_deconv/preprocessing/bulk_preprocessing.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def combine_bulk_dataframes(
    data_frames: list[pd.DataFrame],
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """
    Combines a list of bulk RNA seq dataframes and corrects for batch effects.

    Parameters
    ----------
    data_frames : list[pd.DataFrame]
        List of bulk RNA seq dataframes that should be combined.
    Returns
    -------
    tuple[pd.DataFrame, pd.DataFrame]
        DataFrame, containing the bulk labels as columns and the merged genes as rows and DataFrame containing assignment to original batches.
    """

    for i in range(len(data_frames)):
        data_frames[i] = (
            data_frames[i] * 1e6 / data_frames[i].sum(axis=0)
        )  # CPM everything before reducing genes!

    common_genes = data_frames[0].index
    for i, df in enumerate(data_frames[1:]):
        common_genes = common_genes.intersection(df[df.median(axis=1) > 0].index)

    if len(common_genes) == 0:
        raise ValueError("No shared genes found between input bulk dataframes.")

    data_frames = [df.loc[common_genes].copy() for df in data_frames]

    batch = []
    for i, df in enumerate(data_frames):
        batch.extend([f"batch_{i}" for _ in range(df.shape[1])])

    if len(data_frames) > 1:
        ref = data_frames[0]
        ref_median = ref.median(axis=1)

        aligned = [ref]
        for df in data_frames[1:]:
            tgt_median = df.median(axis=1)
            alpha = (ref_median) / (tgt_median)
            aligned.append(df.mul(alpha, axis=0))

        data_frames = aligned

    combined = pd.concat([df for df in data_frames], axis=1)

    batch_df = pd.DataFrame(batch, columns=["batch"], index=combined.columns)

    return combined, batch_df

hide_deconv.pipelines.deconvolve_hide_pipeline.normalize_bulk_to_cpm(bulk)

Normalize bulk expression to counts per million (CPM).

Duplicate gene labels are summed before normalization. Samples with a total count of zero result in zeros instead of NaN or inf values.

Parameters:

Name Type Description Default
bulk DataFrame

Bulk expression with genes as rows and samples as columns.

required

Returns:

Type Description
DataFrame

CPM normalized bulk expression (genes x samples).

Source code in src/hide_deconv/pipelines/deconvolve_hide_pipeline.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def normalize_bulk_to_cpm(bulk: pd.DataFrame) -> pd.DataFrame:
    """
    Normalize bulk expression to counts per million (CPM).

    Duplicate gene labels are summed before normalization. Samples with a
    total count of zero result in zeros instead of NaN or inf values.

    Parameters
    ----------
    bulk : pd.DataFrame
        Bulk expression with genes as rows and samples as columns.

    Returns
    -------
    pd.DataFrame
        CPM normalized bulk expression (genes x samples).
    """
    bulk = bulk
    if bulk.index.has_duplicates:
        bulk = bulk.groupby(level=0).sum()

    bulk = (bulk * 1e6) / bulk.sum(axis=0)
    bulk = bulk.replace([np.inf, -np.inf], 0).fillna(0)
    return bulk

Single-cell quality control

hide_deconv.pipelines.preprocess_anndata_file(adata, celltype_col, min_cell=100, min_gene_count=200, max_gene_count=5000, mt_percentage_per_cell=0.05, hb_percentage_per_cell=0.05, malat1_percentile_per_cell=0.99, exclude_mito_ribo_rna=True, exclude_hemoglobine=True, filter_low_expressed_genes=True, low_expressed_gene_cell_min=10)

Applies a standard AnnData preprocessing pipeline to a given AnnData file. Removes cells with low quality or high mitochondrial rna expression. Additionally excludes celltypes, that are below the min_cell threshold and removes genes that are either ribosomal, mitochondrial or have a very low expression level.

Genes in adata.var_names can either be human gene symbols or human Ensembl IDs.

Parameters:

adata : ad.AnnData AnnData single cell file, that will be preprocessed. celltype_col : str Column of the AnnData file, that holds the cell type labels min_cell : int = 100 Minimum number of cells per cell type to be included. min_gene_count : int = 100 Minimum summed gene count below which a cell is considered as low quality. max_gene_count : int = 5000 Max summed gene count above which a cell is considered to be low quality. mt_percentage_per_cell: float = 0.05 Percentage of mitochondrial gene expression, above which a cell is considered low quality. hb_percentage_per_cell: float = 0.05 Percentage of haemoglobine gene expression, above which a cell is considered low quality. malat1_percentile_per_cell: float = 0.99 Percentile of MALAT1 expression, above which a cell is considered low quality. exclude_mito_ribo_rna : bool = True Remove genes that are either mitochondrial or ribosomal. exclude_hemoglobine: bool = True Remove genes that are related to haemoglobine. filter_low_expressed_genes : bool = True Remove genes that have a low overall expression level and can thus be considered non-informative. low_expressed_gene_cell_min : int = 10 If filter_low_expressed_genes is True => Number of cells in which a gene has to be expressed at least.

Returns:

Type Description
AnnData

Preprocessed single cells

Source code in src/hide_deconv/pipelines/anndata_preprocess_pipeline.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def preprocess_anndata_file(
    adata: ad.AnnData,
    celltype_col: str,
    min_cell: int = 100,
    min_gene_count: int = 200,
    max_gene_count: int = 5000,
    mt_percentage_per_cell: float = 0.05,
    hb_percentage_per_cell: float = 0.05,
    malat1_percentile_per_cell: float = 0.99,
    exclude_mito_ribo_rna: bool = True,
    exclude_hemoglobine: bool = True,
    filter_low_expressed_genes: bool = True,
    low_expressed_gene_cell_min: int = 10,
) -> ad.AnnData:
    """
    Applies a standard AnnData preprocessing pipeline to a given AnnData file. Removes cells with low quality or high mitochondrial rna expression.
    Additionally excludes celltypes, that are below the min_cell threshold and removes genes that are either ribosomal, mitochondrial or have a very low expression level.

    Genes in adata.var_names can either be human gene symbols or human Ensembl IDs.

    Parameters:
    ----------
    adata : ad.AnnData
        AnnData single cell file, that will be preprocessed.
    celltype_col : str
        Column of the AnnData file, that holds the cell type labels
    min_cell : int = 100
        Minimum number of cells per cell type to be included.
    min_gene_count : int = 100
        Minimum summed gene count below which a cell is considered as low quality.
    max_gene_count : int = 5000
        Max summed gene count above which a cell is considered to be low quality.
    mt_percentage_per_cell: float = 0.05
        Percentage of mitochondrial gene expression, above which a cell is considered low quality.
    hb_percentage_per_cell: float = 0.05
        Percentage of haemoglobine gene expression, above which a cell is considered low quality.
    malat1_percentile_per_cell: float = 0.99
        Percentile of MALAT1 expression, above which a cell is considered low quality.
    exclude_mito_ribo_rna : bool = True
        Remove genes that are either mitochondrial or ribosomal.
    exclude_hemoglobine: bool = True
        Remove genes that are related to haemoglobine.
    filter_low_expressed_genes : bool = True
        Remove genes that have a low overall expression level and can thus be considered non-informative.
    low_expressed_gene_cell_min : int = 10
        If filter_low_expressed_genes is True => Number of cells in which a gene has to be expressed at least.

    Returns
    -------
    ad.AnnData
        Preprocessed single cells
    """

    # Calculate QC metrics, genes are identified either by gene symbol or Ensembl ID
    adata.var["mt"] = adata.var_names.str.startswith("MT-") | adata.var_names.isin(
        MITO_GENES_ENSEMBL
    )
    hb_genes = adata.var_names.str.startswith(
        ("HBA", "HBB", "HBD", "HBE", "HBG", "HBM", "HBQ", "HBZ")
    ) | adata.var_names.isin(HB_GENES_ENSEMBL)
    adata.var["hb"] = hb_genes
    sc.pp.calculate_qc_metrics(adata, qc_vars=["mt", "hb"], inplace=True)

    # create filters
    cell_mask = np.ones(adata.n_obs, dtype=bool)
    cell_mask &= adata.obs["n_genes_by_counts"] >= min_gene_count
    cell_mask &= adata.obs["n_genes_by_counts"] < max_gene_count
    cell_mask &= (adata.obs["pct_counts_mt"] / 100) < mt_percentage_per_cell
    cell_mask &= (adata.obs["pct_counts_hb"] / 100) < hb_percentage_per_cell

    malat1_gene = next(
        (gene for gene in ("MALAT1", MALAT1_ENSEMBL) if gene in adata.var_names), None
    )
    if malat1_gene is not None:
        malat1_values = adata[:, malat1_gene].X

        if hasattr(malat1_values, "toarray"):
            malat1_values = malat1_values.toarray().flatten()
        else:
            malat1_values = malat1_values.flatten()

        malat1_thresh = np.quantile(malat1_values, malat1_percentile_per_cell)
        cell_mask &= malat1_values < malat1_thresh

    ct_counts = adata.obs[celltype_col].value_counts()
    ct_to_keep = set(ct_counts[ct_counts >= min_cell].index)
    cell_mask &= adata.obs[celltype_col].isin(ct_to_keep)

    # Apply filters
    adata = adata[cell_mask].copy()

    gene_mask = np.ones(adata.n_vars, dtype=bool)
    gene_names = adata.var_names

    if exclude_mito_ribo_rna:
        gene_mask &= ~(gene_names.str.startswith(("MT-", "RPS", "RPL")))
        gene_mask &= ~(gene_names.isin(MITO_GENES_ENSEMBL + RIBO_GENES_ENSEMBL))

    if exclude_hemoglobine:
        gene_mask &= ~(
            gene_names.str.startswith(
                ("HBA", "HBB", "HBD", "HBE", "HBG", "HBM", "HBQ", "HBZ")
            )
        )
        gene_mask &= ~(gene_names.isin(HB_GENES_ENSEMBL))

    adata = adata[:, gene_mask].copy()

    if filter_low_expressed_genes:
        sc.pp.filter_genes(adata, min_cells=low_expressed_gene_cell_min)

    return adata

AnnData utilities

hide_deconv.preprocessing.reduce_genes(adata, N, ct_col='cell_type')

Reduce an AnnData object to the N most informative genes.

The function computes the mean expression per cell type and selects the genes with the highest variance between cell types. It returns a copy of the AnnData object restricted to the selected genes.

Parameters:

Name Type Description Default
adata AnnData

Input expression data.

required
N int

Number of genes to select.

required
ct_col str

Column in adata.obs containing the cell type labels used for variance calculation

"cell_type"

Returns:

Type Description
AnnData

A copy of the input AnnData object containing only the selected genes.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def reduce_genes(adata: ad.AnnData, N: int, ct_col: str = "cell_type") -> ad.AnnData:
    """
    Reduce an AnnData object to the N most informative genes.

    The function computes the mean expression per cell type and selects
    the genes with the highest variance between cell types. It returns a
    copy of the AnnData object restricted to the selected genes.

    Parameters
    ----------
    adata : anndata.AnnData
        Input expression data.
    N : int
        Number of genes to select.
    ct_col : str, default="cell_type"
        Column in adata.obs containing the cell type labels used for variance calculation

    Returns
    -------
    anndata.AnnData
        A copy of the input AnnData object containing only the selected genes.

    """
    n_genes_total = adata.n_vars

    N = min(N, n_genes_total)

    ct = adata.obs[ct_col].astype(str).values
    celltypes = np.array(sorted(pd.unique(ct)))

    X = adata.X
    if sp.issparse(X):
        X = X.tocsr()
    else:
        X = np.asarray(X)

    mean_by_ct = np.zeros((len(celltypes), n_genes_total), dtype=np.float64)

    for i, c in enumerate(celltypes):
        rows = np.where(ct == c)[0]
        if rows.size == 0:
            continue
        if sp.issparse(X):
            mean_by_ct[i, :] = np.asarray(X[rows].mean(axis=0)).ravel()
        else:
            mean_by_ct[i, :] = X[rows, :].mean(axis=0)

    var_between = mean_by_ct.var(axis=0)

    top_idx = np.argsort(-var_between)[:N]
    top_genes = adata.var_names[top_idx]

    adata_red = adata[:, top_genes].copy()
    return adata_red

hide_deconv.preprocessing.create_hierarchy(adata, ct_col_sub, ct_col_higher)

Create hiearchy mapping matrices between subtypes and higher-level cell types.

The function constructs for each column in ct_col_higher a binary projection matrix that maps each subtype in ct_col_sub to its corresponding higher-level cell type. Each returned matrix has higher-level cell types as rows and subtypes as columns.

Every cell type must belong to exactly one cell type of the next higher level, otherwise a ValueError is raised (see validate_hierarchy).

Parameters:

Name Type Description Default
adata AnnData

Input expression data containing cell annotations in adata.obs

required
ct_col_sub str

Column in adata.obs containing the lower-level cell type labels.

required
ct_col_higher list[str]

List of column names in adata.obs containing the higher-level cell type labels for which hiearchy matrices should be created, ordered from the finest to the coarsest annotation level.

required

Returns:

Type Description
dict[str, DataFrame]

Dictionary mapping each higher-level annotation column name to a pandas DataFrame with shape (n_higher_types, n_subtypes), where entries are 1 if a subtype belongs to a higher-level type and 0 otherwise.

Raises:

Type Description
ValueError

If a cell type is assigned to more than one cell type of the next higher level.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def create_hierarchy(
    adata: ad.AnnData, ct_col_sub: str, ct_col_higher: list[str]
) -> dict[str, pd.DataFrame]:
    """
    Create hiearchy mapping matrices between subtypes and higher-level cell types.

    The function constructs for each column in ct_col_higher a binary projection matrix
    that maps each subtype in ct_col_sub to its corresponding higher-level cell type.
    Each returned matrix has higher-level cell types as rows and subtypes as columns.

    Every cell type must belong to exactly one cell type of the next higher level,
    otherwise a ValueError is raised (see validate_hierarchy).

    Parameters
    ----------
    adata : anndata.AnnData
        Input expression data containing cell annotations in adata.obs
    ct_col_sub : str
        Column in adata.obs containing the lower-level cell type labels.
    ct_col_higher : list[str]
        List of column names in adata.obs containing the higher-level
        cell type labels for which hiearchy matrices should be created,
        ordered from the finest to the coarsest annotation level.

    Returns
    -------
    dict[str, pd.DataFrame]
        Dictionary mapping each higher-level annotation column name to a
        pandas DataFrame with shape (n_higher_types, n_subtypes), where
        entries are 1 if a subtype belongs to a higher-level type and
        0 otherwise.

    Raises
    ------
    ValueError
        If a cell type is assigned to more than one cell type of the next higher level.
    """

    validate_hierarchy(adata, [ct_col_sub] + list(ct_col_higher))

    obs = adata.obs.copy()

    sub = obs[ct_col_sub].astype(str)
    sub_types = sorted(sub.unique())

    A_dict = {}

    for col in ct_col_higher:
        high = obs[col].astype(str)
        map_df = pd.DataFrame({"sub": sub, "high": high}).drop_duplicates()

        sub_to_high = map_df.set_index("sub")["high"].to_dict()

        high_types = sorted(high.unique())
        A = pd.DataFrame(0, index=high_types, columns=sub_types, dtype=int)

        for s in sub_types:
            h = sub_to_high.get(s, None)
            if h is not None:
                A.loc[h, s] = 1

        A_dict[col] = A

    return A_dict

hide_deconv.preprocessing.validate_hierarchy(adata, celltype_cols)

Check that the cell type annotations form a valid hierarchy.

The columns are expected to be ordered from the finest to the coarsest annotation level. For each pair of neighboring levels, every child cell type must belong to exactly one parent cell type. Multiple child cell types may belong to the same parent cell type.

Parameters:

Name Type Description Default
adata AnnData

Input expression data containing cell annotations in adata.obs.

required
celltype_cols list[str]

Columns in adata.obs containing the cell type labels, ordered from the finest to the coarsest annotation level.

required

Raises:

Type Description
ValueError

If a child cell type is assigned to more than one parent cell type.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def validate_hierarchy(adata: ad.AnnData, celltype_cols: list[str]) -> None:
    """
    Check that the cell type annotations form a valid hierarchy.

    The columns are expected to be ordered from the finest to the coarsest annotation
    level. For each pair of neighboring levels, every child cell type must belong to
    exactly one parent cell type. Multiple child cell types may belong to the same
    parent cell type.

    Parameters
    ----------
    adata : anndata.AnnData
        Input expression data containing cell annotations in adata.obs.
    celltype_cols : list[str]
        Columns in adata.obs containing the cell type labels, ordered from the
        finest to the coarsest annotation level.

    Raises
    ------
    ValueError
        If a child cell type is assigned to more than one parent cell type.
    """

    for child_col, parent_col in zip(celltype_cols[:-1], celltype_cols[1:]):
        pairs = pd.DataFrame(
            {
                "child": adata.obs[child_col].astype(str).to_numpy(),
                "parent": adata.obs[parent_col].astype(str).to_numpy(),
            }
        )
        counts = pairs.value_counts().rename("n_cells").reset_index()
        n_parents = counts.groupby("child")["parent"].nunique()
        conflicts = sorted(n_parents[n_parents > 1].index)

        if not conflicts:
            continue

        lines = []
        for child in conflicts[:MAX_REPORTED_CONFLICTS]:
            parents = counts[counts["child"] == child].sort_values(
                "n_cells", ascending=False
            )
            parents_str = ", ".join(
                f"'{p}' ({n} cells)"
                for p, n in zip(parents["parent"], parents["n_cells"])
            )
            lines.append(f"  - '{child}' -> {parents_str}")
        if len(conflicts) > MAX_REPORTED_CONFLICTS:
            lines.append(f"  ... and {len(conflicts) - MAX_REPORTED_CONFLICTS} more.")

        raise ValueError(
            f"Invalid cell type hierarchy between '{child_col}' and '{parent_col}': "
            f"{len(conflicts)} cell type(s) in '{child_col}' are assigned to more than one "
            f"cell type in '{parent_col}'. Each cell type must belong to exactly one "
            "parent cell type:\n" + "\n".join(lines)
        )

hide_deconv.preprocessing.fill_missing_celltypes(adata, celltype_cols)

Fill missing child cell type labels with the label of their parent cell type.

The columns are expected to be ordered from the finest to the coarsest annotation level. Starting at the coarsest level, every cell without a label in a column receives the (already filled) label of the next coarser column. Cells without a label on all levels are left unchanged.

adata.obs is modified in place.

Parameters:

Name Type Description Default
adata AnnData

Input expression data containing cell annotations in adata.obs.

required
celltype_cols list[str]

Columns in adata.obs containing the cell type labels, ordered from the finest to the coarsest annotation level.

required

Returns:

Type Description
AnnData

The input AnnData object with filled cell type labels.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def fill_missing_celltypes(adata: ad.AnnData, celltype_cols: list[str]) -> ad.AnnData:
    """
    Fill missing child cell type labels with the label of their parent cell type.

    The columns are expected to be ordered from the finest to the coarsest annotation
    level. Starting at the coarsest level, every cell without a label in a column
    receives the (already filled) label of the next coarser column. Cells without a
    label on all levels are left unchanged.

    adata.obs is modified in place.

    Parameters
    ----------
    adata : anndata.AnnData
        Input expression data containing cell annotations in adata.obs.
    celltype_cols : list[str]
        Columns in adata.obs containing the cell type labels, ordered from the
        finest to the coarsest annotation level.

    Returns
    -------
    anndata.AnnData
        The input AnnData object with filled cell type labels.
    """

    for i in range(len(celltype_cols) - 2, -1, -1):
        child_col, parent_col = celltype_cols[i], celltype_cols[i + 1]

        child = adata.obs[child_col]
        parent = adata.obs[parent_col]
        fill_mask = is_missing_celltype(child) & ~is_missing_celltype(parent)

        if not fill_mask.any():
            continue

        filled = child.astype("object").to_numpy(copy=True)
        filled[fill_mask] = parent.astype(str).to_numpy()[fill_mask]
        adata.obs[child_col] = pd.Categorical(filled)

        warnings.warn(
            f"{int(fill_mask.sum())} cells without a cell type label in '{child_col}' "
            f"were assigned the label of their parent cell type in '{parent_col}'."
        )

    return adata

hide_deconv.preprocessing.train_test_split_adata(adata, celltype_col='cell_type', train_frac=0.5, seed=42)

Split an AnnData object into a train and test subset.

The function splits the cells of each cell type independently into a training and a test subset. Samples are shuffled before splitting. For cell types with at least two samples the split ensures that both train and test receive at least one sample.

Parameters:

Name Type Description Default
adata AnnData

Input AnnData object to split.

required
celltype_col str

Column in adata.obs containing the cell type labels used for splitting

"cell_type"
train_frac float

Fraction of samplesper cell type assigned to the training split.

0.5
seed int

Random seed used for shuffling before the split.

42

Returns:

Type Description
tuple[AnnData, AnnData]

A tuple containing the training AnnData object and the test AnnData object.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def train_test_split_adata(
    adata: ad.AnnData,
    celltype_col: str = "cell_type",
    train_frac: float = 0.5,
    seed: int = 42,
) -> tuple[ad.AnnData, ad.AnnData]:
    """
    Split an AnnData object into a train and test subset.

    The function splits the cells of each cell type independently into a training
    and a test subset. Samples are shuffled before splitting. For cell types
    with at least two samples the split ensures that both train and test
    receive at least one sample.

    Parameters
    ----------
    adata : anndata.AnnData
        Input AnnData object to split.
    celltype_col : str, default="cell_type"
        Column in adata.obs containing the cell type labels used for splitting
    train_frac : float, default=0.5
        Fraction of samplesper cell type assigned to the training split.
    seed : int, default=42
        Random seed used for shuffling before the split.

    Returns
    -------
    tuple[ad.AnnData, ad.AnnData]
        A tuple containing the training AnnData object and the test AnnData object.

    """

    rng = np.random.default_rng(seed)
    ct = adata.obs[celltype_col].astype(str).values

    train_idx = []
    test_idx = []

    for celltype in np.unique(ct):
        idx = np.where(ct == celltype)[0]
        rng.shuffle(idx)

        n_train = int(np.floor(len(idx) * train_frac))

        if len(idx) >= 2:
            n_train = max(1, min(n_train, len(idx) - 1))

        train_idx.extend(idx[:n_train])
        test_idx.extend(idx[n_train:])

    train_idx = np.array(train_idx, dtype=int)
    test_idx = np.array(test_idx, dtype=int)

    adata_train = adata[train_idx].copy()
    adata_test = adata[test_idx].copy()

    return adata_train, adata_test

hide_deconv.preprocessing.get_adata_info(ad_file)

Returns a summary of a AnnData file.

Parameters:

Name Type Description Default
ad_file str

Path to AnnData file.

required

Returns:

Type Description
dict[str, object]

Dictionary containing multiple metrics.

Source code in src/hide_deconv/preprocessing/train_preprocessing.py
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def get_adata_info(ad_file: str) -> dict[str, object]:
    """
    Returns a summary of a AnnData file.

    Parameters
    ----------
    ad_file : str
        Path to AnnData file.

    Returns
    -------
    dict[str, object]
        Dictionary containing multiple metrics.
    """

    adata = ad.read_h5ad(ad_file)

    obs = adata.obs.columns.tolist()
    var = adata.var.columns.tolist()
    n_cells, n_genes = adata.shape
    return {"obs": obs, "var": var, "n_cells": n_cells, "n_genes": n_genes}