Documentation for Dataset

scdataloader.data.Dataset dataclass

Bases: Dataset

PyTorch Dataset for loading single-cell data from a LaminDB Collection.

This class wraps LaminDB's MappedCollection to provide additional features: - Management of hierarchical ontology labels (cell type, tissue, disease, etc.) - Automatic encoding of categorical labels to integers - Multi-species gene handling with unified gene indexing - Optional metacell aggregation and KNN neighbor retrieval

The dataset lazily loads data from storage, making it memory-efficient for large collections spanning multiple files.

Parameters:
  • lamin_dataset (Collection) –

    LaminDB Collection containing the artifacts to load.

  • genedf (DataFrame, default: None ) –

    DataFrame with gene information, indexed by gene ID with an 'organism' column. If None, automatically loaded based on organisms in the dataset. Defaults to None.

  • clss_to_predict (List[str], default: list() ) –

    Observation columns to encode as prediction targets. These will be integer-encoded in the output. Defaults to [].

  • hierarchical_clss (List[str], default: list() ) –

    Observation columns with hierarchical ontology structure. These will have their ancestry relationships computed using Bionty. Supported columns: - "cell_type_ontology_term_id" - "tissue_ontology_term_id" - "disease_ontology_term_id" - "development_stage_ontology_term_id" - "assay_ontology_term_id" - "self_reported_ethnicity_ontology_term_id" Defaults to [].

  • join_vars (str, default: None ) –

    How to join variables across artifacts. "inner" for intersection, "outer" for union, None for no joining. Defaults to None.

  • metacell_mode (float, default: 0.0 ) –

    Probability of returning aggregated metacell expression instead of single-cell. Defaults to 0.0.

  • get_knn_cells (bool, default: False ) –

    Whether to include k-nearest neighbor cell expression in the output. Requires precomputed neighbors in the data. Defaults to False.

  • store_location (str, default: None ) –

    Directory path to cache computed indices. Defaults to None.

  • force_recompute_indices (bool, default: False ) –

    Force recomputation of cached data. Defaults to False.

Attributes:
  • mapped_dataset (MappedCollection) –

    Underlying mapped collection for data access.

  • genedf (DataFrame) –

    Gene information DataFrame.

  • organisms (List[str]) –

    List of organism ontology term IDs in the dataset.

  • class_topred (dict[str, set]) –

    Mapping from class name to set of valid labels.

  • labels_groupings (dict[str, dict]) –

    Hierarchical groupings for ontology classes.

  • encoder (dict[str, dict]) –

    Label encoders mapping strings to integers.

Raises:
  • ValueError

    If genedf is None and "organism_ontology_term_id" is not in clss_to_predict.

Example

collection = ln.Collection.filter(key="my_collection").first() dataset = Dataset( ... lamin_dataset=collection, ... clss_to_predict=["organism_ontology_term_id", "cell_type_ontology_term_id"], ... hierarchical_clss=["cell_type_ontology_term_id"], ... ) sample = dataset[0] # Returns dict with "X" and encoded labels

Methods:

Name Description
define_hierarchies

Define hierarchical label groupings from ontology relationships.

get_label_cats

Get combined categorical codes for one or more label columns.

get_unseen_mapped_dataset_elements

Get genes marked as unseen for a specific sample.

define_hierarchies

Define hierarchical label groupings from ontology relationships.

Uses Bionty to retrieve parent-child relationships for ontology terms, then builds groupings mapping parent terms to their descendants. Updates encoders to include parent terms and reorders labels so that leaf terms (directly predictable) come first.

Parameters:
  • clsses (List[str]) –

    List of ontology column names to process.

Raises:
  • ValueError

    If a class name is not in the supported ontology types.

Note

Modifies self.labels_groupings, self.class_topred, and self.mapped_dataset.encoders in place.

