[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EG2WP3BJFTGFX71T5TXVCG":3,"skill-same:01M7EG2WP3BJFTGFX71T5TXVCG":62},{"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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EG2WP3BJFTGFX71T5TXVCG","bio-tcr-bcr-analysis-scirpy-analysis",null,"Integrates single-cell paired TCR\u002FBCR (10x VDJ, AIRR, dandelion, BD Rhapsody) with gene expression in an AnnData\u002FMuData object using scirpy - chain-pairing QC, clonotype definition, clonal expansion, diversity, repertoire overlap, V(D)J usage, and VDJdb specificity. Operates on the awkward-array AIRR model (adata.obsm['airr'], accessed via get.airr after pp.index_chains), not legacy per-chain obs columns. Use when deciding clonotype definition for TCR (exact CDR3-nt identity via define_clonotypes) versus BCR (nucleotide distance clustering via define_clonotype_clusters with normalized_hamming plus same_v_gene\u002Fsame_j_gene, because somatic hypermutation shatters identity clonotypes); tuning receptor_arms (all vs any), dual_ir, and within_group; filtering chain_qc categories (multichain doublets, orphan dropout, extra-VJ dual-TCR) without biasing clonal-expansion and diversity estimates; and overlaying clonality onto the transcriptomic UMAP.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-scirpy-analysis\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-tcr-bcr-analysis-scirpy-analysis\ndescription: Integrates single-cell paired TCR\u002FBCR (10x VDJ, AIRR, dandelion, BD Rhapsody) with gene expression in an AnnData\u002FMuData object using scirpy - chain-pairing QC, clonotype definition, clonal expansion, diversity, repertoire overlap, V(D)J usage, and VDJdb specificity. Operates on the awkward-array AIRR model (adata.obsm['airr'], accessed via get.airr after pp.index_chains), not legacy per-chain obs columns. Use when deciding clonotype definition for TCR (exact CDR3-nt identity via define_clonotypes) versus BCR (nucleotide distance clustering via define_clonotype_clusters with normalized_hamming plus same_v_gene\u002Fsame_j_gene, because somatic hypermutation shatters identity clonotypes); tuning receptor_arms (all vs any), dual_ir, and within_group; filtering chain_qc categories (multichain doublets, orphan dropout, extra-VJ dual-TCR) without biasing clonal-expansion and diversity estimates; and overlaying clonality onto the transcriptomic UMAP.\ntool_type: python\nprimary_tool: scirpy\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"tcr-bcr-analysis\u002Fscirpy-analysis\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: scirpy 0.24+, scanpy 1.10+, anndata 0.10+, mudata 0.3+, awkward 2+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nNote: since scirpy 0.13 the AIRR receptor data lives as an awkward array in `adata.obsm['airr']`, NOT in per-chain `adata.obs['IR_VJ_1_*']` columns. Fields are read with `scirpy.get.airr(...)` after `scirpy.pp.index_chains(...)`. Legacy (pre-0.13) objects must be migrated with `scirpy.io.upgrade_schema()`. Paired GEX+AIRR is held in a MuData with modalities `gex` and `airr`; tool\u002Fplot functions take the MuData and namespace their output obs columns as `airr:\u003Ccolumn>`.\n\n# scirpy Analysis\n\n**\"Analyze my single-cell paired TCR\u002FBCR alongside gene expression\"** -> Ingest AIRR receptor records, QC chain pairing, define clonotypes, and overlay clonality on the transcriptomic embedding, all in one AnnData\u002FMuData object.\n- Python: `scirpy.io.read_10x_vdj()` \u002F `read_airr()` \u002F `from_dandelion()`, `scirpy.pp.index_chains()`, `scirpy.tl.chain_qc()`, `scirpy.tl.define_clonotypes()` (TCR) or `scirpy.tl.define_clonotype_clusters()` (BCR)\n\n## The governing principles\n\nTwo choices silently bias every downstream expansion, diversity, and overlap number. State both explicitly whenever reporting a result.\n\nPrinciple 1 - the clonotype definition is a choice, and TCR and BCR need different ones. TCR does not somatically hypermutate, so all progeny of a founding T cell share the exact CDR3 nucleotide sequence: `tl.define_clonotypes` (implicit `metric='identity', sequence='nt'`) on CDR3-nt plus V and J is correct and defensible. B cells DO hypermutate during affinity maturation, so lineage members are NOT identical - `tl.define_clonotypes` shatters one true BCR lineage into dozens of fake singletons and destroys expansion and diversity estimates (Gupta 2015 *Bioinformatics* 31:3356). BCR requires `tl.define_clonotype_clusters` with a distance metric (`normalized_hamming`), `sequence='nt'` (SHM acts on nucleotides), and `same_v_gene=True, same_j_gene=True` to approximate clonal lineages. Even then scirpy returns clonal CLUSTERS, not germline-rooted phylogenies - hand off to Immcantation\u002Fdandelion\u002FDowser for true lineages, mutation calling, and selection.\n\nPrinciple 2 - single-cell chain QC is the domain-specific hard part, and blanket filtering biases clonality upward. `tl.chain_qc` labels each cell (single pair, orphan VJ\u002FVDJ, extra VJ\u002FVDJ, two full chains, multichain, ambiguous). Multichain and TCR+BCR-ambiguous cells are likely doublets and are excluded from clonotype definition regardless. But dropping ALL orphan and extra-chain cells is not free: large clones capture both chains more often, so orphans are enriched for singletons, and deleting them preferentially removes small clones - inflating apparent clonal expansion and deflating diversity. Match the filter to the question, and report it.\n\n## Clonotype definition: which function\n\n**Goal:** Pick the clonotyping approach that matches the receptor's biology.\n\n| Question | Function | metric \u002F sequence | Best when | Fails when |\n|----------|----------|-------------------|-----------|------------|\n| TCR clonal identity | `define_clonotypes` | identity \u002F nt (implicit) | TCR (no SHM); exact founder-lineage identity | Applied to BCR - SHM fragments lineages |\n| BCR clonal lineage (approx.) | `define_clonotype_clusters` | normalized_hamming \u002F nt + same_v_gene + same_j_gene | BCR; group SHM-diverged members of one lineage | Threshold not data-derived -> chains\u002Fmerges clones |\n| Convergent\u002Ffunctional TCR clusters | `define_clonotype_clusters` | tcrdist or alignment \u002F aa | Antigen-convergent TCRs (different nt, same specificity) | Interpreted as recombination-event counts |\n| Reconcile with bulk beta\u002Fheavy-only | `define_clonotype_clusters` | receptor_arms='VDJ' | Matching single-cell to bulk TRB\u002FIGH repertoires | Paired-chain specificity is discarded |\n\n`pp.ir_dist` computes and caches the VJ\u002FVDJ distance matrices; the subsequent `define_*` call MUST use the SAME `metric` and `sequence` or the cached distances silently mismatch the grouping. For BCR the `cutoff` for `normalized_hamming` is a PERCENT distance, not a nucleotide count: `cutoff=15` means 15% mismatch (~85% identity). Set it from the bimodal distance-to-nearest-neighbor histogram (within-clone mode near 0 vs between-clone mode).\n\n## Clustering parameters and their biology\n\n| Parameter | Options | Meaning \u002F when to change |\n|-----------|---------|--------------------------|\n| `receptor_arms` | all \u002F any \u002F VJ \u002F VDJ | `all` (default): BOTH VJ (alpha\u002Flight) and VDJ (beta\u002Fheavy) must match - stringent, high specificity. `any` rescues single-arm dropout but can merge distinct clones sharing only a beta (beta convergence is real). `VDJ` mimics bulk beta\u002Fheavy-only clonotyping. |\n| `dual_ir` | any \u002F primary_only \u002F all | Handles two chains of one arm. ~30% of T cells carry two productive TRA (allelic inclusion, Padovan 1993 *Science* 262:422) - so extra-VJ is real dual-TCR, not junk. `primary_only` uses the highest-UMI chain; `any` links cells sharing any chain; `all` requires both to correspond. |\n| `same_v_gene` \u002F `same_j_gene` | False \u002F True | Require identical V (and J) gene, not just CDR3. Two cells can convergently share a CDR3 from different V genes; requiring same V\u002FJ enforces common ancestry. Turn ON for BCR lineage stringency. |\n| `within_group` | 'receptor_type' (default) \u002F obs col | Never merge clonotypes across this grouping. Default stops a B cell and a T cell joining one clonotype; set to sample\u002Fpatient to forbid cross-sample clonotypes. |\n\n## Load VDJ and build the joint object\n\n**Goal:** Ingest receptor contigs and pair them with gene expression in one MuData.\n\n**Approach:** `read_10x_vdj` (or `read_airr` \u002F `from_dandelion`) returns an AIRR AnnData; wrap it with the GEX AnnData in a MuData keyed `gex`\u002F`airr`, then index chains before any QC or clonotyping.\n\n```python\nimport scirpy as ir\nimport scanpy as sc\nimport mudata as mu\n\nadata_gex = sc.read_10x_h5('filtered_feature_bc_matrix.h5')\nadata_airr = ir.io.read_10x_vdj('filtered_contig_annotations.csv')  # returns an AnnData, does NOT modify in place\n# ir.io.read_airr(['tra.tsv', 'trb.tsv'])  # AIRR TSV from dandelion\u002FImmcantation\u002Fairrflow\n# ir.io.from_dandelion(dandelion_obj)      # round-trip a dandelion Dandelion object\n# ir.io.upgrade_schema(legacy_adata)       # migrate a pre-0.13 obs-column object first\n\nmdata = mu.MuData({'gex': adata_gex, 'airr': adata_airr})\nir.pp.index_chains(mdata)  # REQUIRED before QC\u002Fclonotyping; builds obsm['chain_indices']\n```\n\n## Chain QC and question-aware filtering\n\n**Goal:** Categorize chain pairing and remove doublets without silently biasing clonality.\n\n**Approach:** Run `chain_qc`, always drop multichain and TCR+BCR-ambiguous doublets, and decide orphan\u002Fextra retention by the downstream question - keep orphans for pure GEX overlay, drop them only for paired-clonotype\u002Fspecificity work.\n\n```python\nir.tl.chain_qc(mdata)  # writes obs: airr:receptor_type, airr:receptor_subtype, airr:chain_pairing\nprint(mdata.obs['airr:chain_pairing'].value_counts())\n\n# Always exclude likely doublets from clonotype definition.\ndrop = ['multichain']\nkeep_types = mdata.obs['airr:receptor_type'].isin(['TCR', 'BCR'])  # exclude 'ambiguous' (TCR+BCR doublet)\npaired = mdata[keep_types & ~mdata.obs['airr:chain_pairing'].isin(drop)].copy()\n\n# For paired-clonotype\u002Fspecificity analysis also require a complete receptor (drop orphans),\n# but note this preferentially deletes small clones -> inflates expansion, deflates diversity.\ncomplete = paired[paired.obs['airr:chain_pairing'].isin(['single pair', 'extra VJ', 'extra VDJ'])].copy()\n```\n\n## Define clonotypes - TCR (identity)\n\n**Goal:** Group T cells sharing an exact CDR3-nucleotide founder rearrangement.\n\n**Approach:** Cache identity distances, then partition; identity on CDR3-nt plus matching arms is the correct TCR clonotype.\n\n```python\nir.pp.ir_dist(complete, metric='identity', sequence='nt', cutoff=0)\nir.tl.define_clonotypes(complete, receptor_arms='all', dual_ir='primary_only')  # writes airr:clone_id\nprint('TCR clonotypes:', complete.obs['airr:clone_id'].nunique())\n```\n\n## Define clonotypes - BCR (distance clusters)\n\n**Goal:** Group SHM-diverged B cells of one lineage that identity clonotyping would shatter.\n\n**Approach:** Use normalized Hamming distance on nucleotides within same-V\u002Fsame-J partitions - this approximates a clonal lineage; identity clonotyping is WRONG for BCR.\n\n```python\n# cutoff=15 is a PERCENT distance for normalized_hamming (15% mismatch ~= 85% identity), NOT 15 nt;\n# confirm from the distance-to-nearest-neighbor histogram (bimodal trough).\nir.pp.ir_dist(complete, metric='normalized_hamming', sequence='nt', cutoff=15)\nir.tl.define_clonotype_clusters(\n    complete,\n    sequence='nt', metric='normalized_hamming',\n    receptor_arms='all', dual_ir='any',\n    same_v_gene=True, same_j_gene=True,   # enforce common ancestry for lineage-grade clones\n)  # writes airr:cc_nt_normalized_hamming (a clonotype-cluster id column)\n# For true germline-rooted lineages, SHM, and selection: hand off to immcantation-analysis \u002F dandelion \u002F Dowser.\n```\n\n## Clonal expansion and diversity\n\n**Goal:** Quantify how expanded each clone is and how diverse each group's repertoire is.\n\n**Approach:** Bin cells by clone size, then compute per-group diversity - but remember both numbers depend entirely on the QC filter and clonotype definition above, so report them alongside.\n\n```python\n# target_col is resolved WITHIN the airr modality, so pass the bare name 'clone_id', not 'airr:clone_id'.\nir.tl.clonal_expansion(mdata, target_col='clone_id')  # bins per cell: singleton \u002F 2 \u002F >= 3 (breakpoints=(1, 2))\nir.pl.clonal_expansion(mdata, target_col='clone_id', groupby='airr:receptor_subtype')\n\n# Alpha diversity per group; groupby names a full mdata.obs column, so it keeps its modality prefix.\nir.tl.alpha_diversity(mdata, groupby='gex:sample', target_col='clone_id', metric='normalized_shannon_entropy')\n\n# Pairwise repertoire sharing (public\u002Fexpanded clones, trafficking) - depth-sensitive; compare at equal depth.\nir.tl.repertoire_overlap(mdata, groupby='gex:sample', target_col='clone_id')\nir.pl.repertoire_overlap(mdata, groupby='gex:sample')\n```\n\n## Overlay clonality on the transcriptome\n\n**Goal:** See which cell states the expanded clones occupy.\n\n**Approach:** Cluster on GEX independently (never on receptor sequence), then color the transcriptomic UMAP by a clonality column pushed into the GEX modality.\n\n```python\n# GEX pipeline lives on mdata['gex']: normalize -> HVG -> PCA -> neighbors -> leiden -> umap (see single-cell\u002Fclustering).\nmdata['gex'].obs['clonal_expansion'] = mdata.obs['airr:clonal_expansion']\nsc.pl.umap(mdata['gex'], color='clonal_expansion')\n\n# clonotype_modularity tests whether a clone's cells are more transcriptionally connected than random\n# (needs sc.pp.neighbors on the GEX modality first) - distinguishes a coherent functional clone from scatter.\nir.tl.clonotype_modularity(mdata, target_col='clone_id')\n```\n\n## Gene usage and specificity\n\n**Goal:** Summarize V(D)J segment usage and annotate antigen specificity.\n\n**Approach:** Plot usage\u002Fspectratype directly; for specificity, match receptors against a reference database by sequence distance (not ML prediction).\n\n```python\nir.pl.vdj_usage(mdata, full_combination=False)      # V-D-J segment flow (Sankey\u002Fribbon)\nir.pl.spectratype(mdata, chain='VDJ_1', color='airr:receptor_subtype')  # CDR3-length distribution\n\n# Antigen specificity by sequence match to a reference DB (reuses the ir_dist machinery).\nvdjdb = ir.datasets.vdjdb()\nir.tl.ir_query(mdata, vdjdb, metric='identity', sequence='aa')\nir.tl.ir_query_annotate(mdata, vdjdb, include_ref_cols=['antigen.species', 'antigen.epitope'])\n# For deeper TCR specificity modelling leave scirpy for tcrdist3 \u002F CoNGA (see specificity-annotation).\n```\n\n## Export AIRR\n\n**Goal:** Hand the receptor table to a bulk\u002Finterchange tool.\n\n**Approach:** Write the AIRR modality as a standard rearrangement TSV; do NOT reconstruct it from stale per-chain obs columns (they no longer exist).\n\n```python\nir.io.write_airr(mdata['airr'], 'scirpy_airr.tsv')\n# Pull specific fields for a custom table with the get accessor, not obs indexing:\njunction_vj = ir.get.airr(mdata, 'junction_aa', 'VJ_1')   # pandas Series\nwith ir.get.airr_context(mdata, 'junction_aa', ['VJ_1', 'VDJ_1']):\n    pass  # AIRR fields temporarily materialized into obs for grouping\u002Fplotting\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| BCR lineages appear as hundreds of singletons; no expansion | Identity `define_clonotypes` used on B cells; SHM makes members non-identical | Use `define_clonotype_clusters` with `metric='normalized_hamming', sequence='nt', same_v_gene=True, same_j_gene=True` |\n| `KeyError: 'IR_VJ_1_junction_aa'` \u002F obs receptor columns missing | Pre-0.13 schema assumed; AIRR now lives in `obsm['airr']` | Access via `ir.get.airr(...)` after `pp.index_chains`; migrate legacy objects with `io.upgrade_schema()` |\n| Expansion looks high, diversity looks low vs a collaborator | Blanket-filtered all orphan\u002Fextra-chain cells, deleting small clones | Keep orphans for GEX overlay; only drop them for paired-clonotype work, and report the filter |\n| `define_*` gives grouping that ignores the chosen metric | `pp.ir_dist` metric\u002Fsequence differ from the `define_*` call | Match `metric` and `sequence` between `ir_dist` and `define_clonotype_clusters` |\n| Clonotype\u002FQC functions error or return nothing | `pp.index_chains` not run before QC\u002Fclonotyping | Run `ir.pp.index_chains(mdata)` immediately after building the MuData |\n| Real T\u002FB cells look receptor-negative | GEX-only cells (contig dropout) treated as VDJ-negative | Keep GEX-only cells with `NaN` clonotype for cell-state analysis; only drop VDJ-only cells failing GEX QC |\n| Spurious shared\u002Fsecondary chains in a hyperexpanded sample | Ambient VDJ mRNA from a dominant clone mis-assigned to droplets | Start from CellRanger `filtered_contig_annotations` (is_cell\u002Fhigh_confidence\u002Fproductive), then drop secondary chains with very low UMI support (`duplicate_count`\u002F`consensus_count`, e.g. \u003C 2-3) before clonotyping |\n| BCR distance clusters look degraded even with correct settings | CellRanger BCR contigs are not IMGT-numbered and include partial\u002Fnonproductive contigs | Reannotate with IgBLAST (dandelion\u002Fairrflow) before `define_clonotype_clusters`, or hand off to Immcantation |\n\n## Related Skills\n\n- mixcr-analysis - Process raw single-cell VDJ FASTQ\n- immcantation-analysis - Proper BCR clonal lineages and SHM downstream\n- specificity-annotation - Antigen-specificity clustering on single-cell clonotypes\n- single-cell\u002Fdata-io - Load and manage the GEX AnnData\u002FMuData\n- single-cell\u002Fclustering - Cell-state clustering to overlay clonality\n- single-cell\u002Fdoublet-detection - Corroborate multichain doublet calls\n\n## References\n\n- Sturm G, Szabo T, Fotakis G, Haider M, Rieder D, Trajanoski Z, Finotello F. Scirpy: a Scanpy extension for analyzing single-cell T-cell receptor-sequencing data. *Bioinformatics* 2020;36(18):4817-4818. doi:10.1093\u002Fbioinformatics\u002Fbtaa611.\n- Suo C, Polanski K, Dann E, et al. Dandelion uses the single-cell adaptive immune receptor repertoire to explore lymphocyte developmental origins. *Nature Biotechnology* 2024;42:40-51. doi:10.1038\u002Fs41587-023-01734-7.\n- Gupta NT, Vander Heiden JA, Uduman M, Gadala-Maria D, Yaari G, Kleinstein SH. Change-O: a toolkit for analyzing large-scale B cell immunoglobulin repertoire sequencing data. *Bioinformatics* 2015;31(20):3356-3358. doi:10.1093\u002Fbioinformatics\u002Fbtv359.\n- Padovan E, Casorati G, Dellabona P, Meyer S, Brockhaus M, Lanzavecchia A. Expression of two T cell receptor alpha chains: dual receptor T cells. *Science* 1993;262:422-424. doi:10.1126\u002Fscience.8211163.\n- Vander Heiden JA, Marquez S, Marthandan N, et al. AIRR Community standardized representations for annotated immune repertoires. *Frontiers in Immunology* 2018;9:2206. doi:10.3389\u002Ffimmu.2018.02206.\n","## Version Compatibility\n\nReference examples tested with: scirpy 0.24+, scanpy 1.10+, anndata 0.10+, mudata 0.3+, awkward 2+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nNote: since scirpy 0.13 the AIRR receptor data lives as an awkward array in `adata.obsm['airr']`, NOT in per-chain `adata.obs['IR_VJ_1_*']` columns. Fields are read with `scirpy.get.airr(...)` after `scirpy.pp.index_chains(...)`. Legacy (pre-0.13) objects must be migrated with `scirpy.io.upgrade_schema()`. Paired GEX+AIRR is held in a MuData with modalities `gex` and `airr`; tool\u002Fplot functions take the MuData and namespace their output obs columns as `airr:\u003Ccolumn>`.\n\n# scirpy Analysis\n\n**\"Analyze my single-cell paired TCR\u002FBCR alongside gene expression\"** -> Ingest AIRR receptor records, QC chain pairing, define clonotypes, and overlay clonality on the transcriptomic embedding, all in one AnnData\u002FMuData object.\n- Python: `scirpy.io.read_10x_vdj()` \u002F `read_airr()` \u002F `from_dandelion()`, `scirpy.pp.index_chains()`, `scirpy.tl.chain_qc()`, `scirpy.tl.define_clonotypes()` (TCR) or `scirpy.tl.define_clonotype_clusters()` (BCR)\n\n## The governing principles\n\nTwo choices silently bias every downstream expansion, diversity, and overlap number. State both explicitly whenever reporting a result.\n\nPrinciple 1 - the clonotype definition is a choice, and TCR and BCR need different ones. TCR does not somatically hypermutate, so all progeny of a founding T cell share the exact CDR3 nucleotide sequence: `tl.define_clonotypes` (implicit `metric='identity', sequence='nt'`) on CDR3-nt plus V and J is correct and defensible. B cells DO hypermutate during affinity maturation, so lineage members are NOT identical - `tl.define_clonotypes` shatters one true BCR lineage into dozens of fake singletons and destroys expansion and diversity estimates (Gupta 2015 *Bioinformatics* 31:3356). BCR requires `tl.define_clonotype_clusters` with a distance metric (`normalized_hamming`), `sequence='nt'` (SHM acts on nucleotides), and `same_v_gene=True, same_j_gene=True` to approximate clonal lineages. Even then scirpy returns clonal CLUSTERS, not germline-rooted phylogenies - hand off to Immcantation\u002Fdandelion\u002FDowser for true lineages, mutation calling, and selection.\n\nPrinciple 2 - single-cell chain QC is the domain-specific hard part, and blanket filtering biases clonality upward. `tl.chain_qc` labels each cell (single pair, orphan VJ\u002FVDJ, extra VJ\u002FVDJ, two full chains, multichain, ambiguous). Multichain and TCR+BCR-ambiguous cells are likely doublets and are excluded from clonotype definition regardless. But dropping ALL orphan and extra-chain cells is not free: large clones capture both chains more often, so orphans are enriched for singletons, and deleting them preferentially removes small clones - inflating apparent clonal expansion and deflating diversity. Match the filter to the question, and report it.\n\n## Clonotype definition: which function\n\n**Goal:** Pick the clonotyping approach that matches the receptor's biology.\n\n| Question | Function | metric \u002F sequence | Best when | Fails when |\n|----------|----------|-------------------|-----------|------------|\n| TCR clonal identity | `define_clonotypes` | identity \u002F nt (implicit) | TCR (no SHM); exact founder-lineage identity | Applied to BCR - SHM fragments lineages |\n| BCR clonal lineage (approx.) | `define_clonotype_clusters` | normalized_hamming \u002F nt + same_v_gene + same_j_gene | BCR; group SHM-diverged members of one lineage | Threshold not data-derived -> chains\u002Fmerges clones |\n| Convergent\u002Ffunctional TCR clusters | `define_clonotype_clusters` | tcrdist or alignment \u002F aa | Antigen-convergent TCRs (different nt, same specificity) | Interpreted as recombination-event counts |\n| Reconcile with bulk beta\u002Fheavy-only | `define_clonotype_clusters` | receptor_arms='VDJ' | Matching single-cell to bulk TRB\u002FIGH repertoires | Paired-chain specificity is discarded |\n\n`pp.ir_dist` computes and caches the VJ\u002FVDJ distance matrices; the subsequent `define_*` call MUST use the SAME `metric` and `sequence` or the cached distances silently mismatch the grouping. For BCR the `cutoff` for `normalized_hamming` is a PERCENT distance, not a nucleotide count: `cutoff=15` means 15% mismatch (~85% identity). Set it from the bimodal distance-to-nearest-neighbor histogram (within-clone mode near 0 vs between-clone mode).\n\n## Clustering parameters and their biology\n\n| Parameter | Options | Meaning \u002F when to change |\n|-----------|---------|--------------------------|\n| `receptor_arms` | all \u002F any \u002F VJ \u002F VDJ | `all` (default): BOTH VJ (alpha\u002Flight) and VDJ (beta\u002Fheavy) must match - stringent, high specificity. `any` rescues single-arm dropout but can merge distinct clones sharing only a beta (beta convergence is real). `VDJ` mimics bulk beta\u002Fheavy-only clonotyping. |\n| `dual_ir` | any \u002F primary_only \u002F all | Handles two chains of one arm. ~30% of T cells carry two productive TRA (allelic inclusion, Padovan 1993 *Science* 262:422) - so extra-VJ is real dual-TCR, not junk. `primary_only` uses the highest-UMI chain; `any` links cells sharing any chain; `all` requires both to correspond. |\n| `same_v_gene` \u002F `same_j_gene` | False \u002F True | Require identical V (and J) gene, not just CDR3. Two cells can convergently share a CDR3 from different V genes; requiring same V\u002FJ enforces common ancestry. Turn ON for BCR lineage stringency. |\n| `within_group` | 'receptor_type' (default) \u002F obs col | Never merge clonotypes across this grouping. Default stops a B cell and a T cell joining one clonotype; set to sample\u002Fpatient to forbid cross-sample clonotypes. |\n\n## Load VDJ and build the joint object\n\n**Goal:** Ingest receptor contigs and pair them with gene expression in one MuData.\n\n**Approach:** `read_10x_vdj` (or `read_airr` \u002F `from_dandelion`) returns an AIRR AnnData; wrap it with the GEX AnnData in a MuData keyed `gex`\u002F`airr`, then index chains before any QC or clonotyping.\n\n```python\nimport scirpy as ir\nimport scanpy as sc\nimport mudata as mu\n\nadata_gex = sc.read_10x_h5('filtered_feature_bc_matrix.h5')\nadata_airr = ir.io.read_10x_vdj('filtered_contig_annotations.csv')  # returns an AnnData, does NOT modify in place\n# ir.io.read_airr(['tra.tsv', 'trb.tsv'])  # AIRR TSV from dandelion\u002FImmcantation\u002Fairrflow\n# ir.io.from_dandelion(dandelion_obj)      # round-trip a dandelion Dandelion object\n# ir.io.upgrade_schema(legacy_adata)       # migrate a pre-0.13 obs-column object first\n\nmdata = mu.MuData({'gex': adata_gex, 'airr': adata_airr})\nir.pp.index_chains(mdata)  # REQUIRED before QC\u002Fclonotyping; builds obsm['chain_indices']\n```\n\n## Chain QC and question-aware filtering\n\n**Goal:** Categorize chain pairing and remove doublets without silently biasing clonality.\n\n**Approach:** Run `chain_qc`, always drop multichain and TCR+BCR-ambiguous doublets, and decide orphan\u002Fextra retention by the downstream question - keep orphans for pure GEX overlay, drop them only for paired-clonotype\u002Fspecificity work.\n\n```python\nir.tl.chain_qc(mdata)  # writes obs: airr:receptor_type, airr:receptor_subtype, airr:chain_pairing\nprint(mdata.obs['airr:chain_pairing'].value_counts())\n\n# Always exclude likely doublets from clonotype definition.\ndrop = ['multichain']\nkeep_types = mdata.obs['airr:receptor_type'].isin(['TCR', 'BCR'])  # exclude 'ambiguous' (TCR+BCR doublet)\npaired = mdata[keep_types & ~mdata.obs['airr:chain_pairing'].isin(drop)].copy()\n\n# For paired-clonotype\u002Fspecificity analysis also require a complete receptor (drop orphans),\n# but note this preferentially deletes small clones -> inflates expansion, deflates diversity.\ncomplete = paired[paired.obs['airr:chain_pairing'].isin(['single pair', 'extra VJ', 'extra VDJ'])].copy()\n```\n\n## Define clonotypes - TCR (identity)\n\n**Goal:** Group T cells sharing an exact CDR3-nucleotide founder rearrangement.\n\n**Approach:** Cache identity distances, then partition; identity on CDR3-nt plus matching arms is the correct TCR clonotype.\n\n```python\nir.pp.ir_dist(complete, metric='identity', sequence='nt', cutoff=0)\nir.tl.define_clonotypes(complete, receptor_arms='all', dual_ir='primary_only')  # writes airr:clone_id\nprint('TCR clonotypes:', complete.obs['airr:clone_id'].nunique())\n```\n\n## Define clonotypes - BCR (distance clusters)\n\n**Goal:** Group SHM-diverged B cells of one lineage that identity clonotyping would shatter.\n\n**Approach:** Use normalized Hamming distance on nucleotides within same-V\u002Fsame-J partitions - this approximates a clonal lineage; identity clonotyping is WRONG for BCR.\n\n```python\n# cutoff=15 is a PERCENT distance for normalized_hamming (15% mismatch ~= 85% identity), NOT 15 nt;\n# confirm from the distance-to-nearest-neighbor histogram (bimodal trough).\nir.pp.ir_dist(complete, metric='normalized_hamming', sequence='nt', cutoff=15)\nir.tl.define_clonotype_clusters(\n    complete,\n    sequence='nt', metric='normalized_hamming',\n    receptor_arms='all', dual_ir='any',\n    same_v_gene=True, same_j_gene=True,   # enforce common ancestry for lineage-grade clones\n)  # writes airr:cc_nt_normalized_hamming (a clonotype-cluster id column)\n# For true germline-rooted lineages, SHM, and selection: hand off to immcantation-analysis \u002F dandelion \u002F Dowser.\n```\n\n## Clonal expansion and diversity\n\n**Goal:** Quantify how expanded each clone is and how diverse each group's repertoire is.\n\n**Approach:** Bin cells by clone size, then compute per-group diversity - but remember both numbers depend entirely on the QC filter and clonotype definition above, so report them alongside.\n\n```python\n# target_col is resolved WITHIN the airr modality, so pass the bare name 'clone_id', not 'airr:clone_id'.\nir.tl.clonal_expansion(mdata, target_col='clone_id')  # bins per cell: singleton \u002F 2 \u002F >= 3 (breakpoints=(1, 2))\nir.pl.clonal_expansion(mdata, target_col='clone_id', groupby='airr:receptor_subtype')\n\n# Alpha diversity per group; groupby names a full mdata.obs column, so it keeps its modality prefix.\nir.tl.alpha_diversity(mdata, groupby='gex:sample', target_col='clone_id', metric='normalized_shannon_entropy')\n\n# Pairwise repertoire sharing (public\u002Fexpanded clones, trafficking) - depth-sensitive; compare at equal depth.\nir.tl.repertoire_overlap(mdata, groupby='gex:sample', target_col='clone_id')\nir.pl.repertoire_overlap(mdata, groupby='gex:sample')\n```\n\n## Overlay clonality on the transcriptome\n\n**Goal:** See which cell states the expanded clones occupy.\n\n**Approach:** Cluster on GEX independently (never on receptor sequence), then color the transcriptomic UMAP by a clonality column pushed into the GEX modality.\n\n```python\n# GEX pipeline lives on mdata['gex']: normalize -> HVG -> PCA -> neighbors -> leiden -> umap (see single-cell\u002Fclustering).\nmdata['gex'].obs['clonal_expansion'] = mdata.obs['airr:clonal_expansion']\nsc.pl.umap(mdata['gex'], color='clonal_expansion')\n\n# clonotype_modularity tests whether a clone's cells are more transcriptionally connected than random\n# (needs sc.pp.neighbors on the GEX modality first) - distinguishes a coherent functional clone from scatter.\nir.tl.clonotype_modularity(mdata, target_col='clone_id')\n```\n\n## Gene usage and specificity\n\n**Goal:** Summarize V(D)J segment usage and annotate antigen specificity.\n\n**Approach:** Plot usage\u002Fspectratype directly; for specificity, match receptors against a reference database by sequence distance (not ML prediction).\n\n```python\nir.pl.vdj_usage(mdata, full_combination=False)      # V-D-J segment flow (Sankey\u002Fribbon)\nir.pl.spectratype(mdata, chain='VDJ_1', color='airr:receptor_subtype')  # CDR3-length distribution\n\n# Antigen specificity by sequence match to a reference DB (reuses the ir_dist machinery).\nvdjdb = ir.datasets.vdjdb()\nir.tl.ir_query(mdata, vdjdb, metric='identity', sequence='aa')\nir.tl.ir_query_annotate(mdata, vdjdb, include_ref_cols=['antigen.species', 'antigen.epitope'])\n# For deeper TCR specificity modelling leave scirpy for tcrdist3 \u002F CoNGA (see specificity-annotation).\n```\n\n## Export AIRR\n\n**Goal:** Hand the receptor table to a bulk\u002Finterchange tool.\n\n**Approach:** Write the AIRR modality as a standard rearrangement TSV; do NOT reconstruct it from stale per-chain obs columns (they no longer exist).\n\n```python\nir.io.write_airr(mdata['airr'], 'scirpy_airr.tsv')\n# Pull specific fields for a custom table with the get accessor, not obs indexing:\njunction_vj = ir.get.airr(mdata, 'junction_aa', 'VJ_1')   # pandas Series\nwith ir.get.airr_context(mdata, 'junction_aa', ['VJ_1', 'VDJ_1']):\n    pass  # AIRR fields temporarily materialized into obs for grouping\u002Fplotting\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| BCR lineages appear as hundreds of singletons; no expansion | Identity `define_clonotypes` used on B cells; SHM makes members non-identical | Use `define_clonotype_clusters` with `metric='normalized_hamming', sequence='nt', same_v_gene=True, same_j_gene=True` |\n| `KeyError: 'IR_VJ_1_junction_aa'` \u002F obs receptor columns missing | Pre-0.13 schema assumed; AIRR now lives in `obsm['airr']` | Access via `ir.get.airr(...)` after `pp.index_chains`; migrate legacy objects with `io.upgrade_schema()` |\n| Expansion looks high, diversity looks low vs a collaborator | Blanket-filtered all orphan\u002Fextra-chain cells, deleting small clones | Keep orphans for GEX overlay; only drop them for paired-clonotype work, and report the filter |\n| `define_*` gives grouping that ignores the chosen metric | `pp.ir_dist` metric\u002Fsequence differ from the `define_*` call | Match `metric` and `sequence` between `ir_dist` and `define_clonotype_clusters` |\n| Clonotype\u002FQC functions error or return nothing | `pp.index_chains` not run before QC\u002Fclonotyping | Run `ir.pp.index_chains(mdata)` immediately after building the MuData |\n| Real T\u002FB cells look receptor-negative | GEX-only cells (contig dropout) treated as VDJ-negative | Keep GEX-only cells with `NaN` clonotype for cell-state analysis; only drop VDJ-only cells failing GEX QC |\n| Spurious shared\u002Fsecondary chains in a hyperexpanded sample | Ambient VDJ mRNA from a dominant clone mis-assigned to droplets | Start from CellRanger `filtered_contig_annotations` (is_cell\u002Fhigh_confidence\u002Fproductive), then drop secondary chains with very low UMI support (`duplicate_count`\u002F`consensus_count`, e.g. \u003C 2-3) before clonotyping |\n| BCR distance clusters look degraded even with correct settings | CellRanger BCR contigs are not IMGT-numbered and include partial\u002Fnonproductive contigs | Reannotate with IgBLAST (dandelion\u002Fairrflow) before `define_clonotype_clusters`, or hand off to Immcantation |\n\n## Related Skills\n\n- mixcr-analysis - Process raw single-cell VDJ FASTQ\n- immcantation-analysis - Proper BCR clonal lineages and SHM downstream\n- specificity-annotation - Antigen-specificity clustering on single-cell clonotypes\n- single-cell\u002Fdata-io - Load and manage the GEX AnnData\u002FMuData\n- single-cell\u002Fclustering - Cell-state clustering to overlay clonality\n- single-cell\u002Fdoublet-detection - Corroborate multichain doublet calls\n\n## References\n\n- Sturm G, Szabo T, Fotakis G, Haider M, Rieder D, Trajanoski Z, Finotello F. Scirpy: a Scanpy extension for analyzing single-cell T-cell receptor-sequencing data. *Bioinformatics* 2020;36(18):4817-4818. doi:10.1093\u002Fbioinformatics\u002Fbtaa611.\n- Suo C, Polanski K, Dann E, et al. Dandelion uses the single-cell adaptive immune receptor repertoire to explore lymphocyte developmental origins. *Nature Biotechnology* 2024;42:40-51. doi:10.1038\u002Fs41587-023-01734-7.\n- Gupta NT, Vander Heiden JA, Uduman M, Gadala-Maria D, Yaari G, Kleinstein SH. Change-O: a toolkit for analyzing large-scale B cell immunoglobulin repertoire sequencing data. *Bioinformatics* 2015;31(20):3356-3358. doi:10.1093\u002Fbioinformatics\u002Fbtv359.\n- Padovan E, Casorati G, Dellabona P, Meyer S, Brockhaus M, Lanzavecchia A. Expression of two T cell receptor alpha chains: dual receptor T cells. *Science* 1993;262:422-424. doi:10.1126\u002Fscience.8211163.\n- Vander Heiden JA, Marquez S, Marthandan N, et al. AIRR Community standardized representations for annotated immune repertoires. *Frontiers in Immunology* 2018;9:2206. doi:10.3389\u002Ffimmu.2018.02206.\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","python","2026-09-20","tcr-bcr-analysis\u002Fscirpy-analysis\u002FSKILL.md","scirpy","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-scirpy-analysis","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-scirpy-analysis",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-scirpy-analysis",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-tcr-bcr-analysis-scirpy-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-scirpy-analysis\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fscirpy_integration.py","SCRIPT","脚本",4240,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-scirpy-analysis\u002Fexamples\u002Fscirpy_integration.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",5189,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-tcr-bcr-analysis-scirpy-analysis\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]