Skip to content

Utilities

This module contains certain utility functions, that can be useful, but didn't fit into any other module.

CELLxGENE download

hide_deconv.download.fetch_cellxgene_catalog()

Fetch the list of all public datasets from CELLxGENE Discover.

The catalog is requested from the CELLxGENE Discover API on every call. Only datasets providing an H5AD file are returned.

Returns:

Type Description
list[dict]

List of datasets. Each dataset is a dictionary with the keys "dataset_id", "title", "collection_name", "organism", "tissue", "disease", "assay", "suspension_type" (lists of labels), "cell_count", "published_at", "url" and "filesize". Additionally the citation information "collection_id", "collection_doi", "collection_doi_label", "citation" and "explorer_url" is stored.

Raises:

Type Description
ConnectionError

If the CELLxGENE Discover API cannot be reached.

Timeout

If the CELLxGENE Discover API does not respond in time.

HTTPError

If the CELLxGENE Discover API returns an error status.

Source code in src/hide_deconv/download/download_file.py
 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
def fetch_cellxgene_catalog() -> list[dict]:
    """
    Fetch the list of all public datasets from CELLxGENE Discover.

    The catalog is requested from the CELLxGENE Discover API on every call.
    Only datasets providing an H5AD file are returned.

    Returns
    -------
    list[dict]
        List of datasets. Each dataset is a dictionary with the keys
        "dataset_id", "title", "collection_name", "organism", "tissue",
        "disease", "assay", "suspension_type" (lists of labels), "cell_count",
        "published_at", "url" and "filesize". Additionally the citation information
        "collection_id", "collection_doi", "collection_doi_label", "citation" and
        "explorer_url" is stored.

    Raises
    ------
    requests.ConnectionError
        If the CELLxGENE Discover API cannot be reached.
    requests.Timeout
        If the CELLxGENE Discover API does not respond in time.
    requests.HTTPError
        If the CELLxGENE Discover API returns an error status.
    """

    response = requests.get(CELLXGENE_DATASETS_URL, timeout=CELLXGENE_API_TIMEOUT)
    response.raise_for_status()

    def labels(entries: list[dict] | None) -> list[str]:
        return list(dict.fromkeys(e["label"] for e in entries or [] if "label" in e))

    catalog = []
    for dataset in response.json():
        if dataset.get("tombstone"):
            continue

        asset = get_h5ad_asset(dataset)
        if asset is None:
            continue

        url, filesize = asset
        catalog.append(
            {
                "dataset_id": dataset["dataset_id"],
                "title": dataset.get("title", ""),
                "collection_name": dataset.get("collection_name", ""),
                "organism": labels(dataset.get("organism")),
                "tissue": labels(dataset.get("tissue")),
                "disease": labels(dataset.get("disease")),
                "assay": labels(dataset.get("assay")),
                "suspension_type": list(dataset.get("suspension_type") or []),
                "cell_count": int(dataset.get("cell_count") or 0),
                "published_at": (dataset.get("published_at") or "")[:10],
                "url": url,
                "filesize": filesize,
                "collection_id": dataset.get("collection_id") or "",
                "collection_doi": dataset.get("collection_doi") or "",
                "collection_doi_label": dataset.get("collection_doi_label") or "",
                "citation": dataset.get("citation") or "",
                "explorer_url": dataset.get("explorer_url") or "",
            }
        )

    return catalog

hide_deconv.download.filter_datasets(datasets, organism=None, tissues=None, diseases=None)

Filter datasets by organism, tissues and diseases.

A dataset matches, if it contains the organism and at least one of the given tissues and at least one of the given diseases. Note that tissues and diseases are annotated per dataset, a matching dataset can therefore also contain cells of other tissues and diseases.

Parameters:

Name Type Description Default
datasets list[dict]

Datasets as returned by fetch_cellxgene_catalog.

required
organism str | None = None

Organism label, e.g. "Homo sapiens". None matches all organisms.

None
tissues list[str] | None = None