Source code in scdataloader/data.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
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
371
372
373
374
375
376
377
378
def define_hierarchies(self, clsses: List[str]):
    """
    Define hierarchical label groupings from ontology relationships.

    Uses Bionty to retrieve parent-child relationships for ontology terms,
    then builds groupings mapping parent terms to their descendants.
    Updates encoders to include parent terms and reorders labels so that
    leaf terms (directly predictable) come first.

    Args:
        clsses (List[str]): List of ontology column names to process.

    Raises:
        ValueError: If a class name is not in the supported ontology types.

    Note:
        Modifies self.labels_groupings, self.class_topred, and
        self.mapped_dataset.encoders in place.
    """
    # TODO: use all possible hierarchies instead of just the ones for which we have a sample annotated with
    self.labels_groupings = {}
    self.class_topred = {}
    for clss in clsses:
        if clss not in [
            "cell_type_ontology_term_id",
            "tissue_ontology_term_id",
            "disease_ontology_term_id",
            "development_stage_ontology_term_id",
            "simplified_dev_stage",
            "age_group",
            "assay_ontology_term_id",
            "self_reported_ethnicity_ontology_term_id",
        ]:
            raise ValueError(
                "class {} not in accepted classes, for now only supported from bionty sources".format(
                    clss
                )
            )
        elif clss == "cell_type_ontology_term_id":
            parentdf = (
                bt.CellType.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )
        elif clss == "tissue_ontology_term_id":
            parentdf = (
                bt.Tissue.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )
        elif clss == "disease_ontology_term_id":
            parentdf = (
                bt.Disease.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )
        elif clss in [
            "development_stage_ontology_term_id",
            "simplified_dev_stage",
            "age_group",
        ]:
            parentdf = (
                bt.DevelopmentalStage.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )
        elif clss == "assay_ontology_term_id":
            parentdf = (
                bt.ExperimentalFactor.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )
        elif clss == "self_reported_ethnicity_ontology_term_id":
            parentdf = (
                bt.Ethnicity.filter()
                .df(include=["parents__ontology_id", "ontology_id"])
                .set_index("ontology_id")
            )

        else:
            raise ValueError(
                "class {} not in accepted classes, for now only supported from bionty sources".format(
                    clss
                )
            )
        cats = set(self.mapped_dataset.encoders[clss].keys())
        groupings, _, leaf_labels = get_ancestry_mapping(cats, parentdf)
        groupings.pop(None, None)
        for i, j in groupings.items():
            if len(j) == 0:
                # that should not happen
                import pdb

                pdb.set_trace()
                groupings.pop(i)

        self.labels_groupings[clss] = groupings
        if clss in self.clss_to_predict:
            # if we have added new clss, we need to update the encoder with them too.
            mlength = len(self.mapped_dataset.encoders[clss])

            mlength -= (
                1
                if self.mapped_dataset.unknown_label
                in self.mapped_dataset.encoders[clss].keys()
                else 0
            )

            for i, v in enumerate(
                set(groupings.keys())
                - set(self.mapped_dataset.encoders[clss].keys())
            ):
                self.mapped_dataset.encoders[clss].update({v: mlength + i})

            # we need to change the ordering so that the things that can't be predicted appear afterward
            self.class_topred[clss] = leaf_labels
            c = 0
            update = {}
            mlength = len(leaf_labels)
            mlength -= (
                1
                if self.mapped_dataset.unknown_label
                in self.mapped_dataset.encoders[clss].keys()
                else 0
            )
            for k, v in self.mapped_dataset.encoders[clss].items():
                if k in self.labels_groupings[clss].keys():
                    update.update({k: mlength + c})
                    c += 1
                elif k == self.mapped_dataset.unknown_label:
                    update.update({k: v})
                    self.class_topred[clss] -= set([k])
                else:
                    update.update({k: v - c})
            self.mapped_dataset.encoders[clss] = update

get_label_cats

Get combined categorical codes for one or more label columns.

Retrieves labels from the mapped dataset and combines them into a single categorical encoding. Useful for creating compound class labels for stratified sampling.

Parameters:
  • obs_keys (str | List[str]) –

    Column name(s) to retrieve and combine.

Returns:
  • ndarray

    np.ndarray: Integer codes representing the (combined) categories. Shape: (n_samples,).

Source code in scdataloader/data.py
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
def get_label_cats(
    self,
    obs_keys: Union[str, List[str]],
) -> np.ndarray:
    """
    Get combined categorical codes for one or more label columns.

    Retrieves labels from the mapped dataset and combines them into a single
    categorical encoding. Useful for creating compound class labels for
    stratified sampling.

    Args:
        obs_keys (str | List[str]): Column name(s) to retrieve and combine.

    Returns:
        np.ndarray: Integer codes representing the (combined) categories.
            Shape: (n_samples,).
    """
    if isinstance(obs_keys, str):
        obs_keys = [obs_keys]
    labels = None
    for label_key in obs_keys:
        labels_to_str = self.mapped_dataset.get_merged_labels(label_key)
        if labels is None:
            labels = labels_to_str
        else:
            labels = concat_categorical_codes([labels, labels_to_str])
    return np.array(labels.codes)

get_unseen_mapped_dataset_elements

Get genes marked as unseen for a specific sample.

Retrieves the list of genes that were not observed (expression = 0 or marked as unseen) for the sample at the given index.

