{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-evidence-insight-cellxgene-census-434ed8ffe1ef","title":"Query CZ CELLxGENE Census for Cross-Tissue Expression Data","summary":"Access and analyze cross-tissue, cross-disease, and cell-type expression data from the CZ CELLxGENE Census using Python libraries like `cellxgene-census`, `tiledbsoma`, and `pyarrow` for population-scale comparisons and reference atlas validation.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-evidence-insight-cellxgene-census-434ed8ffe1ef","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-evidence-insight-cellxgene-census-434ed8ffe1ef","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-evidence-insight-cellxgene-census-434ed8ffe1ef.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-evidence-insight-cellxgene-census-434ed8ffe1ef\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Install `cellxgene-census` and `tiledbsoma` first, and ensure a pinned version of the Census for reproducibility. Use `is_primary_data == True` in filters to avoid double-counting cells from multiple datasets.","instructions":"---\nname: cellxgene-census\ndescription: Programmatically query the CZ CELLxGENE Census (61M+ cells) when you need cross-tissue, disease, or cell-type expression data for population-scale queries and reference atlas comparisons.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n## When to Use\n\n- **Cross-tissue or cross-disease expression comparisons** (e.g., macrophages across lung\/liver\/brain; COVID-19 vs control).\n- **Reference atlas lookups** to contextualize findings from your own single-cell dataset (marker validation, expected expression patterns).\n- **Population-scale metadata exploration** (what tissues\/cell types\/datasets exist; cell counts by cohort attributes).\n- **Large-scale expression statistics** where results exceed RAM and require out-of-core iteration.\n- **Model training on curated atlas data** (e.g., cell-type classifiers) using the experimental PyTorch integration.\n\n## Key Features\n\n- Programmatic access to **versioned** CZ CELLxGENE Census data (human and mouse).\n- Query **cell (obs) metadata** and **gene (var) metadata** with expressive filter syntax.\n- Retrieve expression as **AnnData** for small\/medium queries via `get_anndata()`.\n- Perform **out-of-core** expression access via SOMA `axis_query()` and chunked iteration.\n- Optional **experimental ML utilities** (PyTorch dataloaders\/datasets).\n- Works well with **scanpy** workflows after loading AnnData.\n\n## Dependencies\n\n- `cellxgene-census` (latest)\n- `tiledbsoma` (latest; required for `axis_query()` workflows)\n- `pyarrow` (latest; used for chunked table batches)\n- `anndata` (latest; for `get_anndata()` results)\n- `scanpy` (latest; optional, for downstream analysis)\n- `torch` (latest; optional, for experimental ML integration)\n\nInstall:\n```bash\nuv pip install cellxgene-census\n```\n\nOptional (experimental ML helpers):\n```bash\nuv pip install cellxgene-census[experimental]\n```\n\n## Example Usage\n\nThe following script is a complete, runnable example that:\n1) opens a pinned Census version,  \n2) explores metadata,  \n3) loads a small AnnData slice, and  \n4) runs an out-of-core query to compute a simple statistic.\n\n```python\nimport numpy as np\nimport cellxgene_census\nimport tiledbsoma as soma\n\ndef main():\n    # Pin a version for reproducibility (replace with a valid release if needed)\n    census_version = \"2023-07-25\"\n\n    with cellxgene_census.open_soma(census_version=census_version) as census:\n        # 1) Explore summary info\n        summary = census[\"census_info\"][\"summary\"].read().concat().to_pandas()\n        total_cells = int(summary[\"total_cell_count\"].iloc[0])\n        print(f\"Census version: {census_version}\")\n        print(f\"Total cells: {total_cells:,}\")\n\n        # 2) Explore obs metadata (always filter primary data unless you want duplicates)\n        obs = cellxgene_census.get_obs(\n            census,\n            \"homo_sapiens\",\n            value_filter=\"tissue_general == 'brain' and is_primary_data == True\",\n            column_names=[\"cell_type\", \"tissue_general\", \"disease\", \"donor_id\"],\n        )\n        print(f\"Brain (primary) cells returned (metadata only): {len(obs):,}\")\n        print(\"Top cell types:\")\n        print(obs[\"cell_type\"].value_counts().head(10))\n\n        # 3) Small\/medium query -> AnnData in memory\n        adata = cellxgene_census.get_anndata(\n            census=census,\n            organism=\"Homo sapiens\",\n            obs_value_filter=(\n                \"cell_type == 'T cell' and disease == 'COVID-19' and is_primary_data == True\"\n            ),\n            var_value_filter=\"feature_name in ['CD4', 'CD8A', 'FOXP3']\",\n            obs_column_names=[\"cell_type\", \"tissue_general\", \"disease\", \"donor_id\", \"sex\"],\n        )\n        print(adata)\n        print(\"AnnData X shape:\", adata.X.shape)\n\n        # 4) Large-scale pattern -> out-of-core iteration with axis_query()\n        # Example: compute mean of non-zero expression values for a few genes in brain.\n        query = census[\"census_data\"][\"homo_sapiens\"].axis_query(\n            measurement_name=\"RNA\",\n            obs_query=soma.AxisQuery(\n                value_filter=\"tissue_general == 'brain' and is_primary_data == True\"\n            ),\n            var_query=soma.AxisQuery(\n                value_filter=\"feature_name in ['FOXP2', 'TBR1', 'SATB2']\"\n            ),\n        )\n\n        n = 0\n        s = 0.0\n        for batch in query.X(\"raw\").tables():\n            # batch is a pyarrow.Table with at least: soma_data, soma_dim_0, soma_dim_1\n            values = batch[\"soma_data\"].to_numpy(zero_copy_only=False)\n            n += values.size\n            s += float(values.sum())\n\n        mean_expr = s \/ n if n else np.nan\n        print(f\"Out-of-core mean expression (over returned entries): {mean_expr:.6g}\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Implementation Details\n\n- **Opening the Census**\n  - Use a context manager to ensure resources are released:\n    - `with cellxgene_census.open_soma(...) as census: ...`\n  - For reproducibility, set `census_version=\"YYYY-MM-DD\"`; otherwise the latest stable release is used.\n\n- **Data model (high level)**\n  - Census data is stored in **SOMA** collections.\n  - `census[\"census_info\"]` provides summary tables (e.g., datasets, counts).\n  - `census[\"census_data\"][organism]` provides the experiment for an organism (e.g., `homo_sapiens`).\n\n- **Filtering semantics**\n  - `obs_value_filter` filters **cells** (obs); `var_value_filter` filters **genes** (var).\n  - Combine predicates with `and` \/ `or`; use `in [...]` for multi-value membership.\n  - Best practice: include `is_primary_data == True` to avoid double-counting cells that appear in multiple source datasets.\n\n- **Choosing an access pattern**\n  - Use `get_anndata()` when the result is expected to fit in memory (commonly < ~100k cells, depending on gene count and sparsity).\n  - Use `axis_query()` + `query.X(\"raw\").tables()` for **out-of-core** iteration and incremental statistics.\n\n- **Expression layers \/ matrices**\n  - Examples commonly use `X(\"raw\")` to access raw expression.\n  - Chunk iteration yields Arrow tables with:\n    - `soma_data`: expression values\n    - `soma_dim_0`: obs (cell) coordinates\n    - `soma_dim_1`: var (gene) coordinates\n\n- **Optional ML integration**\n  - The `cellxgene_census.experimental.ml` utilities provide PyTorch-friendly datasets\/dataloaders for training workflows, typically driven by the same obs\/var filtering concepts used elsewhere.","use_cases":["Compare gene expression across tissues (e.g., macrophages in lung, liver, and brain).","Validate marker genes using reference atlas data.","Explore metadata to understand cell type and disease distribution.","Perform out-of-core expression analysis for large-scale datasets."],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Evidence%20Insight\/cellxgene-census\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T13:24:35.000000Z","updated_at":"2026-11-24T12:17:28.000000Z","seo_title":"Query CZ CELLxGENE Census for Cross-Tissue Expression Data","seo_description":"Access and analyze cross-tissue, cross-disease, and cell-type expression data from the CZ CELLxGENE Census for population-scale comparisons and reference atlas validation","seo_keywords":["CZ CELLxGENE Census query","Cross-tissue gene expression analysis","Reference atlas validation","Single-cell data exploration","Out-of-core expression analysis"]}}