Skip to content

Python API

The Python API is organized into preprocessing, deconvolution, model, statistical and visualization components.

The main workflow is:

  1. Load annotated single-cell data and bulk expression data.
  2. Create reference profiles and simulated training bulks.
  3. Train the HIDE model.
  4. Apply domain-transfer and library-size corrections where required.
  5. Predict cell-type proportions.
  6. Analyze and visualize the resulting compositions.

Public API

To run the deconvolution with a single command, you can use:

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

To generate synthetic data, you can use:

hide_deconv.generate_example

===================================================== Functions for creating synthetic data =====================================================

simulate_profiles(rng, n_genes)

Simulate reference profiles for all subtypes.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
n_genes int

Total number of genes.

required

Returns:

Type Description
DataFrame

Reference profiles (genes x subtypes), every column sums to 1.

Source code in src/hide_deconv/example/generate_example.py
 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
def simulate_profiles(rng: np.random.Generator, n_genes: int) -> pd.DataFrame:
    """
    Simulate reference profiles for all subtypes.

    Parameters
    ----------
    rng : np.random.Generator
        Random number generator.
    n_genes : int
        Total number of genes.

    Returns
    -------
    pd.DataFrame
        Reference profiles (genes x subtypes), every column sums to 1.
    """

    qc_genes = EXAMPLE_MT_GENES + EXAMPLE_RIBO_GENES + EXAMPLE_HB_GENES + ["MALAT1"]
    n_regular = n_genes - len(qc_genes)
    gene_names = [f"GENE{i:04d}" for i in range(1, n_regular + 1)] + qc_genes

    subtypes = list(EXAMPLE_HIERARCHY.keys())
    majors = sorted(set(EXAMPLE_HIERARCHY.values()))

    baseline = rng.gamma(0.4, 1.0, n_regular)

    # Disjoint marker genes
    marker_pool = rng.permutation(n_regular)
    major_markers = {
        major: marker_pool[i * 60 : (i + 1) * 60] for i, major in enumerate(majors)
    }
    offset = len(majors) * 60
    sub_markers = {
        sub: marker_pool[offset + i * 30 : offset + (i + 1) * 30]
        for i, sub in enumerate(subtypes)
    }

    profiles = np.zeros((n_genes, len(subtypes)))
    for j, sub in enumerate(subtypes):
        profile = baseline * rng.lognormal(0.0, 0.2, n_regular)
        profile[major_markers[EXAMPLE_HIERARCHY[sub]]] *= rng.lognormal(2.0, 0.5, 60)
        profile[sub_markers[sub]] *= rng.lognormal(1.5, 0.4, 30)
        profile = profile / profile.sum()

        # Fractions of mitochondrial, ribosomal, hemoglobin and MALAT1 counts,
        # that can be removed by the preprocessing
        qc_profile = np.concatenate(
            [
                np.full(len(EXAMPLE_MT_GENES), 0.02 / len(EXAMPLE_MT_GENES)),
                np.full(len(EXAMPLE_RIBO_GENES), 0.05 / len(EXAMPLE_RIBO_GENES)),
                np.full(len(EXAMPLE_HB_GENES), 0.0005 / len(EXAMPLE_HB_GENES)),
                [0.03],
            ]
        )
        profiles[:, j] = np.concatenate([profile * (1 - qc_profile.sum()), qc_profile])

    return pd.DataFrame(profiles, index=gene_names, columns=subtypes)

simulate_single_cells(rng, profiles, n_cells, dispersion=0.3)

Simulate raw single cell counts from the reference profiles using a negative binomial.

Some cells are simulated to have a bad quality.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
profiles DataFrame

Reference profiles (genes x subtypes).

required
n_cells int

Number of cells.

required
dispersion float

Dispersion of the negative binomial distribution.

0.3

Returns:

Type Description
AnnData

Raw counts with the annotation columns cell_type and major in obs.