Tissue labels. None or an empty list matches all tissues.

None
diseases list[str] | None = None

Disease labels. None or an empty list matches all diseases.

None

Returns:

Type Description
list[dict]

Datasets matching all given criteria.

Source code in src/hide_deconv/download/download_file.py
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
def filter_datasets(
    datasets: list[dict],
    organism: str | None = None,
    tissues: list[str] | None = None,
    diseases: list[str] | None = None,
) -> list[dict]:
    """
    Filter datasets by organism, tissues and diseases.

    A dataset matches, if it contains the organism and at least one of the
    given tissues and at least one of the given diseases. Note that tissues and
    diseases are annotated per dataset, a matching dataset can therefore also
    contain cells of other tissues and diseases.

    Parameters
    ----------
    datasets : list[dict]
        Datasets as returned by fetch_cellxgene_catalog.
    organism : str | None = None
        Organism label, e.g. "Homo sapiens". None matches all organisms.
    tissues : list[str] | None = None
        Tissue labels. None or an empty list matches all tissues.
    diseases : list[str] | None = None
        Disease labels. None or an empty list matches all diseases.

    Returns
    -------
    list[dict]
        Datasets matching all given criteria.
    """

    def matches(values: list[str], selection: list[str] | None) -> bool:
        return not selection or any(value in selection for value in values)

    return [
        dataset
        for dataset in datasets
        if (organism is None or organism in dataset["organism"])
        and matches(dataset["tissue"], tissues)
        and matches(dataset["disease"], diseases)
    ]

hide_deconv.download.prepare_cellxgene_adata(path, tissues=None, diseases=None, gene_id='symbol', protein_coding_only=True)

Prepare a downloaded CELLxGENE AnnData file for HIDE-Deconv.

Optionally subsets the cells to the given tissues and diseases. If raw counts are stored in adata.raw, these are moved to adata.X and adata.raw is removed. Spike-ins are always removed and optionally only protein coding genes are kept.

CELLxGENE stores Ensembl IDs as var_names and gene symbols in adata.var["feature_name"]. If gene symbols are selected, these are used as var_names and the Ensembl IDs are stored in adata.var["feature_id"]. Genes with the same gene symbol are summed up. If Ensembl IDs are selected, the index of adata.var is named "feature_id". The file is overwritten with the prepared AnnData object.

Parameters:

Name Type Description Default
path str | Path

Path of the CELLxGENE AnnData file.

required
tissues list[str] | None = None

Keep only cells with these labels in obs["tissue"]. None keeps all tissues.

None
diseases list[str] | None = None

Keep only cells with these labels in obs["disease"]. None keeps all diseases.

None
gene_id str = "symbol"

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

'symbol'
protein_coding_only bool = True

Keep only genes with var["feature_type"] == "protein_coding".

True

Returns:

Type Description
Path

Path of the prepared AnnData file.

Raises:

Type Description
ValueError

If a required obs column is missing, no cells match the selection or gene_id is invalid.

