Showing posts with label Data Parsing. Show all posts
Showing posts with label Data Parsing. Show all posts

Tuesday, November 24, 2026

Working with FASTA & FASTQ in Python



This guide is written for absolute beginners, yet structured deeply enough for intermediate and advanced learners who want a rock-solid conceptual and practical understanding of FASTA and FASTQ files. By the end, you won’t just use these formats — you’ll understand what’s happening under the hood.


1. Why FASTA and FASTQ Matter

Every bioinformatics workflow begins with sequence data.

Before alignment, assembly, variant calling, or expression analysis, your data almost always lives in one of two formats:

  • FASTA → sequence only

  • FASTQ → sequence + quality

If you misunderstand these formats:

  • You misinterpret results

  • You filter incorrectly

  • You trust bad data

So let’s slow down and build intuition properly.


2. FASTA Format — The Simplest Sequence Container

What FASTA Really Is

FASTA is a plain-text format designed to store biological sequences in a human-readable way.

It answers only one question:

What is the sequence?

No probabilities. Just raw letters.


FASTA Structure

>sequence_id optional description
ACTGACTGACTGACTG
ACTGACTG

Rules (Important for Beginners)

  • The first line starts with >

  • Everything after > is metadata (ID + description)

  • The sequence can be:

    • DNA (A, T, G, C, N)

    • RNA (A, U, G, C)

    • Protein (20 amino acids)

  • Sequences can span multiple lines

Computers ignore line breaks — humans benefit from them.


Where FASTA Is Used (Real World Examples)

FASTA files are typically inputs, not raw outputs:

  • Reference genomes (hg38, GRCh38)

  • Transcriptomes (cDNA, mRNA)

  • Protein databases (UniProt)

  • Genome assemblies

  • Contigs and scaffolds

FASTA answers: “What should this look like?”


3. FASTQ Format — FASTA Plus Confidence

Why FASTQ Exists

Sequencing machines do not read bases perfectly.

For every base they output, they also estimate:

How confident am I that this base is correct?

FASTQ stores both the sequence and this confidence.


FASTQ Structure (Four-Line Rule)

@sequence_id
ACTGACTGAC
+
IIIIHHHFFF

What Each Line Means

  1. @ Header (read ID)

  2. Nucleotide sequence

  3. + Separator (may repeat header)

  4. Quality string (ASCII characters)

Critical rule:

The sequence line and quality line must be the same length.


Where FASTQ Is Used

FASTQ files represent raw experimental data:

  • Illumina reads

  • Oxford Nanopore reads

  • PacBio reads

  • QC, trimming, filtering

FASTQ answers: “How confident should I be in this base?”


4. Quality Scores — Phred Scores Made Intuitive

What Is a Phred Score?

A Phred score (Q) measures the probability that a base is wrong.

Formula:

Q = -10 × log10(P_error)

You don’t need to calculate this — just understand what it means.


Common Phred Scores (Memorize This)

PhredError ProbabilityMeaning
Q1010%Very poor
Q201%Acceptable
Q300.1%High quality
Q400.01%Excellent

Most pipelines aim for Q30 or higher.


Why FASTQ Uses ASCII Characters

Storing numbers for every base would be inefficient.

So FASTQ uses a trick:

ASCII_character = Phred_score + 33

Example:

  • Phred 30 → 30 + 33 = 63 → ?

This is why quality lines look like random symbols.


5. Reading FASTA Manually

Before libraries, learn the logic.

sequences = {}
current_id = None

with open("input.fasta") as f:
for line in f:
line = line.strip()
if line.startswith(">"):
current_id = line[1:]
sequences[current_id] = ""
else:
sequences[current_id] += line

What This Teaches

  • Files are read line by line

  • Headers control context

  • Sequences may be multi-line

  • Dictionaries mirror FASTA structure

This removes fear of bioinformatics files.


6. FASTA with Biopython — The Professional Way

