Skip to content

Deconvolution

High-level API

deconvolution runs preprocessing, model training and prediction in one call. It returns one composition DataFrame for each requested cell type layer.

hide_deconv.deconvolution(adata, bulk, celltype_cols=None, n_genes=5000, n_train_bulks=10000, n_cells_per_bulk=100, n_iter=1000, domain_transfer=True, domain_transfer_bulk_count=DOMAIN_TRANSFER_BULK_COUNT, preds_per_bulk=DOMAIN_TRANSFER_PREDS_PER_BULK, alpha_window=DOMAIN_TRANSFER_ALPHA_WINDOW, domain_transfer_seed=DOMAIN_TRANSFER_SEED, library_size_correction=True, seed=42)

Run preprocessing, training and deconvolution in one call.

Parameters:

Name Type Description Default
adata AnnData

Annotated single-cell input data.

required
bulk DataFrame

Bulk expression with genes as rows and samples as columns.

required
celltype_cols list[str]

Cell type annotation columns in adata.obs. The first column is treated as the finest cell type layer. If no columns are specified, column cell_type is used.

None
n_genes int

Number of genes used for training and deconvolution.

5000
n_train_bulks int

Number of training bulks generated for training.

10000
n_cells_per_bulk int

Number of cells sampled per training bulk.

100
n_iter int

Number of training iterations.

1000
domain_transfer bool

Correct for domain transfer between Single Cell and Bulk data.

True
domain_transfer_bulk_count int

Number of simulated bulks used to calculate the domain-transfer factors.

1000
preds_per_bulk int

Approximate number of predictions per bulk sample during domain transfer.

5
alpha_window int

Number of bulk samples used to calculate the domain-transfer factors per window. If there are fewer than alpha_window + preds_per_bulk bulk samples, the composition is estimated without domain transfer.

25
domain_transfer_seed int

Random seed for the simulated bulks and the assignment of the samples to the domain-transfer windows.

2304
library_size_correction bool

Correct for library size differences between Single Cell and Bulk data.

True
seed int

Random seed for the simulated training bulks.

42

Returns:

Type Description
list[DataFrame]

List of estimated composition, same order as the celltype_cols list.

Source code in src/hide_deconv/pipelines/lazy_deconvolution_pipeline.py
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
145
146
147
148
149
150
151
152
153
154
155
156
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def deconvolution(
    adata: ad.AnnData,
    bulk: pd.DataFrame,
    celltype_cols: list[str] | tuple[str, ...] | str | None = None,
    n_genes: int = 5000,
    n_train_bulks: int = 10000,
    n_cells_per_bulk: int = 100,
    n_iter: int = 1000,
    domain_transfer: bool = True,
    domain_transfer_bulk_count: int = DOMAIN_TRANSFER_BULK_COUNT,
    preds_per_bulk: int = DOMAIN_TRANSFER_PREDS_PER_BULK,
    alpha_window: int = DOMAIN_TRANSFER_ALPHA_WINDOW,
    domain_transfer_seed: int = DOMAIN_TRANSFER_SEED,
    library_size_correction: bool = True,
    seed: int = 42,
) -> list[pd.DataFrame]:
    """
    Run preprocessing, training and deconvolution in one call.

    Parameters
    ----------
    adata : anndata.AnnData
        Annotated single-cell input data.
    bulk : pd.DataFrame
        Bulk expression with genes as rows and samples as columns.
    celltype_cols : list[str], default=None
        Cell type annotation columns in adata.obs. The first column is treated as
        the finest cell type layer. If no columns are specified, column cell_type is used.
    n_genes : int, default=5000
        Number of genes used for training and deconvolution.
    n_train_bulks : int, default=10000
        Number of training bulks generated for training.
    n_cells_per_bulk : int, default=100
        Number of cells sampled per training bulk.
    n_iter : int, default=1000
        Number of training iterations.
    domain_transfer : bool, default=True
        Correct for domain transfer between Single Cell and Bulk data.
    domain_transfer_bulk_count : int, default=1000
        Number of simulated bulks used to calculate the domain-transfer factors.
    preds_per_bulk : int, default=5
        Approximate number of predictions per bulk sample during domain transfer.
    alpha_window : int, default=25
        Number of bulk samples used to calculate the domain-transfer factors per window.
        If there are fewer than alpha_window + preds_per_bulk bulk samples, the
        composition is estimated without domain transfer.
    domain_transfer_seed : int, default=2304
        Random seed for the simulated bulks and the assignment of the samples to
        the domain-transfer windows.
    library_size_correction: bool, default = True
        Correct for library size differences between Single Cell and Bulk data.
    seed : int, default=42
        Random seed for the simulated training bulks.

    Returns
    -------
    list[pd.DataFrame]
        List of estimated composition, same order as the celltype_cols list.
    """

    celltype_cols = normalize_celltype_cols(celltype_cols)
    validate_required_columns(adata, celltype_cols)

    bulk = normalize_bulk_to_cpm(bulk)
    adata.obs["library_size"] = np.asarray(adata.X.sum(axis=1)).ravel()
    common_genes = get_common_genes(adata, bulk)
    if len(common_genes) == 0:
        raise ValueError("No shared genes found between adata and bulk.")

    # Normalize before subsetting
    adata = sc.pp.normalize_total(adata, target_sum=1e4, copy=True)

    # Fill on the copy, so that the annotations of the passed adata stay unchanged
    adata = fill_missing_celltypes(adata, celltype_cols)
    validate_hierarchy(adata, celltype_cols)

    library_sizes = (
        adata.obs.groupby(celltype_cols[0])["library_size"]
        .median()
        .rename("Median_Library_Size")
    )
    adata = adata[:, common_genes].copy()

    model, adata = setup_model(
        adata,
        celltype_cols,
        n_genes,
        n_train_bulks,
        n_cells_per_bulk,
        n_iter,
        seed,
    )

    bulk = bulk.loc[model.gene_labels]

    if not library_size_correction:
        library_sizes = None

    predictions, _ = predict_deconvolution_results(
        model,
        adata,
        bulk,
        celltype_cols[0],
        n_cells_per_bulk,
        domain_transfer_bulk_count=domain_transfer_bulk_count,
        preds_per_bulk=preds_per_bulk,
        alpha_window=alpha_window,
        domain_transfer=domain_transfer,
        seed=domain_transfer_seed,
        library_size_correction=library_sizes,
    )

    return predictions

