riot-na 4.0.7
Antibody numbering software
Requires Python: <4.0,>=3.10

# RIOT - Rapid Immunoglobulin Overview Tool

Have some raw antibody sequences? Find matching germlines, perform numbering and get results in a familiar AIRR format!

RIOT supports both nucleotide and amino acid sequences as well as all major schemes: KABAT, CHOTHIA, MARTIN and IMGT.

<details>
  <summary>MOTIVATION</summary>

Antibodies are a cornerstone of the immune system, playing a pivotal role in identifying and neutralizing infections caused by bacteria, viruses, and other pathogens. Understanding their structure, function, can provide insights into both the body's natural defenses and the principles behind many therapeutic interventions, including vaccines and antibody-based drugs. The analysis and annotation of antibody sequences, including the identification of variable, diversity, joining, and constant genes, as well as the delineation of framework regions and complementarity determining regions, are essential for understanding their structure and function. Currently analyzing large volumes of antibody sequences for is routine in antibody discovery, requiring fast and accurate tools. While there are existing tools designed for the annotation and numbering of antibody sequences, they often have limitations such as being restricted to either nucleotide or amino acid sequences, reliance on non-uniform germline databases, or slow execution times. Here we present Rapid Immunoglobulin Overview Tool (RIOT), a novel open source solution for antibody numbering that addresses these shortcomings. RIOT handles nucleotide and amino acid sequence processing, comes with a free germline database, and is computationally efficient. We hope the tool will facilitate rapid annotation of antibody sequencing outputs for the benefit of understanding of antibody biology and discovering novel therapeutics.

</details>