Once logic is clear, use tools.

from Bio import SeqIO

for record in SeqIO.parse("input.fasta", "fasta"):
print(record.id)
print(len(record.seq))

What Biopython Gives You

  • SeqRecord objects

  • Clean parsing

  • Automatic handling of multi-line sequences

  • Easy writing and filtering

This is how real scripts are written.


7. Parsing FASTQ — Sequence Meets Quality

from Bio import SeqIO

for record in SeqIO.parse("reads.fastq", "fastq"):
seq = str(record.seq)
qualities = record.letter_annotations["phred_quality"]

What You Can Access

  • Full sequence

  • Per-base quality list

  • Mean read quality

  • Read length

Biopython decodes ASCII automatically.


8. ASCII to Quality — Seeing Behind the Curtain

Manual decoding logic:

phred = ord(char) - 33

Why this matters:

  • Debugging corrupted FASTQ

  • Understanding QC tools

  • Interview-level knowledge

Experts know why, not just how.


9. Quality-Based Filtering (Core NGS Skill)

Per-Read Filtering

Remove reads with:

  • Mean quality < Q20

  • Length below threshold

if sum(qualities) / len(qualities) >= 20:
keep = True

Why This Is Crucial

  • Low-quality reads misalign

  • Increase false variants

  • Waste computation

QC is always step one.


10. Trimming Low-Quality Ends

Sequencing quality drops at the 3′ end.

Basic trimming logic:

while qualities and qualities[-1] < 20:
qualities.pop()

This is the core idea behind:

  • Trimmomatic

  • fastp

  • Cutadapt

Tools are just optimized versions of this logic.


11. Mini-Project: Build a “Nano-FastQC” Tool (Step-by-Step)

Your script will behave like a tiny version of FastQC:

INPUT
Raw FASTQ file

PROCESS
1. Read sequences
2. Read quality scores
3. Calculate statistics
4. Visualize quality
5. Remove bad reads

OUTPUT
Clean FASTQ file
Quality plot

So the pipeline looks like:

FASTQ → QC analysis → filtering → cleaned FASTQ

Step 0: Requirements 

Python libraries needed

pip install biopython matplotlib

Why?

  • Biopython → read FASTQ safely (no manual parsing errors)

  • matplotlib → quality plots like FastQC


Step 1: Read a FASTQ File

Why this step matters

FASTQ files are large, structured, and easy to break if read incorrectly.
Biopython handles this safely.

Code

from Bio import SeqIO fastq_file = "reads.fastq" records = list(SeqIO.parse(fastq_file, "fastq")) print("Total reads:", len(records))

What learners should understand

  • Each read becomes a SeqRecord object

  • records is a list of reads

  • This is memory-safe for small/medium FASTQ (perfect for learning)


Step 2: Extract Sequence and Quality Scores

What’s inside one FASTQ read?

Each read contains:

  • DNA sequence

  • Per-base Phred quality scores

Code

record = records[0] sequence = str(record.seq) qualities = record.letter_annotations["phred_quality"] print(sequence) print(qualities)

Explain clearly

  • sequence → "ACTG..."

  • qualities → [38, 37, 36, 35, ...]

  • Each number maps to one base

This one-to-one mapping is critical.


Step 3: Compute Per-Read Average Quality

Why this matters

Low-quality reads:

  • Align poorly

  • Increase false positives

  • Waste computation

So we calculate mean quality per read.

Code

def mean_quality(qualities): return sum(qualities) / len(qualities)

Usage:

avg_q = mean_quality(qualities) print("Average quality:", avg_q)

Teaching note

Tell learners:

“This single number decides whether a read lives or dies.”


Step 4: Compute Per-Base Quality (Across All Reads)

Why this matters

FastQC plots:

  • X-axis → base position

  • Y-axis → average quality at that position

We’ll recreate that logic.


Step 4.1: Prepare storage