Source code in src/hide_deconv/download/download_file.py
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
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
332
333
334
335
336
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
def prepare_cellxgene_adata(
    path: str | Path,
    tissues: list[str] | None = None,
    diseases: list[str] | None = None,
    gene_id: str = "symbol",
    protein_coding_only: bool = True,
) -> Path:
    """
    Prepare a downloaded CELLxGENE AnnData file for HIDE-Deconv.

    Optionally subsets the cells to the given tissues and diseases. If raw counts
    are stored in adata.raw, these are moved to adata.X and adata.raw is removed.
    Spike-ins are always removed and optionally only protein coding genes are kept.

    CELLxGENE stores Ensembl IDs as var_names and gene symbols in adata.var["feature_name"].
    If gene symbols are selected, these are used as var_names and the Ensembl IDs are stored
    in adata.var["feature_id"]. Genes with the same gene symbol are summed up. If Ensembl IDs
    are selected, the index of adata.var is named "feature_id".
    The file is overwritten with the prepared AnnData object.

    Parameters
    ----------
    path : str | Path
        Path of the CELLxGENE AnnData file.
    tissues : list[str] | None = None
        Keep only cells with these labels in obs["tissue"]. None keeps all tissues.
    diseases : list[str] | None = None
        Keep only cells with these labels in obs["disease"]. None keeps all diseases.
    gene_id : str = "symbol"
        Gene identifier used as var_names. Either "symbol" or "ensembl".
    protein_coding_only : bool = True
        Keep only genes with var["feature_type"] == "protein_coding".

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

    Raises
    ------
    ValueError
        If a required obs column is missing, no cells match the selection or gene_id is invalid.
    """

    if gene_id not in ("symbol", "ensembl"):
        raise ValueError(f"gene_id must be 'symbol' or 'ensembl', not '{gene_id}'.")

    path = Path(path)

    # Open in backed mode to avoid loading cells into memory that are removed afterwards
    backed = ad.read_h5ad(path, backed="r")
    try:
        mask = np.ones(backed.n_obs, dtype=bool)
        for col, selection in (("tissue", tissues), ("disease", diseases)):
            if not selection:
                continue
            if col not in backed.obs.columns:
                raise ValueError(f"Column '{col}' not found in adata.obs.")
            mask &= backed.obs[col].astype(str).isin(selection).to_numpy()

        if not mask.any():
            raise ValueError("No cells match the selected tissues and diseases.")

        var = backed.var
        var_mask = np.ones(backed.n_vars, dtype=bool)
        if "feature_biotype" in var.columns:
            var_mask &= (var["feature_biotype"].astype(str) != "spike-in").to_numpy()

        if protein_coding_only:
            if "feature_type" in var.columns:
                var_mask &= (
                    var["feature_type"].astype(str) == "protein_coding"
                ).to_numpy()
            else:
                warnings.warn(
                    "Column 'feature_type' not found in adata.var. Genes are not restricted to protein coding genes."
                )

        if mask.all() and var_mask.all():
            adata = backed.to_memory()
        else:
            adata = backed[mask, var_mask].to_memory()
    finally:
        backed.file.close()

    if adata.raw is not None:
        adata.X = adata.raw[:, adata.var_names].X
        del adata.raw

    if gene_id == "symbol":
        adata = switch_adata_var_names(adata, "feature_name", "feature_id")
    elif "feature_id" not in adata.var.columns:
        # Name the index, so that switching the annotation later suggests a meaningful column name
        adata.var.index.name = "feature_id"

    tmp_path = path.with_name(path.stem + ".tmp.h5ad")
    try:
        adata.write_h5ad(tmp_path)
        tmp_path.replace(path)
    except BaseException:
        tmp_path.unlink(missing_ok=True)
        raise

    return path

hide_deconv.download.write_cellxgene_citation(dataset, ad_path)

Write the citation information of a CELLxGENE dataset to a text file.

The file is stored next to the AnnData file as "_citation.txt". It contains the meta information of the dataset, the citation provided by CELLxGENE Discover and the citation of CZ CELLxGENE Discover itself.

Parameters:

Name Type Description Default
dataset dict

Dataset entry as returned by fetch_cellxgene_catalog.

required
ad_path str | Path

Path of the downloaded AnnData file.

required

Returns:

Type Description
Path

Path of the citation file.

