---
name: tessa
description: TESSA (TCR and Expression Joint Clustering) is a Bayesian model that integrates T-cell receptor (TCR) sequence profiling with transcriptomes of T cells. It maps the functional landscape of the TCR repertoire by learning unified representations across modalities. The process employs BriseisEncoder to capture TCR sequence features, creating numerical embeddings that reconstruct Atchley Factor matrices and CDR3 sequences.
---

# TESSA Process Configuration

## Purpose
TESSA (TCR and Expression Joint Clustering) is a Bayesian model that integrates T-cell receptor (TCR) sequence profiling with transcriptomes of T cells. It maps the functional landscape of the TCR repertoire by learning unified representations across modalities. The process employs BriseisEncoder to capture TCR sequence features, creating numerical embeddings that reconstruct Atchley Factor matrices and CDR3 sequences. This enables discovery of functional T-cell clusters based on combined TCR and gene expression information.

## When to Use
- **Antigen-specific TCR analysis**: When analyzing T cells recognizing specific antigens (viral, tumor, etc.)
- **Functional landscape mapping**: To understand the functional heterogeneity of TCR repertoire
- **Multi-dataset integration**: When combining TCR and RNA data across multiple samples/batches
- **Bystander vs specific T cells**: To distinguish antigen-specific T cells from bystanders in immune responses
- **Required upstream**: After `ScRepCombiningExpression` with data that has both TRA and TRB chains
- **NOT for**: BCR data analysis (TESSA is TCR-specific only)

## Configuration Structure

### Process Enablement
```toml
[TESSA]
cache = true  # Enable caching (default: true)
```

### Input Specification
```toml
[TESSA.in]
# Type: CombinedInput (requires both TCR and RNA data)
# Required: yes
# Description: Data generated by ScRepCombiningExpression process
# Format: RDS or qs/qs2 format
screpdata = ["ScRepCombiningExpression"]
```

**Critical requirement**: Input data must have **both TRA and TRB chains**. Cells with only single-chain TCRs will be excluded from analysis.

### Environment Variables

#### Core Parameters
```toml
[TESSA.envs]
# python: str - Path to Python interpreter with TESSA dependencies (default: "python")
# Required: yes if not in PATH
python = "/path/to/python_with_tessa"

# within_sample: flag - TCR network construction scope (default: false)
# false: Construct TCR networks using ALL TCRs in metadata (cross-sample)
# true: Construct networks only within same sample/patient (within-sample)
within_sample = false

# assay: str - Which assay to extract expression matrix from (default: auto)
# Only applies if input is Seurat RDS file
# Auto-detects "SCT" if SCTransform performed, otherwise "RNA"
assay = "SCT"  # or "RNA"

# predefined_b: flag - Use predefined b vector in MCMC (default: false)
# true: TESSA will not update b in MCMC iterations
# false: b vector will be updated during MCMC
# See TESSA paper for details about the b vector
predefined_b = false

# max_iter: int - Maximum MCMC iterations (default: 1000)
# Higher values = more convergence but slower runtime
# Typical range: 500-2000
max_iter = 1000

# save_tessa: flag - Save detailed TESSA results (default: false)
# true: Saves detailed results to sobj@misc$tessa
# false: Only saves cluster assignments and sizes
# Recommended for debugging but increases object size
save_tessa = false
```

## Configuration Examples

### Minimal Configuration
```toml
[TESSA]
[TESSA.in]
screpdata = ["ScRepCombiningExpression"]
```

### Standard Cross-Sample Analysis
```toml
[TESSA]
[TESSA.envs]
python = "/usr/bin/python3"
within_sample = false  # Networks across all samples
max_iter = 1000
assay = "SCT"
```

### Within-Sample Analysis (Multiple Patients)
```toml
[TESSA]
[TESSA.envs]
python = "/usr/bin/python3"
within_sample = true  # Networks within each patient/patient
max_iter = 1500
predefined_b = false
```

### Debugging Mode
```toml
[TESSA]
[TESSA.envs]
python = "/usr/bin/python3"
max_iter = 500
save_tessa = true  # Save full TESSA results for inspection
```

### High-Throughput Mode
```toml
[TESSA]
[TESSA.envs]
python = "/usr/bin/python3"
within_sample = false
max_iter = 500  # Faster, less convergence
predefined_b = true  # Use predefined b for speed
save_tessa = false
```

## Common Patterns

### Pattern 1: Viral-Specific T Cell Analysis
Analyzing T cells from viral infection (e.g., COVID-19, influenza, HIV) to identify virus-specific T cells.

