[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73HTMVKBNRMB7RZYMF3JVGZ":3,"skill-same:01M73HTMVKBNRMB7RZYMF3JVGZ":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73HTMVKBNRMB7RZYMF3JVGZ","popv-cell-annotation",null,"Consensus cell type annotation: runs 10+ algorithms (KNN-Harmony\u002FBBKNN\u002FScanorama\u002FscVI, CellTypist, ONCLASS, Random Forest, SCANVI, SVM, XGBoost) on a labeled reference and transfers labels via majority voting. Outputs per-method labels, consensus, agreement score. Use when single-method annotation is insufficient or you need ensemble uncertainty for novel states; to choose between manual markers, CellTypist and popV, read cell-type-annotation first.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpopv-cell-annotation\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"popv-cell-annotation\"\ndescription: \"Consensus cell type annotation: runs 10+ algorithms (KNN-Harmony\u002FBBKNN\u002FScanorama\u002FscVI, CellTypist, ONCLASS, Random Forest, SCANVI, SVM, XGBoost) on a labeled reference and transfers labels via majority voting. Outputs per-method labels, consensus, agreement score. Use when single-method annotation is insufficient or you need ensemble uncertainty for novel states; to choose between manual markers, CellTypist and popV, read cell-type-annotation first.\"\nlicense: \"BSD-3-Clause\"\n---\n\n# popV Multi-Method Cell Type Transfer\n\n## Overview\n\npopV (Population Voting for single-cell annotation) annotates a query scRNA-seq dataset by running 10+ independent classification algorithms against a labeled reference atlas and aggregating results via majority voting. Each method produces its own label; the final `popv_prediction` is the consensus across all methods, and the `popv_agreement` score quantifies how many methods agree. This ensemble strategy is robust to individual method failures on unusual datasets and provides a principled uncertainty estimate: low agreement highlights novel cell states or annotation gaps.\n\n## When to Use\n\n- Annotating a query dataset by transferring labels from a well-curated reference atlas when you want a consensus rather than a single model's judgment\n- Identifying novel or ambiguous cell states as cells where methods disagree (low `popv_agreement` score)\n- Benchmarking annotation reliability by comparing per-method labels to detect systematic disagreements\n- Annotating large atlas datasets (>100k cells) where batch effects between reference and query are substantial\n- Producing annotation for downstream analyses that require high-confidence labels (clinical data, regulatory submissions)\n- Use **omics-plotting** SKILL for confidence bar charts and method-agreement heatmaps from exported tables (UMAPs stay in scanpy `sc.pl.*`)\n- Use **CellTypist** (celltypist-cell-annotation) instead when speed matters and a pre-trained model matches your tissue; popV is slower because it trains multiple models on your reference\n- Use **scANVI** (scvi-tools-single-cell) instead when you need a single probabilistic deep generative model with formal uncertainty quantification and do not require the ensemble\n\n## Prerequisites\n\n- **Python packages**: `popv>=0.6`, `scanpy>=1.9`, `anndata`, `scvi-tools>=1.0`, `harmonypy`, `bbknn`, `celltypist`\n- **Data requirements**: Two AnnData objects — a labeled reference (`adata_ref`) with cell type labels in `obs`, and an unlabeled query (`adata_query`). Both must be from the same species and have overlapping gene sets. Raw counts in `adata.X` (popV applies its own normalization internally)\n- **Environment**: Python 3.9+; GPU recommended for scVI\u002FSCANVI methods (falls back to CPU); 32 GB RAM recommended for >200k reference cells\n\n```bash\npip install popv scvi-tools harmonypy bbknn celltypist\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: annotationStrategy\n    kind: required\n    source: user\n    ask: \"Name cell types from canonical markers by hand over the clusters, transfer them from an annotated reference by ensemble consensus, or do both and compare the two?\"\n    default: \"ensemble transfer, then confirm against markers\"\n\n  - id: D2\n    param: tissueContext\n    kind: required\n    source: user\n    ask: \"Which tissue is this, and in what state - healthy adult, fetal or developmental, diseased, or perturbed?\"\n    default: null\n\n  - id: D3\n    param: referenceAtlas\n    kind: required\n    source: literature\n    depends_on: [D2]\n    ask: \"Which annotated reference matches that tissue AND that state?\"\n    default: null\n\n  - id: D4\n    param: referenceLabelColumn\n    kind: required\n    source: data\n    depends_on: [D3]\n    ask: \"Which column of the reference holds the cell type labels, and at what granularity?\"\n    default: null\n\n  - id: D5\n    param: markerValidation\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Should the consensus labels be checked against canonical marker expression before they are accepted?\"\n    default: \"checked - method agreement measures consistency, not correctness\"\n\n  - id: D6\n    param: validationMarkerPanel\n    kind: required\n    source: literature\n    depends_on: [D2, D5]\n    ask: \"Which canonical markers should the consensus types be confirmed against?\"\n    default: null\n    skip_if: \"marker validation declined\"\n\n  - id: D7\n    param: consensusThreshold\n    kind: required\n    source: user\n    ask: \"How many of the annotation methods must agree before a label is trusted?\"\n    default: \"80% agreement\"\n\n  - id: D8\n    param: methodSubset\n    kind: required\n    source: user\n    ask: \"Run the full method panel, or drop the slow model-based ones?\"\n    default: \"all methods\"\n\n  - id: D9\n    param: variableGeneCount\n    kind: optional\n    source: user\n    ask: \"How many variable genes should the embedding and nearest-neighbour methods use?\"\n    default: 4000\n\n  - id: D10\n    param: trainingEpochs\n    kind: optional_conditional\n    source: data\n    depends_on: [D8]\n    ask: \"Do the model-based methods need longer training for a large or complex query?\"\n    default: \"50 unsupervised, 20 semi-supervised\"\n    skip_if: \"model-based methods excluded\"\n\n  - id: D11\n    param: gpuUse\n    kind: never_ask\n    source: data\n    reason: \"Falls back to CPU automatically; affects runtime only\"\n    default: true\n```\n\nD1 is asked even though the user has arrived at an ensemble annotator, because\nthe alternative is not visible from here: manual marker naming and reference\ntransfer fail in opposite directions. If the answer is manual only, this skill\nis not the tool — see `cell-type-annotation`.\n\nD5 matters more here than it looks. The agreement score in D7 measures whether\nthe methods concur, not whether they are right — several methods sharing one\nunsuitable reference agree with each other confidently. Markers are the only\noutside check. D4 sets the granularity of every downstream comparison: a\nreference labelled at lineage level cannot produce subtype calls.\n\n## Quick Start\n\nMinimal pipeline from labeled reference and unlabeled query to annotated result:\n\n```python\nimport popv\nimport scanpy as sc\n\n# Load reference (labeled) and query (unlabeled) AnnData objects\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")  # adata_ref.obs[\"cell_type\"] exists\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")\n\n# Prepare combined object with popV preprocessing\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=50,\n)\n\n# Run all annotation methods\npopv.annotation.annotate_data(adata)\n\n# Inspect consensus results for query cells\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nprint(adata[query_mask].obs[[\"popv_prediction\", \"popv_agreement\"]].head(10))\n```\n\n## Core API\n\n### Module 1: Reference and Query Data Setup\n\nBoth AnnData objects must share a gene space and have required metadata columns. popV will subset to the intersection of genes automatically.\n\n```python\nimport anndata as ad\nimport scanpy as sc\nimport numpy as np\n\n# Reference: must have cell type labels and (optionally) batch metadata\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")\nprint(f\"Reference: {adata_ref.n_obs} cells x {adata_ref.n_vars} genes\")\nprint(f\"Cell types: {adata_ref.obs['cell_type'].nunique()} unique labels\")\nprint(f\"Reference cell type counts:\\n{adata_ref.obs['cell_type'].value_counts().head(10)}\")\n\n# Query: no labels required; batch metadata optional\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")\nprint(f\"\\nQuery: {adata_query.n_obs} cells x {adata_query.n_vars} genes\")\n\n# Check gene overlap (popV will handle subsetting but >70% overlap is recommended)\nshared_genes = adata_ref.var_names.intersection(adata_query.var_names)\npct_shared = len(shared_genes) \u002F adata_ref.n_vars\nprint(f\"\\nShared genes: {len(shared_genes)} ({pct_shared:.1%} of reference genes)\")\nif pct_shared \u003C 0.5:\n    print(\"WARNING: \u003C50% gene overlap — annotation quality may be reduced\")\n```\n\n```python\n# Verify required fields before popV setup\nassert \"cell_type\" in adata_ref.obs.columns, \"Reference needs cell type labels\"\n\n# Add batch column if absent (popV requires it even for single-batch data)\nif \"batch\" not in adata_ref.obs.columns:\n    adata_ref.obs[\"batch\"] = \"ref_batch\"\nif \"batch\" not in adata_query.obs.columns:\n    adata_query.obs[\"batch\"] = \"query_batch\"\n\nprint(\"Reference obs columns:\", adata_ref.obs.columns.tolist())\nprint(\"Query obs columns:    \", adata_query.obs.columns.tolist())\n```\n\n### Module 2: POPV Object Creation (Process_Query)\n\n`Process_Query` combines reference and query, normalizes counts, selects HVGs, and prepares the joint embedding needed by all annotation methods.\n\n```python\nimport popv\n\n# Create processed combined AnnData\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",      # obs column with reference labels\n    ref_batch_key=\"batch\",           # obs column with reference batch info\n    query_batch_key=\"batch\",         # obs column with query batch info\n    unknown_celltype_label=\"unknown\",# label to use for query cells before annotation\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",  # directory for scVI\u002FSCANVI model checkpoints\n    n_epochs_unsupervised=50,        # scVI training epochs (increase to 100–200 for large datasets)\n    n_epochs_semisupervised=20,      # scANVI fine-tuning epochs\n    use_gpu=True,                    # GPU for scVI\u002FSCANVI (falls back to CPU if unavailable)\n    hvg=4000,                        # number of highly variable genes to use\n)\n\nprint(f\"Combined object: {adata.n_obs} cells x {adata.n_vars} genes\")\nprint(f\"Dataset labels: {adata.obs['_dataset'].value_counts().to_dict()}\")\n# Expected: {'ref': N_ref, 'query': N_query}\n```\n\n### Module 3: Running the Method Ensemble\n\n`annotate_data` runs all selected methods sequentially and adds per-method label columns plus the consensus to `adata.obs`.\n\n```python\nimport popv\n\n# Run annotation with default set of methods\npopv.annotation.annotate_data(\n    adata,\n    methods=[\n        \"knn_harmony\",    # KNN on Harmony-corrected embedding\n        \"knn_bbknn\",      # KNN on BBKNN cross-batch graph\n        \"knn_scvi\",       # KNN on scVI latent space\n        \"scanvi_popv\",    # Semi-supervised scANVI label transfer\n        \"celltypist_popv\",# CellTypist logistic regression\n        \"rf\",             # Random Forest on HVG expression\n        \"xgboost\",        # XGBoost classifier\n        \"svm\",            # Support Vector Machine\n        \"onclass\",        # ONCLASS (ontology-guided)\n    ],\n)\n\n# Inspect per-method result columns (all end in \"_popv\")\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\npopv_cols = adata.obs.filter(like=\"_popv\").columns.tolist()\nprint(f\"Per-method columns: {popv_cols}\")\nprint(adata[query_mask].obs[popv_cols + [\"popv_prediction\", \"popv_agreement\"]].head(10))\n```\n\n### Module 4: Consensus Results and Agreement Scoring\n\n`popv_prediction` is the majority-vote consensus; `popv_agreement` is the fraction of methods that agreed on the winning label.\n\n```python\nimport pandas as pd\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Consensus label distribution\nprint(\"Consensus cell type distribution:\")\nprint(query_obs[\"popv_prediction\"].value_counts().head(15))\n\n# Agreement score statistics\nprint(f\"\\npopv_agreement statistics:\")\nprint(query_obs[\"popv_agreement\"].describe())\n# agreement = 1.0 → all methods agree; agreement = 0.2 → only 2\u002F10 methods agree\n\n# Cells with high confidence (>80% method agreement)\nhigh_conf = query_obs[\"popv_agreement\"] >= 0.8\nprint(f\"\\nHigh-confidence cells (agreement >= 0.8): {high_conf.sum()} ({high_conf.mean():.1%})\")\n\n# Cells with low confidence — candidate novel states or annotation gaps\nlow_conf = query_obs[\"popv_agreement\"] \u003C 0.5\nprint(f\"Low-confidence cells  (agreement \u003C  0.5): {low_conf.sum()} ({low_conf.mean():.1%})\")\n```\n\n### Module 5: Visualization\n\npopV provides built-in UMAP and heatmap visualization of per-method agreement and consensus labels.\n\n```python\nimport popv\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\n# Compute UMAP on the joint reference+query embedding (if not already present)\nif \"X_umap\" not in adata.obsm:\n    sc.tl.umap(adata)\n\n# popV built-in visualization: UMAP panel showing consensus + agreement\npopv.visualization.predict_celltypes_umap(\n    adata,\n    save=\"popv_annotation_umap.png\",\n)\nprint(\"Saved popv_annotation_umap.png\")\n\n# Custom UMAP panels\nfig, axes = plt.subplots(1, 3, figsize=(21, 6))\nsc.pl.umap(adata, color=\"popv_prediction\", ax=axes[0],\n           title=\"popV Consensus\", legend_loc=\"on data\",\n           legend_fontsize=6, show=False)\nsc.pl.umap(adata, color=\"popv_agreement\", ax=axes[1],\n           cmap=\"RdYlGn\", vmin=0, vmax=1,\n           title=\"Method Agreement Score\", show=False)\nsc.pl.umap(adata, color=\"_dataset\", ax=axes[2],\n           title=\"Reference vs Query\", show=False)\nplt.tight_layout()\nplt.savefig(\"popv_custom_umap.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved popv_custom_umap.png\")\n```\n\n## Key Concepts\n\n### Method Ensemble and Majority Voting\n\npopV runs each method independently; the final prediction is determined by plurality vote across all methods. The `popv_agreement` score equals the fraction of methods that voted for the winning label (e.g., 0.7 = 7\u002F10 methods agreed). This design has several properties:\n\n- **Robustness**: if one method fails or produces outlier labels, the consensus is unaffected if the remaining methods agree\n- **Uncertainty signal**: low agreement does not mean the annotation is wrong — it often flags biologically interesting cells (transitional states, rare populations) that differ from all reference cell types\n- **Method independence**: KNN-based methods depend on the embedding quality; tree-based methods (RF, XGBoost) work directly on expression; SVM works in feature space; CellTypist uses a separate logistic regression. Together they span multiple algorithmic families\n\n### Method Comparison\n\n| Method | Batch Correction | Speed | Best For |\n|--------|-----------------|-------|---------|\n| `knn_harmony` | Harmony | Fast | Moderate batch effects, large datasets |\n| `knn_bbknn` | BBKNN | Fast | Diverse multi-tissue references |\n| `knn_scanorama` | Scanorama | Fast | Multiple heterogeneous batches |\n| `knn_scvi` | scVI VAE | Medium | Complex batch effects, probabilistic embedding |\n| `scanvi_popv` | scVI+labels | Slow | Semi-supervised; most accurate when reference is clean |\n| `celltypist_popv` | None (logistic) | Fast | Immune cells; works well without batch correction |\n| `rf` | None | Medium | Balanced class distributions; interpretable feature importance |\n| `xgboost` | None | Medium | High-confidence predictions on well-separated cell types |\n| `svm` | None | Medium | High-dimensional gene expression; linear boundaries |\n| `onclass` | None | Medium | Ontology-aware; handles unseen cell types via CL ontology |\n\n### ONCLASS and Ontology-Aware Annotation\n\nONCLASS uses the Cell Ontology (CL) to represent cell types as nodes in a knowledge graph and predict unseen cell types by propagating similarity through the ontology. Unlike other methods, ONCLASS can predict a cell type that was not present in the training reference if it is ontologically adjacent to known types. Enable it by including `\"onclass\"` in the methods list.\n\n### Reference Quality Requirements\n\npopV annotation quality scales directly with reference quality:\n\n- **Minimum cell count per type**: 50–100 cells per label; rare types with \u003C20 cells may be missed by KNN methods\n- **Balanced representation**: highly imbalanced references (one type is 80% of cells) cause tree methods to be biased toward the majority class\n- **Label granularity**: coarse labels (10 types) annotate reliably; fine-grained labels (100+ types) require a larger, matched reference\n\n## Common Workflows\n\n### Workflow 1: Standard Reference-Query Annotation\n\n**Goal**: Annotate an unlabeled query dataset using a curated reference atlas end-to-end.\n\n```python\nimport popv\nimport scanpy as sc\nimport pandas as pd\n\n# 1. Load data\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")   # has obs[\"cell_type\"] and obs[\"batch\"]\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")   # no cell type labels\nif \"batch\" not in adata_query.obs.columns:\n    adata_query.obs[\"batch\"] = \"query\"\n\n# 2. Preprocess: build joint normalized object\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=100,\n    n_epochs_semisupervised=30,\n    use_gpu=True,\n    hvg=4000,\n)\nprint(f\"Prepared: {adata.n_obs} total cells\")\n\n# 3. Run ensemble annotation\npopv.annotation.annotate_data(adata)\n\n# 4. Extract query results\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_annotations = adata[query_mask].obs[[\n    \"popv_prediction\", \"popv_agreement\",\n    \"knn_harmony_popv\", \"scanvi_popv\", \"rf_popv\", \"xgboost_popv\"\n]].copy()\n\n# 5. Transfer back to original query object\nadata_query.obs = adata_query.obs.join(\n    query_annotations, how=\"left\"\n)\nprint(f\"Annotated {query_mask.sum()} query cells\")\nprint(query_annotations[\"popv_prediction\"].value_counts().head(10))\n\n# 6. Save annotated query\nadata_query.write_h5ad(\"annotated_query.h5ad\", compression=\"gzip\")\nquery_annotations.to_csv(\"popv_annotations.csv\")\nprint(\"Saved annotated_query.h5ad and popv_annotations.csv\")\n```\n\n### Workflow 2: Confidence Filtering and Novel Cell State Detection\n\n**Goal**: Separate high-confidence annotations from ambiguous cells; flag candidate novel or transitional states for manual review.\n\n```python\nimport popv\nimport scanpy as sc\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Assume adata has been annotated (as in Workflow 1)\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Tier cells by agreement score\nbins = [0.0, 0.5, 0.8, 1.01]\nlabels = [\"low (\u003C0.5)\", \"medium (0.5–0.8)\", \"high (≥0.8)\"]\nquery_obs[\"confidence_tier\"] = pd.cut(\n    query_obs[\"popv_agreement\"], bins=bins, labels=labels, right=False\n)\nprint(\"Cells per confidence tier:\")\nprint(query_obs[\"confidence_tier\"].value_counts())\n\n# High-confidence subset: use popv_prediction directly\nhigh_conf_mask = query_obs[\"popv_agreement\"] >= 0.8\nprint(f\"\\nHigh-confidence annotations ({high_conf_mask.mean():.1%} of query cells):\")\nprint(query_obs[high_conf_mask][\"popv_prediction\"].value_counts().head(10))\n\n# Low-confidence subset: inspect per-method disagreement\nlow_conf = query_obs[query_obs[\"popv_agreement\"] \u003C 0.5]\npopv_method_cols = [c for c in query_obs.columns if c.endswith(\"_popv\") and\n                    c not in (\"popv_prediction\", \"popv_agreement\")]\nprint(f\"\\nLow-confidence cells sample (showing per-method labels):\")\nprint(low_conf[popv_method_cols + [\"popv_prediction\"]].head(10).to_string())\n\n# Save agreement + confidence-tier summaries; render the tier bar chart with the omics-plotting\n# SKILL (skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md) \"Box \u002F Violin \u002F Bar\" recipe -> figures\u002Fpopv_confidence_distribution.png\nquery_obs[[\"popv_agreement\", \"confidence_tier\"]].to_csv(\"popv_confidence.csv\")\nprint(query_obs[\"confidence_tier\"].value_counts().to_string())\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `ref_labels_key` | Process_Query | — | Any `obs` column | Column in `adata_ref.obs` containing training cell type labels |\n| `n_epochs_unsupervised` | Process_Query | `50` | `20`–`500` | scVI training epochs; increase for better embedding on large\u002Fcomplex datasets |\n| `n_epochs_semisupervised` | Process_Query | `20` | `10`–`100` | scANVI fine-tuning epochs on top of scVI |\n| `hvg` | Process_Query | `4000` | `2000`–`8000` | Highly variable genes used for embedding and KNN methods |\n| `use_gpu` | Process_Query | `True` | `True`, `False` | GPU acceleration for scVI\u002FSCANVI; falls back to CPU automatically if no GPU |\n| `methods` | annotate_data | all | List of method names | Subset of methods to run; excluding slow methods (scanvi, onclass) speeds up pipeline |\n| `unknown_celltype_label` | Process_Query | `\"unknown\"` | Any string | Label assigned to query cells before annotation; used to separate reference labels from query |\n| `popv_agreement` | (output) | — | `0.0`–`1.0` | Fraction of methods agreeing on consensus label; `>=0.8` recommended for high confidence |\n\n## Best Practices\n\n1. **Check gene overlap before running**: popV performs best with >70% gene overlap between reference and query. If overlap is \u003C50%, annotation quality degrades significantly — consider using a different reference or imputing missing genes.\n   ```python\n   shared = adata_ref.var_names.intersection(adata_query.var_names)\n   print(f\"Gene overlap: {len(shared) \u002F adata_ref.n_vars:.1%}\")\n   ```\n\n2. **Use raw counts as input**: pass raw (un-normalized) counts in `adata.X` to `Process_Query`. popV internally applies its own normalization. Pre-normalized data can distort the scVI\u002FSCANVI latent space.\n\n3. **Match reference granularity to query biology**: if your query contains subtypes not in the reference, no method will correctly assign them — they will appear as low-agreement cells. Either add them to the reference or accept that the consensus will assign the nearest parent type.\n\n4. **Exclude slow methods when speed matters**: `scanvi_popv` and `onclass` are the slowest. For a quick first-pass, run only `knn_harmony`, `knn_bbknn`, `rf`, `xgboost`, and `celltypist_popv`.\n   ```python\n   popv.annotation.annotate_data(adata, methods=[\"knn_harmony\", \"knn_bbknn\", \"rf\", \"xgboost\", \"celltypist_popv\"])\n   ```\n\n5. **Save trained models for repeated queries**: `Process_Query` stores scVI\u002FSCANVI models in `save_path_trained_models`. Reuse these when annotating additional query batches against the same reference to avoid retraining.\n\n## Common Recipes\n\n### Recipe: Subset to High-Confidence Annotations Only\n\nWhen to use: downstream analyses (DE, trajectory) require clean labels; exclude ambiguous cells.\n\n```python\nimport scanpy as sc\n\n# Annotate as in Workflow 1 first\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nadata_query_annotated = adata[query_mask].copy()\n\n# Keep only high-confidence cells\nhigh_conf = adata_query_annotated[adata_query_annotated.obs[\"popv_agreement\"] >= 0.8].copy()\nprint(f\"High-confidence cells: {high_conf.n_obs} \u002F {adata_query_annotated.n_obs} \"\n      f\"({high_conf.n_obs\u002Fadata_query_annotated.n_obs:.1%})\")\nprint(high_conf.obs[\"popv_prediction\"].value_counts())\n\n# Recompute UMAP on high-confidence subset for visualization\nsc.pp.neighbors(high_conf, use_rep=\"X_scVI\")  # use scVI embedding stored by popV\nsc.tl.umap(high_conf)\nsc.pl.umap(high_conf, color=\"popv_prediction\", save=\"_high_conf_celltypes.png\")\n```\n\n### Recipe: Per-Method Label Comparison Heatmap\n\nWhen to use: understanding where methods disagree to identify systematic biases or novel populations.\n\n```python\nimport pandas as pd\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Collect per-method columns\nmethod_cols = [c for c in query_obs.columns\n               if c.endswith(\"_popv\") and c not in (\"popv_prediction\", \"popv_agreement\")]\n\n# Cross-tabulate two key methods\nct = pd.crosstab(\n    query_obs[\"knn_harmony_popv\"],\n    query_obs[\"scanvi_popv\"],\n    margins=False,\n)\n# Normalize rows\nct_norm = ct.div(ct.sum(axis=1), axis=0)\nct_norm.to_csv(\"popv_method_agreement.csv\")\nprint(f\"Method agreement matrix: {ct_norm.shape} -> popv_method_agreement.csv\")\n# Render with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`) \"Expression heatmap\" recipe (Blues, 0..1)\n# -> figures\u002Fpopv_method_agreement_heatmap.png\n```\n\n### Recipe: Fast Annotation Without Deep Learning Methods\n\nWhen to use: quick annotation without GPU or when scVI\u002FSCANVI training is prohibitively slow (>500k cells).\n\n```python\nimport popv\n\n# Process without training deep generative models (scVI not needed for KNN-Harmony)\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=0,   # skip scVI training\n    n_epochs_semisupervised=0, # skip scANVI training\n    use_gpu=False,\n    hvg=3000,\n)\n\n# Run only fast non-DL methods\npopv.annotation.annotate_data(\n    adata,\n    methods=[\"knn_harmony\", \"knn_bbknn\", \"knn_scanorama\", \"rf\", \"xgboost\", \"svm\", \"celltypist_popv\"],\n)\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nprint(adata[query_mask].obs[[\"popv_prediction\", \"popv_agreement\"]].describe())\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `KeyError: ref_labels_key not in adata_ref.obs` | Reference lacks a cell type column | Verify the column name: `print(adata_ref.obs.columns.tolist())`; update `ref_labels_key` accordingly |\n| Gene space mismatch error | Reference and query have very few shared genes | Check `adata_ref.var_names.intersection(adata_query.var_names)`; if \u003C50% overlap, use a different reference or match gene panels |\n| CUDA out-of-memory for scVI\u002FSCANVI | GPU VRAM insufficient for batch size | Set `use_gpu=False` or reduce `n_epochs_unsupervised`; scVI falls back to CPU automatically on most systems |\n| `onclass_popv` failures on small datasets | ONCLASS requires sufficient label coverage | Remove `\"onclass\"` from the methods list when reference has \u003C10 cell types or \u003C500 cells per type |\n| Very slow annotation (>2 hours) | scVI\u002FSCANVI training on large reference | Subsample reference to 50k cells per type; exclude `\"scanvi_popv\"` and `\"onclass\"` from methods |\n| All cells receive same consensus label | Reference highly imbalanced toward one type | Balance reference by subsampling the dominant type or upsampling rare types before running popV |\n| `popv_agreement` is 0 for many cells | Many methods returning different labels | Inspect per-method columns; consider whether reference covers the query biology; add methods or retrain with a better reference |\n\n## Related Skills\n\n- **celltypist-cell-annotation** — single-model annotation with pre-trained logistic regression; faster but lacks ensemble uncertainty\n- **scanpy-scrna-seq** — preprocessing pipeline (QC, normalization, clustering) that produces AnnData inputs for popV\n- **scvi-tools-single-cell** — scANVI for probabilistic label transfer with a single deep generative model; use when you prefer a formal variational framework over ensemble voting\n- **harmony-batch-correction** — Harmony embedding used by `knn_harmony` method internally; understand it to tune popV's KNN-based methods\n\n## References\n\n- [GitHub: YosefLab\u002FpopV](https:\u002F\u002Fgithub.com\u002FYosefLab\u002FpopV) — official source code, installation instructions, and example notebooks\n- [popV documentation](https:\u002F\u002Fpopv.readthedocs.io\u002F) — API reference and tutorials\n- [Ergen et al., bioRxiv 2023](https:\u002F\u002Fdoi.org\u002F10.1101\u002F2023.06.15.545239) — \"Population-level integration of single-cell datasets enables multi-scale analysis across samples\", original popV preprint\n- [ONCLASS paper — Wang et al., Nature Methods 2021](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01080-9) — ontology-aware cell type classification underlying the ONCLASS method in popV\n","# popV Multi-Method Cell Type Transfer\n\n## Overview\n\npopV (Population Voting for single-cell annotation) annotates a query scRNA-seq dataset by running 10+ independent classification algorithms against a labeled reference atlas and aggregating results via majority voting. Each method produces its own label; the final `popv_prediction` is the consensus across all methods, and the `popv_agreement` score quantifies how many methods agree. This ensemble strategy is robust to individual method failures on unusual datasets and provides a principled uncertainty estimate: low agreement highlights novel cell states or annotation gaps.\n\n## When to Use\n\n- Annotating a query dataset by transferring labels from a well-curated reference atlas when you want a consensus rather than a single model's judgment\n- Identifying novel or ambiguous cell states as cells where methods disagree (low `popv_agreement` score)\n- Benchmarking annotation reliability by comparing per-method labels to detect systematic disagreements\n- Annotating large atlas datasets (>100k cells) where batch effects between reference and query are substantial\n- Producing annotation for downstream analyses that require high-confidence labels (clinical data, regulatory submissions)\n- Use **omics-plotting** SKILL for confidence bar charts and method-agreement heatmaps from exported tables (UMAPs stay in scanpy `sc.pl.*`)\n- Use **CellTypist** (celltypist-cell-annotation) instead when speed matters and a pre-trained model matches your tissue; popV is slower because it trains multiple models on your reference\n- Use **scANVI** (scvi-tools-single-cell) instead when you need a single probabilistic deep generative model with formal uncertainty quantification and do not require the ensemble\n\n## Prerequisites\n\n- **Python packages**: `popv>=0.6`, `scanpy>=1.9`, `anndata`, `scvi-tools>=1.0`, `harmonypy`, `bbknn`, `celltypist`\n- **Data requirements**: Two AnnData objects — a labeled reference (`adata_ref`) with cell type labels in `obs`, and an unlabeled query (`adata_query`). Both must be from the same species and have overlapping gene sets. Raw counts in `adata.X` (popV applies its own normalization internally)\n- **Environment**: Python 3.9+; GPU recommended for scVI\u002FSCANVI methods (falls back to CPU); 32 GB RAM recommended for >200k reference cells\n\n```bash\npip install popv scvi-tools harmonypy bbknn celltypist\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: annotationStrategy\n    kind: required\n    source: user\n    ask: \"Name cell types from canonical markers by hand over the clusters, transfer them from an annotated reference by ensemble consensus, or do both and compare the two?\"\n    default: \"ensemble transfer, then confirm against markers\"\n\n  - id: D2\n    param: tissueContext\n    kind: required\n    source: user\n    ask: \"Which tissue is this, and in what state - healthy adult, fetal or developmental, diseased, or perturbed?\"\n    default: null\n\n  - id: D3\n    param: referenceAtlas\n    kind: required\n    source: literature\n    depends_on: [D2]\n    ask: \"Which annotated reference matches that tissue AND that state?\"\n    default: null\n\n  - id: D4\n    param: referenceLabelColumn\n    kind: required\n    source: data\n    depends_on: [D3]\n    ask: \"Which column of the reference holds the cell type labels, and at what granularity?\"\n    default: null\n\n  - id: D5\n    param: markerValidation\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Should the consensus labels be checked against canonical marker expression before they are accepted?\"\n    default: \"checked - method agreement measures consistency, not correctness\"\n\n  - id: D6\n    param: validationMarkerPanel\n    kind: required\n    source: literature\n    depends_on: [D2, D5]\n    ask: \"Which canonical markers should the consensus types be confirmed against?\"\n    default: null\n    skip_if: \"marker validation declined\"\n\n  - id: D7\n    param: consensusThreshold\n    kind: required\n    source: user\n    ask: \"How many of the annotation methods must agree before a label is trusted?\"\n    default: \"80% agreement\"\n\n  - id: D8\n    param: methodSubset\n    kind: required\n    source: user\n    ask: \"Run the full method panel, or drop the slow model-based ones?\"\n    default: \"all methods\"\n\n  - id: D9\n    param: variableGeneCount\n    kind: optional\n    source: user\n    ask: \"How many variable genes should the embedding and nearest-neighbour methods use?\"\n    default: 4000\n\n  - id: D10\n    param: trainingEpochs\n    kind: optional_conditional\n    source: data\n    depends_on: [D8]\n    ask: \"Do the model-based methods need longer training for a large or complex query?\"\n    default: \"50 unsupervised, 20 semi-supervised\"\n    skip_if: \"model-based methods excluded\"\n\n  - id: D11\n    param: gpuUse\n    kind: never_ask\n    source: data\n    reason: \"Falls back to CPU automatically; affects runtime only\"\n    default: true\n```\n\nD1 is asked even though the user has arrived at an ensemble annotator, because\nthe alternative is not visible from here: manual marker naming and reference\ntransfer fail in opposite directions. If the answer is manual only, this skill\nis not the tool — see `cell-type-annotation`.\n\nD5 matters more here than it looks. The agreement score in D7 measures whether\nthe methods concur, not whether they are right — several methods sharing one\nunsuitable reference agree with each other confidently. Markers are the only\noutside check. D4 sets the granularity of every downstream comparison: a\nreference labelled at lineage level cannot produce subtype calls.\n\n## Quick Start\n\nMinimal pipeline from labeled reference and unlabeled query to annotated result:\n\n```python\nimport popv\nimport scanpy as sc\n\n# Load reference (labeled) and query (unlabeled) AnnData objects\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")  # adata_ref.obs[\"cell_type\"] exists\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")\n\n# Prepare combined object with popV preprocessing\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=50,\n)\n\n# Run all annotation methods\npopv.annotation.annotate_data(adata)\n\n# Inspect consensus results for query cells\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nprint(adata[query_mask].obs[[\"popv_prediction\", \"popv_agreement\"]].head(10))\n```\n\n## Core API\n\n### Module 1: Reference and Query Data Setup\n\nBoth AnnData objects must share a gene space and have required metadata columns. popV will subset to the intersection of genes automatically.\n\n```python\nimport anndata as ad\nimport scanpy as sc\nimport numpy as np\n\n# Reference: must have cell type labels and (optionally) batch metadata\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")\nprint(f\"Reference: {adata_ref.n_obs} cells x {adata_ref.n_vars} genes\")\nprint(f\"Cell types: {adata_ref.obs['cell_type'].nunique()} unique labels\")\nprint(f\"Reference cell type counts:\\n{adata_ref.obs['cell_type'].value_counts().head(10)}\")\n\n# Query: no labels required; batch metadata optional\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")\nprint(f\"\\nQuery: {adata_query.n_obs} cells x {adata_query.n_vars} genes\")\n\n# Check gene overlap (popV will handle subsetting but >70% overlap is recommended)\nshared_genes = adata_ref.var_names.intersection(adata_query.var_names)\npct_shared = len(shared_genes) \u002F adata_ref.n_vars\nprint(f\"\\nShared genes: {len(shared_genes)} ({pct_shared:.1%} of reference genes)\")\nif pct_shared \u003C 0.5:\n    print(\"WARNING: \u003C50% gene overlap — annotation quality may be reduced\")\n```\n\n```python\n# Verify required fields before popV setup\nassert \"cell_type\" in adata_ref.obs.columns, \"Reference needs cell type labels\"\n\n# Add batch column if absent (popV requires it even for single-batch data)\nif \"batch\" not in adata_ref.obs.columns:\n    adata_ref.obs[\"batch\"] = \"ref_batch\"\nif \"batch\" not in adata_query.obs.columns:\n    adata_query.obs[\"batch\"] = \"query_batch\"\n\nprint(\"Reference obs columns:\", adata_ref.obs.columns.tolist())\nprint(\"Query obs columns:    \", adata_query.obs.columns.tolist())\n```\n\n### Module 2: POPV Object Creation (Process_Query)\n\n`Process_Query` combines reference and query, normalizes counts, selects HVGs, and prepares the joint embedding needed by all annotation methods.\n\n```python\nimport popv\n\n# Create processed combined AnnData\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",      # obs column with reference labels\n    ref_batch_key=\"batch\",           # obs column with reference batch info\n    query_batch_key=\"batch\",         # obs column with query batch info\n    unknown_celltype_label=\"unknown\",# label to use for query cells before annotation\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",  # directory for scVI\u002FSCANVI model checkpoints\n    n_epochs_unsupervised=50,        # scVI training epochs (increase to 100–200 for large datasets)\n    n_epochs_semisupervised=20,      # scANVI fine-tuning epochs\n    use_gpu=True,                    # GPU for scVI\u002FSCANVI (falls back to CPU if unavailable)\n    hvg=4000,                        # number of highly variable genes to use\n)\n\nprint(f\"Combined object: {adata.n_obs} cells x {adata.n_vars} genes\")\nprint(f\"Dataset labels: {adata.obs['_dataset'].value_counts().to_dict()}\")\n# Expected: {'ref': N_ref, 'query': N_query}\n```\n\n### Module 3: Running the Method Ensemble\n\n`annotate_data` runs all selected methods sequentially and adds per-method label columns plus the consensus to `adata.obs`.\n\n```python\nimport popv\n\n# Run annotation with default set of methods\npopv.annotation.annotate_data(\n    adata,\n    methods=[\n        \"knn_harmony\",    # KNN on Harmony-corrected embedding\n        \"knn_bbknn\",      # KNN on BBKNN cross-batch graph\n        \"knn_scvi\",       # KNN on scVI latent space\n        \"scanvi_popv\",    # Semi-supervised scANVI label transfer\n        \"celltypist_popv\",# CellTypist logistic regression\n        \"rf\",             # Random Forest on HVG expression\n        \"xgboost\",        # XGBoost classifier\n        \"svm\",            # Support Vector Machine\n        \"onclass\",        # ONCLASS (ontology-guided)\n    ],\n)\n\n# Inspect per-method result columns (all end in \"_popv\")\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\npopv_cols = adata.obs.filter(like=\"_popv\").columns.tolist()\nprint(f\"Per-method columns: {popv_cols}\")\nprint(adata[query_mask].obs[popv_cols + [\"popv_prediction\", \"popv_agreement\"]].head(10))\n```\n\n### Module 4: Consensus Results and Agreement Scoring\n\n`popv_prediction` is the majority-vote consensus; `popv_agreement` is the fraction of methods that agreed on the winning label.\n\n```python\nimport pandas as pd\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Consensus label distribution\nprint(\"Consensus cell type distribution:\")\nprint(query_obs[\"popv_prediction\"].value_counts().head(15))\n\n# Agreement score statistics\nprint(f\"\\npopv_agreement statistics:\")\nprint(query_obs[\"popv_agreement\"].describe())\n# agreement = 1.0 → all methods agree; agreement = 0.2 → only 2\u002F10 methods agree\n\n# Cells with high confidence (>80% method agreement)\nhigh_conf = query_obs[\"popv_agreement\"] >= 0.8\nprint(f\"\\nHigh-confidence cells (agreement >= 0.8): {high_conf.sum()} ({high_conf.mean():.1%})\")\n\n# Cells with low confidence — candidate novel states or annotation gaps\nlow_conf = query_obs[\"popv_agreement\"] \u003C 0.5\nprint(f\"Low-confidence cells  (agreement \u003C  0.5): {low_conf.sum()} ({low_conf.mean():.1%})\")\n```\n\n### Module 5: Visualization\n\npopV provides built-in UMAP and heatmap visualization of per-method agreement and consensus labels.\n\n```python\nimport popv\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\n# Compute UMAP on the joint reference+query embedding (if not already present)\nif \"X_umap\" not in adata.obsm:\n    sc.tl.umap(adata)\n\n# popV built-in visualization: UMAP panel showing consensus + agreement\npopv.visualization.predict_celltypes_umap(\n    adata,\n    save=\"popv_annotation_umap.png\",\n)\nprint(\"Saved popv_annotation_umap.png\")\n\n# Custom UMAP panels\nfig, axes = plt.subplots(1, 3, figsize=(21, 6))\nsc.pl.umap(adata, color=\"popv_prediction\", ax=axes[0],\n           title=\"popV Consensus\", legend_loc=\"on data\",\n           legend_fontsize=6, show=False)\nsc.pl.umap(adata, color=\"popv_agreement\", ax=axes[1],\n           cmap=\"RdYlGn\", vmin=0, vmax=1,\n           title=\"Method Agreement Score\", show=False)\nsc.pl.umap(adata, color=\"_dataset\", ax=axes[2],\n           title=\"Reference vs Query\", show=False)\nplt.tight_layout()\nplt.savefig(\"popv_custom_umap.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved popv_custom_umap.png\")\n```\n\n## Key Concepts\n\n### Method Ensemble and Majority Voting\n\npopV runs each method independently; the final prediction is determined by plurality vote across all methods. The `popv_agreement` score equals the fraction of methods that voted for the winning label (e.g., 0.7 = 7\u002F10 methods agreed). This design has several properties:\n\n- **Robustness**: if one method fails or produces outlier labels, the consensus is unaffected if the remaining methods agree\n- **Uncertainty signal**: low agreement does not mean the annotation is wrong — it often flags biologically interesting cells (transitional states, rare populations) that differ from all reference cell types\n- **Method independence**: KNN-based methods depend on the embedding quality; tree-based methods (RF, XGBoost) work directly on expression; SVM works in feature space; CellTypist uses a separate logistic regression. Together they span multiple algorithmic families\n\n### Method Comparison\n\n| Method | Batch Correction | Speed | Best For |\n|--------|-----------------|-------|---------|\n| `knn_harmony` | Harmony | Fast | Moderate batch effects, large datasets |\n| `knn_bbknn` | BBKNN | Fast | Diverse multi-tissue references |\n| `knn_scanorama` | Scanorama | Fast | Multiple heterogeneous batches |\n| `knn_scvi` | scVI VAE | Medium | Complex batch effects, probabilistic embedding |\n| `scanvi_popv` | scVI+labels | Slow | Semi-supervised; most accurate when reference is clean |\n| `celltypist_popv` | None (logistic) | Fast | Immune cells; works well without batch correction |\n| `rf` | None | Medium | Balanced class distributions; interpretable feature importance |\n| `xgboost` | None | Medium | High-confidence predictions on well-separated cell types |\n| `svm` | None | Medium | High-dimensional gene expression; linear boundaries |\n| `onclass` | None | Medium | Ontology-aware; handles unseen cell types via CL ontology |\n\n### ONCLASS and Ontology-Aware Annotation\n\nONCLASS uses the Cell Ontology (CL) to represent cell types as nodes in a knowledge graph and predict unseen cell types by propagating similarity through the ontology. Unlike other methods, ONCLASS can predict a cell type that was not present in the training reference if it is ontologically adjacent to known types. Enable it by including `\"onclass\"` in the methods list.\n\n### Reference Quality Requirements\n\npopV annotation quality scales directly with reference quality:\n\n- **Minimum cell count per type**: 50–100 cells per label; rare types with \u003C20 cells may be missed by KNN methods\n- **Balanced representation**: highly imbalanced references (one type is 80% of cells) cause tree methods to be biased toward the majority class\n- **Label granularity**: coarse labels (10 types) annotate reliably; fine-grained labels (100+ types) require a larger, matched reference\n\n## Common Workflows\n\n### Workflow 1: Standard Reference-Query Annotation\n\n**Goal**: Annotate an unlabeled query dataset using a curated reference atlas end-to-end.\n\n```python\nimport popv\nimport scanpy as sc\nimport pandas as pd\n\n# 1. Load data\nadata_ref = sc.read_h5ad(\"reference_atlas.h5ad\")   # has obs[\"cell_type\"] and obs[\"batch\"]\nadata_query = sc.read_h5ad(\"query_dataset.h5ad\")   # no cell type labels\nif \"batch\" not in adata_query.obs.columns:\n    adata_query.obs[\"batch\"] = \"query\"\n\n# 2. Preprocess: build joint normalized object\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=100,\n    n_epochs_semisupervised=30,\n    use_gpu=True,\n    hvg=4000,\n)\nprint(f\"Prepared: {adata.n_obs} total cells\")\n\n# 3. Run ensemble annotation\npopv.annotation.annotate_data(adata)\n\n# 4. Extract query results\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_annotations = adata[query_mask].obs[[\n    \"popv_prediction\", \"popv_agreement\",\n    \"knn_harmony_popv\", \"scanvi_popv\", \"rf_popv\", \"xgboost_popv\"\n]].copy()\n\n# 5. Transfer back to original query object\nadata_query.obs = adata_query.obs.join(\n    query_annotations, how=\"left\"\n)\nprint(f\"Annotated {query_mask.sum()} query cells\")\nprint(query_annotations[\"popv_prediction\"].value_counts().head(10))\n\n# 6. Save annotated query\nadata_query.write_h5ad(\"annotated_query.h5ad\", compression=\"gzip\")\nquery_annotations.to_csv(\"popv_annotations.csv\")\nprint(\"Saved annotated_query.h5ad and popv_annotations.csv\")\n```\n\n### Workflow 2: Confidence Filtering and Novel Cell State Detection\n\n**Goal**: Separate high-confidence annotations from ambiguous cells; flag candidate novel or transitional states for manual review.\n\n```python\nimport popv\nimport scanpy as sc\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Assume adata has been annotated (as in Workflow 1)\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Tier cells by agreement score\nbins = [0.0, 0.5, 0.8, 1.01]\nlabels = [\"low (\u003C0.5)\", \"medium (0.5–0.8)\", \"high (≥0.8)\"]\nquery_obs[\"confidence_tier\"] = pd.cut(\n    query_obs[\"popv_agreement\"], bins=bins, labels=labels, right=False\n)\nprint(\"Cells per confidence tier:\")\nprint(query_obs[\"confidence_tier\"].value_counts())\n\n# High-confidence subset: use popv_prediction directly\nhigh_conf_mask = query_obs[\"popv_agreement\"] >= 0.8\nprint(f\"\\nHigh-confidence annotations ({high_conf_mask.mean():.1%} of query cells):\")\nprint(query_obs[high_conf_mask][\"popv_prediction\"].value_counts().head(10))\n\n# Low-confidence subset: inspect per-method disagreement\nlow_conf = query_obs[query_obs[\"popv_agreement\"] \u003C 0.5]\npopv_method_cols = [c for c in query_obs.columns if c.endswith(\"_popv\") and\n                    c not in (\"popv_prediction\", \"popv_agreement\")]\nprint(f\"\\nLow-confidence cells sample (showing per-method labels):\")\nprint(low_conf[popv_method_cols + [\"popv_prediction\"]].head(10).to_string())\n\n# Save agreement + confidence-tier summaries; render the tier bar chart with the omics-plotting\n# SKILL (skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md) \"Box \u002F Violin \u002F Bar\" recipe -> figures\u002Fpopv_confidence_distribution.png\nquery_obs[[\"popv_agreement\", \"confidence_tier\"]].to_csv(\"popv_confidence.csv\")\nprint(query_obs[\"confidence_tier\"].value_counts().to_string())\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `ref_labels_key` | Process_Query | — | Any `obs` column | Column in `adata_ref.obs` containing training cell type labels |\n| `n_epochs_unsupervised` | Process_Query | `50` | `20`–`500` | scVI training epochs; increase for better embedding on large\u002Fcomplex datasets |\n| `n_epochs_semisupervised` | Process_Query | `20` | `10`–`100` | scANVI fine-tuning epochs on top of scVI |\n| `hvg` | Process_Query | `4000` | `2000`–`8000` | Highly variable genes used for embedding and KNN methods |\n| `use_gpu` | Process_Query | `True` | `True`, `False` | GPU acceleration for scVI\u002FSCANVI; falls back to CPU automatically if no GPU |\n| `methods` | annotate_data | all | List of method names | Subset of methods to run; excluding slow methods (scanvi, onclass) speeds up pipeline |\n| `unknown_celltype_label` | Process_Query | `\"unknown\"` | Any string | Label assigned to query cells before annotation; used to separate reference labels from query |\n| `popv_agreement` | (output) | — | `0.0`–`1.0` | Fraction of methods agreeing on consensus label; `>=0.8` recommended for high confidence |\n\n## Best Practices\n\n1. **Check gene overlap before running**: popV performs best with >70% gene overlap between reference and query. If overlap is \u003C50%, annotation quality degrades significantly — consider using a different reference or imputing missing genes.\n   ```python\n   shared = adata_ref.var_names.intersection(adata_query.var_names)\n   print(f\"Gene overlap: {len(shared) \u002F adata_ref.n_vars:.1%}\")\n   ```\n\n2. **Use raw counts as input**: pass raw (un-normalized) counts in `adata.X` to `Process_Query`. popV internally applies its own normalization. Pre-normalized data can distort the scVI\u002FSCANVI latent space.\n\n3. **Match reference granularity to query biology**: if your query contains subtypes not in the reference, no method will correctly assign them — they will appear as low-agreement cells. Either add them to the reference or accept that the consensus will assign the nearest parent type.\n\n4. **Exclude slow methods when speed matters**: `scanvi_popv` and `onclass` are the slowest. For a quick first-pass, run only `knn_harmony`, `knn_bbknn`, `rf`, `xgboost`, and `celltypist_popv`.\n   ```python\n   popv.annotation.annotate_data(adata, methods=[\"knn_harmony\", \"knn_bbknn\", \"rf\", \"xgboost\", \"celltypist_popv\"])\n   ```\n\n5. **Save trained models for repeated queries**: `Process_Query` stores scVI\u002FSCANVI models in `save_path_trained_models`. Reuse these when annotating additional query batches against the same reference to avoid retraining.\n\n## Common Recipes\n\n### Recipe: Subset to High-Confidence Annotations Only\n\nWhen to use: downstream analyses (DE, trajectory) require clean labels; exclude ambiguous cells.\n\n```python\nimport scanpy as sc\n\n# Annotate as in Workflow 1 first\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nadata_query_annotated = adata[query_mask].copy()\n\n# Keep only high-confidence cells\nhigh_conf = adata_query_annotated[adata_query_annotated.obs[\"popv_agreement\"] >= 0.8].copy()\nprint(f\"High-confidence cells: {high_conf.n_obs} \u002F {adata_query_annotated.n_obs} \"\n      f\"({high_conf.n_obs\u002Fadata_query_annotated.n_obs:.1%})\")\nprint(high_conf.obs[\"popv_prediction\"].value_counts())\n\n# Recompute UMAP on high-confidence subset for visualization\nsc.pp.neighbors(high_conf, use_rep=\"X_scVI\")  # use scVI embedding stored by popV\nsc.tl.umap(high_conf)\nsc.pl.umap(high_conf, color=\"popv_prediction\", save=\"_high_conf_celltypes.png\")\n```\n\n### Recipe: Per-Method Label Comparison Heatmap\n\nWhen to use: understanding where methods disagree to identify systematic biases or novel populations.\n\n```python\nimport pandas as pd\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nquery_obs = adata[query_mask].obs.copy()\n\n# Collect per-method columns\nmethod_cols = [c for c in query_obs.columns\n               if c.endswith(\"_popv\") and c not in (\"popv_prediction\", \"popv_agreement\")]\n\n# Cross-tabulate two key methods\nct = pd.crosstab(\n    query_obs[\"knn_harmony_popv\"],\n    query_obs[\"scanvi_popv\"],\n    margins=False,\n)\n# Normalize rows\nct_norm = ct.div(ct.sum(axis=1), axis=0)\nct_norm.to_csv(\"popv_method_agreement.csv\")\nprint(f\"Method agreement matrix: {ct_norm.shape} -> popv_method_agreement.csv\")\n# Render with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`) \"Expression heatmap\" recipe (Blues, 0..1)\n# -> figures\u002Fpopv_method_agreement_heatmap.png\n```\n\n### Recipe: Fast Annotation Without Deep Learning Methods\n\nWhen to use: quick annotation without GPU or when scVI\u002FSCANVI training is prohibitively slow (>500k cells).\n\n```python\nimport popv\n\n# Process without training deep generative models (scVI not needed for KNN-Harmony)\nadata = popv.preprocessing.Process_Query(\n    adata_ref,\n    adata_query,\n    ref_labels_key=\"cell_type\",\n    ref_batch_key=\"batch\",\n    query_batch_key=\"batch\",\n    unknown_celltype_label=\"unknown\",\n    save_path_trained_models=\".\u002Fpopv_models\u002F\",\n    n_epochs_unsupervised=0,   # skip scVI training\n    n_epochs_semisupervised=0, # skip scANVI training\n    use_gpu=False,\n    hvg=3000,\n)\n\n# Run only fast non-DL methods\npopv.annotation.annotate_data(\n    adata,\n    methods=[\"knn_harmony\", \"knn_bbknn\", \"knn_scanorama\", \"rf\", \"xgboost\", \"svm\", \"celltypist_popv\"],\n)\n\nquery_mask = adata.obs[\"_dataset\"] == \"query\"\nprint(adata[query_mask].obs[[\"popv_prediction\", \"popv_agreement\"]].describe())\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `KeyError: ref_labels_key not in adata_ref.obs` | Reference lacks a cell type column | Verify the column name: `print(adata_ref.obs.columns.tolist())`; update `ref_labels_key` accordingly |\n| Gene space mismatch error | Reference and query have very few shared genes | Check `adata_ref.var_names.intersection(adata_query.var_names)`; if \u003C50% overlap, use a different reference or match gene panels |\n| CUDA out-of-memory for scVI\u002FSCANVI | GPU VRAM insufficient for batch size | Set `use_gpu=False` or reduce `n_epochs_unsupervised`; scVI falls back to CPU automatically on most systems |\n| `onclass_popv` failures on small datasets | ONCLASS requires sufficient label coverage | Remove `\"onclass\"` from the methods list when reference has \u003C10 cell types or \u003C500 cells per type |\n| Very slow annotation (>2 hours) | scVI\u002FSCANVI training on large reference | Subsample reference to 50k cells per type; exclude `\"scanvi_popv\"` and `\"onclass\"` from methods |\n| All cells receive same consensus label | Reference highly imbalanced toward one type | Balance reference by subsampling the dominant type or upsampling rare types before running popV |\n| `popv_agreement` is 0 for many cells | Many methods returning different labels | Inspect per-method columns; consider whether reference covers the query biology; add methods or retrain with a better reference |\n\n## Related Skills\n\n- **celltypist-cell-annotation** — single-model annotation with pre-trained logistic regression; faster but lacks ensemble uncertainty\n- **scanpy-scrna-seq** — preprocessing pipeline (QC, normalization, clustering) that produces AnnData inputs for popV\n- **scvi-tools-single-cell** — scANVI for probabilistic label transfer with a single deep generative model; use when you prefer a formal variational framework over ensemble voting\n- **harmony-batch-correction** — Harmony embedding used by `knn_harmony` method internally; understand it to tune popV's KNN-based methods\n\n## References\n\n- [GitHub: YosefLab\u002FpopV](https:\u002F\u002Fgithub.com\u002FYosefLab\u002FpopV) — official source code, installation instructions, and example notebooks\n- [popV documentation](https:\u002F\u002Fpopv.readthedocs.io\u002F) — API reference and tutorials\n- [Ergen et al., bioRxiv 2023](https:\u002F\u002Fdoi.org\u002F10.1101\u002F2023.06.15.545239) — \"Population-level integration of single-cell datasets enables multi-scale analysis across samples\", original popV preprint\n- [ONCLASS paper — Wang et al., Nature Methods 2021](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-021-01080-9) — ontology-aware cell type classification underlying the ONCLASS method in popV\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fpopv-cell-annotation",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill popv-cell-annotation",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill popv-cell-annotation",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill popv-cell-annotation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpopv-cell-annotation\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]