max_length = max(len(r.seq) for r in records) base_qualities = [[] for _ in range(max_length)]

What this creates:

base_qualities[0] → qualities of base 1 from all reads base_qualities[1] → qualities of base 2 from all reads ...

Step 4.2: Fill base-wise qualities

for record in records: quals = record.letter_annotations["phred_quality"] for i, q in enumerate(quals): base_qualities[i].append(q)

Step 4.3: Average per base

avg_base_quality = [ sum(qs) / len(qs) if qs else 0 for qs in base_qualities ]

Now you have FastQC-style data.


Step 5: Plot Base Quality Distribution

Why plotting is important

Humans understand patterns visually, not from tables.

Typical Illumina pattern:

  • High quality at start

  • Drop at 3′ end


Code (Simple & Clean)

import matplotlib.pyplot as plt plt.figure() plt.plot(avg_base_quality) plt.xlabel("Base position") plt.ylabel("Average Phred Quality") plt.title("Per-base Quality Distribution") plt.show()

Teaching insight

  • Falling curve → trimming needed

  • Flat high curve → excellent run

  • Sudden drops → sequencing issue


Step 6: Filter Low-Quality Reads

Define your rule (important!)

We choose:

  • Mean quality ≥ Q20

why?? Because:

  • Q20 = 1% error

  • Industry minimum standard


Code

filtered_records = [] for record in records: qualities = record.letter_annotations["phred_quality"] if mean_quality(qualities) >= 20: filtered_records.append(record) print("Reads after filtering:", len(filtered_records))

Filtering is:

  • NOT deleting randomly

  • A data-quality decision


Step 7: Trim Low-Quality Ends

Why trimming is separate from filtering

  • Filtering removes entire reads

  • Trimming fixes partially bad reads


Basic trimming logic (3′ end)

def trim_read(record, threshold=20): seq = str(record.seq) quals = record.letter_annotations["phred_quality"] while quals and quals[-1] < threshold: quals.pop() seq = seq[:-1] record.seq = record.seq.__class__(seq) record.letter_annotations["phred_quality"] = quals return record

Use it:

trimmed_records = [trim_read(r) for r in filtered_records]

Step 8: Write Clean FASTQ Output

Why this step is crucial

QC without output = useless.
Pipelines expect clean FASTQ.


Code

from Bio import SeqIO SeqIO.write(trimmed_records, "clean_reads.fastq", "fastq")

Now learners have:

  • Input FASTQ

  • Output FASTQ

  • Quality plot


Final Result: What you Built

They now have a tool that can:

✅ Read FASTQ
✅ Understand quality scores
✅ Reproduce FastQC logic
✅ Visualize sequencing quality
✅ Filter poor reads
✅ Output clean data


Why This Is a STRONG Portfolio Project

You can confidently say:

“I understand FASTQ internally — not just how to run tools.”

This project proves:

  • Python skills

  • NGS understanding

  • QC logic

  • Pipeline thinking


Skills Gained

  • FASTQ parsing mastery

  • Quality interpretation

  • Visualization thinking

  • Pipeline logic

  • Portfolio-ready project

This bridges theory → real bioinformatics work.


Final Takeaway

FASTA and FASTQ are not “just file formats”.

They represent:

  • Biological truth

  • Experimental uncertainty

  • Data quality

Once you understand them deeply, every downstream tool makes sense.

This foundation separates users from bioinformaticians.



💬 Join the Conversation:

What was the most interesting or surprising thing you learned from this Nano-FastQC mini-project?

If you were to improve this tool, what feature would you add next and why?



If this post helped you understand FASTQ better,
drop a 👍 or comment “QC makes sense now” — it helps others find this tutorial too.

Editor’s Picks and Reader Favorites

The 2026 Bioinformatics Roadmap: How to Build the Right Skills From Day One

  If the universe flipped a switch and I woke up at level-zero in bioinformatics — no skills, no projects, no confidence — I wouldn’t touch ...