Package 'immLynx'

Title: Linking Advanced TCR Python Pipelines and Hugging Face Models in R
Description: A comprehensive toolkit that bridges popular Python-based immune repertoire analysis tools and Hugging Face protein language models into the R environment. Provides unified interfaces for TCR distance calculations (tcrdist3), sequence generation probability (OLGA), selection inference (soNNia), clustering (clusTCR), protein embeddings (ESM-2), metaclone discovery (metaclonotypist), clonal expansion prediction from gene expression (scXpand), near-neighbor search by symmetric deletion lookup (pyrepseq), and deep generative featurization (DeepTCR). Fully compatible with the scRepertoire and immApex ecosystem for single-cell immune repertoire analysis.
Authors: Nick Borcherding [aut, cre] (ORCID: <https://orcid.org/0000-0003-1427-6342>)
Maintainer: Nick Borcherding <[email protected]>
License: MIT + file LICENSE
Version: 1.1.3
Built: 2026-10-27 14:54:06 UTC
Source: https://github.com/bioc/immLynx

Help Index


Convert TCR Data to tcrdist3 Format

Description

Converts TCR data from immLynx/scRepertoire format to the format required by tcrdist3 for distance calculations.

Usage

convertToTcrdist(
  tcr_data,
  chains = c("beta", "alpha", "both"),
  include_count = TRUE
)

Arguments

tcr_data

A data.frame from extractTCRdata() or similar source

chains

Which chains to include: "alpha", "beta", or "both". Default is "beta".

include_count

Logical. If TRUE, adds a 'count' column (default 1). Default is TRUE.

Value

A data.frame in tcrdist3 format with columns:

count

Clone count (default 1)

v_a_gene

Alpha V gene (if alpha chain included)

j_a_gene

Alpha J gene (if alpha chain included)

cdr3_a_aa

Alpha CDR3 amino acid sequence (if alpha chain included)

v_b_gene

Beta V gene (if beta chain included)

j_b_gene

Beta J gene (if beta chain included)

cdr3_b_aa

Beta CDR3 amino acid sequence (if beta chain included)

Examples

# Convert long-format TCR data to tcrdist3 format
tcr_data <- data.frame(
  barcode = paste0("cell_", 1:5),
  cdr3_aa = c("CASSLGTGELFF", "CASSIRSSYEQYF", "CASSYSTGELFF",
              "CASNQGLNEKLFF", "CASSLDRNEQFF"),
  v = paste0("TRBV", c("7-2", "12-3", "5-1", "28", "7-9")),
  j = paste0("TRBJ", c("2-2", "1-1", "2-7", "1-5", "2-1")),
  chain = rep("TRB", 5),
  stringsAsFactors = FALSE
)
tcrdist_format <- convertToTcrdist(tcr_data, chains = "beta")
head(tcrdist_format)

Export Single-Cell + Immune Receptor Data to scanpy/scirpy Format

Description

Exports a SingleCellExperiment or Seurat object, optionally combined with scRepertoire immune receptor metadata, to scanpy/scirpy-compatible H5AD or H5MU files. Writes an AIRR rearrangement TSV sidecar by default when receptor data is present.

Usage

exportToScanpy(
  input,
  output_dir,
  format = c("h5ad", "h5mu"),
  write_airr = TRUE,
  obs_columns = NULL,
  reductions = NULL,
  assay = "counts",
  chains = c("both", "TRA", "TRB", "TRG", "TRD", "IGH", "IGL", "IGK"),
  overwrite = FALSE,
  verbose = TRUE
)

Arguments

input

A SingleCellExperiment or Seurat object.

output_dir

Directory to write outputs into. Created if missing. Files written with fixed names: adata.h5ad, airr_rearrangement.tsv.gz, and (for H5MU) mudata.h5mu.

format

Either "h5ad" (gene expression only) or "h5mu" (combined GEX + AIRR via scirpy/muon). Default "h5ad".

write_airr

Logical. Write the standalone AIRR TSV sidecar when immune receptor data is present. Default TRUE.

obs_columns

Character vector of colData columns to keep. Default NULL: keep all non-list columns; additionally drop scRepertoire CT* columns when format = "h5mu".

reductions

Character vector of reducedDimNames() to write. Default NULL: write all.

assay

Assay name to populate adata.X. Default "counts".

chains

Which receptor loci to extract: "both" (TRA + TRB), or any of "TRA", "TRB", "TRG", "TRD", "IGH", "IGL", "IGK".

overwrite

Logical. Overwrite existing output files. Default FALSE.

verbose

Logical. Emit progress messages. Default TRUE.

Value

Invisibly, a list with paths: h5ad, airr, h5mu (any of which may be NULL if not written).

Examples

data(immLynx_example)

# Inspect what would be written without invoking Python.
airr <- immLynx:::.buildAIRR(immLynx_example, chains = "TRB")
head(airr)


# Gene expression only -> adata.h5ad (+ AIRR sidecar by default).
out_h5ad <- exportToScanpy(
  immLynx_example,
  output_dir = tempfile("scanpy_h5ad_"),
  format     = "h5ad"
)
file.exists(out_h5ad$h5ad)
file.exists(out_h5ad$airr)

# Subset metadata and embeddings before writing.
out_lite <- exportToScanpy(
  immLynx_example,
  output_dir  = tempfile("scanpy_lite_"),
  format      = "h5ad",
  obs_columns = c("Patient", "Type", "clusters"),
  write_airr  = FALSE
)

# Combined GEX + AIRR -> mudata.h5mu (requires the scanpy export
# basilisk env; the first call may take several minutes to install).
out_h5mu <- exportToScanpy(
  immLynx_example,
  output_dir = tempfile("scanpy_h5mu_"),
  format     = "h5mu",
  chains     = "TRB"
)

Extract TCR Data from SingleCellExperiment Object

Description

Extracts T-cell receptor data from a SingleCellExperiment object that has been processed with scRepertoire. This is a convenience wrapper around immApex::getIR() that provides additional formatting options.

Usage

extractTCRdata(
  input,
  chains = c("TRB", "TRA", "TRG", "TRD", "IGH", "IGL", "IGK", "both"),
  format = c("long", "wide"),
  remove_na = TRUE
)

Arguments

input

A SingleCellExperiment object containing scRepertoire TCR data in metadata.

chains

Which chains to extract: "TRA", "TRB", "TRG", "TRD", "IGH", "IGL", "IGK", or "both" (for TRA and TRB). Default is "TRB".

format

Output format: "long" (one row per chain) or "wide" (one row per cell with columns for each chain). Default is "long".

remove_na

Logical. If TRUE, removes rows with NA CDR3 sequences. Default is TRUE.

Value

A data.frame containing:

barcode

Cell barcode

cdr3_aa

CDR3 amino acid sequence

cdr3_nt

CDR3 nucleotide sequence (if available)

v

V gene

d

D gene (if applicable)

j

J gene

c

C gene (if available)

chain

Chain type (TRA, TRB, etc.)

Examples

# Extract beta chain data
data(immLynx_example)
tcr_data <- extractTCRdata(immLynx_example, chains = "TRB")
head(tcr_data)

Generate Random TCR Sequences using OLGA

Description

Generate random TCR sequences from OLGA's generative model.

Usage

generateOLGA(n = 100, model = "humanTRB")

Arguments

n

Number of sequences to generate.

model

OLGA model to use: "humanTRB", "humanTRA", "humanIGH", "mouseTRB".

Value

Data.frame with generated sequences (nt_seq, aa_seq, v_index, j_index).

Examples

# Available models
models <- c("humanTRB", "humanTRA", "humanIGH", "mouseTRB")

  # Generate 100 random human TRB sequences
  random_seqs <- generateOLGA(n = 100, model = "humanTRB")
  head(random_seqs)

  # Generate human TRA sequences
  tra_seqs <- generateOLGA(n = 50, model = "humanTRA")

  # Generate mouse TRB sequences
  mouse_seqs <- generateOLGA(n = 200, model = "mouseTRB")

Initialize a Hugging Face Model and Tokenizer

Description

Downloads or loads a cached pre-trained model and its corresponding tokenizer from the Hugging Face Hub. Uses the basilisk-managed Python environment which includes transformers and torch.

Usage

huggingModel(model_name = "facebook/esm2_t12_35M_UR50D")

Arguments

model_name

A string specifying the model identifier from the Hugging Face Hub. For ESM-2 35M, this is "facebook/esm2_t12_35M_UR50D". Other options include "facebook/esm2_t33_650M_UR50D" for larger models.

Value

A list containing the R-wrapped Python objects for the 'model' and 'tokenizer', along with the basilisk process handle. The process must be stopped when no longer needed via basilisk::basiliskStop().

See Also

tokenizeSequences, proteinEmbeddings, runEmbeddings

Examples

# Default model is ESM-2 35M
model_name <- "facebook/esm2_t12_35M_UR50D"

  # Load the default ESM-2 35M model
  hf_components <- huggingModel(model_name)
  names(hf_components)  # "model", "tokenizer", "proc"

  # Use with tokenizeSequences and proteinEmbeddings
  sequences <- c("CASSLGTGELFF", "CASSIRSSYEQYF")
  tokenized <- tokenizeSequences(hf_components$tokenizer,
                                 sequences)
  embeddings <- proteinEmbeddings(hf_components$model,
                                  tokenized,
                                  pool = "mean",
                                  chunk_size = 32)

  # Clean up the basilisk process when done
  basilisk::basiliskStop(hf_components$proc)

Example Single-Cell RNA-seq Data with TCR Information

Description

An SCE object containing single-cell RNA-seq data from multiple patients with integrated T-cell receptor (TCR) repertoire data from scRepertoire. This dataset is useful for demonstrating the functionality of immLynx analysis functions.

Usage

data(immLynx_example)

Format

An SCE object with the following components:

Assays

RNA expression data

Metadata

Cell-level metadata including:

  • orig.ident: Original sample identifier (e.g., "P17B", "P17L")

  • nCount_RNA: Total RNA counts per cell

  • nFeature_RNA: Number of detected genes per cell

  • CTgene: TCR gene information (V/J genes)

  • CTnt: TCR CDR3 nucleotide sequences

  • CTaa: TCR CDR3 amino acid sequences

  • CTstrict: Strict TCR identifier combining gene and sequence

  • clonalFrequency: Number of cells sharing the same TCR

  • clonalProportion: Proportion of cells with the same TCR

  • cloneSize: Categorical clone size (Small, Medium, Large, Hyperexpanded)

  • Patient: Patient identifier (P17, P18, P19, P20)

  • Type: Sample type (B = Blood, L = Lymph node)

  • clusters: Cell cluster assignments

Details

This dataset was created by combining 10X Genomics single-cell gene expression and VDJ sequencing data from 8 samples across 4 patients. Each patient contributed two samples: blood (B) and lymph node (L) tissue. More information on the data can be found in the following [manuscript](https://pubmed.ncbi.nlm.nih.gov/33622974/).

Examples

data(immLynx_example)
immLynx_example

List available scXpand pretrained models

Description

Returns the pan-cancer models published with scXpand. By default this reads a static table shipped with immLynx so it never triggers a multi-gigabyte Python environment build. Set refresh = TRUE to query the installed scxpand package, which is authoritative if upstream has added models.

Usage

listScXpandModels(refresh = FALSE)

Arguments

refresh

Logical. Query the installed scxpand package rather than the static table. Requires the scXpand basilisk environment and will build it on first use. Default FALSE.

Value

A data.frame with columns model_name, model_type, version and description. When refresh = TRUE, model_type and description may be NA for models absent from the static table.

Examples

listScXpandModels()


# Authoritative, but builds the scXpand environment on first call.
listScXpandModels(refresh = TRUE)

Get Protein Embeddings from a Model

Description

Applies a pre-trained model to a batch of tokenized sequences to generate embeddings. This is the core embedding function used by runEmbeddings.

Usage

proteinEmbeddings(
  model,
  tokenized.batch,
  pool = c("none", "mean", "cls"),
  chunk_size = NULL,
  prefer_dtype = c("float16", "bfloat16", "float32"),
  prefer_device = c("auto", "cuda", "mps", "cpu")
)

Arguments

model

HF model (from AutoModel or similar), typically obtained via huggingModel.

tokenized.batch

A *list* of tokenized tensors OR a list of such lists (i.e., already minibatched). If you pass a single big batch, set chunk_size. Typically obtained via tokenizeSequences.

pool

One of "mean", "cls", or "none". "mean" is recommended for sequence-level embeddings.

chunk_size

If tokenized.batch is a single big batch, split it into chunks of this many sequences. Ignored if you pre-batched upstream.

prefer_dtype

One of "float16", "bfloat16", "float32". Lower precision uses less memory but may reduce accuracy.

prefer_device

One of "auto", "cuda", "mps", "cpu". "auto" will select the best available device.

Value

An R matrix [n_sequences x hidden] if pool != "none". If pool == "none", returns a list of arrays per chunk.

See Also

runEmbeddings for a higher-level wrapper that works directly with SingleCellExperiment objects.

Examples

sequences <- c("CASSLGTGELFF", "CASSIRSSYEQYF", "CASSYSTGELFF")

  # Full workflow: load model, tokenize, embed
  hf_components <- huggingModel()
  tokenized <- tokenizeSequences(hf_components$tokenizer,
                                 sequences)

  # Mean pooling (recommended for sequence-level tasks)
  embeddings <- proteinEmbeddings(hf_components$model,
                                  tokenized,
                                  pool = "mean",
                                  chunk_size = 32)
  dim(embeddings)  # [n_sequences x hidden_dim]

  # CLS token embedding
  cls_emb <- proteinEmbeddings(hf_components$model,
                               tokenized,
                               pool = "cls",
                               chunk_size = 32)

  # Per-token embeddings (no pooling)
  token_emb <- proteinEmbeddings(hf_components$model,
                                 tokenized,
                                 pool = "none",
                                 chunk_size = 32)

  # Use GPU with half precision for speed
  embeddings_gpu <- proteinEmbeddings(
      hf_components$model, tokenized,
      pool = "mean", chunk_size = 64,
      prefer_device = "cuda",
      prefer_dtype = "float16")

Run clusTCR Clustering on scRepertoire Data

Description

This function extracts TCR sequences from a SingleCellExperiment object with scRepertoire data and performs clustering using the clusTCR algorithm.

Usage

runClustTCR(
  input,
  chains = c("TRB", "TRA", "both"),
  method = "mcl",
  combine_chains = FALSE,
  return_object = TRUE,
  column_prefix = "clustcr",
  ...
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data in the metadata.

chains

Character string specifying which chains to use: "TRA", "TRB", or "both". Default is "TRB".

method

Clustering method passed to clusTCR. Default is "mcl" (Markov Clustering), which is accurate for typical repertoire datasets.

combine_chains

Logical. If TRUE and chains="both", concatenates alpha and beta sequences with "_". Default is FALSE (clusters chains separately).

return_object

Logical. If TRUE, adds cluster assignments back to the input object metadata. If FALSE, returns only the clustering results. Default is TRUE.

column_prefix

Prefix for the new metadata column(s). Default is "clustcr".

...

Additional arguments passed to calculate.clustcr (e.g., inflation).

Value

If return_object=TRUE, returns the input object with cluster assignments added to metadata. If return_object=FALSE, returns a data.frame with barcodes and cluster assignments.

Examples

data(immLynx_example)

  # Cluster TRB chain using MCL algorithm
  sce <- runClustTCR(immLynx_example,
                            chains = "TRB")

  # Adjust MCL inflation parameter
  sce <- runClustTCR(immLynx_example,
                            chains = "TRB",
                            inflation = 3.0)

  # Cluster both chains separately
  sce <- runClustTCR(immLynx_example,
                            chains = "both")

  # Combine alpha and beta chains before clustering
  sce <- runClustTCR(immLynx_example,
                            chains = "both",
                            combine_chains = TRUE)

  # Get results as data.frame
  clusters_df <- runClustTCR(immLynx_example,
                             chains = "TRB",
                             return_object = FALSE)

Featurize TCR Sequences with the DeepTCR Variational Autoencoder

Description

Extracts CDR3 amino acid sequences from a SingleCellExperiment object and learns a low-dimensional representation using DeepTCR's unsupervised variational autoencoder (DeepTCR_U).

Usage

runDeepTCR(
  input,
  chains = c("TRB", "TRA", "both"),
  latent_dim = 256,
  use_genes = FALSE,
  stop_criterion = 0.01,
  combine_chains = FALSE,
  reduction_name = "tcr_deeptcr",
  reduction_key = "DeepTCR_",
  return_object = TRUE,
  seed = NULL,
  verbose = TRUE,
  ...
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Which chain(s) to featurize: "TRB", "TRA", or "both". Default is "TRB".

latent_dim

Width of the VAE latent space. Default is 256.

use_genes

Logical. If TRUE, includes V and J gene usage alongside the CDR3 sequence. Default is FALSE, sequence only.

stop_criterion

Training convergence threshold passed to Train_VAE. Default is 0.01.

combine_chains

Logical. If TRUE and chains="both", concatenates alpha and beta sequences with "_". Default is FALSE.

reduction_name

Name for the dimensional reduction. Default is "tcr_deeptcr".

reduction_key

Key prefix for the reduction columns. Default is "DeepTCR_".

return_object

Logical. If TRUE, adds features as a dimensional reduction. If FALSE, returns the raw features. Default is TRUE.

seed

Optional integer passed to Train_VAE as 'graph_seed' for reproducible training. Default is NULL.

verbose

Logical. If FALSE, suppresses DeepTCR's training output. Default is TRUE.

...

Additional arguments passed to calculate.deepTCR().

Details

The VAE is trained on unique sequences rather than on cells. DeepTCR's own documentation notes that 'Load_Data' does not merge identical amino acid sequences, so passing a redundant repertoire would both waste training time and weight the loss toward expanded clones. Features are expanded back onto cells afterward, so two cells sharing a CDR3 share a feature vector.

DeepTCR runs in its own basilisk environment ('deepTCREnv') because it pins TensorFlow 2.12 and an older numpy, pandas, and scipy stack that cannot coexist with the main immLynx environment. The first call builds that environment, which is a large download.

'latent_dim' sets the requested width. DeepTCR prunes uninformative latent features during training, so the returned matrix may be narrower.

Value

If return_object=TRUE, the input object with features added as the 'reduction_name' reduction. Cells with no sequence for the requested chain get NA. If return_object=FALSE, a list with 'features' (one row per unique sequence), 'sequences', 'barcodes', and 'explained_variance_ratio'.

Examples

data(immLynx_example)

  # Learn a 64-dimensional representation of the TRB repertoire
  sce <- runDeepTCR(immLynx_example,
                    chains = "TRB",
                    latent_dim = 64)

  # Include V and J gene usage
  sce <- runDeepTCR(immLynx_example,
                    chains = "TRB",
                    use_genes = TRUE)

  # Get the raw feature matrix
  res <- runDeepTCR(immLynx_example,
                    chains = "TRB",
                    return_object = FALSE)
  dim(res$features)

Generate Protein Language Model Embeddings for TCR Sequences

Description

Extracts TCR CDR3 sequences from a SingleCellExperiment object and generates embeddings using a protein language model (e.g., ESM-2).

Usage

runEmbeddings(
  input,
  chains = c("TRB", "TRA", "both"),
  model_name = "facebook/esm2_t12_35M_UR50D",
  pool = "mean",
  chunk_size = 32,
  reduction_name = "tcr_esm",
  reduction_key = "ESM_",
  return_object = TRUE,
  ...
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Which chain(s) to embed: "TRB", "TRA", or "both". Default is "TRB".

model_name

Hugging Face model name. Default is "facebook/esm2_t12_35M_UR50D". Other options: "facebook/esm2_t33_650M_UR50D", "facebook/esm2_t36_3B_UR50D"

pool

Pooling method: "mean", "cls", or "none". Default is "mean".

chunk_size

Number of sequences to process at once. Default is 32.

reduction_name

Name for the dimensional reduction. Default is "tcr_esm".

reduction_key

Key prefix for embeddings in reduction. Default is "ESM_".

return_object

Logical. If TRUE, adds embeddings as dimensional reduction. If FALSE, returns list with embeddings and metadata. Default is TRUE.

...

Additional arguments passed to proteinEmbeddings().

Details

This function uses protein language models to generate dense vector representations of TCR CDR3 sequences. These embeddings can be used for: - Dimensionality reduction and visualization - Clustering TCRs by sequence similarity - Downstream machine learning tasks

Value

If return_object=TRUE, returns input object with embeddings added as a dimensional reduction. If FALSE, returns list with embeddings matrix and metadata.

Examples

data(immLynx_example)

  # Generate ESM-2 embeddings for TRB chain
  sce <- runEmbeddings(immLynx_example,
                              chains = "TRB")

  # Use a larger ESM-2 model
  sce <- runEmbeddings(immLynx_example,
                              chains = "TRB",
                              model_name = "facebook/esm2_t33_650M_UR50D")

  # Embed both chains together
  sce <- runEmbeddings(immLynx_example,
                              chains = "both")

  # Use CLS pooling instead of mean pooling
  sce <- runEmbeddings(immLynx_example,
                              chains = "TRB",
                              pool = "cls")

  # Get raw embeddings as a list
  emb_list <- runEmbeddings(immLynx_example,
                            chains = "TRB",
                            return_object = FALSE)
  dim(emb_list$embeddings)

Perform HLA Association Analysis on Metaclones

Description

Tests associations between metaclone membership and HLA alleles using Fisher's exact test with FDR correction.

Usage

runHLAassociation(
  metaclone_data,
  hla_data,
  by = "barcode",
  fdr_threshold = 0.05
)

Arguments

metaclone_data

A data.frame with metaclone assignments, typically from runMetaclonotypist() with return_input=FALSE.

hla_data

A data.frame with HLA typing information. Must have a 'barcode' or 'sample' column for matching and columns for each HLA allele.

by

Column name to use for matching between datasets. Default is "barcode".

fdr_threshold

FDR threshold for significance. Default is 0.05.

Value

A data.frame with HLA association results:

metaclone

Metaclone identifier

hla_allele

HLA allele tested

odds_ratio

Association odds ratio

pvalue

Raw p-value from Fisher's exact test

fdr

FDR-adjusted p-value

significant

Whether FDR < threshold

Examples

# Create example metaclone and HLA data
metaclone_data <- data.frame(
  barcode = paste0("cell_", 1:20),
  metaclone = rep(c("MC1", "MC2"), each = 10),
  stringsAsFactors = FALSE
)
hla_data <- data.frame(
  barcode = paste0("cell_", 1:20),
  HLA_A = c(rep("A*02:01", 8), rep("A*01:01", 4),
            rep("A*02:01", 3), rep("A*01:01", 5)),
  stringsAsFactors = FALSE
)
results <- runHLAassociation(metaclone_data, hla_data)

Run Metaclonotypist for TCR Metaclone Discovery

Description

Identifies TCR metaclones (groups of related T cell receptors) using the metaclonotypist pipeline. Metaclonotypist uses a two-stage approach: fast edit-distance-based screening followed by TCRdist or SCEPTR refinement.

Usage

runMetaclonotypist(
  input,
  chains = c("beta", "alpha"),
  method = c("tcrdist", "sceptr"),
  max_edits = 2,
  max_dist = NULL,
  clustering = c("cc", "leiden", "louvain", "mcl"),
  resolution = 1,
  return_input = TRUE,
  column_name = "metaclone"
)

Arguments

input

A SingleCellExperiment object with scRepertoire data, or a data.frame with TCR data.

chains

Which chain to analyze: "alpha" or "beta". Default is "beta".

method

Distance metric for refinement: "tcrdist" (default) or "sceptr".

max_edits

Maximum CDR3 edit distance for initial screening. Default is 2.

max_dist

Maximum distance threshold for clustering. Default is 20 for tcrdist, 1.5 for sceptr.

clustering

Clustering algorithm: "cc" (connected components, default), "leiden", "louvain", or "mcl".

resolution

Resolution parameter for leiden/louvain clustering. Default is 1.0.

return_input

Logical. If TRUE and input is a SingleCellExperiment object, adds metaclone assignments to metadata. Default is TRUE.

column_name

Name for the metadata column. Default is "metaclone".

Details

Metaclonotypist identifies groups of related TCRs that may recognize similar antigens. The algorithm: 1. Uses the Symdel algorithm for fast edit-distance-based candidate identification 2. Refines candidates using TCRdist or SCEPTR similarity metrics 3. Applies graph-based clustering (Leiden by default) to identify metaclones

Value

If return_input=TRUE and input is a SingleCellExperiment, returns the object with metaclone assignments added to metadata. Otherwise returns a data.frame with:

barcode

Cell barcode

cdr3_aa

CDR3 amino acid sequence

metaclone

Metaclone cluster assignment

metaclone_size

Number of cells in the metaclone

References

Metaclonotypist: https://github.com/qimmuno/metaclonotypist

Examples

data(immLynx_example)

  # Run metaclonotypist on beta chain
  sce <- runMetaclonotypist(immLynx_example, chains = "beta")

  # Get results as data.frame instead of adding to object
  metaclones <- runMetaclonotypist(immLynx_example,
                                   return_input = FALSE)

  # Adjust edit distance threshold
  sce <- runMetaclonotypist(immLynx_example,
                                   max_edits = 3,
                                   max_dist = 50)

Calculate Generation Probability (Pgen) for TCRs in scRepertoire Data

Description

Extracts TCR sequences from a SingleCellExperiment object and calculates their generation probability using OLGA.

Usage

runOLGA(
  input,
  chains = c("TRB", "TRA"),
  model = NULL,
  organism = "human",
  use_vj_genes = FALSE,
  return_object = TRUE,
  column_name = "olga_pgen"
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Which chain to analyze: "TRA" or "TRB". Default is "TRB".

model

OLGA model to use. Options: "humanTRB", "humanTRA", "humanIGH", "mouseTRB". If NULL, will be inferred from organism and chains parameters.

organism

Organism: "human" or "mouse". Used if model is NULL. Default is "human".

use_vj_genes

Logical. If TRUE, includes V and J gene information in Pgen calculation. Default is FALSE (sequence-only Pgen).

return_object

Logical. If TRUE, adds Pgen values to metadata. Default is TRUE.

column_name

Name for the metadata column. Default is "olga_pgen".

Value

If return_object=TRUE, returns input object with Pgen added to metadata. If FALSE, returns data.frame with barcodes, sequences, and Pgen values.

Examples

data(immLynx_example)

  # Calculate Pgen for TRB chain
  sce <- runOLGA(immLynx_example, chains = "TRB")

  # Calculate Pgen for TRA chain
  sce <- runOLGA(immLynx_example, chains = "TRA")

  # Include V and J gene information
  sce <- runOLGA(immLynx_example,
                        chains = "TRB",
                        use_vj_genes = TRUE)

  # Get results as data.frame
  pgen_df <- runOLGA(immLynx_example,
                     chains = "TRB",
                     return_object = FALSE)

  # Specify model explicitly for mouse data
  sce <- runOLGA(immLynx_example,
                        model = "mouseTRB")

Predict T-cell clonal expansion from gene expression with scXpand

Description

Runs inference with a scXpand pretrained pan-cancer model to estimate, for each cell, the probability that it belongs to an expanded T-cell clone. scXpand uses gene expression only, so this works on datasets with no paired TCR sequencing. When the object does carry scRepertoire clone calls, runScXpand also derives ground-truth expansion labels so the prediction can be benchmarked against the observed repertoire.

Usage

runScXpand(
  input,
  model_name = "pan_cancer_autoencoder",
  assay = "counts",
  gene_ids = "rownames",
  map_symbols = c("auto", "always", "never"),
  ensembl_min_frac = 0.5,
  multi_map = c("first", "expand", "drop"),
  collapse = c("sum", "first", "drop"),
  derive_labels = TRUE,
  clone_col = NULL,
  sample_col = NULL,
  median_basis = c("clone", "cell"),
  label_cells = c("clonal", "all"),
  threshold = 0.5,
  obs_columns = NULL,
  batch_size = 1024L,
  num_workers = 0L,
  work_dir = NULL,
  cache_dir = NULL,
  keep_files = FALSE,
  overwrite = FALSE,
  column_prefix = "scXpand",
  return_object = TRUE,
  verbose = TRUE
)

Arguments

input

A SingleCellExperiment or Seurat object. SingleCellExperiment is the native format and is used without conversion; Seurat objects are converted in and returned as Seurat.

model_name

Pretrained model to use. See listScXpandModels. Default "pan_cancer_autoencoder".

assay

Assay holding raw UMI counts. Default "counts".

gene_ids

Where to find gene identifiers: "rownames" (default), the name of a rowData column, or a character vector of length nrow(input).

map_symbols

One of "auto" (map symbols to Ensembl IDs only if too few identifiers already look like Ensembl IDs), "always", or "never". Mapping requires org.Hs.eg.db and AnnotationDbi.

ensembl_min_frac

Minimum fraction of identifiers that must resolve to Ensembl IDs. Default 0.5. Lower it for targeted panels.

multi_map

How to resolve one symbol mapping to several Ensembl IDs: "first" (default, lexicographically first), "expand" (emit all), or "drop".

collapse

How to resolve several rows mapping to one Ensembl ID: "sum" (default), "first", or "drop".

derive_labels

Logical. Derive ground-truth expansion labels from clone data when present. Default TRUE.

clone_col

Column holding clone identity. Default NULL: use "CTstrict" if present, else "CTaa".

sample_col

Column identifying the sample or patient that clone sizes are tabulated within. Default NULL, which pools all cells into one sample and warns.

median_basis

"clone" (default) or "cell". See Details.

label_cells

"clonal" (default) scores only cells with a clone call, which guarantees the ground-truth column has no missing values; "all" scores every cell.

threshold

Probability cutoff for the binary call. Default 0.5.

obs_columns

Character vector of colData columns to carry into the staged H5AD. Default NULL: all of them, minus list-columns and the scRepertoire CT* columns.

batch_size

Inference batch size. Default 1024.

num_workers

DataLoader workers. Default 0, because worker processes forking out of embedded Python inside a basilisk child can hang on macOS. Raise it on Linux for speed.

work_dir

Directory for the staged H5AD and scXpand's own output. Default NULL: a temporary directory, removed on exit.

cache_dir

Directory for downloaded pretrained models. Default NULL: a scxpand subdirectory of tools::R_user_dir("immLynx", "cache"). Passing this explicitly matters because scXpand's own default would write a .scxpand_cache directory into the current working directory.

keep_files

Logical. Keep the staged H5AD and scXpand outputs. Default FALSE.

overwrite

Logical. Replace an existing adata.h5ad in an explicitly supplied work_dir. Default FALSE.

column_prefix

Prefix for the columns written back. Default "scXpand".

return_object

Logical. Return the input object with new columns (default), or a data.frame of per-cell results.

verbose

Logical. Emit progress messages. Default TRUE.

Details

Input requirements. scXpand's pretrained models were trained on raw UMI counts from T cells indexed by Ensembl gene ID. All three matter:

  • Raw counts. Normalized or log-transformed values are rejected. Use assay = "counts".

  • Ensembl IDs. Most Seurat and scRepertoire objects carry gene symbols; see gene_ids and map_symbols.

  • T cells only. Filter to T cells before calling. There is no reliable programmatic check, and predictions on non-T cells are meaningless.

Genes the model expects but cannot find are zero-filled by scXpand, and extra genes are ignored, so a partial overlap degrades quietly rather than erroring. That is why the gene mapping summary is worth reading.

Symbol mapping. When identifiers are symbols, they are mapped through org.Hs.eg.db (SYMBOL first, then ALIAS). One symbol often maps to several Ensembl IDs because of alternate haplotypes: HLA-DRA maps to eight. multi_map = "first" takes the lexicographically first, which is reproducible but may pick a scaffold the model does not know; multi_map = "expand" emits every candidate, which maximizes overlap with the model's panel at the cost of a larger staged matrix. Several input rows can also land on one Ensembl ID, in which case collapse decides what happens (summing raw counts is the default and preserves UMI semantics).

Expansion labels. scXpand calls a cell expanded when its clone size exceeds 1.5 times the median clone size for its sample. Clone sizes are tabulated fresh from clone_col within sample_col; scRepertoire's clonalFrequency column is deliberately not used, because combineExpression() computes it under whatever group.by was in effect and it is not necessarily a per-sample count. "Median clone size" is genuinely ambiguous, so median_basis selects the reading: "clone" takes the median over unique clones, which in typical 10x data is 1 (most clones are singletons) and therefore reduces the rule to clone size at least 2; "cell" takes the median over cells, which is dominated by large clones and is much stricter.

Cost. The first call builds a dedicated basilisk environment (Python 3.11, PyTorch CPU, scxpand) that occupies several gigabytes, and downloads the selected model (roughly 35 MB) from figshare into cache_dir. Both are reused afterwards. If a download does fail, clear cache_dir before retrying: the downloader caches the failed response and will otherwise keep reusing it.

Value

If return_object = TRUE, the input object (same class) with <prefix>_expansion_prob and <prefix>_expansion_pred added to cell metadata, plus <prefix>_clone_id_size, <prefix>_median_clone_size and <prefix>_expansion_truth when labels were derived. A run summary is stored under metadata(x)$scXpand for SingleCellExperiment or x@misc$scXpand for Seurat, holding the model info, the gene mapping report, scXpand's metrics and an independently computed AUROC. If return_object = FALSE, a data.frame with one row per scored cell and the run summary attached as attr(x, "scXpand").

Examples

data(immLynx_example)

# The label derivation is pure R and runs without Python. Note that the
# derived clone sizes are tabulated per sample and so need not match the
# clonalFrequency column scRepertoire wrote.
labs <- immLynx:::.deriveExpansionLabels(
  immLynx_example,
  sample_col = "Patient"
)
table(labs$expansion, useNA = "ifany")


# Full inference. The example object carries gene symbols and is not
# filtered to T cells, so this demonstrates the mechanics rather than a
# meaningful biological result.
sce <- runScXpand(
  immLynx_example,
  sample_col = "Patient",
  assay      = "counts"
)
summary(SummarizedExperiment::colData(sce)$scXpand_expansion_prob)
S4Vectors::metadata(sce)$scXpand$auroc_immLynx

Run soNNia Selection Analysis

Description

Infer selection pressures on TCRs using soNNia. Requires a background dataset of unselected sequences (generated by OLGA).

Usage

runSoNNia(
  input,
  chains = c("TRB", "TRA"),
  background_file,
  organism = "human",
  save_folder = "sonia_output",
  n_epochs = 100,
  return_object = TRUE
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Which chain to analyze: "TRB" or "TRA". Default is "TRB".

background_file

Path to CSV file with background sequences (from generateOLGA).

organism

Organism: "human" or "mouse". Default is "human".

save_folder

Directory to save soNNia model. Default is "sonia_output".

n_epochs

Number of training epochs. Default is 100.

return_object

If TRUE, adds selection scores to metadata. Default is TRUE.

Details

This function requires a background dataset of unselected TCR sequences, which can be generated using generateOLGA(). The selected sequences are extracted from the input object and compared to this background to infer selection pressures.

Value

If return_object=TRUE, returns input object with selection scores in metadata. Otherwise returns the soNNia results.

Examples

data(immLynx_example)
## Not run: 
  # Step 1: Generate background sequences with OLGA
  background <- generateOLGA(n = 1000, model = "humanTRB")
  bg_file <- tempfile(fileext = ".csv")
  utils::write.csv(background, bg_file, row.names = FALSE)

  # Step 2: Run soNNia selection analysis
  sce <- runSoNNia(immLynx_example,
                          chains = "TRB",
                          background_file = bg_file)

  # Get raw results instead of adding to object
  sonia_results <- runSoNNia(immLynx_example,
                             chains = "TRB",
                             background_file = bg_file,
                             return_object = FALSE)

## End(Not run)

Find Near-Neighbor CDR3 Sequences by Symmetric Deletion Lookup

Description

Extracts CDR3 amino acid sequences from a SingleCellExperiment object and finds all pairs within a given edit distance using the symmetric deletion lookup ("symdel") algorithm from pyrepseq. This is the same algorithm described in the XT-neighbor preprint, running on CPU rather than GPU.

Usage

runSymdelNeighbors(
  input,
  chains = c("TRB", "TRA", "both"),
  max_edits = 1,
  max_returns = NULL,
  n_cpu = 1,
  combine_chains = FALSE,
  return_object = TRUE,
  column_prefix = "symdel",
  ...
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Which chain(s) to search: "TRB", "TRA", or "both". Default is "TRB".

max_edits

Maximum edit distance defining a neighbor. Default is 1.

max_returns

Maximum number of neighbors to return per sequence. Default is NULL, meaning no limit.

n_cpu

Number of CPU processes for the search. Default is 1.

combine_chains

Logical. If TRUE and chains="both", concatenates alpha and beta sequences with "_" before searching. Default is FALSE.

return_object

Logical. If TRUE, adds a per-cell neighbor count to the input object. If FALSE, returns the neighbor edge list. Default is TRUE.

column_prefix

Prefix for the new metadata column. Default is "symdel", producing a "symdel_degree" column.

...

Additional arguments passed to calculate.symdel().

Details

The search runs over unique sequences rather than over cells. Repertoires carry heavy clonal redundancy, so this is both substantially faster and what the symdel algorithm expects. Results are mapped back to cells afterward.

Degree is a neighborhood-density measure. High-degree sequences sit inside dense clusters of similar receptors, which is the signal used to identify convergent recombination and antigen-driven expansion. For explicit cluster assignments, see runClustTCR.

Value

If return_object=TRUE, the input object with a '<prefix>_degree' column added to colData giving the number of neighbors found for each cell's CDR3 sequence. Cells with no sequence for the requested chain get NA. If return_object=FALSE, a data.frame with columns 'from_seq', 'to_seq', and 'distance', one row per undirected neighbor pair.

Examples

data(immLynx_example)

  # Neighbors within one edit on the TRB chain
  sce <- runSymdelNeighbors(immLynx_example, chains = "TRB")

  # Widen the search to two edits
  sce <- runSymdelNeighbors(immLynx_example,
                            chains = "TRB",
                            max_edits = 2)

  # Get the neighbor edge list instead
  edges <- runSymdelNeighbors(immLynx_example,
                              chains = "TRB",
                              return_object = FALSE)
  head(edges)

Calculate TCR Distances on scRepertoire Data

Description

This function extracts TCR sequences from a SingleCellExperiment object with scRepertoire data and calculates pairwise TCR distances using tcrdist3.

Usage

runTCRdist(
  input,
  chains = "beta",
  organism = "human",
  compute_distances = TRUE,
  add_to_object = FALSE
)

Arguments

input

A SingleCellExperiment or Seurat object containing scRepertoire TCR data.

chains

Character vector specifying chains: "alpha", "beta", or c("alpha", "beta"). Default is "beta".

organism

Organism: "human" or "mouse". Default is "human".

compute_distances

Logical. Whether to compute full distance matrix. Default TRUE.

add_to_object

Logical. If TRUE, attempts to add distance matrix to object (stored in metadata for SCE). Default is FALSE due to large matrix size.

Value

A list containing:

distances

Distance matrices (pw_alpha, pw_beta, pw_cdr3_a_aa, pw_cdr3_b_aa)

barcodes

Cell barcodes corresponding to matrix rows/columns

tcr_data

The formatted TCR data.frame used for analysis

If add_to_object=TRUE, returns the input object with distances stored.

Examples

data(immLynx_example)

  # Calculate TCR distances for beta chain
  dist_results <- runTCRdist(immLynx_example,
                             chains = "beta")

  # Access the distance matrix
  dist_matrix <- dist_results$distances
  barcodes <- dist_results$barcodes

  # Calculate for both chains
  dist_both <- runTCRdist(immLynx_example,
                          chains = c("alpha", "beta"))

  # Add distances directly to the object
  sce <- runTCRdist(immLynx_example,
                           chains = "beta",
                           add_to_object = TRUE)

Summarize TCR Repertoire Statistics

Description

Generates summary statistics for TCR repertoire data including diversity metrics, clonality measures, and sequence characteristics.

Usage

summarizeTCRrepertoire(
  input,
  chains = c("TRB", "TRA", "both"),
  group.by = NULL,
  calculate_diversity = TRUE
)

Arguments

input

A SingleCellExperiment object with scRepertoire data, or a data.frame from extractTCRdata().

chains

Which chains to summarize: "TRB", "TRA", or "both". Default is "TRB".

group.by

Optional metadata column for grouping (SingleCellExperiment objects only).

calculate_diversity

Logical. If TRUE, calculates diversity indices. Default is TRUE.

Value

An object of class TCR_summary containing summary statistics for the TCR repertoire.

Examples

# Summarize from a data.frame
tcr_data <- data.frame(
  barcode = paste0("cell_", 1:10),
  cdr3_aa = c("CASSLGTGELFF", "CASSIRSSYEQYF", "CASSLGTGELFF",
              "CASSYSTGELFF", "CASSIRSSYEQYF", "CASSLGTGELFF",
              "CASNQGLNEKLFF", "CASSYSTGELFF", "CASSLGTGELFF",
              "CASSIRSSYEQYF"),
  v = rep("TRBV7-2", 10),
  j = rep("TRBJ2-2", 10),
  chain = rep("TRB", 10),
  stringsAsFactors = FALSE
)
summary <- summarizeTCRrepertoire(tcr_data)
print(summary)

S4 Class for TCR Repertoire Summary

Description

Formal S4 class to store summary statistics for a TCR repertoire, including diversity metrics, clonality measures, and sequence characteristics.

Usage

## S4 method for signature 'TCR_summary'
show(object)

Arguments

object

A TCR_summary object.

Value

An S4 object of class TCR_summary containing the summary statistics described in the slots. The show method prints a formatted summary to the console and returns invisible(NULL).

Slots

total_cells

Integer. Total number of cells with TCR data.

unique_clonotypes

Integer. Number of unique clonotypes.

clonotype_ratio

Numeric. Ratio of unique clonotypes to total cells.

diversity

List of diversity indices (Shannon, Simpson, etc.), or NULL.

top_clones

Data.frame of the top 10 most frequent clonotypes.

cdr3_length

List with CDR3 length distribution statistics.

gene_usage

List of V and J gene usage data.frames.

chains

Character. Chain(s) summarized.


Tokenize Amino Acid Sequences

Description

Takes a vector of amino acid sequences and uses a Hugging Face tokenizer to convert them into numerical input IDs suitable for model input. The tokenizer should be obtained from huggingModel, which manages the Python environment via basilisk.

Usage

tokenizeSequences(
  tokenizer,
  aa_sequences,
  padding = TRUE,
  truncation = TRUE,
  return_tensors = "pt"
)

Arguments

tokenizer

The tokenizer object returned by huggingModel.

aa_sequences

A character vector of amino acid sequences (e.g., CDR3 sequences).

padding

A logical or string. If TRUE, pads sequences to the length of the longest sequence in the batch. Defaults to TRUE.

truncation

A logical. If TRUE, truncates sequences to the model's maximum input length. Defaults to TRUE.

return_tensors

A string specifying the format for the returned tensors. "pt" for PyTorch tensors, "tf" for TensorFlow. Defaults to "pt".

Value

The tokenized output, typically a dictionary-like object containing 'input_ids' and 'attention_mask'.

See Also

huggingModel, proteinEmbeddings, runEmbeddings

Examples

sequences <- c("CASSLGTGELFF", "CASSIRSSYEQYF", "CASSYSTGELFF")

  # Initialize model and tokenizer
  hf_components <- huggingModel()

  # Tokenize CDR3 sequences
  tokenized <- tokenizeSequences(hf_components$tokenizer,
                                 sequences)

  # Tokenize without padding (variable-length output)
  tokenized_nopad <- tokenizeSequences(
      hf_components$tokenizer,
      sequences,
      padding = FALSE)

  # Pass tokenized output to proteinEmbeddings
  embeddings <- proteinEmbeddings(hf_components$model,
                                  tokenized,
                                  pool = "mean",
                                  chunk_size = 32)

  # Clean up
  basilisk::basiliskStop(hf_components$proc)

Validate TCR Data Format

Description

Validates that TCR data is in the correct format for immLynx analysis functions. Checks for required columns, valid sequence formats, and gene nomenclature.

Usage

validateTCRdata(
  tcr_data,
  check_genes = FALSE,
  check_sequences = TRUE,
  strict = FALSE
)

Arguments

tcr_data

A data.frame containing TCR data

check_genes

Logical. If TRUE, validates gene names against IMGT nomenclature. Default is FALSE.

check_sequences

Logical. If TRUE, validates that CDR3 sequences contain only valid amino acids. Default is TRUE.

strict

Logical. If TRUE, stops with error on validation failure. If FALSE, returns validation report. Default is FALSE.

Value

If strict=FALSE, returns a list with:

valid

Logical indicating overall validity

errors

Character vector of error messages

warnings

Character vector of warning messages

summary

Summary statistics of the data

If strict=TRUE, returns TRUE invisibly on success or stops with error.

Examples

# Create example TCR data
tcr_data <- data.frame(
  barcode = paste0("cell_", 1:5),
  cdr3_aa = c("CASSLGTGELFF", "CASSIRSSYEQYF", "CASSYSTGELFF",
              "CASNQGLNEKLFF", "CASSLDRNEQFF"),
  v = paste0("TRBV", c("7-2", "12-3", "5-1", "28", "7-9")),
  j = paste0("TRBJ", c("2-2", "1-1", "2-7", "1-5", "2-1")),
  chain = rep("TRB", 5),
  stringsAsFactors = FALSE
)
report <- validateTCRdata(tcr_data, strict = FALSE)
report$valid
report$summary