From 1a542667251614cf4626a273933bfdb3edab0fe3 Mon Sep 17 00:00:00 2001 From: Robrecht Cannoodt Date: Thu, 19 Nov 2026 13:45:44 +0100 Subject: [PATCH 1/2] annotate test resources in lamin --- scripts/create_test_resources/README.md | 4 +- .../cxg_immune_cell_atlas.ipynb | 2 + .../cxg_mouse_pancreas_atlas.ipynb | 2 + scripts/create_test_resources/helpers.py | 38 +- .../create_test_resources/lamin_annotate.py | 361 ++++++++++++++++++ scripts/create_test_resources/run_notebook.sh | 2 +- 6 files changed, 402 insertions(+), 7 deletions(-) create mode 100644 scripts/create_test_resources/lamin_annotate.py diff --git a/scripts/create_test_resources/README.md b/scripts/create_test_resources/README.md index 08818ed..db53e78 100644 --- a/scripts/create_test_resources/README.md +++ b/scripts/create_test_resources/README.md @@ -20,7 +20,7 @@ Each notebook in this directory creates one set of test resources: it runs a wor You need Docker, Nextflow, the components built with `viash ns build --setup cachedbuild`, and write access to `openproblems/data-dev`. The `.lamin` directory in the root of this repository connects it to that instance. Run a notebook with: ```bash -uv run --with 'lamindb[aws]' --with nbconvert --with ipykernel \ +uv run --with 'lamindb[aws,bionty]' --with 'anndata>=0.13' --with nbconvert --with ipykernel \ scripts/create_test_resources/run_notebook.sh scripts/create_test_resources/pancreas.ipynb ``` @@ -28,4 +28,6 @@ This tracks the run in LaminDB with the project `openproblems-bio/datasets`, lin The workflows are deterministic, so rerunning a notebook without changes returns the existing artifacts and collection. If the outputs change, the collection gets a new version; update its uid in `_viash.yaml` if this repository's own tests use it. +Each dataset artifact is also annotated with what the OpenProblems website shows about a dataset (`lamin_annotate.py`): a schema with every slot of its file format in `src/api`, the ontology terms in `obs`, the `dataset_*` metadata, the structure of the store, counts of cells per category, processing parameters and its references. + `helpers.py` holds the steps the notebooks share. diff --git a/scripts/create_test_resources/cxg_immune_cell_atlas.ipynb b/scripts/create_test_resources/cxg_immune_cell_atlas.ipynb index 371e5e4..19f9ab8 100644 --- a/scripts/create_test_resources/cxg_immune_cell_atlas.ipynb +++ b/scripts/create_test_resources/cxg_immune_cell_atlas.ipynb @@ -117,6 +117,8 @@ " output_dir / \"cxg_immune_cell_atlas\",\n", " [\"dataset.anndata.zarr\"],\n", " key=\"resources_test/datasets/cxg_immune_cell_atlas\",\n", + " specs=helpers.SCRNASEQ_SPECS,\n", + " modality=\"scrnaseq\",\n", " description=\"Immune Cell Atlas (CELLxGENE), three donors, subsampled to 600 cells and 1500 genes\",\n", ")" ], diff --git a/scripts/create_test_resources/cxg_mouse_pancreas_atlas.ipynb b/scripts/create_test_resources/cxg_mouse_pancreas_atlas.ipynb index 038cff3..e2d8b60 100644 --- a/scripts/create_test_resources/cxg_mouse_pancreas_atlas.ipynb +++ b/scripts/create_test_resources/cxg_mouse_pancreas_atlas.ipynb @@ -121,6 +121,8 @@ " output_dir / \"cxg_mouse_pancreas_atlas\",\n", " [f\"{step}.anndata.zarr\" for step in steps],\n", " key=\"resources_test/datasets/cxg_mouse_pancreas_atlas\",\n", + " specs=helpers.SCRNASEQ_SPECS,\n", + " modality=\"scrnaseq\",\n", " description=\"Mouse pancreatic islet atlas (CELLxGENE), three donors, subsampled to 600 cells and 1500 genes\",\n", ")" ], diff --git a/scripts/create_test_resources/helpers.py b/scripts/create_test_resources/helpers.py index 6229b09..541a4e8 100644 --- a/scripts/create_test_resources/helpers.py +++ b/scripts/create_test_resources/helpers.py @@ -12,6 +12,8 @@ import lamindb as ln +import lamin_annotate + INSTANCE = "openproblems/data-dev" PROJECT = "openproblems-bio/datasets" REPO_URL = "https://github.com/openproblems-bio/datasets" @@ -23,6 +25,15 @@ def git(*args): REPO_ROOT = Path(git("rev-parse", "--show-toplevel")) +# file format of each processing step of a scRNA-seq dataset +SCRNASEQ_SPECS = { + "raw.anndata.zarr": "src/api/file_raw.yaml", + "normalized.anndata.zarr": "src/api/file_normalized.yaml", + "hvg.anndata.zarr": "src/api/file_hvg.yaml", + "pca.anndata.zarr": "src/api/file_pca.yaml", + "dataset.anndata.zarr": "src/api/file_common_dataset.yaml", +} + def check_instance(): """Make sure the .lamin dev-dir in the repo root selected the right instance.""" @@ -54,6 +65,13 @@ def run_workflow(workflow, params, highmem=None, output_dir=None): run to publish into the same directory. """ output_dir = Path(output_dir or tempfile.mkdtemp()) + + # record the parameters on the run, e.g. which source release and query a dataset came from + run = ln.context.run + if run is not None: + run.params = {**(run.params or {}), workflow: params} + run.save() + params_file = output_dir / f"params_{workflow.replace('/', '_')}.json" params_file.write_text(json.dumps({**params, "publish_dir": str(output_dir)})) configs = ["-c", "common/nextflow_helpers/labels_ci.config"] @@ -76,20 +94,30 @@ def run_workflow(workflow, params, highmem=None, output_dir=None): return output_dir -def save_collection(output_dir, files, key, description): +def save_collection(output_dir, files, key, description, specs=None, modality=None): """Store each file as an artifact under `key` and group them in a collection with that key. Earlier versions keep their files, so a pinned version of the collection stays downloadable. + Files with a file format in `specs` are annotated with everything the website shows about + a dataset (see `lamin_annotate`). """ - artifacts = [ - ln.Artifact( + specs = specs or {} + artifacts = [] + for file in files: + artifact = ln.Artifact( output_dir / file, key=f"{key}/{file}", description=f"{description}: {file}", overwrite_versions=False, ).save() - for file in files - ] + if file in specs: + lamin_annotate.annotate_artifact( + artifact, + REPO_ROOT / specs[file], + modality=modality, + bib_path=REPO_ROOT / "common/library.bib", + ) + artifacts.append(artifact) collection = ln.Collection(artifacts, key=key, description=description).save() print(f"lamin://{INSTANCE}/collection/{collection.uid}") return collection diff --git a/scripts/create_test_resources/lamin_annotate.py b/scripts/create_test_resources/lamin_annotate.py new file mode 100644 index 0000000..72fd2c8 --- /dev/null +++ b/scripts/create_test_resources/lamin_annotate.py @@ -0,0 +1,361 @@ +"""Annotate LaminDB artifacts with everything the OpenProblems website shows about a dataset. + +Validation stays in OpenProblems (`validate_dataset`); this module records the result in +LaminDB, so the hub page and the website can be rendered from the instance alone: + +* a schema generated from the `src/api` file format, with every slot (`obs`, `var`, `uns`, + `layers`, `obsm`, ...), so the structure of the file is documented next to the data +* ontology terms of the `*_ontology_term_id` columns, linked through bionty +* the `dataset_*` metadata and processing parameters as feature values +* the actual structure of the store (slot, name, dtype, shape) and cell counts per category +* references from the bibliography, with their DOI + +Each file format has its own reader for the structure and summary of a store; for now only +`anndata_zarr` exists, MuData, SpatialData, data frames and JSON/YAML get one later. +""" + +import re +from pathlib import Path + +import bionty as bt +import lamindb as ln +import yaml +import zarr + +# spec types to lamindb dtypes +DTYPES = { + "string": str, + "categorical": str, + "integer": int, + "long": int, + "double": float, + "float": float, + "boolean": bool, + "object": dict, +} + +# obs columns validated against an ontology, as in the CELLxGENE schema +ONTOLOGY_COLUMNS = { + "assay_ontology_term_id": "cat[bionty.ExperimentalFactor.ontology_id]", + "cell_type_ontology_term_id": "cat[bionty.CellType.ontology_id]", + "development_stage_ontology_term_id": "cat[bionty.DevelopmentalStage.ontology_id]", + # CELLxGENE uses PATO:0000461 ("normal") next to MONDO diseases + "disease_ontology_term_id": "cat[bionty.Disease.ontology_id|bionty.Phenotype.ontology_id]", + "organism_ontology_term_id": "cat[bionty.Organism.ontology_id]", + "self_reported_ethnicity_ontology_term_id": "cat[bionty.Ethnicity.ontology_id]", + "sex_ontology_term_id": "cat[bionty.Phenotype.ontology_id]", + "tissue_ontology_term_id": "cat[bionty.Tissue.ontology_id]", + "tissue_general_ontology_term_id": "cat[bionty.Tissue.ontology_id]", +} + +# registries in which to create the placeholder terms CELLxGENE uses ("unknown", "na") +PLACEHOLDER_REGISTRIES = { + "development_stage_ontology_term_id": bt.DevelopmentalStage, + "self_reported_ethnicity_ontology_term_id": bt.Ethnicity, + "sex_ontology_term_id": bt.Phenotype, +} + +# obs columns of which the number of cells per category is stored +COUNT_COLUMNS = [ + "assay", "cell_type", "development_stage", "disease", "donor_id", "organism", + "self_reported_ethnicity", "sex", "tissue", "tissue_general", "batch", +] + +CURATED_SLOTS = ["obs", "var", "uns"] +ROOT_TYPE = "OpenProblems" + + +def load_spec(path): + """Read a `src/api` file spec, resolving `__merge__` like viash does.""" + path = Path(path) + spec = yaml.safe_load(path.read_text()) + parent = spec.pop("__merge__", None) + if parent is None: + return spec + return _merge(load_spec((path.parent / parent).resolve()), spec) + + +def _merge(a, b): + if isinstance(a, dict) and isinstance(b, dict): + return {**a, **{k: _merge(a[k], v) if k in a else v for k, v in b.items()}} + if isinstance(a, list) and isinstance(b, list): + return a + b + return b + + +# --- registries ---------------------------------------------------------------------------- + +def _get_or_create(registry, **fields): + record = registry.filter(**fields).one_or_none() + return record if record is not None else registry(**fields).save() + + +def _feature_type(name): + """Features are grouped per slot, since e.g. `dataset_id` means something else in obs and uns.""" + root = _get_or_create(ln.Feature, name=ROOT_TYPE, is_type=True) + return _get_or_create(ln.Feature, name=name, is_type=True, type=root) + + +def _feature(name, dtype, type_name, description=None): + ftype = _feature_type(type_name) + feature = ln.Feature.filter(name=name, type=ftype).one_or_none() + if feature is None: + feature = ln.Feature(name=name, dtype=dtype, type=ftype, description=description).save() + return feature + + +def _spec_feature(item, slot): + name = item["name"] + if slot == "obs" and name in ONTOLOGY_COLUMNS: + dtype = ONTOLOGY_COLUMNS[name] + elif slot == "uns" and item.get("multiple"): + dtype = list[DTYPES[item["type"]]] + else: + dtype = DTYPES[item["type"]] + feature = _feature(name, dtype, slot, (item.get("description") or "").strip() or None) + return feature if item.get("required", True) else feature.with_config(optional=True) + + +def spec_schemas(spec_path): + """Turn a file spec into a LaminDB schema with every slot, and one with the slots lamindb can curate.""" + spec = load_spec(spec_path) + fmt = spec["info"]["format"] + name = spec.get("label") or Path(spec_path).stem + slots = { + slot: ln.Schema( + name=f"{name}: {slot}", + features=[_spec_feature(item, slot) for item in items], + otype="DataFrame" if slot in ("obs", "var") else None, + ).save() + for slot, items in fmt.items() + if slot != "type" and isinstance(items, list) and items + } + description = (spec.get("summary") or "").strip() or None + full = ln.Schema(name=name, otype="AnnData", slots=slots, description=description).save() + curated = ln.Schema( + name=f"{name} (curated slots)", + otype="AnnData", + slots={slot: schema for slot, schema in slots.items() if slot in CURATED_SLOTS}, + ).save() + return spec, full, curated + + +# --- reading a store ----------------------------------------------------------------------- + +def _describe_element(node): + """Type, dtype and shape of an element in an anndata zarr store, from its metadata only.""" + if isinstance(node, zarr.Array): + return {"type": node.attrs.get("encoding-type", "array"), "dtype": str(node.dtype), "shape": list(node.shape)} + encoding = node.attrs.get("encoding-type") + if encoding in ("csr_matrix", "csc_matrix"): + return {"type": encoding, "dtype": str(node["data"].dtype), "shape": list(node.attrs["shape"])} + if encoding == "categorical": + return { + "type": "categorical", + "dtype": str(node["categories"].dtype), + "shape": list(node["codes"].shape), + "n_categories": node["categories"].shape[0], + } + if encoding and encoding.startswith("nullable-"): + return {"type": encoding, "dtype": str(node["values"].dtype), "shape": list(node["values"].shape)} + if encoding == "dataframe": + index = node[node.attrs["_index"]] + return {"type": "dataframe", "shape": [index.shape[0], len(node.attrs["column-order"])]} + return {"type": encoding or "dict", "keys": sorted(node.keys())} + + +def _anndata_structure(path, spec): + """Per slot, the name, type, dtype and shape of each element, with the description from the spec.""" + root = zarr.open_group(path, mode="r") + fmt = spec["info"]["format"] + structure = {} + for slot in ["X", "obs", "var", "layers", "obsm", "obsp", "varm", "varp", "uns"]: + if slot not in root: + continue + descriptions = {item["name"]: (item.get("description") or "").strip() for item in fmt.get(slot, []) or [] if isinstance(item, dict)} + if slot == "X": + structure["X"] = [{"name": "X", **_describe_element(root["X"])}] + continue + group = root[slot] + names = group.attrs["column-order"] if slot in ("obs", "var") else sorted(group.keys()) + structure[slot] = [ + {"name": name, **_describe_element(group[name]), "description": descriptions.get(name)} + for name in names + ] + return structure + + +def _anndata_summary(path, structure): + """Dataset-level numbers and counts that are shown next to the data.""" + import anndata as ad + + root = zarr.open_group(path, mode="r") + obs = ad.io.read_elem(root["obs"]) + var = ad.io.read_elem(root["var"]) + uns = ad.io.read_elem(root["uns"]) if "uns" in root else {} + summary = {"n_vars": int(var.shape[0])} + for column, feature in [("donor_id", "n_donors"), ("batch", "n_batches")]: + if column in obs: + summary[feature] = int(obs[column].nunique()) + if "hvg" in var: + summary["n_hvg"] = int(var["hvg"].sum()) + obsm = {item["name"]: item for item in structure.get("obsm", [])} + if "X_pca" in obsm: + summary["n_pca_components"] = int(obsm["X_pca"]["shape"][1]) + knn_params = uns.get("knn", {}).get("params", {}) + if "n_neighbors" in knn_params: + summary["knn_n_neighbors"] = int(knn_params["n_neighbors"]) + summary["obs_counts"] = { + column: {str(k): int(v) for k, v in obs[column].value_counts().items()} + for column in COUNT_COLUMNS + if column in obs + } + return obs, summary, uns + + +FORMATS = { + "anndata_zarr": {"structure": _anndata_structure, "summary": _anndata_summary, "curator": ln.curators.AnnDataCurator}, +} + + +# --- annotating ---------------------------------------------------------------------------- + +def _register_organisms(ontology_ids): + """Register the species itself for each organism term. + + Ensembl lists mouse strains under the same NCBI Taxonomy term as mouse, so bionty can't + pick a record, and lamindb then loops forever saving the duplicates. + """ + for ontology_id in ontology_ids: + if bt.Organism.filter(ontology_id=ontology_id).exists(): + continue + records = bt.Organism.from_source(ontology_id=ontology_id) + if isinstance(records, list): + records = min(records, key=lambda record: len(record.name)) + records.save() + + +def _curate(artifact, curated_schema, curator_class, obs): + """Validate obs/var/uns with lamindb and link the ontology terms.""" + if "organism_ontology_term_id" in obs: + _register_organisms(obs["organism_ontology_term_id"].unique()) + curator = curator_class(artifact, curated_schema) + try: + curator.validate() + except ln.errors.ValidationError: + for column, values in curator.slots["obs"].cat.non_validated.items(): + registry = PLACEHOLDER_REGISTRIES.get(column) + if registry is None: + raise + _register_missing_terms(registry, column, values, obs) + curator.validate() + curator.save_artifact() + + +def _register_missing_terms(registry, column, values, obs): + """Register terms that are not in the default ontology of a registry. + + Mouse development stages are in MmusDv rather than the default HsapDv, so other sources + are tried first. What's left are CELLxGENE placeholders ("unknown", "na"), which get the + label of the matching obs column as name. + """ + label_column = column.removesuffix("_ontology_term_id") + labels = dict(zip(obs[column].astype(str), obs[label_column].astype(str))) if label_column in obs else {} + entity = f"bionty.{registry.__name__}" + sources = bt.Source.filter(entity=entity).order_by("-currently_used") + for value in values: + record = None + for source in sources: + try: + record = registry.from_source(ontology_id=value, source=source, mute=True) + except Exception: + record = None + if record is not None and not isinstance(record, list): + break + record = None + if record is None: + record = registry(name=labels.get(value, value), ontology_id=value, description="CELLxGENE placeholder term") + record.save() + + +def _bib_entry(bib_text, key): + match = re.search(r"@\w+\s*\{\s*" + re.escape(key) + r"\s*,(.*?)\n\}", bib_text, flags=re.S) + if match is None: + return None + fields = {} + for field, value in re.findall(r"(\w+)\s*=\s*\{((?:[^{}]|\{[^{}]*\})*)\}", match.group(1)): + fields[field.lower()] = re.sub(r"[{}]", "", " ".join(value.split())) + return fields + + +def _link_references(artifact, keys, bib_path): + bib_text = Path(bib_path).read_text() + for key in keys: + entry = _bib_entry(bib_text, key) + if entry is None: + print(f"Reference '{key}' not found in {bib_path}") + continue + doi = entry.get("doi") + reference = ln.Reference.filter(doi=doi).one_or_none() if doi else None + if reference is None: + reference = ln.Reference.filter(abbr=key).one_or_none() + if reference is None: + reference = ln.Reference( + name=entry.get("title", key), + abbr=key, + doi=doi, + url=entry.get("url") or (f"https://doi.org/{doi}" if doi else None), + ).save() + artifact.references.add(reference) + + +def annotate_artifact(artifact, spec_path, modality, bib_path): + """Record what OpenProblems knows about a dataset artifact in LaminDB.""" + spec, full_schema, curated_schema = spec_schemas(spec_path) + fmt = FORMATS[spec["info"]["format"]["type"]] + + # an unchanged file is the same artifact, which is already annotated + if artifact.schema_id == full_schema.id: + print(f"{artifact.key} is already annotated") + return artifact + + path = artifact.cache() + structure = fmt["structure"](path, spec) + obs, summary, uns = fmt["summary"](path, structure) + + # validate the slots lamindb can curate, and link their ontology terms + _curate(artifact, curated_schema, fmt["curator"], obs) + + # document every slot of the file format, not only the curated ones + artifact.schema = full_schema + artifact.n_observations = int(obs.shape[0]) + artifact.save() + + # the metadata in uns, the summary and the structure as feature values + uns_features = {feature.name: feature for feature in full_schema.slots["uns"].members} if "uns" in full_schema.slots else {} + values = {} + for name, value in uns.items(): + if name not in uns_features: + continue + if hasattr(value, "tolist"): + value = value.tolist() + if isinstance(value, (str, int, float, bool, list)): + values[uns_features[name]] = value + for name, value in {**summary, "structure": structure}.items(): + values[_feature(name, dict if isinstance(value, dict) else int, "dataset")] = value + artifact.features.add_values(values) + + # modality, for grouping datasets on the website + if modality is not None: + modality_type = _get_or_create(ln.ULabel, name="Modality", is_type=True) + artifact.ulabels.add(_get_or_create(ln.ULabel, name=modality, type=modality_type)) + + # references, with their DOI + references = uns.get("dataset_reference") + if references is not None: + _link_references(artifact, [references] if isinstance(references, str) else list(references), bib_path) + + if artifact.description is None and uns.get("dataset_summary"): + artifact.description = uns["dataset_summary"] + artifact.save() + return artifact diff --git a/scripts/create_test_resources/run_notebook.sh b/scripts/create_test_resources/run_notebook.sh index 9d9f86a..d9b3df2 100755 --- a/scripts/create_test_resources/run_notebook.sh +++ b/scripts/create_test_resources/run_notebook.sh @@ -3,7 +3,7 @@ # Run a test resource notebook and save it, including its report, to LaminDB. # # Usage: -# uv run --with 'lamindb[aws]' --with nbconvert --with ipykernel \ +# uv run --with 'lamindb[aws,bionty]' --with 'anndata>=0.13' --with nbconvert --with ipykernel \ # scripts/create_test_resources/run_notebook.sh scripts/create_test_resources/pancreas.ipynb set -eo pipefail From 31c0a5efe05d567ac19c3fa6cfeea0b01cba86d3 Mon Sep 17 00:00:00 2001 From: Robrecht Cannoodt Date: Thu, 19 Nov 2026 13:56:05 +0100 Subject: [PATCH 2/2] update changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7fef24..fbf8e07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ * MAJOR CHANGE: All loaders, components and workflows write AnnData zarr stores instead of h5ad files, and the file formats in `src/api` are now `anndata_zarr`. Every Docker image sets `ANNDATA_ZARR_WRITE_FORMAT=3`. Multimodal datasets are still two AnnData stores, spatial datasets one. +* NEW FUNCTIONALITY: Test resource artifacts in LaminDB are annotated with what the OpenProblems website shows about a dataset (`scripts/create_test_resources/lamin_annotate.py`): a schema with every slot of the `src/api` file format, the ontology terms in `obs`, the `dataset_*` metadata, the structure of the store, cell counts per category, processing parameters, the modality and references with their DOI. The notebooks record the workflow parameters on their run. + * MAJOR CHANGE: Test resources are generated by notebooks in `scripts/create_test_resources` and stored as one collection per notebook in the public LaminDB instance `openproblems/data-dev`. CI syncs them with `edaro/viash-actions`. `pancreas.ipynb` replaces `pancreas.sh`. * MINOR CHANGE: The CELLxGENE immune cell atlas, CELLxGENE mouse pancreas atlas, Visium mouse brain, NeurIPS 2021 bone marrow and sci-CAR cell lines test resources are generated by notebooks too. Their subsampling is now seeded, and the CELLxGENE ones no longer pass cell cycle gene symbols as `keep_features`, which never matched their Ensembl gene ids. `neurips2022_pbmc.sh` is not converted yet.