Source code in src/hide_deconv/example/generate_example.py
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
def simulate_single_cells(
    rng: np.random.Generator,
    profiles: pd.DataFrame,
    n_cells: int,
    dispersion: float = 0.3,
) -> ad.AnnData:
    """
    Simulate raw single cell counts from the reference profiles using a negative binomial.

    Some cells are simulated to have a bad quality.

    Parameters
    ----------
    rng : np.random.Generator
        Random number generator.
    profiles : pd.DataFrame
        Reference profiles (genes x subtypes).
    n_cells : int
        Number of cells.
    dispersion : float, default=0.3
        Dispersion of the negative binomial distribution.

    Returns
    -------
    ad.AnnData
        Raw counts with the annotation columns cell_type and major in obs.
    """

    subtypes = list(profiles.columns)
    fractions = np.array([EXAMPLE_SC_FRACTIONS[sub] for sub in subtypes])
    celltypes = rng.choice(subtypes, size=n_cells, p=fractions / fractions.sum())

    library_sizes = np.array([EXAMPLE_LIBRARY_SIZES[ct] for ct in celltypes])
    library_sizes = library_sizes * rng.lognormal(0.0, 0.3, n_cells)

    mean = profiles[celltypes].to_numpy().T * library_sizes[:, None]

    # Low quality cells
    is_mt = profiles.index.isin(EXAMPLE_MT_GENES)
    high_mt = rng.random(n_cells) < 0.03
    mean[np.ix_(high_mt, is_mt)] *= 15
    low_count = rng.random(n_cells) < 0.02
    mean[low_count] *= 0.05

    counts = rng.poisson(rng.gamma(1 / dispersion, mean * dispersion))

    obs = pd.DataFrame(
        {
            "cell_type": pd.Categorical(celltypes, categories=subtypes),
            "major": pd.Categorical(
                [EXAMPLE_HIERARCHY[ct] for ct in celltypes],
                categories=sorted(set(EXAMPLE_HIERARCHY.values())),
            ),
        },
        index=[f"cell_{i:05d}" for i in range(1, n_cells + 1)],
    )

    return ad.AnnData(
        X=sp.csr_matrix(counts.astype(np.float32)),
        obs=obs,
        var=pd.DataFrame(index=profiles.index),
    )

simulate_compositions(rng, sample_sheet, concentration=40.0)

Simulate compositions depending on disease and medication.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
sample_sheet DataFrame

Sample sheet containing the columns SampleID, disease and medication.

required
concentration float

Concentration of the Dirichlet distribution.

40.0

Returns:

Type Description
DataFrame

Cell type compositions (subtypes x samples).

Source code in src/hide_deconv/example/generate_example.py
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
236
237
238
def simulate_compositions(
    rng: np.random.Generator, sample_sheet: pd.DataFrame, concentration: float = 40.0
) -> pd.DataFrame:
    """
    Simulate compositions depending on disease and medication.

    Parameters
    ----------
    rng : np.random.Generator
        Random number generator.
    sample_sheet : pd.DataFrame
        Sample sheet containing the columns SampleID, disease and medication.
    concentration : float, default=40.0
        Concentration of the Dirichlet distribution.

    Returns
    -------
    pd.DataFrame
        Cell type compositions (subtypes x samples).
    """

    subtypes = list(EXAMPLE_HEALTHY_COMPOSITION.keys())
    compositions = []

    for _, sample in sample_sheet.iterrows():
        mean = pd.Series(EXAMPLE_HEALTHY_COMPOSITION)

        if sample["disease"] == "disease":
            for ct, effect in EXAMPLE_DISEASE_EFFECT.items():
                mean[ct] *= effect

        for ct, effect in EXAMPLE_MEDICATION_EFFECT.get(
            sample["medication"], {}
        ).items():
            mean[ct] *= effect

        mean = mean / mean.sum()
        compositions.append(rng.dirichlet(concentration * mean.to_numpy()))

    return pd.DataFrame(
        np.array(compositions).T, index=subtypes, columns=sample_sheet["SampleID"]
    )

simulate_bulk(rng, profiles, compositions, is_disease, n_deg=40, dispersion=0.05)

Simulate raw bulk counts from cell type compositions.

Cell types contribute proportional to their library size. A gene wise domain shift between single cell and bulk data is applied and a set of genes is differentially expressed in disease patients independent of the composition.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
profiles DataFrame

Relative expression profiles (genes x subtypes).

required
compositions DataFrame

Cell type compositions (subtypes x samples).

