Cellxgene Census 标志

Cellxgene Census

社区
jaechang-hits
cellxgene-census

Query CELLxGENE Census (61M+ cells). Search by cell type/tissue/disease/organism; get AnnData, stream out-of-core, train PyTorch models. For your own data use scanpy; for annotated data use anndata.

概览

发布者jaechang-hits
代码仓库SciAgent-Skills
技能名称cellxgene-census
星标数
381
复刻数
45
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 jaechang-hits 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Cellxgene Census AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/jaechang-hits/SciAgent-Skills/tree/main/skills/genomics-bioinformatics/single-cell/cellxgene-census
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/jaechang-hits/SciAgent-Skills.git /tmp/SciAgent-Skills
mkdir -p .claude/skills
cp -r /tmp/SciAgent-Skills/skills/genomics-bioinformatics/single-cell/cellxgene-census .claude/skills/cellxgene-census
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Cellxgene Census,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Cellxgene Census。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Cellxgene Census 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

CZ CELLxGENE Census

Overview

CZ CELLxGENE Census provides programmatic access to 61+ million standardized single-cell RNA-seq observations from human and mouse. It enables population-scale queries by cell type, tissue, disease, and donor metadata, returning expression data as AnnData objects or PyTorch dataloaders for ML workflows.

When to Use

  • Querying single-cell expression data across tissues, diseases, or cell types from a curated atlas
  • Building reference datasets for cell type classification or marker gene discovery
  • Training ML models on large-scale single-cell data (PyTorch integration)
  • Comparing gene expression across conditions (e.g., COVID-19 vs healthy) at population scale
  • Exploring what single-cell datasets are available for a tissue or disease of interest
  • For analyzing your own scRNA-seq data, use scanpy instead
  • For manipulating AnnData objects (subsetting, concatenation), use anndata instead

Prerequisites

bash
pip install cellxgene-census
# For ML workflows
pip install cellxgene-census[experimental]

API Rate Limits: Census uses TileDB-SOMA cloud backend. No explicit rate limit, but large queries (>1M cells) should use out-of-core processing (Module 4) to avoid memory exhaustion. Always use context managers for proper resource cleanup.

Quick Start

python
import cellxgene_census

with cellxgene_census.open_soma() as census:
    # Get B cells from lung
    adata = cellxgene_census.get_anndata(
        census=census,
        organism="Homo sapiens",
        obs_value_filter="cell_type == 'B cell' and tissue_general == 'lung' and is_primary_data == True",
        obs_column_names=["cell_type", "disease", "donor_id"],
    )
    print(f"Retrieved {adata.n_obs} cells × {adata.n_vars} genes")
    # Retrieved ~15000 cells × 60664 genes

Core API

1. Opening and Exploring the Census

Connect to Census and discover available data.

python
import cellxgene_census

# Open latest stable version (always use context manager)
with cellxgene_census.open_soma() as census:
    # Summary statistics
    summary = census["census_info"]["summary"].read().concat().to_pandas()
    print(f"Total cells: {summary['total_cell_count'][0]:,}")

    # List all datasets
    datasets = census["census_info"]["datasets"].read().concat().to_pandas()
    print(f"Total datasets: {len(datasets)}")
    print(datasets[["dataset_title", "cell_count"]].head())
python
# Open specific version for reproducibility
with cellxgene_census.open_soma(census_version="2023-07-25") as census:
    # Reproducible analysis code here
    pass

2. Cell Metadata Queries

Query cell-level metadata without downloading expression data.

python
import cellxgene_census

with cellxgene_census.open_soma() as census:
    # Get unique cell types in brain
    cell_metadata = cellxgene_census.get_obs(
        census,
        "homo_sapiens",
        value_filter="tissue_general == 'brain' and is_primary_data == True",
        column_names=["cell_type", "disease", "assay"]
    )
    print(f"Total brain cells: {len(cell_metadata):,}")
    print(cell_metadata["cell_type"].value_counts().head(10))
python
    # Gene metadata query
    gene_metadata = cellxgene_census.get_var(
        census,
        "homo_sapiens",
        value_filter="feature_name in ['CD4', 'CD8A', 'FOXP3']",
        column_names=["feature_id", "feature_name", "feature_length"]
    )
    print(gene_metadata)
    # Returns DataFrame with Ensembl IDs, gene symbols, and lengths

3. Expression Data Queries (Small-Medium Scale)

Retrieve expression matrices as AnnData objects for queries returning <100k cells.

python
import cellxgene_census

with cellxgene_census.open_soma() as census:
    # Query by cell type + tissue + disease
    adata = cellxgene_census.get_anndata(
        census=census,
        organism="Homo sapiens",
        obs_value_filter="cell_type == 'T cell' and disease == 'COVID-19' and is_primary_data == True",
        var_value_filter="feature_name in ['CD4', 'CD8A', 'CD19', 'FOXP3']",
        obs_column_names=["cell_type", "tissue_general", "donor_id"],
    )
    print(f"Shape: {adata.shape}")  # (n_cells, 4)
    print(f"Metadata columns: {list(adata.obs.columns)}")