Source code in src/hide_deconv/download/download_file.py
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
428
429
430
431
432
433
434
435
436
def write_cellxgene_citation(dataset: dict, ad_path: str | Path) -> Path:
    """
    Write the citation information of a CELLxGENE dataset to a text file.

    The file is stored next to the AnnData file as "<AnnData file name>_citation.txt".
    It contains the meta information of the dataset, the citation provided by
    CELLxGENE Discover and the citation of CZ CELLxGENE Discover itself.

    Parameters
    ----------
    dataset : dict
        Dataset entry as returned by fetch_cellxgene_catalog.
    ad_path : str | Path
        Path of the downloaded AnnData file.

    Returns
    -------
    Path
        Path of the citation file.
    """

    ad_path = Path(ad_path)
    citation_path = ad_path.with_name(f"{ad_path.stem}_citation.txt")

    doi = dataset.get("collection_doi")
    collection_id = dataset.get("collection_id")

    info = [
        ("Dataset", dataset.get("title")),
        ("Dataset ID", dataset.get("dataset_id")),
        ("Collection", dataset.get("collection_name")),
        ("Publication", dataset.get("collection_doi_label")),
        ("DOI", f"https://doi.org/{doi}" if doi else None),
        (
            "Collection URL",
            f"{CELLXGENE_COLLECTIONS_URL}/{collection_id}" if collection_id else None,
        ),
        ("Explorer URL", dataset.get("explorer_url")),
        ("Published", dataset.get("published_at")),
        ("Downloaded", date.today().isoformat()),
    ]

    # Skip entries without information
    lines = ["Citation information of the CELLxGENE Discover dataset", ""]
    lines += [f"{label + ':':<16}{value}" for label, value in info if value]

    if dataset.get("citation"):
        lines += ["", "Citation provided by CELLxGENE Discover:", dataset["citation"]]

    if not doi:
        lines += ["", "No publication DOI is available for this dataset."]

    lines += [
        "",
        "Please cite the original publication of the dataset and CZ CELLxGENE Discover:",
        CELLXGENE_PLATFORM_CITATION,
    ]

    citation_path.write_text("\n".join(lines) + "\n", encoding="utf-8")

    return citation_path

AnnData utilities

hide_deconv.utils.subset_adata_obs(adata, obs_col, values)

Subset a AnnData dataframe, such that a specified observation column only contains certain values.

Parameters:

Name Type Description Default
adata AnnData

AnnData dataframe, that should be subsetted.

required
obs_col str

Name of observation that should be subsetted.

required
values str

List of values, that should be kept in observation.

required

Returns:

Type Description
AnnData

Subsetted AnnData dataframe.

Source code in src/hide_deconv/utils/anndata_utils.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def subset_adata_obs(adata: ad.AnnData, obs_col: str, values: list) -> ad.AnnData:
    """
    Subset a AnnData dataframe, such that a specified observation column only contains certain values.

    Parameters
    ----------
    adata : ad.AnnData
        AnnData dataframe, that should be subsetted.
    obs_col : str
        Name of observation that should be subsetted.
    values : str
        List of values, that should be kept in observation.

    Returns
    -------
    ad.AnnData
        Subsetted AnnData dataframe.
    """

    adata = adata[adata.obs[obs_col].isin(values)]

    return adata

hide_deconv.utils.create_annotation_template(adata, obs_col, example_col_name='new_cell_layer_example')

Create a template for adding higher annotation layers.

Parameters:

Name Type Description Default
adata AnnData

AnnData dataframe.

required
obs_col str

Observation column with the sub cell types layer.

required
example_col_name str

Name of the example column that is initialized with the same values.

"new_cell_layer_example"

Returns:

Type Description
DataFrame

Template dataframe with the selected annotation layer and an example column.

Source code in src/hide_deconv/utils/anndata_utils.py
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
def create_annotation_template(
    adata: ad.AnnData,
    obs_col: str,
    example_col_name: str = "new_cell_layer_example",
) -> pd.DataFrame:
    """
    Create a template for adding higher annotation layers.

    Parameters
    ----------
    adata : ad.AnnData
        AnnData dataframe.
    obs_col : str
        Observation column with the sub cell types layer.
    example_col_name : str, default="new_cell_layer_example"
        Name of the example column that is initialized with the same values.

    Returns
    -------
    pd.DataFrame
        Template dataframe with the selected annotation layer and an example column.
    """

    template = pd.DataFrame(adata.obs[obs_col].drop_duplicates()).copy()
    template[example_col_name] = template[obs_col]

    return template

hide_deconv.utils.add_annotation_columns_from_template(adata, annotation_df, sub_ct_col)

