---
title: Sequence analysis guide
description: Parse FASTA and GenBank with Biotite, read GC content, run pairwise and multiple alignments over a substitution matrix, and write a consensus FASTA.
---

Sequence analysis lets you parse FASTA and GenBank files, run pairwise and multiple alignments, and summarize consensus and conservation. Your substitution matrix, gap penalty, and how you normalize bases beforehand are what most affect the alignments you get.

> **Where this code runs**

> You cannot open a shell on the platform yourself. The scripts on this page are plain Biotite Python and shell: ask Ivy in chat to run them in the chat's [code workspace](/docs/sandbox), which ships Biotite, or run them on your own machine.

## Parse common formats

```python
from biotite.sequence.io import load_sequence

fasta = load_sequence("inputs/sequences/demo.fasta", format="fasta")
genbank = load_sequence("inputs/sequences/demo.gb", format="genbank")

seq = fasta.get_sequence()
print("Sequence length:", len(seq))
print("GC%:", seq.get_gc_content()*100)
```

## Pairwise alignment

```python
from biotite.sequence.align import (
    align_optimal,
    SubstitutionMatrix,
    PairwiseAlignment
)
from biotite.sequence import NucleotideSequence

ref = NucleotideSequence("ATGCGTAGCATGACTG")
query = NucleotideSequence("ATGCGTAGAATGACTA")

matrix = SubstitutionMatrix.std_nucleotide_matrix()
alignments = align_optimal(query, ref, matrix, gap_penalty=-8)

best: PairwiseAlignment = alignments[0]
print(best)
print("Score:", best.score)
```

## Multiple sequence alignment summary

Use Biotite to generate consensus and per-position conservation:

```python
from biotite.sequence import NucleotideSequence
from biotite.sequence.align import SubstitutionMatrix, align_multiple

seqs = [
    NucleotideSequence("ATGCGTAGCATGACTG"),
    NucleotideSequence("ATGCGTAGAATGACTA"),
    NucleotideSequence("ATGCGTAGCATGACCG"),
]

matrix = SubstitutionMatrix.std_nucleotide_matrix()
msa = align_multiple(seqs, matrix)

consensus = msa.get_consensus()
print("Consensus:", consensus)
print("Conservation scores:", msa.get_conservation())
```

## Basic quality checks

- Validate file encodings before ingestion; prefer UTF-8.
- For large batches, stream FASTA/GenBank files to avoid loading everything into
  memory.
- Normalize ambiguous bases and upper/lowercase before running alignments.

## Export results

```python
from biotite.sequence.io.fasta import FastaFile

fasta_out = FastaFile()
fasta_out["consensus"] = consensus
with open("outputs/consensus.fasta", "w", encoding="utf-8") as handle:
    fasta_out.write(handle)
```
