Source: https://docs.nygen.io/CyteArc/tutorials/immune-repertoires/ Revision: cd2e02032844b36d2f536548f515d9cb0229efb9 Structured page: https://docs.nygen.io/CyteArc/tutorials.immune-repertoires.json Immune repertoires Start from a public 10x Genomics dataset of 10,548 peripheral blood mononuclear cells (PBMCs) from one healthy human donor, import the T cell receptor (TCR) and B cell receptor (BCR) chains of the 9,361 cells that pass quality control, group the cells that share a receptor into clonotypes, and compare the clonal structure of five T cell types. Expanded clones are rare in this donor’s blood: 137 of 4,791 T cells belong to clonotypes of two or more cells. These clonotypes hold 17% of the effector memory CD8 T cells and 24% of the T cells in the cluster of mucosal-associated invariant T (MAIT) and gamma delta (γδ) T cells, against under 3% of the other T cell types. The alpha chains of 85% of that cluster’s clonotypes use TRAV1-2, the V gene of the semi-invariant MAIT receptor, so its T cells with a TCR are mostly MAIT cells. Among 820 B cells, grouping junctions that differ by somatic mutation adds one class-switched IgG1 family to the two pairs of IgM B cells that share identical junctions. A developing T or B cell builds each receptor chain by joining a V and a J gene segment, with a D segment between them in some chains, and nucleotides are lost and added at the joints, so almost every naive cell carries a receptor of its own. The junction of each chain spans the joints and encodes the CDR3 loop, the most variable part of the receptor and its main contact with the antigen. A cell that meets its antigen divides, and its descendants keep its receptor, so the cells of a clone share their receptor, and an expanded clone marks an immune response. Single-cell immune profiling sequences the receptor transcripts of each cell beside its transcriptome. This page is one of four on clonal analysis, and here the receptor itself marks each clone. Lineage tracing follows clones that lentiviral LARRY barcodes mark in mouse hematopoiesis, lineage recorders cuts the PEtracer phylogeny of a mouse embryo into clones, and mitochondrial lineage tracing calls clones in a human tumor from somatic mitochondrial DNA variants. Each page saves its clones in the store as an artifact , a result recorded with its inputs and parameters, and the clone summaries of ds.clones, such as expansion, diversity and overlap, take the clones of any of the four pages. Download the example 10x Genomics publishes “Human PBMC from a Healthy Donor, 10k cells (v2)” under CC BY 4.0: PBMCs of one donor, profiled with a 5’ gene expression library, a library of 19 antibodies, and two V(D)J libraries that enrich the TCR and BCR transcripts of the same cells. Cell Ranger 5.0.0 processed each library. Download three of its files: the filtered feature-barcode matrix, with the cells that Cell Ranger called, and the AIRR Rearrangement file of each V(D)J library, with the chains that Cell Ranger assembled with high confidence in the barcodes it called cells. Each file is checked against its SHA-256 checksum, and a failed download is tried again after a pause. The downloads and the store go to a temporary directory; use a project directory to keep them. import csv import hashlib import shutil import time from http.client import HTTPException from pathlib import Path from tempfile import TemporaryDirectory from urllib.request import Request, urlopen import pandas as pd import cytearc from cytearc.storage.count_matrix import CountMatrixPolicy # Keep routine logs and progress bars out of the results. cytearc.configure_output(level="WARNING", progress=False) # Keep this example's downloads and store together. work = TemporaryDirectory() output_dir = Path(work.name) # Pin the three files so that a changed download cannot alter the example silently. base_url = "https://cf.10xgenomics.com/samples/cell-vdj/5.0.0/sc5p_v2_hs_PBMC_10k/" sources = { "expression": ( "sc5p_v2_hs_PBMC_10k_filtered_feature_bc_matrix.h5", "d82e92f73fbe01bc2b41b1aa96220617cdbad53ef5387edead67daf5f012cc96", ), "tcr": ( "sc5p_v2_hs_PBMC_10k_t_airr_rearrangement.tsv", "70376051c9e6cf2df79c881c38bb25bcf29763d7a57e3e7062b7a95c870e70b0", ), "bcr": ( "sc5p_v2_hs_PBMC_10k_b_airr_rearrangement.tsv", "b031516f2ea81c46ab07f267371d868d28fe22806d55fde65f6c6d91faa78efd", ), } attempts = 3 paths = {} for name, (file_name, expected_digest) in sources.items(): path = output_dir / file_name # Name the client, because the host refuses Python's default one. request = Request(base_url + file_name, headers={"User-Agent": "CyteArc documentation"}) # Copy the response in blocks without holding the file in memory, and try # again after a pause when the connection fails. for attempt in range(1, attempts + 1): try: with urlopen(request, timeout=60) as response, path.open("wb") as target: shutil.copyfileobj(response, target) break except (OSError, HTTPException) as error: if attempt == attempts: raise RuntimeError( f"Downloading {file_name} failed {attempts} times; " f"check the connection to {base_url}" ) from error time.sleep(30 * attempt) # Reject a file whose contents differ from the verified source. with path.open("rb") as source: actual_digest = hashlib.file_digest(source, "sha256").hexdigest() if actual_digest != expected_digest: raise ValueError(f"Checksum mismatch for {path.name}") paths[name] = path # Show the size of each completed download. pd.Series( {name: path.stat().st_size / 1_000_000 for name, path in paths.items()}, name="Downloaded MB", ).round(1) expression 29.9 tcr 25.5 bcr 5.9 Name: Downloaded MB, dtype: float64 Cluster the expression data A cell’s receptor is easier to interpret beside its expression, so start with the expression library. CrToZarr writes its matrix to a new store with an RNA and an ADT assay. The RNA recipe , ds.pipeline.rna, then filters cells on their quality metrics, normalizes the counts of highly variable genes and reduces them with PCA, clusters the cells and embeds them with UMAP, calls doublets, and ranks the markers of each cluster. It returns a pipeline run , the record of these steps, from which run["clusters"], run["umap"] and the other results are read. # Write the expression matrix into a new store, in count shards of half the # default size so that the import fits in the memory of a laptop with 8 GB. store_path = output_dir / "pbmc_10k_v2.zarr" cytearc.CrToZarr( cytearc.CrH5Reader(str(paths["expression"])), zarr_loc=str(store_path), policy=CountMatrixPolicy(unitBytes=500_000_000, chunkBytes=50_000_000), ).dump() # Analyze the RNA assay with the standard recipe. ds = cytearc.DataStore(str(store_path), default_assay="RNA") run = ds.pipeline.rna(label="rna") clusters = run["clusters"] # Count the store's cells and features, and the cells that pass quality # control, which the clusters hold. cluster_labels = ds.artifacts.load_values(clusters).to_pandas() print( f"{ds.cells.N:,} cells, {ds.RNA.feats.N:,} genes and {ds.ADT.feats.N} antibodies; " f"{len(cluster_labels):,} cells pass quality control" ) # Count each cluster's cells and the share that the recipe calls doublets, # and name its strongest markers. predicted_doublets = ds.artifacts.load_values( run["doublets"], value="predicted_doublets" ).to_pandas() markers = ds.markers.load(marker=run["markers"]) top_markers = markers.groupby("group_id", sort=False)["feature_name"].agg( lambda names: ", ".join(names.head(6)) ) pd.DataFrame( { "Cells": cluster_labels.value_counts().sort_index(), "Share of predicted doublets": predicted_doublets.groupby(cluster_labels) .mean() .round(2), "Top markers": top_markers.set_axis(top_markers.index.astype(cluster_labels.dtype)), } ).rename_axis("Cluster") 10,548 cells, 36,601 genes and 19 antibodies; 9,361 cells pass quality control Cells Share of predicted doublets \ Cluster 1 2238 0.00 2 1809 0.00 3 1213 0.01 4 977 0.01 5 879 0.07 6 733 0.00 7 447 0.06 8 379 0.03 9 281 0.03 10 227 0.95 11 98 0.00 12 55 0.02 13 25 0.00 Top markers Cluster 1 ADTRP, FHIT, NOG, CHRM3-AS2, EPHX2, MAL 2 QPCT, NLRP12, FOLR3, CES1, CLEC4E, S100A12 3 TNFRSF4, CRIP2, CD40LG, INPP4B, AQP3, CD28 4 LINC02446, CD248, CD8B, LRRN3, NELL2, C20orf204 5 MS4A1, FCER2, CD19, LINC00926, VPREB3, FCRL1 6 CLEC10A, IL1B, PID1, LGALS2, SIRPA, CPVL 7 KLRF1, SH2D1B, PRSS23, FGFBP2, GNLY, KLRD1 8 CD8A, KLRC4, CD8B, GZMK, TIGIT, LINC01871 9 SLC4A10, TRDV2, RORC, TRGV9, TRAV1-2, SCART1 10 S100A12, S100A8, CYP1B1, S100A9, RGS2, VCAN 11 CDKN1C, CTSL, HES4, NEURL1, AC064805.1, TCF7L2 12 LILRA4, SERPINF1, TPM2, DERL3, MZB1, TLR9 13 CLU, PPBP, SPARC, GNG11, TRIM58, ACRBP # Compare the markers of each cell type across the clusters. marker_panel = { "T cell": ["CD3E", "CD4", "CD8A", "CCR7"], "Cytotoxic": ["GZMK", "NKG7", "GNLY"], "MAIT and γδ T": ["SLC4A10", "KLRB1", "TRDV2", "TRGV9"], "B cell": ["MS4A1", "CD79A"], "Monocyte": ["CD14", "LYZ", "FCGR3A"], "Dendritic cell": ["CLEC10A", "LILRA4"], "Platelet": ["PPBP"], } ds.plots.dotplot(features=marker_panel, groups=clusters, standardize="feature") Dot plot of 19 marker genes in seven bracketed groups, from T cell to platelet markers, across 13 clusters; color shows each gene's standardized mean expression and dot size the share of the cluster's cells that detect it. CD3E is high in clusters 1, 3, 4, 8 and 9, SLC4A10, TRDV2 and TRGV9 only in cluster 9, MS4A1 and CD79A in cluster 5, CD14 and LYZ in clusters 2, 6 and 10, LILRA4 in cluster 12 and PPBP in cluster 13. Image: https://docs.nygen.io/CyteArc/build/de9239ed2155385f43b5911846cdc0aa.png Quality control keeps 9,361 of the 10,548 cells, in 13 clusters. CD3E marks the T cells of clusters 1, 3, 4, 8 and 9. CCR7 with CD4 marks the naive CD4 T cells of cluster 1, and CCR7 with CD8A the naive CD8 T cells of cluster 4. Cluster 3 holds memory CD4 T cells, with less CCR7, and GZMK with CD8A marks the effector memory CD8 T cells of cluster 8. Cluster 9 expresses SLC4A10 and KLRB1, markers of MAIT cells, and TRDV2 and TRGV9, V genes of the delta and gamma chains of γδ T cells; TRAV1-2, the V gene of the MAIT alpha chain, is among its top markers. MS4A1 and CD79A mark the B cells of cluster 5, and NKG7 and GNLY without CD3E the NK cells of cluster 7. CD14 and LYZ mark the classical monocytes of clusters 2 and 6, and CLEC10A the type 2 conventional dendritic cells (cDC2s) that cluster 6 also holds. FCGR3A marks the CD16 monocytes of cluster 11, LILRA4 the plasmacytoid dendritic cells (pDCs) of cluster 12, and PPBP the platelets of cluster 13. Cluster 10 expresses monocyte genes beside some T cell genes, and the recipe calls 95% of its cells doublets, droplets that captured two cells. Name each cluster by its cell type, and save each cell’s type as a cell column, so that later steps can group cells by it. # Name each cluster by its cell type. cell_type_by_cluster = { 1: "CD4 naive", 2: "CD14 monocyte", 3: "CD4 memory", 4: "CD8 naive", 5: "B", 6: "monocyte and cDC2", 7: "NK", 8: "CD8 effector memory", 9: "MAIT and γδ T", 10: "doublet", 11: "CD16 monocyte", 12: "pDC", 13: "platelet", } # Save each cell's type as a cell column, and name the cells that quality # control removed "not analyzed". cell_types = cluster_labels.map(cell_type_by_cluster) ds.cells.insert( "cell_type", cell_types.reindex(ds.cells.fetch_all("ids"), fill_value="not analyzed"), overwrite=True, ) # Locate the cell types on the UMAP. ds.plots.embedding(layout=run["umap"], color_by="cell_type") UMAP of the 9,361 analyzed cells colored and labeled by cell type: the CD4 naive, CD4 memory, CD8 naive, CD8 effector memory and MAIT and γδ T cells on the left, B cells at the top, CD14 monocytes, monocytes and cDC2s and CD16 monocytes on the right, NK cells at the bottom, and small groups of doublets, pDCs and platelets. Image: https://docs.nygen.io/CyteArc/build/18d4d38654257b3a2c81a47ed63bd770.png Import the receptor contigs Cell Ranger writes the contigs of each V(D)J library, one receptor chain each, to an AIRR Rearrangement file: each contig’s V, D, J and constant genes, its junction, its UMI count, and its sequence aligned to the germline genes. The library’s filtered_contig_annotations.csv holds the same contigs without their sequences. repertoire.import_receptors reads either file and joins each contig to the cell whose ID is its barcode. Import the TCR and BCR files together, so that a cell with chains of both kinds is found. Import them for the cells that the recipe analyzed, which the run saves as a cell selection, a fixed set of cells that later calls take as cell_selection: run["analysis_cell_selection"]. The receptors then share the cells of the recipe’s clusters and UMAP. An analyzed cell without a chain gets the receptor type no IR, for no immune receptor. Each cell keeps up to two chains of each arm of its receptor: the VJ arm holds the chains that join V and J segments (TRA, TRG, IGK and IGL), and the VDJ arm those that also join a D segment (TRB, TRD and IGH). Ranked by UMI count, the first two chains of each arm fill the slots VJ_1 and VJ_2, or VDJ_1 and VDJ_2, and the first of each arm is the cell’s primary chain. A cell’s chains give it a receptor type, a subtype and a chain pairing, in the categories of scirpy Sturm et al., 2020 , which the repertoire API reference lists. # Import the TCR and BCR contigs of the analyzed cells. receptors = ds.repertoire.import_receptors( [paths["tcr"], paths["bcr"]], cell_selection=run["analysis_cell_selection"], ) # Count the cells of each receptor type, and the predicted doublets among them. receptor_cells = ds.repertoire.load_receptors(receptors).cells receptor_types = receptor_cells["receptor_type"] doublets_by_type = predicted_doublets.groupby(receptor_types, observed=True) pd.DataFrame( { "Cells": receptor_types.value_counts(), "Predicted doublets": doublets_by_type.sum(), "Share of predicted doublets": doublets_by_type.mean().round(2), } ).rename_axis("Receptor type") /tmp/ipykernel_4/3384346788.py:2: DiagnosticWarning: 25 of 6214 barcodes of the contig files match no cell of the store, for example 'AAGGTTCTCCTGTAGA-1', 'AGCGTATGTTTCCACC-1', 'CATCAGAGTCCGTGAC-1', 'CCCATACAGAGGACGG-1', 'CCCATACAGAGTGAGA-1'. Check barcode_prefix, barcode_suffix and barcode_pattern against the store's cell IDs. receptors = ds.repertoire.import_receptors( Cells Predicted doublets Share of predicted doublets Receptor type BCR 820 35 0.04 TCR 5049 218 0.04 ambiguous 78 56 0.72 multichain 8 3 0.38 no IR 3406 34 0.01 The import warns that 25 of the 6,214 barcodes in the contig files match no cell of the store: Cell Ranger calls the cells of each library separately, and its V(D)J analysis called these barcodes cells while its expression analysis did not. Of the 9,361 analyzed cells, 5,049 carry a TCR and 820 a BCR. Ambiguous cells hold chains of both receptors, and multichain cells more than two chains of an arm. Both often come from doublets: the recipe predicts 72% of the ambiguous cells (56 of 78) and 3 of the 8 multichain cells to be doublets, against 4% of the cells with a TCR or a BCR. # Compare the receptors and chain pairings of the cell types. ds.plots.receptor_qc(receptors, group_by="cell_type") Three panels. The first two stack each cell type's cells by receptor type and by chain pairing, as fractions: the T cell types carry TCRs and the B cells BCRs, mostly as a single pair, and under a tenth of the B cells are ambiguous; most doublets carry a TCR and some a BCR; the MAIT and γδ T cluster has a TCR in about half its cells; and monocytes, NK cells, dendritic cells and platelets carry almost no receptor. The third counts all cells by their number of chains in each arm, from 0 to 3 or more; most cells with a receptor hold one chain per arm. Image: https://docs.nygen.io/CyteArc/build/09f97735c928bef026accdc8642c666d.png The receptors agree with the expression clusters: nearly every T cell carries a TCR and nearly every B cell a BCR, while monocytes, NK cells and dendritic cells carry almost none. Most T and B cells hold a single pair, one chain of each arm. A second VJ chain, extra VJ, is common in T cells, which can express alpha chains from both alleles, and orphan VDJ and orphan VJ cells lack the chain of one arm, often because its transcript was not captured. Two clusters break this pattern. The doublets express monocyte genes, yet most of them carry a TCR or a BCR, which no monocyte has: these droplets captured a monocyte together with a T or B cell. In the MAIT and γδ T cluster, nearly half the cells have no chain, because the TCR file holds only alpha and beta chains, and the γδ T cells of the cluster pair a gamma with a delta chain. The cluster’s cells with a TCR are mostly MAIT cells, as their alpha chains show below, and the following sections call them MAIT cells. # Color the cells of the UMAP by receptor type, in the colors of the plot above. ds.plots.embedding(layout=run["umap"], color_by=receptors) UMAP of the analyzed cells colored by receptor type: TCRs over the T cells; BCRs over the B cells, with most of the ambiguous cells gathered at one edge of them and a few scattered among them; TCRs on the doublets along the lower edge of the CD14 monocytes and BCRs on a small group of doublets to the right of the B cells; and no receptor over the monocytes, dendritic cells, NK cells, platelets and part of the MAIT and γδ T cluster. Image: https://docs.nygen.io/CyteArc/build/fc1c60fe180203891c168622ba78ac96.png Most of the ambiguous cells gather at one edge of the B cells, and a few scatter among them. Chains from ambient RNA would scatter, so the gathered cells are more likely doublets of a B and a T cell, as the recipe’s doublet calls suggest. Group cells into clonotypes A clonotype groups cells that share their receptor, as the cells of one clone do. By default, repertoire.clonotypes links two cells whose chains have identical nucleotide junctions in both arms, or in their one arm for cells with chains of one arm only, and takes the connected groups of these links as clonotypes. Cells of different receptor types never share a clonotype. Options change what must agree: sequence="aa" compares residues instead of nucleotides, receptor_arms sets the arms that must match, and dual_ir the chains of each arm. Clonotypes are numbered by size, so clonotype_1 holds the most cells. # Group the cells with a receptor into clonotypes of identical junctions. clonotypes = ds.repertoire.clonotypes(receptors) # List the largest clonotypes with the genes and junctions of their primary chains. clonotype_table = ds.repertoire.load_clonotypes(clonotypes).clonotypes clonotype_table[ [ "clonotype", "n_cells", "receptor_type", "VJ_1_v_call", "VJ_1_j_call", "VJ_1_junction_aa", "VDJ_1_v_call", "VDJ_1_junction_aa", ] ].head(10) clonotype n_cells receptor_type VJ_1_v_call VJ_1_j_call \ 0 clonotype_1 8 TCR TRAV26-2 TRAJ24 1 clonotype_2 8 TCR TRAV1-2 TRAJ33 2 clonotype_3 7 TCR TRAV17 TRAJ16 3 clonotype_4 4 TCR TRAV8-6 TRAJ37 4 clonotype_5 4 TCR TRAV1-2 TRAJ33 5 clonotype_6 3 TCR TRAV22 TRAJ23 6 clonotype_7 3 TCR TRAV14/DV4 TRAJ45 7 clonotype_8 3 TCR TRAV17 TRAJ54 8 clonotype_9 3 TCR TRAV24 TRAJ45 9 clonotype_10 3 TCR TRAV1-2 TRAJ33 VJ_1_junction_aa VDJ_1_v_call VDJ_1_junction_aa 0 CICRSWGKLQF TRBV7-3 CASSLGAPTEAFF 1 CAHMDSNYQLIW TRBV20-1 CSARAVLAGDAGEQFF 2 CATDVSDGQKLLF TRBV19 CASSIKGGLYNEQFF 3 CAGVGNTGKLIF TRBV7-3 CASSLIGDVSYTF 4 CAVMDSNYQLIW 5 CATVNQGGKLIF TRBV20-1 CSADQGYGELFF 6 CAMREGGDSGGGADGLTF TRBV7-8 CASSPLGRHLGAFF 7 CATDAWQGAQKLVF TRBV4-1 CASSNTPNTEAFF 8 CAFIPGGGADGLTF TRBV19 CASSIKGGHQPQHF 9 CAAMDSNYQLIW TRBV6-5 CASSYVEGSSYEQYF # Show how many clonotypes have each size, and the largest ones. ds.plots.clone_abundance(clonotypes) Two panels. Left: the number of clonotypes of each size, on log scales, one line per receptor type; most TCR and BCR clonotypes hold one cell, and the TCR line falls to one or two clonotypes at four, seven and eight cells. Right: bars of the 20 largest clonotypes, labeled by the junction of their primary chain, from two TCR clonotypes of eight cells, CASSLGAPTEAFF and CSARAVLAGDAGEQFF, down to clonotypes of two cells, among them the only two BCR clonotypes with more than one cell. Image: https://docs.nygen.io/CyteArc/build/849c5f81b7fe3497e7a19fb948efd399.png Almost every clonotype holds one cell, and the largest two hold eight each. A healthy donor’s blood holds mostly naive T and B cells, each with a receptor of its own, and the 5,049 T cells and 820 B cells with a receptor sample a small part of repertoires of millions of clones. B cells share clonotypes even more rarely: two clonotypes of two cells. Three of the ten largest clonotypes join TRAV1-2 to TRAJ33 in an alpha chain of 12 residues, such as CAVMDSNYQLIW: the semi-invariant alpha chain of MAIT cells, which many MAIT clones share with different beta chains Reantragoon et al., 2013 . clonotype_5 holds four cells with that alpha chain and no beta chain. Cells with chains of one arm are linked by that arm alone, so clonotype_5 can join MAIT cells of several clones. Find the expanded T cell clones From here on, follow the T cells. Keep the cells with a TCR in the clusters of the five T cell types, and leave out the predicted doublets, whose expression mixes two cells. ds.select_cells saves each choice as a cell selection. clones.expansion places each cell in a category by the number of cells of its clonotype among the cells kept: 1 cell, 2 cells, 3 to 5 cells, 6 to 20 cells, 21 to 100 cells and more than 100 cells by default. With several samples, pass group_by="sample", so that each clonotype counts the cells of its own sample; this example holds one. The clone summaries measure each receptor type apart, so their groups carry the receptor type, as in CD4 naive, TCR. # Keep the cells with a TCR in the T cell clusters, leaving out predicted doublets. singlets = ds.select_cells(run["doublets"], value="predicted_doublets", include=[False]) t_cells = ds.select_cells(receptors, include=["TCR"], cell_selection=singlets) t_cells = ds.select_cells(clusters, include=[1, 3, 4, 8, 9], cell_selection=t_cells) # Place each T cell in an expansion category by the size of its clonotype. expansion = ds.clones.expansion(clonotypes, cell_selection=t_cells) # Count the cells and clonotypes of each category. categories = ( ds.clones.load_expansion(expansion) .categories.drop(columns="group") .set_index("category") .round({"fraction": 3}) ) expanded = categories.loc[categories.index != "1 cell", "n_cells"].sum() print(f"{expanded} of {categories['n_cells'].sum():,} T cells belong to clonotypes of 2 or more cells") categories 137 of 4,791 T cells belong to clonotypes of 2 or more cells n_cells n_clones fraction category 1 cell 4654 4654 0.971 2 cells 78 39 0.016 3 to 5 cells 38 12 0.008 6 to 20 cells 21 3 0.004 21 to 100 cells 0 0 0.000 more than 100 cells 0 0 0.000 # Compare the expansion of the T cell types. expansion_figure = ds.plots.clonal_expansion(expansion, group_by="cell_type") # Read each T cell type's share of cells in expanded clonotypes, and in its # ten largest clonotypes, from the figure's tables. tables = expansion_figure.tables single = tables["categories"].query("category == '1 cell'").set_index("group")["fraction"] top_ten = tables["rank_windows"].query("window == '1 to 10'").set_index("group")["fraction"] pd.DataFrame( {"In clonotypes of 2 or more cells": 1 - single, "In the 10 largest clonotypes": top_ten} ).round(3) Two panels of stacked bars for the five T cell types. Top: the fraction of cells by the size of their clonotype; clonotypes of two or more cells hold 17% of the effector memory CD8 T cells and 24% of the MAIT and γδ T cells, and almost none of the naive T cells. Bottom: the fraction of cells by the rank of their clonotype within the cell type; the ten largest clonotypes hold about a tenth of the effector memory CD8 T cells and a fifth of the MAIT and γδ T cells. Image: https://docs.nygen.io/CyteArc/build/4d32fe22b0213b6d2530757a9d866905.png In clonotypes of 2 or more cells \ group CD4 memory, TCR 0.025 CD4 naive, TCR 0.007 CD8 effector memory, TCR 0.170 CD8 naive, TCR 0.000 MAIT and γδ T, TCR 0.238 In the 10 largest clonotypes group CD4 memory, TCR 0.018 CD4 naive, TCR 0.007 CD8 effector memory, TCR 0.116 CD8 naive, TCR 0.011 MAIT and γδ T, TCR 0.185 Expanded clonotypes, of two or more cells, are most common in two cell types: they hold 17% of the effector memory CD8 T cells and 24% of the MAIT cells, against 2.5% of the memory CD4 T cells and under 1% of the naive T cells. Ranking each cell type’s clonotypes by size agrees: the ten largest hold 11.6% of the effector memory CD8 T cells and 18.5% of the MAIT cells. In a cell type without expanded clonotypes, the ten largest are ten single cells, 1.1% of the naive CD8 T cells. Compare the diversity of the T cell types A repertoire’s diversity is how many clonotypes it holds and how evenly its cells spread over them. Every observed index depends on how many cells a group holds, because a larger sample finds more clonotypes. Hill numbers Hill, 1973 put the indices on one scale, the effective number of clonotypes: order 0 counts clonotypes, order 1, the exponential of Shannon entropy, weighs them by frequency, and order 2, the inverse Simpson index, counts the dominant ones. clones.diversity reports them as observed, as asymptotic estimates, and at a common size and a common sample coverage, rarefied or extrapolated as Chao et al. (2014) derive, so that groups of different sizes can be compared. The sample coverage estimates the share of a population’s cells whose clonotype the sample holds. Almost every clonotype of the naive T cells holds one cell, so their coverage is near 0, and so is the default common coverage. Compare the T cell types at the common size instead, by default the smallest of the groups’ doubled sizes, so that no group is extrapolated beyond twice its size. # Measure the diversity of each T cell type's clonotypes. diversity = ds.clones.diversity(clonotypes, group_by="cell_type", cell_selection=t_cells) # Compare the Hill numbers of the cell types at their common size. hill = diversity.hill.pivot(index="group", columns="order", values="at_size") hill.columns = [f"Order {order} at {diversity.size} cells" for order in hill.columns] diversity.indices.set_index("group")[["n_cells", "n_clones", "coverage"]].join( hill.round(1) ).round({"coverage": 3}) n_cells n_clones coverage Order 0 at 302 cells \ group CD4 memory, TCR 1181 1168 0.021 301.1 CD4 naive, TCR 2187 2181 0.005 301.9 CD8 effector memory, TCR 336 298 0.170 269.7 CD8 naive, TCR 936 936 0.000 302.0 MAIT and γδ T, TCR 151 130 0.226 238.3 Order 1 at 302 cells Order 2 at 302 cells group CD4 memory, TCR 300.8 300.2 CD4 naive, TCR 301.8 301.8 CD8 effector memory, TCR 249.1 209.2 CD8 naive, TCR 302.0 302.0 MAIT and γδ T, TCR 210.4 154.3 At 302 cells, the naive T cells hold about 302 clonotypes at every order, one for almost every cell, and the memory CD4 T cells about 300. The effector memory CD8 T cells hold 270 clonotypes at order 0 and 209 at order 2, and the MAIT cells 238 and 154: fewer, and fewer still at the higher orders, which weigh their large clonotypes more. The 151 MAIT cells are fewer than 302, so their values at 302 cells are extrapolated. Rarefaction and extrapolation draw each group’s Hill number against the cells sampled. Draw order 2, which separates the cell types most, from one cell to the common size, beside the sample coverage. # Rarefy and extrapolate each T cell type's Hill number of order 2 up to the # common size. rarefaction = ds.clones.rarefaction( clonotypes, group_by="cell_type", cell_selection=t_cells, orders=[2], endpoint=diversity.size, ) ds.plots.clonal_rarefaction(rarefaction) Two panels for the five T cell types from 1 to 302 cells: the Hill number of order 2 and the sample coverage against the cells sampled, solid where rarefied and dashed where extrapolated, with a dot at the MAIT cluster's 151 observed cells. The naive T cells and the memory CD4 T cells rise along one straight line to about 300 with coverage near 0, while the effector memory CD8 T cells bend to about 210 and the MAIT cells to about 155, and their coverage climbs to about 0.16 and, extrapolated, 0.33 at 302 cells. Image: https://docs.nygen.io/CyteArc/build/8c418dec62b22fbc40d0cdb19f31e441.png The curves of the naive T cells and the memory CD4 T cells rise along one straight line, each new cell a new clonotype, and their sample coverage stays near 0: these repertoires are far larger than the cells sampled. The curves of the effector memory CD8 T cells and the MAIT cells bend away as their expanded clonotypes recur, and their coverage climbs; at their observed sizes of 336 and 151 cells, the table above gives 0.17 and 0.23. Find the clonotypes that T cell types share A clone whose cells took several fates leaves its clonotype in several cell types. clones.overlap compares every pair of groups by the clonotypes they share, with indices such as the Jaccard index, the share of the two groups’ clonotypes that both hold, and the Morisita-Horn index, which weighs clonotypes by their cells. Draw the number of clonotypes that each pair shares, index="shared", and list the shared clonotypes with their primary chains. # Count the clonotypes that each pair of T cell types shares. overlap = ds.clones.overlap(clonotypes, group_by="cell_type", cell_selection=t_cells) ds.plots.clone_overlap(overlap, index="shared") # List the shared clonotypes: the cells of each one in each T cell type, from # the T cells that the expansion measured, and the primary chains of its # representative cell. t_cell_ids = ds.clones.load_expansion(expansion).cells.index t_cell_clonotypes = pd.DataFrame( { "clonotype": ds.repertoire.load_clonotypes(clonotypes).cells.loc[t_cell_ids, "clonotype"], "cell_type": cell_types.loc[t_cell_ids], } ) cells_by_type = ( t_cell_clonotypes.groupby(["clonotype", "cell_type"], observed=True) .size() .unstack(fill_value=0) ) shared = cells_by_type[(cells_by_type > 0).sum(axis="columns") > 1] shared.loc[:, (shared > 0).any()].join( clonotype_table.set_index("clonotype")[ ["VJ_1_v_call", "VJ_1_j_call", "VJ_1_junction_aa", "VDJ_1_v_call", "VDJ_1_junction_aa"] ] ) Heatmap of the number of clonotypes that each pair of the five T cell types shares, with a blank diagonal: three between the naive and memory CD4 T cells, two between the memory CD4 T cells and the MAIT and γδ T cluster, and none between the other pairs. Image: https://docs.nygen.io/CyteArc/build/da1ca9d9ddb1be6cface01c1ce9e3622.png CD4 memory CD4 naive MAIT and γδ T VJ_1_v_call VJ_1_j_call \ clonotype clonotype_14 2 0 1 TRAV20 TRAJ21 clonotype_21 1 0 1 clonotype_31 1 1 0 TRAV25 TRAJ22 clonotype_36 1 1 0 TRAV13-1 TRAJ5 clonotype_57 1 1 0 TRAV12-1 TRAJ37 VJ_1_junction_aa VDJ_1_v_call VDJ_1_junction_aa clonotype clonotype_14 CAVQAGDNFNKFYF TRBV20-1 CSARAGTASNQPQHF clonotype_21 TRBV6-5 CASSYSLAGEGADTQYF clonotype_31 CAAEPGSARQLTF TRBV12-5 CASGFGGLAGRDTQYF clonotype_36 CASTGRRALTF TRBV7-3 CASSSYIPFQPNTEAFF clonotype_57 CVASSNTGKLIF TRBV4-1 CASSQVRAANNSPLHF The T cell types share few clonotypes: three between the naive and memory CD4 T cells, each with one cell in either type, and two between the memory CD4 T cells and the MAIT and γδ T cluster. Neither of those two carries the MAIT alpha chain. clonotype_14 pairs a TRAV20 alpha chain with a TRBV20-1 beta chain in two memory CD4 T cells and one cell of that cluster, which therefore also holds conventional T cells, and clonotype_21 joins two cells with a beta chain only, linked by that chain alone. Most clones appear once among the 4,791 T cells, so counts this small cannot show which cell types a clone spans; deeper sampling, or blood drawn during an immune response, would give enough shared clonotypes to compare. Compare V and J genes The V and J genes of a repertoire identify invariant T cells: MAIT cells pair TRAV1-2 with TRAJ33, and less often with TRAJ12 or TRAJ20 Reantragoon et al., 2013 . repertoire.gene_usage counts each cell’s primary chain of each arm within its locus, so TRA and TRB genes get shares of their own; with count="clonotypes" it counts each clonotype once, so that one expanded clone does not decide a gene’s share. For each locus, the heatmap shows the genes that rank highest in any cell type, and max_genes=40 shows nearly every gene that these T cells use. The table below it lists the three V genes of each locus that the most MAIT clonotypes use. # Compare the V genes of the T cell types, counting each clonotype once, in a # figure tall enough to name every gene and cell type. usage = ds.repertoire.gene_usage( clonotypes, count="clonotypes", group_by="cell_type", cell_selection=t_cells ) ds.plots.gene_usage(usage, max_genes=40, figsize=(7.5, 10)) # List the three V genes of each locus that the most MAIT clonotypes use, with # their share of every T cell type's clonotypes. mait = "MAIT and γδ T" shares = usage.table.pivot_table( index=["locus", "v_call"], columns="group", values="fraction", fill_value=0 ) top_mait = shares.sort_values(["locus", mait], ascending=[True, False]).groupby(level="locus").head(3) top_mait.round(2) Two heatmaps, TRA and TRB, of the fraction of each T cell type's clonotypes that use each of 40 V genes, on one color scale from 0 to about 0.85. The MAIT and γδ T column is bright at TRAV1-2 and lighter at TRBV20-1, TRBV6-2 and TRBV6-4, while the other four cell types spread thinly over many genes. Image: https://docs.nygen.io/CyteArc/build/c6d4d11d2b1383cf0f3aa32cf1660d5e.png group CD4 memory CD4 naive CD8 effector memory CD8 naive \ locus v_call TRA TRAV1-2 0.02 0.01 0.05 0.07 TRAV14/DV4 0.02 0.02 0.05 0.05 TRAV19 0.03 0.02 0.06 0.07 TRB TRBV20-1 0.12 0.10 0.06 0.05 TRBV6-4 0.00 0.00 0.00 0.00 TRBV6-2 0.05 0.04 0.04 0.03 group MAIT and γδ T locus v_call TRA TRAV1-2 0.85 TRAV14/DV4 0.03 TRAV19 0.02 TRB TRBV20-1 0.23 TRBV6-4 0.23 TRBV6-2 0.16 # Pair the V and J genes of each locus, counting each clonotype once, and draw # the 13 most used of each, as many as a page-wide figure can label. pairs = ds.repertoire.gene_usage( clonotypes, genes=("v_call", "j_call"), count="clonotypes", cell_selection=t_cells ) ds.plots.gene_pairing(pairs, max_genes=13, figsize=(8.5, 4.5)) # List the three most frequent pairs of each locus. pairs.table.groupby("locus").head(3).set_index(["locus", "v_call", "j_call"])[ ["n_clonotypes", "fraction"] ].round(3) Two heatmaps, TRA and TRB, of the fraction of T cell clonotypes that pair each of the 13 most used V genes with each of the 13 most used J genes, on one color scale from 0 to 0.022. TRAV1-2 with TRAJ33 is the one bright square, at the top of the scale, the most frequent pair of either locus; in TRB, TRBV20-1 with TRBJ2-7 and with TRBJ2-1 lead, at 0.017 and 0.016. Image: https://docs.nygen.io/CyteArc/build/b6b20a59d351055c80542c9bafebfecb.png n_clonotypes fraction locus v_call j_call TRA TRAV1-2 TRAJ33 97 0.022 TRAJ20 18 0.004 TRAV29/DV5 TRAJ29 15 0.003 TRB TRBV20-1 TRBJ2-7 80 0.017 TRBJ2-1 73 0.016 TRBJ1-1 53 0.011 In the MAIT and γδ T cluster, the alpha chains of 85% of the clonotypes use TRAV1-2, against 1% to 7% in the other T cell types, so the cluster’s T cells with a TCR are mostly MAIT cells, beside conventional T cells such as the cell of clonotype_14. The cluster’s beta chains favor TRBV20-1 and TRBV6-4, at 23% of its clonotypes each, and TRBV6-2, at 16%. The other T cell types hardly use TRBV6-4, and they spread their clonotypes over many genes, as diverse repertoires do. Across all T cells, TRAV1-2 with TRAJ33, the MAIT alpha chain, is the most frequent V and J pair of either locus: 97 clonotypes use it, 2.2% of those with an alpha chain, and TRAV1-2 with TRAJ20 comes second among the alpha chains, in 18. The leading beta pairs join TRBV20-1, the most used TRBV gene, to TRBJ2-7 and TRBJ2-1, in 80 and 73 clonotypes. Group B cells into clonal families B cells mutate the genes of their receptor as they mature in germinal centers, so the cells of one B cell clone can differ in their junctions, and identical junctions split such a clone apart. With metric, repertoire.clonotypes links chains whose junctions are similar instead of identical: here, nucleotide junctions of equal length that differ at no more than 15% of their positions, with the same V and J genes, the generic threshold of 85% junction similarity that scirpy’s B cell tutorial uses. The threshold decides the families and depends on how mutated the repertoire is, so max_distance has no default: report the distance you choose. # Link chains whose nucleotide junctions differ in at most 15 percent of their # positions, with the same V and J genes. families = ds.repertoire.clonotypes( receptors, metric="normalized_hamming", max_distance=15, same_v_gene=True, same_j_gene=True, ) # Count the B cells by the size of their clonotype under each definition. b_cell_ids = receptor_cells.index[receptor_types == "BCR"] pd.DataFrame( { name: ds.repertoire.load_clonotypes(ref).cells.loc[b_cell_ids, "clone_size"].value_counts() for name, ref in {"Identical junctions": clonotypes, "Clonal families": families}.items() } ).rename_axis("Cells of the clonotype") Identical junctions Clonal families Cells of the clonotype 1 816 814 2 4 6 # Show the B cells whose family holds more than one cell, with their primary chains. family_cells = ds.repertoire.load_clonotypes(families).cells.loc[b_cell_ids] family_cells[family_cells["clone_size"] >= 2].join( receptor_cells[["VDJ_1_c_call", "VDJ_1_junction_aa", "VJ_1_junction_aa"]] ).sort_values("clonotype") clonotype clone_size VDJ_1_c_call VDJ_1_junction_aa \ ids CAACCAAGTCTTCAAG-1 clonotype_18 2 IGHM CARGTRGRSSGYYSNW TGCGGGTCATTGGTAC-1 clonotype_18 2 IGHM CARGTRGRSSGYYSNW CCACCTAAGGATGGAA-1 clonotype_19 2 IGHM CARQNFDILTGYSIDYW CCTCTGATCGTACCGG-1 clonotype_19 2 IGHM CARQNFDILTGYSIDYW ATCCACCAGATAGCAT-1 clonotype_20 2 IGHG1 CAHHLSFGGNWAFAHW GAGTCCGGTCTTGATG-1 clonotype_20 2 IGHG1 CAHHASFGGNWAFAHW VJ_1_junction_aa ids CAACCAAGTCTTCAAG-1 CQQYNNWPPYTF TGCGGGTCATTGGTAC-1 CQQYNNWPPYTF CCACCTAAGGATGGAA-1 CAAWDDSLNGLYVF CCTCTGATCGTACCGG-1 CAAWDDSLNGLYVF ATCCACCAGATAGCAT-1 CAAWDDSLNGSYVF GAGTCCGGTCTTGATG-1 CAAWDDSLNGSYVF With identical junctions, two pairs of IgM B cells share a clonotype. The families add one pair of IgG1 B cells whose heavy chain junctions differ in one residue, CAHHLSFGGNWAFAHW and CAHHASFGGNWAFAHW, and whose light chain junctions match, the pattern that somatic hypermutation leaves within a class-switched clone. The same rules would join T cells with similar receptors from different clones, since T cell receptors do not mutate. Keep the clonotypes of identical junctions for T cells. Export the contigs CyteArc leaves B cell lineage trees, somatic hypermutation and isotype switching to tools such as Immcantation and dandelion, which compute from each contig’s sequence the IMGT-gapped alignments that they need. repertoire.export_airr writes the contigs as an AIRR Rearrangement file Vander Heiden et al., 2018 , the format that these tools and scirpy read. Each row is one contig, with the fields that the import kept, its sequence among them, and two columns that the export fills: cell_id, the cell’s ID in this store, and clone_id, the cell’s clonotype in the artifact passed, here its clonal family. # Write the contigs with each cell's clonal family as its clone. airr_path = output_dir / "pbmc_10k_v2_airr.tsv.gz" ds.repertoire.export_airr(families, airr_path) # Read the file without quoting, as the format writes it, and show its first # B cell contigs. exported = pd.read_csv( airr_path, sep="\t", dtype=str, keep_default_na=False, quoting=csv.QUOTE_NONE ) exported.loc[ exported["locus"].isin(["IGH", "IGK", "IGL"]), ["sequence_id", "cell_id", "clone_id", "locus", "v_call", "c_call", "junction_aa", "sequence"], ].head() /tmp/ipykernel_4/2714039787.py:3: DiagnosticWarning: 154 contig IDs repeat; their later occurrences are written with a suffix such as _2 ds.repertoire.export_airr(families, airr_path) sequence_id cell_id clone_id locus \ 15 AAACCTGTCATATCGG-1_contig_1 AAACCTGTCATATCGG-1 clonotype_347 IGK 17 AAACCTGTCCGTTGTC-1_contig_1 AAACCTGTCCGTTGTC-1 clonotype_503 IGK 18 AAACCTGTCCGTTGTC-1_contig_2 AAACCTGTCCGTTGTC-1 clonotype_503 IGH 19 AAACCTGTCGAGAACG-1_contig_1 AAACCTGTCGAGAACG-1 clonotype_334 IGL 20 AAACCTGTCGAGAACG-1_contig_2 AAACCTGTCGAGAACG-1 clonotype_334 IGH v_call c_call junction_aa \ 15 IGKV1-8 IGKC CQQYDELPVTF 17 IGKV1-8 IGKC CQQYYSYPRTF 18 IGHV1-69D IGHM CATTYYYDSSGYYQNDAFDIW 19 IGLV5-45 IGLC3 CMIWHSSAWVV 20 IGHV1-2 IGHM CAREIEGDGVFEIW sequence 15 TGGGGAGGAGTCAGTCCCAACCAGGACACGGCCTGGACATGAGGGT... 17 AGGAGTCAGACCCTGTCAGGACACAGCATAGACATGAGGGTCCCCG... 18 ATCACATAACAACCACATTCCTCCTCTAAAGAAGCCCCTGGGAGCA... 19 ACTGTGGGGGTAAGAGGTTGTGTCCACCATGGCCTGGACTCCTCTC... 20 GGGAGCATCACCCAGCAACCACATCTGTCCTCTAGAGAATCCCCTG... Cell Ranger names contigs _contig_ in the TCR and the BCR file alike, so a cell with contigs in both files repeats an ID. The format requires unique IDs, so the export warns that 154 IDs repeat and writes their later occurrences with a suffix. The file’s T cell contigs carry the families too, so export clonotypes for an analysis of T cells. Build on this analysis This example holds one sample of one donor. With several donors, pass within="donor" to repertoire.clonotypes, so that identical receptors of two donors stay apart, and measure expansion, diversity and overlap with group_by="sample". clones.track and plots.clone_tracking follow clonotypes across time points, and repertoire.spectratype compares junction lengths. Compare conditions with one value per sample, since the cells of one sample are not independent observations; CytePool runs such comparisons. To test whether two cell types share more clonotypes than chance, pass the clonotypes to clones.coupling, which compares their coupling with that of shuffled cell labels, as mitochondrial lineage tracing does with the cell types of a tumor. The repertoire API reference and the clones API reference list the options of each call and the validation against scirpy, scRepertoire, immunarch and iNEXT. References¶ Sturm, G., Szabo, T., Fotakis, G., Haider, M., Rieder, D., Trajanoski, Z., & Finotello, F. (2020). Scirpy: a Scanpy extension for analyzing single-cell T-cell receptor-sequencing data. Bioinformatics, 36(18), 4817–4818. 10.1093/bioinformatics/btaa611 Reantragoon, R., Corbett, A. J., Sakala, I. G., Gherardin, N. A., Furness, J. B., Chen, Z., Eckle, S. B. G., Uldrich, A. P., Birkinshaw, R. W., Patel, O., Kostenko, L., Meehan, B., Kedzierska, K., Liu, L., Fairlie, D. P., Hansen, T. H., Godfrey, D. I., Rossjohn, J., McCluskey, J., & Kjer-Nielsen, L. (2013). Antigen-loaded MR1 tetramers define T cell receptor heterogeneity in mucosal-associated invariant T cells. Journal of Experimental Medicine, 210(11), 2305–2320. 10.1084/jem.20130958 Hill, M. O. (1973). Diversity and Evenness: A Unifying Notation and Its Consequences. Ecology, 54(2), 427–432. 10.2307/1934352 Chao, A., Gotelli, N. J., Hsieh, T. C., Sander, E. L., Ma, K. H., Colwell, R. K., & Ellison, A. M. (2014). Rarefaction and extrapolation with Hill numbers: a framework for sampling and estimation in species diversity studies. Ecological Monographs, 84(1), 45–67. 10.1890/13-0133.1 Vander Heiden, J. A., Marquez, S., Marthandan, N., Bukhari, S. A. C., Busse, C. E., Corrie, B., Hershberg, U., Kleinstein, S. H., Matsen IV, F. A., Ralph, D. K., Rosenfeld, A. M., Schramm, C. A., The AIRR Community, Christley, S., & Laserson, U. (2018). AIRR Community Standardized Representations for Annotated Immune Repertoires. Frontiers in Immunology, 9, 2206. 10.3389/fimmu.2018.02206