Parameters:
  • idx (int) –

    Sample index in the dataset.

Returns:
  • list[str]

    List[str]: List of unseen gene identifiers.

Source code in scdataloader/data.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def get_unseen_mapped_dataset_elements(self, idx: int) -> list[str]:
    """
    Get genes marked as unseen for a specific sample.

    Retrieves the list of genes that were not observed (expression = 0 or
    marked as unseen) for the sample at the given index.

    Args:
        idx (int): Sample index in the dataset.

    Returns:
        List[str]: List of unseen gene identifiers.
    """
    return [str(i)[2:-1] for i in self.mapped_dataset.uns(idx, "unseen_genes")]

scdataloader.data.SimpleAnnDataset

Bases: Dataset

Simple PyTorch Dataset wrapper for a single AnnData object.

Provides a lightweight interface for using AnnData with PyTorch DataLoaders, compatible with the scDataLoader collator. Useful for inference on new data that isn't stored in LaminDB.

Parameters:
  • adata (AnnData) –

    AnnData object containing expression data.

  • obs_to_output (List[str], default: [] ) –

    Observation columns to include in output dictionaries. Defaults to [].

  • layer (str, default: None ) –

    Layer name to use for expression values. If None, uses adata.X. Defaults to None.

  • get_knn_cells (bool, default: False ) –

    Whether to include k-nearest neighbor expression data. Requires precomputed neighbors in adata.obsp. Defaults to False.

  • encoder (dict[str, dict], default: None ) –

    Dictionary mapping observation column names to encoding dictionaries (str -> int). Defaults to None.

Attributes:
  • adataX (ndarray) –

    Dense expression matrix.

  • encoder (dict) –

    Label encoders.

  • obs_to_output (DataFrame) –

    Observation metadata to include.

  • distances (scipy.sparse matrix) –

    KNN distance matrix (if get_knn_cells=True).

Raises:
  • ValueError

    If get_knn_cells=True but "connectivities" not in adata.obsp.

Example

dataset = SimpleAnnDataset( ... adata=my_adata, ... obs_to_output=["cell_type", "organism_ontology_term_id"], ... encoder={"organism_ontology_term_id": {"NCBITaxon:9606": 0}}, ... ) loader = DataLoader(dataset, batch_size=32, collate_fn=collator)

Source code in scdataloader/data.py
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 __init__(
    self,
    adata: AnnData,
    obs_to_output: Optional[List[str]] = [],
    layer: Optional[str] = None,
    get_knn_cells: bool = False,
    encoder: Optional[dict[str, dict]] = None,
):
    """
    Simple PyTorch Dataset wrapper for a single AnnData object.

    Provides a lightweight interface for using AnnData with PyTorch DataLoaders,
    compatible with the scDataLoader collator. Useful for inference on new data
    that isn't stored in LaminDB.

    Args:
        adata (AnnData): AnnData object containing expression data.
        obs_to_output (List[str], optional): Observation columns to include in
            output dictionaries. Defaults to [].
        layer (str, optional): Layer name to use for expression values. If None,
            uses adata.X. Defaults to None.
        get_knn_cells (bool, optional): Whether to include k-nearest neighbor
            expression data. Requires precomputed neighbors in adata.obsp.
            Defaults to False.
        encoder (dict[str, dict], optional): Dictionary mapping observation column
            names to encoding dictionaries (str -> int). Defaults to None.

    Attributes:
        adataX (np.ndarray): Dense expression matrix.
        encoder (dict): Label encoders.
        obs_to_output (pd.DataFrame): Observation metadata to include.
        distances (scipy.sparse matrix): KNN distance matrix (if get_knn_cells=True).

    Raises:
        ValueError: If get_knn_cells=True but "connectivities" not in adata.obsp.

    Example:
        >>> dataset = SimpleAnnDataset(
        ...     adata=my_adata,
        ...     obs_to_output=["cell_type", "organism_ontology_term_id"],
        ...     encoder={"organism_ontology_term_id": {"NCBITaxon:9606": 0}},
        ... )
        >>> loader = DataLoader(dataset, batch_size=32, collate_fn=collator)
    """
    self.adataX = adata.layers[layer] if layer is not None else adata.X
    self.adataX = self.adataX.toarray() if issparse(self.adataX) else self.adataX
    self.encoder = encoder if encoder is not None else {}

    self.obs_to_output = adata.obs[obs_to_output]
    self.get_knn_cells = get_knn_cells
    if get_knn_cells and "connectivities" not in adata.obsp:
        raise ValueError("neighbors key not found in adata.obsm")
    if get_knn_cells:
        self.distances = adata.obsp["distances"]