```toml
[TESSA]
[TESSA.in]
screpdata = ["ScRepCombiningExpression"]

[TESSA.envs]
python = "/usr/bin/python3"
within_sample = true  # Keep within patient to avoid cross-contamination
max_iter = 1000
assay = "SCT"
save_tessa = true  # Inspect viral-specific clusters
```

**Use case**: Distinguish SARS-CoV-2-specific T cells from bystanders in COVID-19 patient samples. TESSA clusters can reveal functional states specific to viral recognition.

### Pattern 2: Tumor-Infiltrating Lymphocyte (TIL) Analysis
Analyzing T cells in tumor microenvironment to identify tumor-recognizing T cells.

```toml
[TESSA]
[TESSA.in]
screpdata = ["ScRepCombiningExpression"]

[TESSA.envs]
python = "/usr/bin/python3"
within_sample = false  # Combine across tumor samples
max_iter = 1200
assay = "SCT"
predefined_b = false
save_tessa = true
```

**Use case**: Identify tumor-specific TIL clusters and their functional states across multiple tumor samples from different patients. Helps discover shared tumor antigen recognition patterns.

### Pattern 3: Longitudinal Immune Response
Analyzing T cell evolution across time points in same individual.

```toml
[TESSA]
[TESSA.in]
screpdata = ["ScRepCombiningExpression"]

[TESSA.envs]
python = "/usr/bin/python3"
within_sample = true  # Networks within individual + timepoint
max_iter = 1000
assay = "SCT"
save_tessa = false
```

**Use case**: Track T cell functional changes during treatment or disease progression. Each time point analyzed separately to understand temporal dynamics.

### Pattern 4: Vaccine Response Study
Analyzing T cell responses to vaccination across multiple subjects.

```toml
[TESSA]
[TESSA.in]
screpdata = ["ScRepCombiningExpression"]

[TESSA.envs]
python = "/usr/bin/python3"
within_sample = false  # Find shared vaccine-specific clusters across subjects
max_iter = 1500
assay = "SCT"
predefined_b = false
save_tessa = true
```

**Use case**: Identify vaccine-specific T cell clusters shared across multiple vaccinated individuals. Higher iterations ensure convergence in cross-subject analysis.

## Dependencies

### Upstream Processes
- **Required**: `ScRepCombiningExpression`
- **Required**: `ScRepLoading` (provides TCR data)
- **Required**: `SeuratPreparing` (provides RNA data)
- **Optional**: `SeuratClustering` (for comparison with TESSA clusters)

### Downstream Analysis
TESSA output adds two columns to Seurat metadata:
- `TESSA_Cluster`: Cluster assignments (use for clustering visualization)
- `TESSA_Cluster_Size`: Cluster cell counts (use for cluster statistics)

**Common downstream analyses**:
- `SeuratClusterStats`: Visualize TESSA clusters on UMAP
- `ClusterMarkers`: Find markers specific to each TESSA cluster
- `ScFGSEA`: Pathway enrichment per TESSA cluster
- `CellCellCommunication`: Analyze communication within/between TESSA clusters
- `ScrnaMetabolicLandscape`: Metabolic profiling of functional T cell states

## Validation Rules

### TCR Data Requirements
- **Mandatory**: Both TRA and TRB chains must be present
- **Single-chain TCRs**: Cells with only TRA or only TRB will be excluded
- **Minimum cells**: Requires sufficient T cells with paired TCRs (typically >100 cells)
- **Data quality**: High-quality TCR sequences recommended (TESSA uses sequence embeddings)

### Python Environment
- **TESSA dependencies**: Must have `tessa` Python package and dependencies installed
- **BriseisEncoder**: Required for TCR sequence embedding
- **Python version**: Compatible with Python 3.8+
- **Specify path**: Use `envs.python` if TESSA not in default Python path

### Convergence Criteria
- **max_iter**: Set high enough for MCMC convergence (check with save_tessa=true)
- **Typical convergence**: 1000 iterations sufficient for most datasets
- **Large datasets**: May require 1500+ iterations
- **Quick exploration**: Can use 500 iterations with predefined_b=true

## Troubleshooting

### Issue: "No TCR data found" or empty TESSA clusters
**Cause**: Input data lacks both TRA and TRB chains or has insufficient cells.

