[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AWVYPGQ8SNB19BJWS3D4RW":3,"skill-same:01M7AWVYPGQ8SNB19BJWS3D4RW":56},{"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":28,"commitSha":29,"skillDirectory":30,"forksCount":14,"repositoryHtmlUrl":31,"repositoryHomepageUrl":6,"ownerHtmlUrl":32,"ownerBlogUrl":33,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M7AWVYPGQ8SNB19BJWS3D4RW","scvi-tools",null,"Probabilistic single-cell RNA-seq with scvi-tools — scVI for a batch-corrected latent space, scANVI for semi-supervised label transfer, and Bayesian differential expression. Reach for this skill to integrate scRNA-seq batches, embed cells for clustering, transfer annotations from a reference onto a query, or score differentially expressed genes per cluster. For spatial deconvolution \u002F mapping use the cell2location, DestVI, or Tangram methods instead.","flyme2bluemoon\u002Fskills","flyme2bluemoon","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F37197710?v=4","01M7AWSKCXRPGZSNS26MTB5YR4","Matthew Shen","01M7AWSKE11G83QK1885PSGJ3K",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills-examples\u002Fclaude-science-skills\u002Fscvi-tools\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: scvi-tools\ndescription: >\n  Probabilistic single-cell RNA-seq with scvi-tools — scVI for a\n  batch-corrected latent space, scANVI for semi-supervised label transfer,\n  and Bayesian differential expression. Reach for this skill to integrate\n  scRNA-seq batches, embed cells for clustering, transfer annotations from a\n  reference onto a query, or score differentially expressed genes per cluster.\n  For spatial deconvolution \u002F mapping use the cell2location, DestVI, or\n  Tangram methods instead.\nlicense: Apache-2.0\nmetadata:\n  requirements: [gpu]\n  display-name: scvi-tools\n---\n\n# scvi-tools — scVI \u002F scANVI\n\nscvi-tools (Gayoso et al. 2022, github.com\u002Fscverse\u002Fscvi-tools, BSD-3-Clause)\nwraps a family\nof deep generative models for single-cell omics. The scRNA-seq core is **scVI**\n(unsupervised batch-corrected latent embedding) and **scANVI** (scVI + a\nclassifier head for semi-supervised cell-type label transfer). Both expect\n**raw integer UMI counts** and emit a low-dimensional `X_scVI` \u002F `X_scANVI`\nthat drops into the scanpy neighbors → leiden → umap pipeline.\n\n## How to run\n\n### scVI — batch-corrected latent space\n\n```python\nimport scanpy as sc\nimport scvi\n\nadata = sc.read_h5ad(\"dataset.h5ad\")\nadata.layers[\"counts\"] = adata.X.copy()          # preserve raw BEFORE any normalize\u002Flog1p\nsc.pp.normalize_total(adata); sc.pp.log1p(adata) # optional, for HVG \u002F plotting only\nsc.pp.highly_variable_genes(adata, n_top_genes=2000, batch_key=\"batch\", subset=True)\n\nscvi.model.SCVI.setup_anndata(adata, layer=\"counts\", batch_key=\"batch\")\nmodel = scvi.model.SCVI(adata, n_latent=30)\nmodel.train(max_epochs=200, early_stopping=True, accelerator=\"gpu\", devices=1)\n\nadata.obsm[\"X_scVI\"] = model.get_latent_representation()\nadata.layers[\"scvi_normalized\"] = model.get_normalized_expression(library_size=1e4)\n```\n\n### scANVI — label transfer from a partially-annotated reference\n\n```python\nlvae = scvi.model.SCANVI.from_scvi_model(\n    model, labels_key=\"cell_type\", unlabeled_category=\"Unknown\",\n)\nlvae.train(max_epochs=20, n_samples_per_label=100, accelerator=\"gpu\", devices=1)\n\nadata.obsm[\"X_scANVI\"] = lvae.get_latent_representation()\nadata.obs[\"pred_cell_type\"] = lvae.predict()\n```\n\n`accelerator=\"gpu\", devices=1` is the PyTorch-Lightning spelling; the legacy\n`use_gpu=` kwarg was **removed** in scvi-tools 1.x and now raises `TypeError`.\n\nHard labels hide uncertainty: `lvae.predict(soft=True)` returns per-cell\nclass probabilities (a DataFrame, one column per cell type). Keep\n`.max(axis=1)` alongside the labels and treat cells below a threshold\n(e.g. 0.8) as low-confidence instead of accepting every call.\n\n### Query-to-reference mapping (scArches)\n\nTo annotate a new dataset against an **already-trained** reference atlas,\ndon't retrain from scratch — map the query onto the frozen reference\n(scArches-style transfer learning; see the reference-mapping guide at\ndocs.scvi-tools.org):\n\n```python\nadata_query.layers[\"counts\"] = adata_query.X.copy()  # raw counts, like the reference\nadata_query.obs[\"cell_type\"] = \"Unknown\"             # query starts unlabeled\nscvi.model.SCANVI.prepare_query_anndata(adata_query, lvae)  # align genes; missing → zero-padded\nquery = scvi.model.SCANVI.load_query_data(adata_query, lvae)\nquery.train(max_epochs=100, plan_kwargs={\"weight_decay\": 0.0})\n\nadata_query.obsm[\"X_scANVI\"] = query.get_latent_representation()\nadata_query.obs[\"pred_cell_type\"] = query.predict()\n```\n\nThe query also needs the reference's `batch` column in `.obs`.\n`weight_decay: 0.0` keeps fine-tuning from eroding the frozen reference\nlatent space. The same classmethods exist on `scvi.model.SCVI` for an\nunlabeled reference (embedding only, no label transfer).\n\nFor later scArches mapping, the reference should be built with\n`encode_covariates=True` set on the `scvi.model.SCVI(...)` constructor\n(default `False`; scANVI inherits it via `from_scvi_model`) — the encoder\nis only conditioned on batch\u002Fcovariates when this is set, and an\nun-conditioned encoder ignores the query's batch, so surgery can't adapt\nthe latent space to it. `load_query_data` still runs without it, but\nmapping quality suffers; the reference-mapping tutorial at\ndocs.scvi-tools.org shows the full recommended `arches_params`.\n\n## Differential expression\n\n```python\nde = model.differential_expression(\n    groupby=\"leiden\", group1=\"3\",   # group2=None → vs. all other cells\n    mode=\"change\", delta=0.25,\n)\ntop = de.sort_values(\"proba_de\", ascending=False).head(50)\n```\n\nFor one-vs-rest leave `group2` out — `\"rest\"` is scanpy's\n`rank_genes_groups` convention, not scvi-tools'; here `group2` is a literal\ncategory name and `\"rest\"` would match zero cells.\n\nscvi-tools ≥1.4 defaults to `mode=\"vanilla\"`, whose result columns are\nexactly:\n\n```\n['proba_m1', 'proba_m2', 'bayes_factor', 'scale1', 'scale2', 'raw_mean1',\n 'raw_mean2', 'non_zeros_proportion1', 'non_zeros_proportion2',\n 'raw_normalized_mean1', 'raw_normalized_mean2', 'comparison', 'group1',\n 'group2']\n```\n\n— no `lfc_*`, no `proba_de`, no `is_de_fdr_*`. **Pass `mode=\"change\"`** to\nget `lfc_mean` \u002F `lfc_median` \u002F `proba_de` \u002F `is_de_fdr_0.05`. Sort on\n`proba_de` (or on `bayes_factor` if you deliberately stayed in vanilla\nmode).\n\nTwo further knobs (DE user guide, docs.scvi-tools.org): `fdr_target` sets\nthe posterior-expected-FDR level the `is_de_fdr_*` call column is computed\nat (default 0.05), and `delta=None` swaps the fixed log-fold-change\nthreshold for one estimated from the data.\n\n## Output format\n\n| Key                            | What                                                   |\n| ------------------------------ | ------------------------------------------------------ |\n| `adata.obsm[\"X_scVI\"]`         | `n_cells × n_latent` batch-corrected embedding         |\n| `adata.obsm[\"X_scANVI\"]`       | label-aware embedding (better separates known classes) |\n| `adata.obs[\"pred_cell_type\"]`  | scANVI predicted label per cell                        |\n| `adata.layers[\"scvi_normalized\"]` | decoded expression, library-size normalized         |\n| DE dataframe                   | per-gene `lfc_*` \u002F `proba_de` (with `mode=\"change\"`)   |\n\n## Remote compute\n\nA100-class GPU recommended for >50k cells. The prebuilt **`singlecell_gpu`**\nModal env ships scvi-tools 1.4.2 + scanpy 1.11.5 + anndata 0.11.4 — read\n`compute_details({provider: 'byoc:modal', mode: 'read'})` for the current\nimage ref, then:\n\n```python\nc = host.compute.create('modal', provider_params={\n    'image':  '\u003Cimage ref from compute_details>',   # e.g. im-...\n    'gpu':    'A100',\n    'cpu':    8,\n    'memory': 32768,\n    'timeout': 3600,          # container wall clock — optional; omitted → Settings default\n})\njob = c.submit_job(\n    intent=\"scVI+scANVI on 80k cells — 1×A100, ~15 min\",\n    inputs=[\n        \"dataset.h5ad\",\n        \"pipeline.py\",\n    ],\n    command=\"python pipeline.py\",\n    outputs=[\"out\u002F**\"],\n    run_timeout_s=2400,\n)\n# the Job repr just printed itself (id, notes, deadline) — cell ends here; the kernel never waits on the job\n```\n\n`h5ad_safe_obs` is auto-loaded into the **local** analysis kernel only — in\n`pipeline.py` running on Modal, paste the helper at the top of the script\n(or inline the `pd.Index(np.asarray(..., dtype=object))` coercion) before\n`.write_h5ad()`.\n\nThen call the `wait_for_notification` brain-tool. When `compute_done`\narrives, `save_artifacts(payload[\"output_files\"])`. For the full record,\nre-enter the kernel and bind the **compute handle** (not the job)\nseparately — `.close()` lives on the handle, not on the job:\n\n```python\nc = host.compute.create('modal')\nres = c.attach_job(job_id).result()   # a read, never a wait: files, stdout_tail, notes, ...\nc.close(intent=\"scVI run done — stop the sandbox\")\n```\n\nSee the `remote-compute-modal` skill for orchestration details.\n\n## Gotchas\n\n| Gotcha | What happens \u002F fix |\n|---|---|\n| `differential_expression()` defaults to `mode=\"vanilla\"` (scvi-tools ≥1.4) | `KeyError: 'lfc_mean'` \u002F `'proba_de'` when sorting — pass `mode=\"change\"` to get `lfc_*`\u002F`proba_de`\u002F`is_de_fdr_*`; in vanilla mode sort on `bayes_factor`. |\n| `adata.obs` index\u002Fcolumns are `string[pyarrow]` (`ArrowStringArray`) | `.write_h5ad()` dies with `IORegistryError: No method registered for writing \u003Cclass 'pandas.arrays.ArrowStringArray'>` (anndata #2377). Coerce before writing: `adata.obs = h5ad_safe_obs(adata.obs)` (kernel helper — local kernel only; inline the coercion in remote `pipeline.py`). **`.astype(str)` alone is not enough** — on a pyarrow-backed Index\u002FSeries it returns another Arrow-backed array; round-trip through `np.asarray(..., dtype=object)`. `anndata.settings.allow_write_nullable_strings = True` does **not** cover Arrow-backed strings. |\n| `use_gpu=` kwarg | Removed in 1.x → `TypeError: train() got an unexpected keyword argument 'use_gpu'`. Use `accelerator=\"gpu\", devices=1`. |\n| Log-normalized data fed to `setup_anndata` | Silent garbage — scVI's NB likelihood needs raw integer counts. Stash counts in `adata.layers[\"counts\"]` *before* normalize\u002Flog1p and pass `layer=\"counts\"`. |\n\n## Troubleshooting\n\n| Symptom | Fix |\n|---|---|\n| `KeyError: 'lfc_mean'` (or `'proba_de'`, `'is_de_fdr_0.05'`) on DE result | Add `mode=\"change\"` to `differential_expression()`; the default vanilla mode has no LFC columns. |\n| `IORegistryError: No method registered for writing \u003Cclass 'pandas.arrays.ArrowStringArray'>` on `.write_h5ad()` | `adata.obs = h5ad_safe_obs(adata.obs)` (and `adata.var` if needed) before writing. The `allow_write_nullable_strings` flag does not help here. |\n| `TypeError: ... unexpected keyword argument 'use_gpu'` | Replace with `accelerator=\"gpu\", devices=1`. |\n| `ValueError: ... non-negative integers` \u002F NB loss explodes | `layer=\"counts\"` points at log\u002Ffloat data — restore raw counts. |\n| `MisconfigurationException: No supported gpu backend found` | No CUDA visible — drop `accelerator`\u002F`devices` to fall back to CPU, or dispatch via Remote compute. |\n| `UnicodeEncodeError: 'ascii' codec can't encode character ...` writing a summary \u002F printing | Container has no `LANG` so Python defaults to ASCII. Open files with `encoding=\"utf-8\"` and\u002For `sys.stdout.reconfigure(encoding=\"utf-8\")` at script top. The prebuilt `singlecell_gpu` env sets `PYTHONIOENCODING=utf-8`, so this only bites user-built images. |\n| `AttributeError: ... object has no attribute 'close'` on a job handle | You chained `host.compute.create(...).attach_job(...)` and called `.close()` on the job. Bind the compute handle separately and close that — see Remote compute above. |\n| Batches stay separated on the `X_scVI` UMAP (under-correction) | Integrate harder: raise `n_top_genes` (e.g. 4000) or train longer; double-check `batch_key` names the real technical batch. |\n| Known-distinct cell types merge after integration (over-correction) | Use scANVI with whatever labels exist — the label-aware embedding keeps known classes separated. (Moving a variable from `batch_key` to `categorical_covariate_keys` does not help: both are conditioned on identically.) |\n\n---\n\n**Next**: cluster on `X_scVI` with scanpy (`sc.pp.neighbors(use_rep=\"X_scVI\")`\n→ `sc.tl.leiden` → `sc.tl.umap`); for spatial deconvolution train\ncell2location \u002F DestVI \u002F Tangram on the scRNA-seq reference.\n","# scvi-tools — scVI \u002F scANVI\n\nscvi-tools (Gayoso et al. 2022, github.com\u002Fscverse\u002Fscvi-tools, BSD-3-Clause)\nwraps a family\nof deep generative models for single-cell omics. The scRNA-seq core is **scVI**\n(unsupervised batch-corrected latent embedding) and **scANVI** (scVI + a\nclassifier head for semi-supervised cell-type label transfer). Both expect\n**raw integer UMI counts** and emit a low-dimensional `X_scVI` \u002F `X_scANVI`\nthat drops into the scanpy neighbors → leiden → umap pipeline.\n\n## How to run\n\n### scVI — batch-corrected latent space\n\n```python\nimport scanpy as sc\nimport scvi\n\nadata = sc.read_h5ad(\"dataset.h5ad\")\nadata.layers[\"counts\"] = adata.X.copy()          # preserve raw BEFORE any normalize\u002Flog1p\nsc.pp.normalize_total(adata); sc.pp.log1p(adata) # optional, for HVG \u002F plotting only\nsc.pp.highly_variable_genes(adata, n_top_genes=2000, batch_key=\"batch\", subset=True)\n\nscvi.model.SCVI.setup_anndata(adata, layer=\"counts\", batch_key=\"batch\")\nmodel = scvi.model.SCVI(adata, n_latent=30)\nmodel.train(max_epochs=200, early_stopping=True, accelerator=\"gpu\", devices=1)\n\nadata.obsm[\"X_scVI\"] = model.get_latent_representation()\nadata.layers[\"scvi_normalized\"] = model.get_normalized_expression(library_size=1e4)\n```\n\n### scANVI — label transfer from a partially-annotated reference\n\n```python\nlvae = scvi.model.SCANVI.from_scvi_model(\n    model, labels_key=\"cell_type\", unlabeled_category=\"Unknown\",\n)\nlvae.train(max_epochs=20, n_samples_per_label=100, accelerator=\"gpu\", devices=1)\n\nadata.obsm[\"X_scANVI\"] = lvae.get_latent_representation()\nadata.obs[\"pred_cell_type\"] = lvae.predict()\n```\n\n`accelerator=\"gpu\", devices=1` is the PyTorch-Lightning spelling; the legacy\n`use_gpu=` kwarg was **removed** in scvi-tools 1.x and now raises `TypeError`.\n\nHard labels hide uncertainty: `lvae.predict(soft=True)` returns per-cell\nclass probabilities (a DataFrame, one column per cell type). Keep\n`.max(axis=1)` alongside the labels and treat cells below a threshold\n(e.g. 0.8) as low-confidence instead of accepting every call.\n\n### Query-to-reference mapping (scArches)\n\nTo annotate a new dataset against an **already-trained** reference atlas,\ndon't retrain from scratch — map the query onto the frozen reference\n(scArches-style transfer learning; see the reference-mapping guide at\ndocs.scvi-tools.org):\n\n```python\nadata_query.layers[\"counts\"] = adata_query.X.copy()  # raw counts, like the reference\nadata_query.obs[\"cell_type\"] = \"Unknown\"             # query starts unlabeled\nscvi.model.SCANVI.prepare_query_anndata(adata_query, lvae)  # align genes; missing → zero-padded\nquery = scvi.model.SCANVI.load_query_data(adata_query, lvae)\nquery.train(max_epochs=100, plan_kwargs={\"weight_decay\": 0.0})\n\nadata_query.obsm[\"X_scANVI\"] = query.get_latent_representation()\nadata_query.obs[\"pred_cell_type\"] = query.predict()\n```\n\nThe query also needs the reference's `batch` column in `.obs`.\n`weight_decay: 0.0` keeps fine-tuning from eroding the frozen reference\nlatent space. The same classmethods exist on `scvi.model.SCVI` for an\nunlabeled reference (embedding only, no label transfer).\n\nFor later scArches mapping, the reference should be built with\n`encode_covariates=True` set on the `scvi.model.SCVI(...)` constructor\n(default `False`; scANVI inherits it via `from_scvi_model`) — the encoder\nis only conditioned on batch\u002Fcovariates when this is set, and an\nun-conditioned encoder ignores the query's batch, so surgery can't adapt\nthe latent space to it. `load_query_data` still runs without it, but\nmapping quality suffers; the reference-mapping tutorial at\ndocs.scvi-tools.org shows the full recommended `arches_params`.\n\n## Differential expression\n\n```python\nde = model.differential_expression(\n    groupby=\"leiden\", group1=\"3\",   # group2=None → vs. all other cells\n    mode=\"change\", delta=0.25,\n)\ntop = de.sort_values(\"proba_de\", ascending=False).head(50)\n```\n\nFor one-vs-rest leave `group2` out — `\"rest\"` is scanpy's\n`rank_genes_groups` convention, not scvi-tools'; here `group2` is a literal\ncategory name and `\"rest\"` would match zero cells.\n\nscvi-tools ≥1.4 defaults to `mode=\"vanilla\"`, whose result columns are\nexactly:\n\n```\n['proba_m1', 'proba_m2', 'bayes_factor', 'scale1', 'scale2', 'raw_mean1',\n 'raw_mean2', 'non_zeros_proportion1', 'non_zeros_proportion2',\n 'raw_normalized_mean1', 'raw_normalized_mean2', 'comparison', 'group1',\n 'group2']\n```\n\n— no `lfc_*`, no `proba_de`, no `is_de_fdr_*`. **Pass `mode=\"change\"`** to\nget `lfc_mean` \u002F `lfc_median` \u002F `proba_de` \u002F `is_de_fdr_0.05`. Sort on\n`proba_de` (or on `bayes_factor` if you deliberately stayed in vanilla\nmode).\n\nTwo further knobs (DE user guide, docs.scvi-tools.org): `fdr_target` sets\nthe posterior-expected-FDR level the `is_de_fdr_*` call column is computed\nat (default 0.05), and `delta=None` swaps the fixed log-fold-change\nthreshold for one estimated from the data.\n\n## Output format\n\n| Key                            | What                                                   |\n| ------------------------------ | ------------------------------------------------------ |\n| `adata.obsm[\"X_scVI\"]`         | `n_cells × n_latent` batch-corrected embedding         |\n| `adata.obsm[\"X_scANVI\"]`       | label-aware embedding (better separates known classes) |\n| `adata.obs[\"pred_cell_type\"]`  | scANVI predicted label per cell                        |\n| `adata.layers[\"scvi_normalized\"]` | decoded expression, library-size normalized         |\n| DE dataframe                   | per-gene `lfc_*` \u002F `proba_de` (with `mode=\"change\"`)   |\n\n## Remote compute\n\nA100-class GPU recommended for >50k cells. The prebuilt **`singlecell_gpu`**\nModal env ships scvi-tools 1.4.2 + scanpy 1.11.5 + anndata 0.11.4 — read\n`compute_details({provider: 'byoc:modal', mode: 'read'})` for the current\nimage ref, then:\n\n```python\nc = host.compute.create('modal', provider_params={\n    'image':  '\u003Cimage ref from compute_details>',   # e.g. im-...\n    'gpu':    'A100',\n    'cpu':    8,\n    'memory': 32768,\n    'timeout': 3600,          # container wall clock — optional; omitted → Settings default\n})\njob = c.submit_job(\n    intent=\"scVI+scANVI on 80k cells — 1×A100, ~15 min\",\n    inputs=[\n        \"dataset.h5ad\",\n        \"pipeline.py\",\n    ],\n    command=\"python pipeline.py\",\n    outputs=[\"out\u002F**\"],\n    run_timeout_s=2400,\n)\n# the Job repr just printed itself (id, notes, deadline) — cell ends here; the kernel never waits on the job\n```\n\n`h5ad_safe_obs` is auto-loaded into the **local** analysis kernel only — in\n`pipeline.py` running on Modal, paste the helper at the top of the script\n(or inline the `pd.Index(np.asarray(..., dtype=object))` coercion) before\n`.write_h5ad()`.\n\nThen call the `wait_for_notification` brain-tool. When `compute_done`\narrives, `save_artifacts(payload[\"output_files\"])`. For the full record,\nre-enter the kernel and bind the **compute handle** (not the job)\nseparately — `.close()` lives on the handle, not on the job:\n\n```python\nc = host.compute.create('modal')\nres = c.attach_job(job_id).result()   # a read, never a wait: files, stdout_tail, notes, ...\nc.close(intent=\"scVI run done — stop the sandbox\")\n```\n\nSee the `remote-compute-modal` skill for orchestration details.\n\n## Gotchas\n\n| Gotcha | What happens \u002F fix |\n|---|---|\n| `differential_expression()` defaults to `mode=\"vanilla\"` (scvi-tools ≥1.4) | `KeyError: 'lfc_mean'` \u002F `'proba_de'` when sorting — pass `mode=\"change\"` to get `lfc_*`\u002F`proba_de`\u002F`is_de_fdr_*`; in vanilla mode sort on `bayes_factor`. |\n| `adata.obs` index\u002Fcolumns are `string[pyarrow]` (`ArrowStringArray`) | `.write_h5ad()` dies with `IORegistryError: No method registered for writing \u003Cclass 'pandas.arrays.ArrowStringArray'>` (anndata #2377). Coerce before writing: `adata.obs = h5ad_safe_obs(adata.obs)` (kernel helper — local kernel only; inline the coercion in remote `pipeline.py`). **`.astype(str)` alone is not enough** — on a pyarrow-backed Index\u002FSeries it returns another Arrow-backed array; round-trip through `np.asarray(..., dtype=object)`. `anndata.settings.allow_write_nullable_strings = True` does **not** cover Arrow-backed strings. |\n| `use_gpu=` kwarg | Removed in 1.x → `TypeError: train() got an unexpected keyword argument 'use_gpu'`. Use `accelerator=\"gpu\", devices=1`. |\n| Log-normalized data fed to `setup_anndata` | Silent garbage — scVI's NB likelihood needs raw integer counts. Stash counts in `adata.layers[\"counts\"]` *before* normalize\u002Flog1p and pass `layer=\"counts\"`. |\n\n## Troubleshooting\n\n| Symptom | Fix |\n|---|---|\n| `KeyError: 'lfc_mean'` (or `'proba_de'`, `'is_de_fdr_0.05'`) on DE result | Add `mode=\"change\"` to `differential_expression()`; the default vanilla mode has no LFC columns. |\n| `IORegistryError: No method registered for writing \u003Cclass 'pandas.arrays.ArrowStringArray'>` on `.write_h5ad()` | `adata.obs = h5ad_safe_obs(adata.obs)` (and `adata.var` if needed) before writing. The `allow_write_nullable_strings` flag does not help here. |\n| `TypeError: ... unexpected keyword argument 'use_gpu'` | Replace with `accelerator=\"gpu\", devices=1`. |\n| `ValueError: ... non-negative integers` \u002F NB loss explodes | `layer=\"counts\"` points at log\u002Ffloat data — restore raw counts. |\n| `MisconfigurationException: No supported gpu backend found` | No CUDA visible — drop `accelerator`\u002F`devices` to fall back to CPU, or dispatch via Remote compute. |\n| `UnicodeEncodeError: 'ascii' codec can't encode character ...` writing a summary \u002F printing | Container has no `LANG` so Python defaults to ASCII. Open files with `encoding=\"utf-8\"` and\u002For `sys.stdout.reconfigure(encoding=\"utf-8\")` at script top. The prebuilt `singlecell_gpu` env sets `PYTHONIOENCODING=utf-8`, so this only bites user-built images. |\n| `AttributeError: ... object has no attribute 'close'` on a job handle | You chained `host.compute.create(...).attach_job(...)` and called `.close()` on the job. Bind the compute handle separately and close that — see Remote compute above. |\n| Batches stay separated on the `X_scVI` UMAP (under-correction) | Integrate harder: raise `n_top_genes` (e.g. 4000) or train longer; double-check `batch_key` names the real technical batch. |\n| Known-distinct cell types merge after integration (over-correction) | Use scANVI with whatever labels exist — the label-aware embedding keeps known classes separated. (Moving a variable from `batch_key` to `categorical_covariate_keys` does not help: both are conditioned on identically.) |\n\n---\n\n**Next**: cluster on `X_scVI` with scanpy (`sc.pp.neighbors(use_rep=\"X_scVI\")`\n→ `sc.tl.leiden` → `sc.tl.umap`); for spatial deconvolution train\ncell2location \u002F DestVI \u002F Tangram on the scRNA-seq reference.\n",{"name":5,"license":15,"metadata":24,"description":27},{"display-name":5,"requirements":25},[26],"gpu","Probabilistic single-cell RNA-seq with scvi-tools — scVI for a batch-corrected latent space, scANVI for semi-supervised label transfer, and Bayesian differential expression. Reach for this skill to integrate scRNA-seq batches, embed cells for clustering, transfer annotations from a reference onto a query, or score differentially expressed genes per cluster. For spatial deconvolution \u002F mapping use the cell2location, DestVI, or Tangram methods instead.\n","main","9a28ca56870fad42cc4efa04a1d487c07a561ab1","skills-examples\u002Fclaude-science-skills\u002Fscvi-tools","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon","https:\u002F\u002Fflyme2bluemoon.github.io","Computer Science and Biology @ McGill University | making computer do cool thing","2026-10-31 13:32:13",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add flyme2bluemoon\u002Fskills --skill scvi-tools",{"tool":42,"command":43},"bunx","bunx skills add flyme2bluemoon\u002Fskills --skill scvi-tools",{"tool":45,"command":46},"pnpm","pnpm dlx skills add flyme2bluemoon\u002Fskills --skill scvi-tools","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills-examples\u002Fclaude-science-skills\u002Fscvi-tools\u002FSKILL.md",true,[50],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"kernel.py","SCRIPT","脚本",1982,"https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills-examples\u002Fclaude-science-skills\u002Fscvi-tools\u002Fkernel.py",[57,65,72,79,86,93],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AWZ83KYJ9YSB4E5VQJ1K9B","unslop","Edit substantive human-facing prose to remove AI writing patterns while preserving meaning and tone.","MIT","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Funslop\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":61,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7AWZ4FJPVNRMFFJC6JSHHKQ","pstack-principle-type-system-discipline","Apply when designing types, reviewing a function signature, or writing code in any statically-typed language. Make illegal states unrepresentable, brand semantic primitives, parse external data at boundaries, refuse to lie to the compiler, exhaust variants, derive from authoritative schemas.","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Fpstack-principle-type-system-discipline\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":61,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7AWZ11K4KET3ASESNABPE52","pstack-principle-test-behavior-not-implementation","Apply when you write, change, or keep a test. Call the code the way its users do and assert the result they observe against a literal expected value. If the test would still pass when every imported function returns undefined, rewrite the assertion or delete the test.","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Fpstack-principle-test-behavior-not-implementation\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":61,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7AWYWT47M5JG7XV6ZK6QSSX","pstack-principle-subtract-before-you-add","Apply when sequencing an addition, refactor, or rewrite. Remove dead weight, redundant validators, and stub references first, then build on the simpler base.","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Fpstack-principle-subtract-before-you-add\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":61,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7AWYTNNHNGHB583NEV888BB","pstack-principle-sequence-verifiable-units","Sequence migrations or dependent changes around meaningful verification boundaries.","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Fpstack-principle-sequence-verifiable-units\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":61,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7AWYQ2C15PV2W2V6ZVMK3ZM","pstack-principle-separate-before-serializing-shared-state","Apply when concurrent actors might write to the same file, branch, key, or state object. Eliminate the sharing first; serialize structurally only when one shared writer is a real invariant.","https:\u002F\u002Fgithub.com\u002Fflyme2bluemoon\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpstack\u002Fpstack-principle-separate-before-serializing-shared-state\u002FSKILL.md",[],[]]