Filter syntax reference:

  • Combine conditions: and, or
  • Multiple values: feature_name in ['CD4', 'CD8A']
  • Comparison: cell_count > 1000
  • Always include is_primary_data == True to avoid duplicate cells

4. Large-Scale Out-of-Core Queries

Stream expression data in chunks for queries exceeding available RAM.

python
import cellxgene_census
import tiledbsoma as soma

with cellxgene_census.open_soma() as census:
    # Estimate query size first
    metadata = cellxgene_census.get_obs(
        census, "homo_sapiens",
        value_filter="tissue_general == 'brain' and is_primary_data == True",
        column_names=["soma_joinid"]
    )
    n_cells = len(metadata)
    print(f"Query will return {n_cells:,} cells")

    # If >100k cells, use streaming
    query = census["census_data"]["homo_sapiens"].axis_query(
        measurement_name="RNA",
        obs_query=soma.AxisQuery(
            value_filter="tissue_general == 'brain' and is_primary_data == True"
        ),
        var_query=soma.AxisQuery(
            value_filter="feature_name in ['FOXP2', 'TBR1', 'SATB2']"
        )
    )

    # Incremental statistics
    n_obs, total = 0, 0.0
    for batch in query.X("raw").tables():
        values = batch["soma_data"].to_numpy()
        n_obs += len(values)
        total += values.sum()

    print(f"Processed {n_obs:,} non-zero entries, mean={total/n_obs:.4f}")

5. Dataset Presence Matrix

Check which datasets measured specific genes (not all genes are in all datasets).

python
import cellxgene_census

with cellxgene_census.open_soma() as census:
    presence = cellxgene_census.get_presence_matrix(
        census,
        "homo_sapiens",
        var_value_filter="feature_name in ['CD4', 'CD8A', 'PTPRC']"
    )
    print(f"Presence matrix shape: {presence.shape}")
    # (n_datasets, n_genes) — True if gene measured in dataset

6. PyTorch ML Integration

Train models directly on Census data using the experimental dataloader.

python
from cellxgene_census.experimental.ml import experiment_dataloader
import cellxgene_census

with cellxgene_census.open_soma() as census:
    dataloader = experiment_dataloader(
        census["census_data"]["homo_sapiens"],
        measurement_name="RNA",
        X_name="raw",
        obs_value_filter="tissue_general == 'liver' and is_primary_data == True",
        obs_column_names=["cell_type"],
        batch_size=128,
        shuffle=True,
    )

    for batch in dataloader:
        X = batch["X"]           # Gene expression tensor
        labels = batch["obs"]    # Cell metadata
        print(f"Batch X shape: {X.shape}, labels: {list(labels.columns)}")
        break  # Show first batch only

Key Concepts

Census Data Model

The Census is organized as a SOMA (Stack of Matrices, Annotated) collection:

census/
├── census_info/
│   ├── summary          # Total cell counts
│   └── datasets         # Dataset metadata
└── census_data/
    ├── homo_sapiens/
    │   └── ms_RNA/
    │       ├── obs      # Cell metadata (61M+ rows)
    │       ├── var      # Gene metadata (~60k rows)
    │       └── X/raw    # Expression matrix (sparse)
    └── mus_musculus/
        └── ...

Key Metadata Fields

FieldTypeDescriptionExample Values
cell_typestrCell Ontology label"B cell", "neuron", "macrophage"
tissue_generalstrCoarse tissue grouping"brain", "lung", "blood"
tissuestrSpecific tissue"prefrontal cortex", "alveolar tissue"
diseasestrDisease state"normal", "COVID-19", "lung adenocarcinoma"
assaystrSequencing assay"10x 3' v3", "Smart-seq2"
is_primary_databoolTrue = unique cellAlways filter True
donor_idstrDonor identifierUsed for batch effects

tissue_general vs tissue

Use tissue_general for broad cross-tissue analyses and tissue for specific tissue queries:

python
# Broad: all immune system cells
obs_value_filter = "tissue_general == 'immune system'"
# Specific: only PBMCs
obs_value_filter = "tissue == 'peripheral blood mononuclear cell'"

Common Workflows

Workflow 1: Cross-Tissue Cell Type Comparison

Goal: Compare macrophage gene expression across tissues.

python
import cellxgene_census
import scanpy as sc

with cellxgene_census.open_soma() as census:
    adata = cellxgene_census.get_anndata(
        census=census,
        organism="Homo sapiens",
        obs_value_filter=(
            "cell_type == 'macrophage' and "
            "tissue_general in ['lung', 'liver', 'brain'] and "
            "is_primary_data == True"
        ),
        obs_column_names=["cell_type", "tissue_general", "donor_id", "disease"],
    )
    print(f"Macrophages: {adata.n_obs} cells from {adata.obs['tissue_general'].nunique()} tissues")

    # Standard scanpy analysis
    sc.pp.normalize_total(adata, target_sum=1e4)
    sc.pp.log1p(adata)
    sc.pp.highly_variable_genes(adata, n_top_genes=2000)
    sc.pp.pca(adata, n_comps=50)
    sc.pp.neighbors(adata)
    sc.tl.umap(adata)

    # Differential expression across tissues
    sc.tl.rank_genes_groups(adata, groupby="tissue_general")
    sc.pl.umap(adata, color=["tissue_general", "disease"])