Add higher annotation layers from an edited template dataframe.

Parameters:

Name Type Description Default
adata AnnData

AnnData dataframe that should receive new observation columns.

required
annotation_df DataFrame

Edited annotation template.

required
sub_ct_col str

Observation column that matches the original cell type layer.

required

Returns:

Type Description
tuple[AnnData, list[str]]

Updated AnnData object and a list with the newly added observation columns.

Source code in src/hide_deconv/utils/anndata_utils.py
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 add_annotation_columns_from_template(
    adata: ad.AnnData,
    annotation_df: pd.DataFrame,
    sub_ct_col: str,
) -> tuple[ad.AnnData, list[str]]:
    """
    Add higher annotation layers from an edited template dataframe.

    Parameters
    ----------
    adata : ad.AnnData
        AnnData dataframe that should receive new observation columns.
    annotation_df : pd.DataFrame
        Edited annotation template.
    sub_ct_col : str
        Observation column that matches the original cell type layer.

    Returns
    -------
    tuple[ad.AnnData, list[str]]
        Updated AnnData object and a list with the newly added observation columns.
    """

    if sub_ct_col not in annotation_df.columns:
        raise ValueError(
            f"Cell type column '{sub_ct_col}' is missing from the annotation template."
        )

    template_sub_ct = annotation_df[sub_ct_col].astype(str)
    if template_sub_ct.duplicated().any():
        raise ValueError(
            "The cell type column in the annotation template must contain each cell type only once."
        )

    added_columns = [col for col in annotation_df.columns if col != sub_ct_col]

    updated_adata = adata.copy()
    anchor_values = updated_adata.obs[sub_ct_col].astype(str)
    template_index = annotation_df.set_index(sub_ct_col)

    for column in added_columns:
        mapping = template_index[column].to_dict()
        updated_adata.obs[column] = anchor_values.map(mapping)

    return updated_adata, added_columns

hide_deconv.utils.switch_adata_var_names(adata, var_col, old_var_col)

Switch the gene annotation used as adata.var_names, e.g. from Ensembl IDs to gene symbols.

The current var_names are stored in adata.var[old_var_col], the column var_col is used as new var_names. Genes that share the same new identifier are combined by summing their expression (as done for duplicate gene symbols in bulk data). For combined genes, adata.var[old_var_col] contains all previous identifiers separated by ";" and all other columns of adata.var contain the value of the first gene.

Parameters:

Name Type Description Default
adata AnnData

AnnData dataframe, whose var_names should be switched.

required
var_col str

Column of adata.var, that should be used as new var_names.

required
old_var_col str

Name of the column in adata.var, where the current var_names are stored.

required

Returns:

Type Description
AnnData

AnnData dataframe with switched var_names.

Raises:

Type Description
ValueError

If var_col is not a column of adata.var or old_var_col is already used by another column.