## Links:
- [PyPI](https://pypi.org/project/riot-na/)
- [Source code](https://github.com/NaturalAntibody/riot_na)
- [Collab example](https://colab.research.google.com/drive/1xKO4udsX5gmnY88eDKWsQaUnHsLuFwVA?usp=sharing)

## Requirements
 - Python ^3.10
 - C compiler (reason: `scikit-bio`)

## Quickstart
```
> pip install riot-na

> riot_na -s GGGCGTTTTGGCAC...

{
    "sequence_header": "-",
    "sequence": "GGGCGTTTTGGCAC...",
    "numbering_scheme": "imgt",
    "locus": "igh",
    "stop_codon": False,
    "vj_in_frame": True,
    "v_frameshift": False,
    "j_frameshift": False,
    "productive": True,
    "rev_comp": False,
    "complete_vdj": True,
    "v_call": "IGHV1-69*01",
    "d_call": "IGHD3-3*01",
    "j_call": "IGHJ6*02",
    "c_call": "IGHM",
    "v_frame": 0,
    ...
}
```

## Installation

Riot is distributed in prebuild binary wheels for all major platforms. Just run in your chosen virtualenv:

```
pip install riot-na
```

## Usage
### CLI

```
Usage: riot_na [OPTIONS]

Options:
  -f, --input-file PATH           Path to input FASTA file.
  -s, --sequence TEXT             Input sequence.
  -o, --output-file PATH          Path to output CSV file. If not specified,
                                  stdout is used.
  --scheme [KABAT|CHOTHIA|IMGT|MARTIN]
                                  Which numbering scheme should be used: IMGT,
                                  KABAT, CHOTHIA, MARTIN. Default IMGT
  --species [HOMO_SAPIENS|MUS_MUSCULUS|CUSTOM]
                                  Which species germline sequences should be
                                  used. Default is all species.
  --input-type [NT|AA]            What kind of sequences are provided on
                                  input. Default is nucleotide sequences.
  -p, --ncpu INTEGER              Number of parallel processes to use. Default
                                  is number of physical cores.
  -e, --extend_alignment BOOLEAN  Include unaligned beginning of the query
                                  sequence in numbering.This option impacts
                                  only amino acid sequences passed with -s option.
  --multiple-domains BOOLEAN      Return all domains of multiple domain
                                  proteins.
  --help                          Show this message and exit.

```

#### Examples:
Run on single sequence and print output to stdout:
```
riot_na -s <sequence>
```
Run on single sequence and save output to csv:
```
riot_na -s <sequence> -o result.csv
```
Run on fasta file:
```
riot_na -f input.fasta -o results.csv
```
### API Nucleotides

```python
from riot_na import create_riot_nt, Organism, Scheme, RiotNumberingNT, AirrRearrangementEntryNT

riot_nt: RiotNumberingNT = create_riot_nt(allowed_species = (Organism.HOMO_SAPIENS,))
airr_result: AirrRearrangementEntryNT = riot_nt.run_on_sequence(
                    header = "SRR13857054.957936",
                    query_sequence = "GAACCAAACTGACTGTCCTAGGCCAGCCCAAGTCTTCGCCATCAGTCACCCTGTTTCCACCTTCCCCTGAAGAGCTAAAAAAA",
                    scheme = Scheme.KABAT
                )
```

### API Amino Acids

```python
from riot_na import create_riot_aa, Organism, Scheme, RiotNumberingAA, AirrRearrangementEntryAA

riot_aa: RiotNumberingAA = create_riot_aa(allowed_species = (Organism.HOMO_SAPIENS,))
airr_result: AirrRearrangementEntryAA = riot_aa.run_on_sequence(
                    header = "SRR13385915.5101835",
                    query_sequence = "QVTLKESGPVLVKPTETLTLTCTVSGFSLSNARMGVSWIRQPPGKALEWLAHIFSNDEKSYSTSLKSRLTISKDTSKSQVVLTMTNMDPGDTATYYCARRGGTIFGVVIILVRRPPL",
                    scheme = Scheme.KABAT,
                    extend_alignment = True
                )
```

### Caching
We provide two cached wrappers for `create_riot_nt()` and `crate_riot_aa()` functions - `get_or_create_riot_nt()` | `get_or_create_riot_aa()`. They can be used exactly the same way as base functions:

```python
from riot_na import get_or_create_riot_aa, Organism, Scheme, RiotNumberingAA, AirrRearrangementEntryAA

riot_aa: RiotNumberingAA = get_or_create_riot_aa(allowed_species = (Organism.HOMO_SAPIENS,))
airr_result: AirrRearrangementEntryAA = riot_aa.run_on_sequence(
                    header = "SRR13385915.5101835",
                    query_sequence = "QVTLKESGPVLVKPTETLTLTCTVSGFSLSNARMGVSWIRQPPGKALEWLAHIFSNDEKSYSTSLKSRLTISKDTSKSQVVLTMTNMDPGDTATYYCARRGGTIFGVVIILVRRPPL",
                    scheme = Scheme.KABAT,
                    extend_alignment = True
                )
```


### Multiprocessing
Riot uses precompiled Rust module for prefiltering. This means the RiotNumberingNT/AA objects are unpickable, so you cannot pass it as a worker's parameter in eg. `mp.Pool()` or use it in Spark's UDF functions. This is achievable by using cached wrappers we provide `get_or_create_riot_nt()` | `get_or_create_riot_aa()`. Below you can find working and not working examples.

The following will not work:

```python
import functools
import multiprocessing as mp
from riot_na import create_riot_aa, AirrRearrangementEntryAA, RiotNumberingAA

seqs = ["EVQLVESGGGLVQPGGSLRLSCAASGFNIKDTYIHWVRQAPGKGLEWVARIYPTNGYTRYADSVKGRFTISADTSKNTAYLQMNSLRAEDTAVYYCARGGSFYYYYMDVWGQGTLVTVSSASTKGPSVFPLAPSSKSTSGGTAALGCLVKDYFPEPVTVSWNSGALTSGVHTFPAVLQSSGLYSLSSVVTVPSSSLGTQTYICNVNHKPSNTKVDKKVEPKSCDKTGHHHHHHHHG"] * 10

def worker(riot: RiotNumberingAA, seq: str) -> AirrRearrangementEntryAA:
    airr = riot.run_on_sequence("-", seq)
    return airr

riot = create_riot_aa()

worker_partial = functools.partial(worker, riot)

with mp.Pool() as pool:
    res = pool.map(worker_partial, seqs)

# Output: TypeError: cannot pickle 'builtins.Prefiltering' object
```
The proper way:
```python
import multiprocessing as mp
from riot_na import get_or_create_riot_aa, AirrRearrangementEntryAA

seqs = ["EVQLVESGGGLVQPGGSLRLSCAASGFNIKDTYIHWVRQAPGKGLEWVARIYPTNGYTRYADSVKGRFTISADTSKNTAYLQMNSLRAEDTAVYYCARGGSFYYYYMDVWGQGTLVTVSSASTKGPSVFPLAPSSKSTSGGTAALGCLVKDYFPEPVTVSWNSGALTSGVHTFPAVLQSSGLYSLSSVVTVPSSSLGTQTYICNVNHKPSNTKVDKKVEPKSCDKTGHHHHHHHHG"] * 10


def worker(seq: str) -> AirrRearrangementEntryAA:
    riot = get_or_create_riot_aa()
    airr = riot.run_on_sequence("-", seq)
    return airr

with mp.Pool() as pool:
    res = pool.map(worker, seqs)
```

Spark UDF example:

```python
import json
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf
from cachetools import cached
from riot_na import get_or_create_riot_aa, RiotNumberingAA

spark = SparkSession.builder.appName("Riot on Spark").getOrCreate()

seq = "EVQLVESGGGLVQPGGSLRLSCAASGFNIKDTYIHWVRQAPGKGLEWVARIYPTNGYTRYADSVKGRFTISADTSKNTAYLQMNSLRAEDTAVYYCARGGSFYYYYMDVWGQGTLVTVSSASTKGPSVFPLAPSSKSTSGGTAALGCLVKDYFPEPVTVSWNSGALTSGVHTFPAVLQSSGLYSLSSVVTVPSSSLGTQTYICNVNHKPSNTKVDKKVEPKSCDKTGHHHHHHHHG"

df = spark.createDataFrame([{"seq":  seq}]*10)

@udf
def number_sequence(seq: str)-> str:
    riot = get_or_create_riot_aa()
    airr = riot.run_on_sequence("-", seq)
    return json.dumps(airr.__dict__)

df.select(number_sequence("seq")).collect()
```

For a pure Python solution (without the use of `cachetools` package) you can check `riot_na/api/api_mp.py` file.


## Multidomains support
RIOT's multidomains support allows detection and numbering of multiple immunoglobulin domains within a single protein sequence, such as therapeutic antibodies containing both heavy chain (VH) and light chain (VL) domains. When enabled with the --multiple-domains flag (or return_all_domains=True in the API), RIOT returns separate numbering results for each detected domain rather than just the best single match. The system automatically identifies domain boundaries, truncates sequences at the beginning of each V gene segment, and provides additional metadata including the original query sequence and segment start/end positions for each domain. This is particularly useful for analyzing therapeutic constructs like bispecific antibodies, CAR-T constructs, or other multi-domain fusion proteins where each immunoglobulin domain needs independent numbering and analysis.

## Germline database
RIOT uses OGRDB as a primary source of germline alleles. Database version as of 22.01.2024 was used.
C genes are imported from igblast FTP site fhttps://ftp.ncbi.nih.gov/blast/executables/igblast/release/database/ncbi_human_c_genes.tar


## Data format

This section describes the fields of numbering result object AirrRearrangementEntry(AA). It is based on AIRR Rearrangement Schema format extended by 7 columns highlighted in the table (bold) and emptied of the unnecessary ones. There are also some differences in fields’ definitions, so the AIRR format specification should be treated only as a loose reference. Description of the original AIRR format can be found [here](https://docs.airr-community.org/en/stable/datarep/rearrangements.html#fields).


Attributes:


1. All fields in the format are required (always present)
2. All fields are nullable, with the exception of _sequence_header_ and _sequence_

### AirrRearrangementNT fields definitions

| Name                            | Type                                        | Definition                                                                                                                                                                                                                                                                                                                                                                                       |
| :------------------------------ | :------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sequence_header                 | string                                      | Fasta header for given input sequence (when numbering a FASTA file) or value of sequence_header parameter (when using RiotNumberingNT API).                                                                                                                                                                                                                                                      |
| sequence                        | string                                      | The segment nucleotide sequence. May be truncated to the beginning of v_gene when --multiple-domains flag is enabled                                                                                                                                                                                                                                                                             |
| sequence_aa                     | string                                      | Translated query sequence.                                                                                                                                                                                                                                                                                                                                                                       |
| numbering_scheme                | enum ["imgt", "kabat", "chothia", "martin"] | Used numbering scheme, default is "imgt".                                                                                                                                                                                                                                                                                                                                                        |
| locus                           | string                                      | Gene locus (chain type).                                                                                                                                                                                                                                                                                                                                                                         |
| locus_species                   | string                                      | Binomial designation of the species from which the locus originates.                                                                                                                                                                                                                                                                                                                             |
| stop_codon                      | boolean                                     | True if the aligned sequence contains a stop codon.                                                                                                                                                                                                                                                                                                                                              |
| vj_in_frame                     | boolean                                     | True if the V and J gene alignments are in-frame.  In details: distance between v_alignement reading frame and j_alignment reading frame is divisible by 3.                                                                                                                                                                                                                                      |
| v_frameshift                    | boolean                                     | True if the V gene in the query nucleotide sequence contains a translational frameshift relative to the frame of the V gene reference sequence. In other words: sum of insertions and deletions between consecutive matches in alignment is divisible by 3.                                                                                                                                      |
| j_frameshift                    | boolean                                     | True if the J gene in the query nucleotide sequence contains a translational frameshift relative to the frame of the J gene reference sequence.  In other words: sum of insertions and deletions between consecutive matches in alignment is divisible by 3.                                                                                                                                     |
| productive                      | boolean                                     | True if the V(D)J sequence is predicted to be productive.  In details: stop_codon is False and vj_in_frame is True                                                                                                                                                                                                                                                                               |
| rev_comp                        | boolean                                     | True if the alignment is on the opposite strand (reverse complemented) with respect to the query sequence. If True, indicates the sequence field contains a reverse complemented original query sequence.                                                                                                                                                                                        |
| complete_vdj                    | boolean                                     | True if the sequence alignment spans the entire V(D)J region. Meaning, sequence_alignment includes both the first V gene codon that encodes the mature polypeptide chain (i.e., after the leader sequence) and the last complete codon of the J gene (i.e., before the J-C splice site). This does not require an absence of deletions within the internal FWR and CDR regions of the alignment. |
| v_call                          | string                                      | V gene with allele.                                                                                                                                                                                                                                                                                                                                                                              |
| d_call                          | string                                      | D gene with allele.                                                                                                                                                                                                                                                                                                                                                                              |
| j_call                          | string                                      | J gene with allele.                                                                                                                                                                                                                                                                                                                                                                              |
| c_call                          | string                                      | Constant region gene with allele.                                                                                                                                                                                                                                                                                                                                                                |
| **v_frame**                     | enum [0, 1, 2]                              | V frame offset from v_alignment_start.                                                                                                                                                                                                                                                                                                                                                           |
| **j_frame**                     | enum [0, 1, 2]                              | J frame offset from j_alignment_start.                                                                                                                                                                                                                                                                                                                                                           |
| sequence_alignment              | string                                      | Gapped alignment of query sequence spanning V-J segment aligned to germline, reverse complemented if needed.                                                                                                                                                                                                                                                                                     |
| germline_alignment              | string                                      | Gapped aligned germline sequence spanning the same region as the sequence_alignment field (V(D)J region). Segments between matched germlines are gapped to match query sequence length.                                                                                                                                                                                                          |
| sequence_alignment_aa           | string                                      | Amino acid translation of the sequence_alignment.                                                                                                                                                                                                                                                                                                                                                |
| germline_alignment_aa           | string                                      | Amino acid translation of the germline_alignment.                                                                                                                                                                                                                                                                                                                                                |
| v_alignment_start               | integer                                     | Start position of the V gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                          |
| v_alignment_end                 | integer                                     | End position of the V gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                            |
| d_alignment_start               | integer                                     | Start position of the D gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                          |
| d_alignment_end                 | integer                                     | End position of the D gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                            |
| j_alignment_start               | integer                                     | Start position of the J gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                          |
| j_alignment_end                 | integer                                     | End position of the J gene alignment in sequence_alignment (1-based closed interval).                                                                                                                                                                                                                                                                                                            |                                                                                                                                                                                                                                                                                                          |
| v_sequence_alignment            | string                                      | Aligned portion of query sequence assigned to the V gene.                                                                                                                                                                                                                                                                                                                                        |
| v_sequence_alignment_aa         | string                                      | Amino acid translation of the v_sequence_alignment field.                                                                                                                                                                                                                                                                                                                                        |
| v_germline_alignment            | string                                      | Aligned V gene germline sequence.                                                                                                                                                                                                                                                                                                                                                                |
| v_germline_alignment_aa         | string                                      | Aligned amino acid V gene germline sequence.                                                                                                                                                                                                                                                                                                                                                     |
| d_sequence_alignment            | string                                      | Aligned portion of query sequence assigned to the D gene.                                                                                                                                                                                                                                                                                                                                        |
| d_germline_alignment            | string                                      | Aligned D gene germline sequence.                                                                                                                                                                                                                                                                                                                                                                |
| j_sequence_alignment            | string                                      | Aligned portion of query sequence assigned to the J gene.                                                                                                                                                                                                                                                                                                                                        |
| j_sequence_alignment_aa         | string                                      | Amino acid translation of the j_sequence_alignment field.                                                                                                                                                                                                                                                                                                                                        |
| j_germline_alignment            | string                                      | Aligned J gene germline sequence.                                                                                                                                                                                                                                                                                                                                                                |
| j_germline_alignment_aa         | string                                      | Aligned amino acid J gene germline sequence.                                                                                                                                                                                                                                                                                                                                                     |
| c_sequence_alignment            | string                                      | Aligned portion of query sequence assigned to the constant region.                                                                                                                                                                                                                                                                                                                               |
| c_germline_alignment            | string                                      | Aligned constant region germline sequence.                                                                                                                                                                                                                                                                                                                                                       |
| fwr1                            | string                                      | Nucleotide sequence of the aligned FWR1 region.                                                                                                                                                                                                                                                                                                                                                  |
| fwr1_aa                         | string                                      | Amino acid translation of the fwr1 field.                                                                                                                                                                                                                                                                                                                                                        |
| cdr1                            | string                                      | Nucleotide sequence of the aligned CDR1 region.                                                                                                                                                                                                                                                                                                                                                  |
| cdr1_aa                         | string                                      | Amino acid translation of the cdr1 field.                                                                                                                                                                                                                                                                                                                                                        |
| fwr2                            | string                                      | Nucleotide sequence of the aligned FWR2 region.                                                                                                                                                                                                                                                                                                                                                  |
| fwr2_aa                         | string                                      | Amino acid translation of the fwr2 field.                                                                                                                                                                                                                                                                                                                                                        |
| cdr2                            | string                                      | Nucleotide sequence of the aligned CDR2 region.                                                                                                                                                                                                                                                                                                                                                  |
| cdr2_aa                         | string                                      | Amino acid translation of the cdr2 field.                                                                                                                                                                                                                                                                                                                                                        |
| fwr3                            | string                                      | Nucleotide sequence of the aligned FWR3 region.                                                                                                                                                                                                                                                                                                                                                  |
| fwr3_aa                         | string                                      | Amino acid translation of the fwr3 field.                                                                                                                                                                                                                                                                                                                                                        |
| cdr3                            | string                                      | Nucleotide sequence of the aligned CDR3 region.                                                                                                                                                                                                                                                                                                                                                  |
| cdr3_aa                         | string                                      | Amino acid translation of the cdr3 field.                                                                                                                                                                                                                                                                                                                                                        |
| fwr4                            | string                                      | Nucleotide sequence of the aligned FWR4 region.                                                                                                                                                                                                                                                                                                                                                  |
| fwr4_aa                         | string                                      | Amino acid translation of the fwr4 field.                                                                                                                                                                                                                                                                                                                                                        |
| junction                        | string                                      | Junction region nucleotide sequence, where the junction is defined as the CDR3 plus the two flanking conserved codons.                                                                                                                                                                                                                                                                           |
| junction_aa                     | string                                      | Amino acid translation of the junction.                                                                                                                                                                                                                                                                                                                                                          |
| junction_length                 | integer                                     | Number of nucleotides in the junction sequence.                                                                                                                                                                                                                                                                                                                                                  |
| junction_aa_length              | integer                                     | Number of amino acids in the junction sequence.                                                                                                                                                                                                                                                                                                                                                  |
| v_score                         | number                                      | Alignment score (Smith-Waterman) for the V gene.