Workflow 2: Disease-Associated Gene Expression

Goal: Compare marker gene expression between COVID-19 and healthy controls.

  1. Query metadata to identify available cell types in COVID-19 data (Core API module 2)
  2. Retrieve expression data for selected cell types and marker genes (Core API module 3)
  3. Compute mean expression per cell type per condition
  4. Visualize with scanpy dotplot or matrixplot

Key Parameters

ParameterFunction/EndpointDefaultRange / OptionsEffect
organismget_anndata, get_obs—"Homo sapiens", "Mus musculus"Species selection
census_versionopen_somalatest stableDate string "YYYY-MM-DD"Pin to specific data release
obs_value_filterget_anndata, get_obsNoneSOMA filter expressionCell-level filtering
var_value_filterget_anndata, get_varNoneSOMA filter expressionGene-level filtering
obs_column_namesget_anndata, get_obsall columnslist of field namesReduces data transfer
batch_sizeexperiment_dataloader12832–512PyTorch batch size
shuffleexperiment_dataloaderFalseTrue/FalseRandomize training order

Best Practices

  1. Always filter is_primary_data == True: Without this filter, duplicate cells across datasets inflate counts and bias analyses.

  2. Estimate query size before loading: Call get_obs() with column_names=["soma_joinid"] to count cells before downloading expression data. Use out-of-core processing for >100k cells.

  3. Pin census_version for reproducibility: The default "latest stable" changes periodically. Always specify the version for published analyses.

  4. Select only needed metadata columns: Passing obs_column_names reduces data transfer and memory usage significantly for large queries.

  5. Use tissue_general for cross-tissue analyses: The tissue field has hundreds of specific values; tissue_general provides ~30 coarse groupings suitable for comparative analyses.

  6. Anti-pattern — querying all genes when you need a few: Specify var_value_filter to retrieve only genes of interest. Downloading the full ~60k gene matrix for 3 marker genes wastes bandwidth and memory.

Common Recipes

Recipe: Multi-Tissue Dataset Summary

python
import cellxgene_census
import pandas as pd

with cellxgene_census.open_soma() as census:
    metadata = cellxgene_census.get_obs(
        census, "homo_sapiens",
        value_filter="is_primary_data == True",
        column_names=["tissue_general", "cell_type", "disease"]
    )
    summary = metadata.groupby("tissue_general").agg(
        n_cells=("cell_type", "size"),
        n_cell_types=("cell_type", "nunique"),
        n_diseases=("disease", "nunique"),
    ).sort_values("n_cells", ascending=False)
    print(summary.head(10))

Recipe: Export Census Subset to h5ad

python
import cellxgene_census

with cellxgene_census.open_soma() as census:
    adata = cellxgene_census.get_anndata(
        census=census,
        organism="Homo sapiens",
        obs_value_filter="tissue_general == 'heart' and is_primary_data == True",
        obs_column_names=["cell_type", "disease", "donor_id", "assay"],
    )
    adata.write_h5ad("heart_cells.h5ad")
    print(f"Saved {adata.n_obs} cells to heart_cells.h5ad")

Troubleshooting

ProblemCauseSolution
MemoryError on get_anndata()Query returns too many cellsCheck count with get_obs() first; use out-of-core axis_query() for >100k cells
Duplicate cells in resultsMissing is_primary_data == True filterAdd is_primary_data == True to all obs_value_filter queries
Gene not foundWrong gene name or gene not in CensusCheck spelling (case-sensitive); try Ensembl ID via feature_id; verify with get_presence_matrix()
ConnectionError / timeoutCensus backend temporarily unavailableRetry after 1-2 minutes; pin a specific census_version for reliability
Version inconsistenciesUsing default "latest" across sessionsAlways specify census_version in production code
Slow query performanceDownloading all metadata columnsSpecify only needed columns via obs_column_names
ImportError: cellxgene_censusPackage not installedpip install cellxgene-census (note the hyphen)

Related Skills

  • scanpy-scrna-seq — downstream analysis of Census data (clustering, DEG, visualization)
  • anndata-data-structure — manipulating AnnData objects returned by Census queries
  • esm-protein-language-model — protein embeddings from sequences; complementary to Census gene expression data

References

常见问题

Cellxgene Census AI 技能有什么作用?

Query CELLxGENE Census (61M+ cells). Search by cell type/tissue/disease/organism; get AnnData, stream out-of-core, train PyTorch models. For your own data use scanpy; for annotated data use anndata.

为什么在 TypingMind 中使用 Cellxgene Census?

因为您只需安装一次,就能搭配任何模型使用。Cellxgene Census 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Cellxgene Census?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/jaechang-hits/SciAgent-Skills/tree/main/skills/genomics-bioinformatics/single-cell/cellxgene-census。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Cellxgene Census?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Cellxgene Census 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Cellxgene Census 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Cellxgene Census AI 技能免费吗?

是的。jaechang-hits 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