Prediction with domain transfer

predict_deconvolution_results applies a trained model to bulk samples and corrects for domain transfer between simulated and real bulks.

hide_deconv.pipelines.deconvolve_hide_pipeline.predict_deconvolution_results(model, adata, bulk, celltype_col, n_cells_per_bulk, domain_transfer_bulk_count=DOMAIN_TRANSFER_BULK_COUNT, preds_per_bulk=DOMAIN_TRANSFER_PREDS_PER_BULK, alpha_window=DOMAIN_TRANSFER_ALPHA_WINDOW, domain_transfer=True, seed=DOMAIN_TRANSFER_SEED, return_errors=False, library_size_correction=None)

Predict cell type compositions with optional domain transfer.

If domain transfer is enabled, the bulk samples are processed in a sliding window scheme. For each window, alpha_window samples are used to calculate gene wise domain-transfer factors with respect to simulated bulks, which are then applied to the remaining samples before prediction. Each sample is thereby predicted multiple times and the predictions are averaged.

If there are fewer than alpha_window + preds_per_bulk bulk samples, the composition is estimated without domain transfer.

Note: adata must be normalized to 1e4 on the complete gene set (e.g. via sc.pp.normalize_total), analogous to the data used for training.

Parameters:

Name Type Description Default
model HIDE

Trained HIDE model.

required
adata AnnData | None

Normalized single-cell data used to simulate bulks for domain transfer. Only required if domain_transfer is True.

required
bulk DataFrame

CPM normalized bulk expression (genes x samples).

required
celltype_col str

Column in adata.obs containing the finest cell type labels.

required
n_cells_per_bulk int

Number of cells sampled per simulated bulk. Should match the training bulks.

required
domain_transfer_bulk_count int

Number of simulated bulks used to calculate the domain-transfer factors.

1000
preds_per_bulk int

Approximate number of predictions per bulk sample.

5
alpha_window int

Number of bulk samples used to calculate the domain-transfer factors per window.

25
domain_transfer bool

If True correct for domain transfer between simulated and real bulks.

True
seed int

Random seed for the simulated bulks.

2304
return_errors bool

If True return the standard deviation of the predictions per sample.

False
library_size_correction Series | None

Median library sizes of the finest cell type layer. If provided, the predictions are corrected for library size differences.

None

Returns:

Type Description
tuple[list[DataFrame], list[DataFrame]]

Estimated compositions per cell type layer and, if return_errors is True and domain transfer was applied, the corresponding standard deviations. Otherwise the second list is empty.

Source code in src/hide_deconv/pipelines/deconvolve_hide_pipeline.py
 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
