Datasets:
Download loader.py from btraven/splatter-cube-pbmc3k: direct link, hf CLI and curl.
- Browser
- Download file 4.88 kB
-
https://huggingface.co/datasets/btraven/splatter-cube-pbmc3k/resolve/main/loader.py
- Command line
-
hf download hf://datasets/btraven/splatter-cube-pbmc3k/loader.py
-
curl -L -o loader.py https://huggingface.co/datasets/btraven/splatter-cube-pbmc3k/resolve/main/loader.py
4.88 kB
| """Loader for the Splatter cube dataset. | |
| Single file, no install: drop it next to your code, or | |
| from huggingface_hub import hf_hub_download | |
| exec(open(hf_hub_download("btraven/splatter-cube-pbmc3k", "loader.py", repo_type="dataset")).read()) | |
| Works against the Hub or a local copy of the dataset directory: | |
| catalog() # every simulation, as a DataFrame | |
| load(de_prob=0.02, de_fac_loc=1.3, n_groups=8, seed=42) # -> AnnData | |
| for ad in load_many(de_prob=0.01): ... # all seeds / cluster counts | |
| Requires pandas and anndata; huggingface_hub only when reading from the Hub. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| from functools import lru_cache | |
| REPO = "btraven/splatter-cube-pbmc3k" # substituted per cube by package_hf.R | |
| # The CSV keeps splatter's own parameter names, which contain dots and camel | |
| # case. Callers get python-friendly keywords instead. | |
| ALIASES = { | |
| "de_prob": "de.prob", | |
| "de_fac_loc": "de.facLoc", | |
| "bcv_common": "bcv.common", | |
| "dropout_mid": "dropout.mid", | |
| "dropout_type": "dropout.type", | |
| "lib_loc": "lib.loc", | |
| "n_groups": "nGroups", | |
| "point": "point", | |
| "seed": "seed", | |
| "sparsity": "sparsity", | |
| } | |
| def _fetch(relpath: str, source: str | None = None) -> str: | |
| """Local path for a file in the dataset, downloading from the Hub if needed.""" | |
| if source is not None: | |
| p = os.path.join(os.path.expanduser(source), relpath) | |
| if not os.path.exists(p): | |
| raise FileNotFoundError(f"{p} (is {source} a copy of the dataset?)") | |
| return p | |
| from huggingface_hub import hf_hub_download | |
| return hf_hub_download(REPO, relpath, repo_type="dataset") | |
| def catalog(source: str | None = None): | |
| """Every simulation: parameters, realised sparsity, clustering scores.""" | |
| import pandas as pd | |
| return pd.read_csv(_fetch("metrics.csv", source)) | |
| def _select(source=None, **query): | |
| import numpy as np | |
| df = catalog(source) | |
| for key, want in query.items(): | |
| if key not in ALIASES: | |
| raise TypeError( | |
| f"unknown parameter {key!r}; choose from {sorted(ALIASES)}") | |
| col = df[ALIASES[key]] | |
| # float levels are written to CSV at full precision, so compare | |
| # approximately rather than trusting 1.3 == 1.3000000000000003 | |
| hit = np.isclose(col, want) if np.issubdtype(col.dtype, np.floating) \ | |
| else col == want | |
| if not hit.any(): | |
| raise ValueError( | |
| f"no simulation with {key}={want!r}; " | |
| f"available: {sorted(col.unique().tolist())}") | |
| df = df[hit] | |
| return df | |
| def _read(row, source): | |
| import anndata | |
| ad = anndata.read_h5ad(_fetch(row["file"], source)) | |
| ad.uns["cube"] = row.to_dict() # the parameters travel with the data | |
| return ad | |
| def load(source: str | None = None, **query): | |
| """The single simulation matching `query`, as an AnnData. | |
| Ground truth is in `.obs["Group"]`; the generating parameters are in | |
| `.uns["cube"]`. Raises if the query is ambiguous, so a silently arbitrary | |
| pick is never returned. | |
| """ | |
| hits = _select(source, **query) | |
| if len(hits) > 1: | |
| varies = [c for c in ALIASES.values() if hits[c].nunique() > 1] | |
| raise ValueError( | |
| f"{len(hits)} simulations match; narrow by {varies or ['seed']}") | |
| return _read(hits.iloc[0], source) | |
| def load_many(source: str | None = None, **query): | |
| """Every simulation matching `query`, lazily, in catalog order.""" | |
| for _, row in _select(source, **query).iterrows(): | |
| yield _read(row, source) | |
| import sys | |
| # Only when actually run as `python loader.py` -- the README's exec(open(...).read()) | |
| # idiom inherits __name__ == "__main__" from its caller and would trip this. | |
| if __name__ == "__main__" and os.path.basename(sys.argv[0]) == "loader.py": | |
| src = (sys.argv[1] if len(sys.argv) > 1 | |
| else os.path.dirname(os.path.abspath(sys.argv[0]))) | |
| cat = catalog(src) | |
| assert len(cat) == 180, len(cat) | |
| assert cat["ari_kmeans"].between(0, 1.01).all() | |
| ad = load(src, de_prob=0.02, de_fac_loc=1.3, n_groups=8, seed=42) | |
| assert ad.shape == (2000, 16085), ad.shape | |
| assert ad.obs["Group"].nunique() == 8 | |
| assert ad.uns["cube"]["de.prob"] == 0.02 | |
| assert ad.X.min() >= 0 | |
| assert len(list(load_many(src, de_prob=0.01, n_groups=4))) == 12 | |
| for bad, err in [(dict(de_prob=0.5), ValueError), | |
| (dict(nonsense=1), TypeError), | |
| (dict(de_prob=0.02), ValueError)]: # ambiguous | |
| try: | |
| load(src, **bad) | |
| except err: | |
| pass | |
| else: | |
| raise AssertionError(f"{bad} should have raised {err.__name__}") | |
| print(f"ok: {len(cat)} sims, loaded {ad.shape[0]}x{ad.shape[1]}, " | |
| f"{ad.obs['Group'].nunique()} groups") | |