Source code in src/hide_deconv/utils/anndata_utils.py
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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
def switch_adata_var_names(
    adata: ad.AnnData, var_col: str, old_var_col: str
) -> ad.AnnData:
    """
    Switch the gene annotation used as adata.var_names, e.g. from Ensembl IDs to gene symbols.

    The current var_names are stored in adata.var[old_var_col], the column var_col is
    used as new var_names. Genes that share the same new identifier are combined by summing
    their expression (as done for duplicate gene symbols in bulk data). For combined genes,
    adata.var[old_var_col] contains all previous identifiers separated by ";" and all other
    columns of adata.var contain the value of the first gene.

    Parameters
    ----------
    adata : ad.AnnData
        AnnData dataframe, whose var_names should be switched.
    var_col : str
        Column of adata.var, that should be used as new var_names.
    old_var_col : str
        Name of the column in adata.var, where the current var_names are stored.

    Returns
    -------
    ad.AnnData
        AnnData dataframe with switched var_names.

    Raises
    ------
    ValueError
        If var_col is not a column of adata.var or old_var_col is already used by another column.
    """

    new_names = get_var_names_from_column(adata, var_col)

    if old_var_col == var_col or old_var_col in adata.var.columns:
        raise ValueError(f"Column '{old_var_col}' already exists in adata.var.")

    old_names = pd.Series(adata.var_names.astype(str), index=adata.var_names)
    codes, unique_names = pd.factorize(new_names)

    # No genes have to be combined, exchange only annotation
    if len(unique_names) == adata.n_vars:
        switched = adata.copy()
        switched.var[old_var_col] = old_names.to_numpy()
        switched.var = switched.var.drop(columns=var_col)
        switched.var_names = new_names
        return switched

    indicator = sp.csr_matrix(
        (np.ones(adata.n_vars), (np.arange(adata.n_vars), codes)),
        shape=(adata.n_vars, len(unique_names)),
    )

    def combine(matrix):
        combined = matrix @ indicator.astype(matrix.dtype)
        return sp.csr_matrix(combined) if sp.issparse(matrix) else np.asarray(combined)

    # Keep annotation of the first gene of each new index
    _, first_idx = np.unique(codes, return_index=True)
    var = adata.var.iloc[first_idx].drop(columns=var_col).copy()
    var[old_var_col] = old_names.groupby(codes).agg(";".join).to_numpy()
    var.index = pd.Index(unique_names, name=var_col)

    switched = ad.AnnData(
        X=combine(adata.X),
        obs=adata.obs.copy(),
        var=var,
        uns=adata.uns.copy(),
        obsm=adata.obsm.copy(),
        obsp=adata.obsp.copy(),
        layers={
            key: combine(layer)
            for key, layer in adata.layers.items()
            if key is not None  # Fix for newer AnnData version
        },
    )

    if adata.raw is not None:
        switched.raw = adata.raw.to_adata()

    return switched

hide_deconv.utils.get_var_names_from_column(adata, var_col)

Get the gene identifiers that result from using a column of adata.var as var_names.

Missing or empty values are replaced by the current var_names.

Parameters:

Name Type Description Default
adata AnnData

AnnData dataframe.

required
var_col str

Column of adata.var, that should be used as var_names.

required

Returns:

Type Description
Index

New gene identifiers in the order of adata.var_names. Can contain duplicates.

Raises:

Type Description
ValueError

If var_col is not a column of adata.var.

Source code in src/hide_deconv/utils/anndata_utils.py
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
def get_var_names_from_column(adata: ad.AnnData, var_col: str) -> pd.Index:
    """
    Get the gene identifiers that result from using a column of adata.var as var_names.

    Missing or empty values are replaced by the current var_names.

    Parameters
    ----------
    adata : ad.AnnData
        AnnData dataframe.
    var_col : str
        Column of adata.var, that should be used as var_names.

    Returns
    -------
    pd.Index
        New gene identifiers in the order of adata.var_names. Can contain duplicates.

    Raises
    ------
    ValueError
        If var_col is not a column of adata.var.
    """

    if var_col not in adata.var.columns:
        raise ValueError(f"Column '{var_col}' not found in adata.var.")

    values = adata.var[var_col].astype(object)
    missing = values.isna() | (values.astype(str).str.strip() == "")

    # Keep the current identifier for genes without a value in var_col
    new_names = values.where(~missing, pd.Series(adata.var_names, index=values.index))

    return pd.Index(new_names.astype(str), name=var_col)

MTX conversion

hide_deconv.utils.mtx_to_adata(mtx_path, barcodes_path, genes_path)

Read a mtx file and convert it to a anndata

Parameters:

Name Type Description Default
mtx_path str

Path to mtx file

required
barcodes_path str

Path to mtx barcodes

required
genes_path str

Path to mtx genes

required

Returns:

Type Description
AnnData

AnnData object containing the converted mtx file

Source code in src/hide_deconv/utils/mtx_utils.py
 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