202
203
204
205
206
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
def predict_deconvolution_results(
    model: HIDE,
    adata: ad.AnnData | None,
    bulk: pd.DataFrame,
    celltype_col: str,
    n_cells_per_bulk: int,
    domain_transfer_bulk_count: int = DOMAIN_TRANSFER_BULK_COUNT,
    preds_per_bulk: int = DOMAIN_TRANSFER_PREDS_PER_BULK,
    alpha_window: int = DOMAIN_TRANSFER_ALPHA_WINDOW,
    domain_transfer: bool = True,
    seed: int = DOMAIN_TRANSFER_SEED,
    return_errors: bool = False,
    library_size_correction: pd.Series | None = None,
) -> tuple[list[pd.DataFrame], list[pd.DataFrame]]:
    """
    Predict cell type compositions with optional domain transfer.

    If domain transfer is enabled, the bulk samples are processed in a sliding
    window scheme. For each window, alpha_window samples are used to calculate
    gene wise domain-transfer factors with respect to simulated bulks, which are
    then applied to the remaining samples before prediction. Each sample is
    thereby predicted multiple times and the predictions are averaged.

    If there are fewer than alpha_window + preds_per_bulk bulk samples, the
    composition is estimated without domain transfer.

    **Note:** adata must be normalized to 1e4 on the complete gene set
    (e.g. via sc.pp.normalize_total), analogous to the data used for training.

    Parameters
    ----------
    model : HIDE
        Trained HIDE model.
    adata : anndata.AnnData | None
        Normalized single-cell data used to simulate bulks for domain transfer.
        Only required if domain_transfer is True.
    bulk : pd.DataFrame
        CPM normalized bulk expression (genes x samples).
    celltype_col : str
        Column in adata.obs containing the finest cell type labels.
    n_cells_per_bulk : int
        Number of cells sampled per simulated bulk. Should match the training bulks.
    domain_transfer_bulk_count : int, default=1000
        Number of simulated bulks used to calculate the domain-transfer factors.
    preds_per_bulk : int, default=5
        Approximate number of predictions per bulk sample.
    alpha_window : int, default=25
        Number of bulk samples used to calculate the domain-transfer factors per window.
    domain_transfer : bool, default=True
        If True correct for domain transfer between simulated and real bulks.
    seed : int, default=2304
        Random seed for the simulated bulks.
    return_errors : bool, default=False
        If True return the standard deviation of the predictions per sample.
    library_size_correction : pd.Series | None, default=None
        Median library sizes of the finest cell type layer. If provided, the
        predictions are corrected for library size differences.

    Returns
    -------
    tuple[list[pd.DataFrame], list[pd.DataFrame]]
        Estimated compositions per cell type layer and, if return_errors is True
        and domain transfer was applied, the corresponding standard deviations.
        Otherwise the second list is empty.
    """

    if not domain_transfer or bulk.shape[1] < alpha_window + preds_per_bulk:
        if domain_transfer and bulk.shape[1] < alpha_window + preds_per_bulk:
            warnings.warn(
                "Not enough bulk samples for the domain-transfer windowing scheme. Estimating composition without domain transfer!"
            )

        predictions = model.predict(
            bulk, norm=True, library_sizes=library_size_correction
        )["prediction"]

        return predictions, []

    if adata is None:
        raise ValueError("adata is required when domain_transfer is enabled.")

    # adata is expected to be normalized to 1e4 on the complete gene set
    common_genes = [gene for gene in model.gene_labels if gene in adata.var_names]
    adata = adata[:, common_genes].copy()

    Y_domain, _ = create_bulks(
        adata,
        domain_transfer_bulk_count,
        n_cells_per_bulk,
        celltype_col=celltype_col,
        seed=seed,
    )

    bulk_names = bulk.columns.tolist()
    windows = get_domain_transfer_windows(
        bulk_names, alpha_window, preds_per_bulk, seed
    )

    common_genes = Y_domain.index.intersection(bulk.index).intersection(
        model.gene_labels
    )
    Y_domain = Y_domain.loc[common_genes]
    bulk = bulk.loc[common_genes]

    accum = [{bulk_name: [] for bulk_name in bulk_names} for _ in range(model.L)]

    for alpha_cols in windows:
        Y_alpha = bulk.loc[common_genes, alpha_cols]

        alpha = get_domain_transfer_factor(Y_alpha, Y_domain)
        alpha = alpha.loc[common_genes]
        alpha_inv = 1.0 / alpha
        alpha_inv.replace([np.inf, -np.inf], 0, inplace=True)
        alpha_inv.fillna(1.0, inplace=True)

        test_cols = [
            bulk_name for bulk_name in bulk_names if bulk_name not in alpha_cols
        ]
        if not test_cols:
            continue

        Y_test = bulk.loc[common_genes, test_cols]
        Y_test_adj = Y_test.mul(alpha_inv, axis=0)

        preds = model.predict(
            Y_test_adj, norm=True, library_sizes=library_size_correction
        )["prediction"]

        for layer in range(model.L):
            C_est = preds[layer]
            for col in C_est.columns:
                accum[layer][col].append(C_est[[col]])

    deconv_res: list[pd.DataFrame] = []
    deconv_errs: list[pd.DataFrame] = []
    for layer in range(model.L):
        means = []
        errors = []
        for bulk_name in bulk_names:
            stacked = pd.concat(accum[layer][bulk_name], axis=1)
            means.append(stacked.mean(axis=1))
            if return_errors:
                errors.append(stacked.std(axis=1, ddof=0))

        C_mean = pd.concat(means, axis=1)
        C_mean.columns = bulk_names
        deconv_res.append(C_mean)

        if return_errors:
            C_std = pd.concat(errors, axis=1)
            C_std.columns = bulk_names
            deconv_errs.append(C_std)

    if return_errors:
        return deconv_res, deconv_errs
    else:
        return deconv_res, []