required
is_disease ndarray

Boolean mask of disease samples.

required
n_deg int

Number of genes differentially expressed in disease samples.

40
dispersion float

Dispersion of the negative binomial distribution.

0.05

Returns:

Type Description
DataFrame

Raw bulk counts (genes x samples).

Source code in src/hide_deconv/example/generate_example.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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
def simulate_bulk(
    rng: np.random.Generator,
    profiles: pd.DataFrame,
    compositions: pd.DataFrame,
    is_disease: np.ndarray,
    n_deg: int = 40,
    dispersion: float = 0.05,
) -> pd.DataFrame:
    """
    Simulate raw bulk counts from cell type compositions.

    Cell types contribute proportional to their library size. A gene wise
    domain shift between single cell and bulk data is applied and a set of
    genes is differentially expressed in disease patients independent of the
    composition.

    Parameters
    ----------
    rng : np.random.Generator
        Random number generator.
    profiles : pd.DataFrame
        Relative expression profiles (genes x subtypes).
    compositions : pd.DataFrame
        Cell type compositions (subtypes x samples).
    is_disease : np.ndarray
        Boolean mask of disease samples.
    n_deg : int, default=40
        Number of genes differentially expressed in disease samples.
    dispersion : float, default=0.05
        Dispersion of the negative binomial distribution.

    Returns
    -------
    pd.DataFrame
        Raw bulk counts (genes x samples).
    """

    library_sizes = pd.Series(EXAMPLE_LIBRARY_SIZES)[profiles.columns]
    weights = compositions.loc[profiles.columns].mul(library_sizes, axis=0)

    mean = profiles.to_numpy() @ weights.to_numpy()

    # Gene wise domain shift between single cell and bulk RNA-seq
    mean *= rng.lognormal(0.0, 0.5, profiles.shape[0])[:, None]

    # Composition independent differentially expressed genes
    regular_genes = np.flatnonzero(profiles.index.str.startswith("GENE"))
    deg_idx = rng.choice(regular_genes, size=n_deg, replace=False)
    deg_effect = rng.choice([-1.0, 1.0], size=n_deg) * rng.uniform(0.8, 1.5, n_deg)
    mean[np.ix_(deg_idx, is_disease)] *= np.exp(deg_effect)[:, None]

    depth = rng.lognormal(np.log(2e7), 0.2, mean.shape[1])
    mean = mean / mean.sum(axis=0) * depth

    counts = rng.poisson(rng.gamma(1 / dispersion, mean * dispersion))

    return pd.DataFrame(counts, index=profiles.index, columns=compositions.columns)

simulate_survival(rng, sample_sheet, compositions, max_follow_up=60.0)

Simulate survival times in months.

The hazard increases with disease and age and decreases with the abundance of T_CD8 cells.

Parameters:

Name Type Description Default
rng Generator

Random number generator.

required
sample_sheet DataFrame

Sample sheet containing the columns SampleID, disease and age.

required
compositions DataFrame

Cell type compositions (subtypes x samples).

required
max_follow_up float

Maximum follow up time in months.

60.0

Returns:

Type Description
DataFrame

Sample sheet with the additional columns survival_time and event.

Source code in src/hide_deconv/example/generate_example.py
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def simulate_survival(
    rng: np.random.Generator,
    sample_sheet: pd.DataFrame,
    compositions: pd.DataFrame,
    max_follow_up: float = 60.0,
) -> pd.DataFrame:
    """
    Simulate survival times in months.

    The hazard increases with disease and age and decreases with the
    abundance of T_CD8 cells.

    Parameters
    ----------
    rng : np.random.Generator
        Random number generator.
    sample_sheet : pd.DataFrame
        Sample sheet containing the columns SampleID, disease and age.
    compositions : pd.DataFrame
        Cell type compositions (subtypes x samples).
    max_follow_up : float, default=60.0
        Maximum follow up time in months.

    Returns
    -------
    pd.DataFrame
        Sample sheet with the additional columns survival_time and event.
    """

    t_cd8 = compositions.loc["T_CD8", sample_sheet["SampleID"]].to_numpy()
    t_cd8 = (t_cd8 - t_cd8.mean()) / t_cd8.std()

    log_hazard = (
        np.log(1 / 80)
        + 1.0 * (sample_sheet["disease"] == "disease").to_numpy()
        + 0.03 * (sample_sheet["age"].to_numpy() - 60)
        - 0.8 * t_cd8
    )

    event_time = rng.exponential(1 / np.exp(log_hazard))
    censor_time = np.minimum(rng.exponential(120, len(sample_sheet)), max_follow_up)

    sample_sheet = sample_sheet.copy()
    sample_sheet["survival_time"] = np.round(np.minimum(event_time, censor_time), 1)
    sample_sheet["event"] = (event_time <= censor_time).astype(int)

    return sample_sheet