def mtx_to_adata(mtx_path: str, barcodes_path: str, genes_path: str) -> ad.AnnData:
    """
    Read a mtx file and convert it to a anndata

    Parameters
    -----------
    mtx_path : str
        Path to mtx file
    barcodes_path : str
        Path to mtx barcodes
    genes_path : str
        Path to mtx genes

    Returns
    --------
    ad.AnnData
        AnnData object containing the converted mtx file

    """

    # Read barcodes
    if Path(barcodes_path).suffix == ".tsv":
        barcodes = pd.read_csv(barcodes_path, header=None, sep="\t")
    elif Path(barcodes_path).suffix == ".csv":
        barcodes = pd.read_csv(barcodes_path, header=None)
    else:
        raise ValueError("Barcode file must either be a csv or tsv table.")

    # Read genes
    if Path(genes_path).suffix == ".tsv":
        genes = pd.read_csv(genes_path, header=None, sep="\t")
    elif Path(genes_path).suffix == ".csv":
        genes = pd.read_csv(genes_path, header=None)
    else:
        raise ValueError("Features file must either be a csv or tsv table.")

    # Read matrix
    data_mtx = mmread(mtx_path).tocsr()
    X = data_mtx.T

    obs = pd.DataFrame(index=barcodes.iloc[:, 0].astype(str))
    obs.index.name = "barcode"

    var = pd.DataFrame(index=genes.iloc[:, 0].astype(str))
    var.index.name = "gene"

    adata = ad.AnnData(
        X=X,
        obs=obs,
        var=var,
    )

    return adata

hide_deconv.utils.mtx_to_csv(mtx_path, barcodes_path, genes_path)

Read a mtx file and convert it to a pandas DataFrame

Parameters:

Name Type Description Default
mtx_path str

Path to mtx file

required
barcodes_path str

Path to mtx barcodes

required
genes_path str

Path to mtx genes

required

Returns:

Type Description
DataFrame

Dataframe containing the converted mtx file

Source code in src/hide_deconv/utils/mtx_utils.py
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
60
def mtx_to_csv(mtx_path: str, barcodes_path: str, genes_path: str) -> pd.DataFrame:
    """
    Read a mtx file and convert it to a pandas DataFrame

    Parameters
    -----------
    mtx_path : str
        Path to mtx file
    barcodes_path : str
        Path to mtx barcodes
    genes_path : str
        Path to mtx genes

    Returns
    --------
    pd.DataFrame
        Dataframe containing the converted mtx file

    """

    # Read barcodes, separate between tsv and csv table
    if Path(barcodes_path).suffix == ".tsv":
        barcodes = pd.read_csv(barcodes_path, header=None, sep="\t")
    elif Path(barcodes_path).suffix == ".csv":
        barcodes = pd.read_csv(barcodes_path, header=None)
    else:
        raise ValueError("Barcode file must either be a csv or tsv table.")

    # Read genes
    if Path(genes_path).suffix == ".tsv":
        genes = pd.read_csv(genes_path, header=None, sep="\t")
    elif Path(genes_path).suffix == ".csv":
        genes = pd.read_csv(genes_path, header=None)
    else:
        raise ValueError("Features file must either be a csv or tsv table.")

    # Read matrix
    data_mtx = mmread(mtx_path)
    data_df = pd.DataFrame.sparse.from_spmatrix(
        data_mtx
    )  # , index=genes.iloc[:,0], columns=barcodes.iloc[:,0])
    data_df = data_df.sparse.to_dense()

    data_df = data_df.set_index(genes.iloc[:, 0])
    data_df.columns = barcodes.iloc[:, 0]

    return data_df

Sample sheets and cohorts

hide_deconv.utils.filter_sample_sheet(sample_sheet, sample_id_col)

Filter a sample sheet, such that only non-NaN sample id's are kept.

Parameters:

Name Type Description Default
sample_sheet DataFrame

Sample sheet.

required
sample_id_col str

Name of column that holds the sample ids.

required

Returns:

Type Description
tuple[Series, DataFrame]

Valid Sample Ids, Sample Sheet only with non-NaN Sample Id Samples