**Solutions**:
1. Verify `ScRepCombiningExpression` output includes TCR data
2. Check TCR data has both TRA and TRB columns
3. Increase cell count (filter out low-quality cells upstream)
4. Use `ScRepLoading.envs.chain = "both"` to ensure both chains loaded

### Issue: Python import errors for TESSA/BriseisEncoder
**Cause**: TESSA dependencies not installed in specified Python environment.

**Solutions**:
1. Install TESSA: `pip install tessa`
2. Specify correct Python path: `[TESSA.envs] python = "/path/to/python"`
3. Create dedicated conda environment with TESSA dependencies
4. Verify BriseisEncoder import works: `python -c "from BriseisEncoder import *"`

### Issue: Very slow runtime
**Cause**: MCMC iterations or dataset too large.

**Solutions**:
1. Reduce `max_iter` to 500-800
2. Set `predefined_b = true` (skip b vector updates)
3. Filter to top N cells before analysis
4. Use `within_sample = true` for parallel per-sample processing

### Issue: Poor cluster separation or biologically meaningless clusters
**Cause**: Insufficient convergence or inappropriate network scope.

**Solutions**:
1. Increase `max_iter` to 1500-2000
2. Adjust `within_sample` based on biological question:
   - Cross-sample analysis: `within_sample = false`
   - Patient-specific analysis: `within_sample = true`
3. Check data quality (remove low-quality cells)
4. Set `predefined_b = false` to allow full MCMC learning

### Issue: TESSA not recognizing SCT assay
**Cause**: Assay not specified when input is RDS file.

**Solutions**:
1. Explicitly set: `[TESSA.envs] assay = "SCT"`
2. Verify SCT assay exists in Seurat object
3. Alternatively use `assay = "RNA"` for standard assay

## Technical Details

### TESSA Algorithm Components
1. **BriseisEncoder**: Creates numerical embeddings from TCR sequences
2. **Atchley Factor reconstruction**: Rebuilds amino acid properties from embeddings
3. **CDR3 peptide prediction**: Uses RandomForest to predict CDR3 sequences
4. **Bayesian MCMC**: Jointly models TCR and expression data
5. **Network construction**: Builds TCR similarity networks (within_sample or cross-sample)

### Output Metadata Columns
- `TESSA_Cluster`: Integer cluster assignments (1, 2, 3, ...)
- `TESSA_Cluster_Size`: Count of cells in each cluster (per row)

### Accessing Full TESSA Results
When `save_tessa = true`, detailed results saved to `sobj@misc$tessa`:
- Full MCMC traces
- Cluster probabilities
- Network structures
- Embedding matrices

**Access in R**: `tessa_results <- srtobj@misc$tessa`

## External References

### TESSA Paper
- **Main paper**: Zhang et al. (2021) "Mapping the Functional Landscape of TCR Repertoire by Single T Cell Transcriptomics", *Nature Methods*, 18:92–99
- **Link**: https://www.nature.com/articles/s41592-020-01020-3

### BriseisEncoder Paper
- **Paper**: Lu et al. (2021) "Deep learning-based prediction of the T cell receptor-antigen binding specificity", *Nature Machine Intelligence*
- **Link**: https://www.nature.com/articles/s42256-021-00383-2

### TESSA GitHub
- **Repository**: https://github.com/jcao89757/TESSA
- **Documentation**: TESSA_main.py README and usage examples
- **Installation**: pip install tessa

### scRepertoire Reference
- **combineExpression**: https://rdrr.io/github/ncborcherding/scRepertoire/man/combineexpression
- Used by upstream `ScRepCombiningExpression` process

## Best Practices

1. **Verify TCR data quality** before running TESSA
2. **Use appropriate `within_sample` setting**:
   - Cross-sample: False (shared biology across samples)
   - Patient-specific: True (avoid mixing patients)
3. **Start with `max_iter = 1000`**, increase if convergence issues
4. **Set `save_tessa = true`** for first run to inspect results
5. **Compare TESSA clusters with expression clusters** (SeuratClustering)
6. **Validate clusters biologically** using known markers or antigens
7. **Use sufficient cell numbers** (>100 cells recommended for robust clustering)

## Related Processes

- **ScRepCombiningExpression**: Required upstream process (provides TCR+RNA data)
- **CDR3Clustering**: Alternative TCR clustering (sequence-based, not expression-integrated)
- **ScFGSEA**: Pathway enrichment analysis on TESSA clusters
- **ClusterMarkers**: Find markers distinguishing TESSA clusters
- **ScrnaMetabolicLandscape**: Metabolic profiling of TESSA clusters