generate_example(seed=42, n_cells=3000, n_genes=2000, n_patients=60)

Generate a synthetic example dataset to test the functionality of HIDE-Deconv.

The single cell data contains six immune cell subtypes (column cell_type), which are grouped into three major cell types (column major). The bulk samples are split into healthy and disease patients. Disease patients receive one of three medications, which together with the disease state affect the cell type composition. Survival depends on disease, age and the abundance of T_CD8 cells.

Note: The data is synthetic.

Parameters:

Name Type Description Default
seed int

Random seed for reproducible data.

42
n_cells int

Number of single cells.

3000
n_genes int

Number of genes.

2000
n_patients int

Number of bulk samples. Half of the patients are healthy.

60

Returns:

Type Description
tuple[AnnData, DataFrame, DataFrame]

Single cells with raw counts, bulk with raw counts (genes x samples) and sample sheet with the columns SampleID, disease, medication, age, sex, survival_time and event.

Source code in src/hide_deconv/example/generate_example.py
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
394
395
396
397
398
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
def generate_example(
    seed: int = 42,
    n_cells: int = 3000,
    n_genes: int = 2000,
    n_patients: int = 60,
) -> tuple[ad.AnnData, pd.DataFrame, pd.DataFrame]:
    """
    Generate a synthetic example dataset to test the functionality of HIDE-Deconv.

    The single cell data contains six immune cell subtypes (column cell_type),
    which are grouped into three major cell types (column major). The bulk
    samples are split into healthy and disease patients. Disease patients
    receive one of three medications, which together with the disease state
    affect the cell type composition. Survival depends on disease, age and the
    abundance of T_CD8 cells.

    Note: The data is **synthetic**.
    Parameters
    ----------
    seed : int, default=42
        Random seed for reproducible data.
    n_cells : int, default=3000
        Number of single cells.
    n_genes : int, default=2000
        Number of genes.
    n_patients : int, default=60
        Number of bulk samples. Half of the patients are healthy.

    Returns
    -------
    tuple[ad.AnnData, pd.DataFrame, pd.DataFrame]
        Single cells with raw counts, bulk with raw counts (genes x samples) and
        sample sheet with the columns SampleID, disease, medication, age, sex,
        survival_time and event.
    """

    rng = np.random.default_rng(seed)

    profiles = simulate_profiles(rng, n_genes)
    adata = simulate_single_cells(rng, profiles, n_cells)

    # Shuffle healthy and disease patients
    n_healthy = n_patients // 2
    disease = rng.permutation(
        ["healthy"] * n_healthy + ["disease"] * (n_patients - n_healthy)
    )
    medication = np.where(
        disease == "disease",
        rng.choice(list(EXAMPLE_MEDICATION_EFFECT.keys()), size=n_patients),
        "none",
    )

    sample_sheet = pd.DataFrame(
        {
            "SampleID": [f"P{i:03d}" for i in range(1, n_patients + 1)],
            "disease": disease,
            "medication": medication,
            "age": np.clip(rng.normal(60, 10, n_patients), 30, 90).astype(int),
            "sex": rng.choice(["female", "male"], size=n_patients),
        }
    )

    compositions = simulate_compositions(rng, sample_sheet)
    bulk = simulate_bulk(
        rng, profiles, compositions, (sample_sheet["disease"] == "disease").to_numpy()
    )
    bulk.columns.name = None
    sample_sheet = simulate_survival(rng, sample_sheet, compositions)

    return adata, bulk, sample_sheet