Source code in src/hide_deconv/utils/sample_sheet_utils.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def filter_sample_sheet(
    sample_sheet: pd.DataFrame, sample_id_col: str
) -> tuple[pd.Series, pd.DataFrame]:
    """
    Filter a sample sheet, such that only non-NaN sample id's are kept.

    Parameters
    ----------
    sample_sheet : pd.DataFrame
        Sample sheet.
    sample_id_col : str
        Name of column that holds the sample ids.

    Returns
    -------
    tuple[pd.Series, pd.DataFrame]
        Valid Sample Ids, Sample Sheet only with non-NaN Sample Id Samples
    """

    ids = remove_nan_sample_ids(sample_sheet[sample_id_col])
    filtered_sample_sheet = sample_sheet[sample_sheet[sample_id_col].isin(ids.values)]

    return ids, filtered_sample_sheet

hide_deconv.utils.combine_categorical_cohorts(sample_sheet, cohort_col, new_col_name, n_groups)

Combines various categorical cohorts into new ones.

Source code in src/hide_deconv/utils/cohort_utils.py
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
def combine_categorical_cohorts(
    sample_sheet: pd.DataFrame, cohort_col: str, new_col_name: str, n_groups: int
) -> pd.DataFrame:
    """
    Combines various categorical cohorts into new ones.
    """

    cohort_values = [str(value) for value in sample_sheet[cohort_col].dropna().unique()]
    remaining_values = cohort_values.copy()
    combined_values = pd.Series(pd.NA, index=sample_sheet.index, dtype="object")
    cohort_series = sample_sheet[cohort_col].astype(str)
    valid_rows = sample_sheet[cohort_col].notna()

    for group_idx in range(n_groups):
        group_name = inquirer.text(
            message=f"Enter name for cohort group {group_idx + 1}:",
            mandatory=True,
        ).execute()

        selected_values = inquirer.checkbox(
            message=f"Select cohort values for '{group_name}':",
            choices=remaining_values,
            max_height=5,
            mandatory=True,
            mandatory_message="Please select at least one entry.",
        ).execute()

        selected_values = [str(value) for value in selected_values]
        if len(selected_values) == 0:
            raise ValueError("Please select at least one entry.")

        combined_values.loc[valid_rows & cohort_series.isin(selected_values)] = (
            group_name
        )
        remaining_values = [
            value for value in remaining_values if value not in selected_values
        ]

        if group_idx < n_groups - 1 and len(remaining_values) == 0:
            raise ValueError(
                "Not enough cohort values left to create the requested groups."
            )

    sample_sheet[new_col_name] = combined_values
    return sample_sheet

hide_deconv.utils.combine_numerical_cohorts(sample_sheet, cohort_col, new_col_name, method, threshold=None)

Combines numerical values in a high / low group split by either mean, median or greater equal

Source code in src/hide_deconv/utils/cohort_utils.py
 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
def combine_numerical_cohorts(
    sample_sheet: pd.DataFrame,
    cohort_col: str,
    new_col_name: str,
    method: str,
    threshold: float | None = None,
) -> pd.DataFrame:
    """
    Combines numerical values in a high / low group split by either mean, median or greater equal
    """

    values = pd.to_numeric(sample_sheet[cohort_col], errors="coerce")
    valid_rows = values.notna()

    if valid_rows.sum() < 2:
        raise ValueError("The selected column needs at least two numerical values.")

    if method == "mean":
        calc_threshold = float(values.loc[valid_rows].mean())
    elif method == "median":
        calc_threshold = float(values.loc[valid_rows].median())
    elif method == "greater equal":
        calc_threshold = float(threshold)
    else:
        raise NotImplementedError("Method not implemented")

    combined_values = pd.Series(pd.NA, index=sample_sheet.index, dtype="object")
    combined_values.loc[valid_rows & (values >= calc_threshold)] = "high"
    combined_values.loc[valid_rows & (values < calc_threshold)] = "low"

    sample_sheet[new_col_name] = combined_values

    return sample_sheet