To download single cell data from CELLxGENE, you can use:

hide_deconv.download_sc_cellxgene(dataset_id, save_dir, tissues=None, diseases=None, catalog=None, gene_id='symbol', protein_coding_only=True)

Download a single cell dataset from CELLxGENE Discover.

The dataset is stored as ".h5ad" in save_dir. Afterwards, the cells are optionally subset to the given tissues and diseases and raw counts stored in adata.raw are moved to adata.X. Spike-ins are removed and optionally only protein coding genes are kept. Either gene symbols or Ensembl IDs are used as var_names, the other identifier is kept in adata.var. The citation information of the dataset is stored as "_citation.txt" in save_dir.

Parameters:

Name Type Description Default
dataset_id str

CELLxGENE dataset ID.

required
save_dir str | Path

Folder, where the AnnData file will be stored.

required
tissues list[str] | None = None

Keep only cells of these tissues. None keeps all tissues.

None
diseases list[str] | None = None

Keep only cells of these diseases. None keeps all diseases.

None
catalog list[dict] | None = None

Catalog as returned by fetch_cellxgene_catalog. If None, the catalog is fetched from the CELLxGENE Discover API.

None
gene_id str = "symbol"

Gene identifier used as var_names. Either "symbol" or "ensembl".

'symbol'
protein_coding_only bool = True

Keep only protein coding genes.

True

Returns:

Type Description
Path

Path of the downloaded AnnData file.

Raises:

Type Description
ValueError

If the dataset ID is not found in the catalog.

NotADirectoryError

If save_dir is not an existing folder.

Source code in src/hide_deconv/download/download_file.py
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def download_sc_cellxgene(
    dataset_id: str,
    save_dir: str | Path,
    tissues: list[str] | None = None,
    diseases: list[str] | None = None,
    catalog: list[dict] | None = None,
    gene_id: str = "symbol",
    protein_coding_only: bool = True,
) -> Path:
    """
    Download a single cell dataset from CELLxGENE Discover.

    The dataset is stored as "<dataset_id>.h5ad" in save_dir. Afterwards, the
    cells are optionally subset to the given tissues and diseases and raw counts
    stored in adata.raw are moved to adata.X. Spike-ins are removed and optionally
    only protein coding genes are kept. Either gene symbols or Ensembl IDs are used
    as var_names, the other identifier is kept in adata.var. The citation information
    of the dataset is stored as "<dataset_id>_citation.txt" in save_dir.

    Parameters
    ----------
    dataset_id : str
        CELLxGENE dataset ID.
    save_dir : str | Path
        Folder, where the AnnData file will be stored.
    tissues : list[str] | None = None
        Keep only cells of these tissues. None keeps all tissues.
    diseases : list[str] | None = None
        Keep only cells of these diseases. None keeps all diseases.
    catalog : list[dict] | None = None
        Catalog as returned by fetch_cellxgene_catalog. If None, the catalog is
        fetched from the CELLxGENE Discover API.
    gene_id : str = "symbol"
        Gene identifier used as var_names. Either "symbol" or "ensembl".
    protein_coding_only : bool = True
        Keep only protein coding genes.

    Returns
    -------
    Path
        Path of the downloaded AnnData file.

    Raises
    ------
    ValueError
        If the dataset ID is not found in the catalog.
    NotADirectoryError
        If save_dir is not an existing folder.
    """

    save_dir = Path(save_dir).expanduser()
    if not save_dir.is_dir():
        raise NotADirectoryError(f"'{save_dir}' is not an existing folder.")

    if catalog is None:
        catalog = fetch_cellxgene_catalog()

    dataset = next((d for d in catalog if d["dataset_id"] == dataset_id), None)
    if dataset is None:
        raise ValueError(f"Dataset '{dataset_id}' not found on CELLxGENE Discover.")

    save_path = download_file(dataset["url"], save_dir / f"{dataset_id}.h5ad")

    ad_path = prepare_cellxgene_adata(
        save_path,
        tissues=tissues,
        diseases=diseases,
        gene_id=gene_id,
        protein_coding_only=protein_coding_only,
    )
    write_cellxgene_citation(dataset, ad_path)

    return ad_path

The API is grouped in modules: