Skip to content

Learning Objectives

  • Understand the structure and content of FASTQ files and their significance in sequencing workflows.
  • Use basic Bash commands to explore, inspect, and manipulate FASTQ files effectively.
  • Understand the relationship between base-calling accuracy and quality scores, and what these scores indicate about sequencing data reliability.
  • Interpret the key metrics and visual outputs generated by FastQC to evaluate data quality.

Why Quality Control Is Essential

Quality control (QC) is a critical first step in any sequencing workflow. It ensures that the raw data generated by sequencing machines is reliable and free from technical artefacts that could compromise subsequent analyses. Without proper QC, common issues such as base-calling errors, adapter contamination and sequencing biases may remain unnoticed, resulting in inaccurate alignments, incorrect variant calls and misleading biological conclusions. By carefully assessing sequencing data at the outset, QC safeguards the integrity of the entire analysis pipeline and maximises confidence in downstream results.

Base Calling

Sequencing platforms generate raw signals as they read nucleotide sequences. Base-calling algorithms analyse these signals to determine the sequence of bases (A, T, C, G) in the original DNA or RNA sample.

  • Illumina technology uses fluorescently labelled nucleotides and optical detection. Base calling involves interpreting the intensity and wavelength of fluorescence signals to identify each base.
  • PacBio detects fluorescently labelled nucleotides in real time during nucleotide incorporation, analysing these signals to call bases.
  • Oxford Nanopore (ONT) measures changes in ionic current as nucleotides pass through a nanopore. Base calling translates these current changes into nucleotide sequences.

This translation from raw signal to nucleotide bases is inherently error-prone, and accuracy depends heavily on the base-calling algorithm used. The confidence in each base assignment is expressed as a probability, which is encoded efficiently to reduce file size. Both the sequence and its quality probabilities are recorded together in the FASTQ format.

FASTQ File Format

The FASTQ format contains both the nucleotide sequence (line 2) and the corresponding quality scores (line 4).

1: @m54073_190302_105548/4325680/ccs.........................⇽ sequence header
2: TGGATCACTTGTGCAAGCATCACATCGTAGAGCTTGTCCTTGGTCTGCGA........⇽ sequence
3: +.........................................................⇽ separator line
4: p~~L~jubw~n~V~2~u~[sygSN~g~K~k~~~o~u}q}|is~~~~~~~k........⇽ quality encoding

Quality Score

Quality scores based on the Phred scale quantify the confidence in each base call. These scores typically range from 0 to 40, with higher scores indicating a higher probability that the base call is correct. The Phred quality score Q relates logarithmically to the error probability E:

Q = -10 * log10(E)
E = 10^(-Q/10)
P = 1 - E

where P is the probability that the base call is accurate.

Quality Encoding

Quality scores are encoded as single ASCII characters for compact storage alongside the sequence data. Each quality score between 0 and 40 is converted to a corresponding ASCII symbol by adding 33 to the numeric value. Characters range from ! (score 0) to I (score 40).

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI       ➞  Encoding Character
 |        |         |         |         |
 34       43        53        63        73      ➞  ASCII Code
 ⇣        ⇣         ⇣         ⇣         ⇣
 1        10        20        30        40      ➞  Q-Score (ASCII Code - 33)
 ⇣        ⇣         ⇣         ⇣         ⇣
 21%      90%       99%       99.9%     99.99%  ➞  Base call accuracy

File Size

FASTQ files can be very large, often containing millions of reads and reaching several gigabytes. Work with compressed FASTQ files (.fastq.gz) wherever possible. Most bioinformatics tools read compressed files directly, so there is usually no need to decompress them.

Raw Reads Inspection

Inspecting raw sequencing reads is an essential first step before running a full QC report. A few simple command-line checks help you confirm that the downloaded data is complete, correctly paired, and uncorrupted.

  • Confirm the file structure and completeness
  • Check that forward and reverse reads are properly matched (Illumina and Aviti only)
  • Identify obvious issues like truncation, missing data, or unusual headers

Catching such problems early avoids wasting time on flawed datasets and ensures your results are based on trustworthy data.

A waste of time or worth your while?

It may seem unnecessary to explore your data before running QC, but we think it is time well spent. QC is an important step before filtering or processing data, but it has its limits. The better you understand your data from the start, the more control you have over it. For example, uneven sequencing depth or a low read count in some samples helps you interpret the QC report correctly. Noticing an uneven number of reads in R1 and R2 would indicate an incomplete download. Discovering high PhiX levels in your subset tells you a filtering step may be needed. There are many good reasons to explore your data before jumping into analysis.

FASTQ Case Study

In this case study, we examine a single sample sequenced using Illumina paired-end technology. The data consists of two compressed FASTQ files, one for each read direction.

Navigate to your working directory and verify that the expected FASTQ files are present.

## Working directory (if you already have it)
cd ${HOME}/GDA/qc
ls -lh C-1_R[12].fastq.gz

If the files or folder are missing, create the directory and download the sample files:

cd ${HOME}
mkdir qc; cd qc
curl -O "https://www.gdc-docs.ethz.ch/GeneticDiversityAnalysis/GDA/data/C-1_R1.fastq.gz"
curl -O "https://www.gdc-docs.ethz.ch/GeneticDiversityAnalysis/GDA/data/C-1_R2.fastq.gz"

MD5 checksums for verifying the downloaded files:

# 4a2e8876742302fad5bd24cba76c3cc6  C-1_R1.fastq.gz
# e0ce4ae266e8b2cedbc9580a3025712a  C-1_R2.fastq.gz

Verification

Before doing anything else, verify that the download completed successfully using md5sum.

## Linux
md5sum C-1_R1.fastq.gz
md5sum C-1_R2.fastq.gz
## Mac
# md5 C-1_R1.fastq.gz
# md5 C-1_R2.fastq.gz

Compare the calculated MD5 hash with the provided value. A match confirms the file is intact. A mismatch indicates corruption or an incomplete download.

Corruption and Integrity

When downloading raw FASTQ files from online repositories, there is a possibility that files become corrupted during transfer. Verifying the MD5 checksum confirms that the download completed correctly and that the file matches the original unaltered version released by the data provider.

Exploration

The following steps are flexible and not bound to a strict protocol. The key is to examine the files or a subset of them to gain insight into their content and structure.

A good starting point is to inspect the first and last four lines of each FASTQ file to verify that the records appear complete and correctly formatted.

## Test completeness
zcat C-1_R1.fastq.gz | head -n 4
zcat C-1_R1.fastq.gz | tail -n 4
zcat C-1_R2.fastq.gz | head -n 4
zcat C-1_R2.fastq.gz | tail -n 4
# If zcat does not work on your system, try:
# zcat < C-1_R1.fastq.gz | head -n 4
# gzcat C-1_R2.fastq.gz | head -n 4
What does a FASTQ header tell you?
  ⎧the unique instrument name
  |       ⎧the run id
  |       |  ⎧the flowcell id
  |       |  |               ⎧flowcell lane
  |       |  |               |
1 @M01072:41:000000000-A942B:1:1101:11853:2457 1:N:0:1
2 GTGCCAGCAGCCGCGGTAATACGTAGGTGGCAAGCGTTATCCGGATTTATTGTGC...
3 +
4 >>1>>11>11>>1EC?E?CFBFAGFC0GB/CG1EACFE/BFE///AEG1DF122A...
  | |          |
  | |          └─ C ➞ E ➞ 36 Phred Quality Score (Q) ➞ 99.975% Base call accuracy
  | └─ G ➞ 1 ➞ 16 Phred Quality Score (Q) ➞ 97.488% Base call accuracy
  └─ G ➞ > ➞ 29 Phred Quality Score (Q) ➞ 99.874% Base call accuracy

A few character encoding examples:

Position 1, Nucleotide G, Character >

Q = ascii(>) - 33 = 29
E = 10^(-2.9) = 0.00126 = 0.126%
P = 1 - 0.00126 = 99.874%

Position 3, Nucleotide G, Character 1

Q = ascii(1) - 33 = 16
E = 10^(-1.6) = 0.02512 = 2.511%
P = 1 - 0.02512 = 97.488%

Position 14, Nucleotide C, Character E

Q = ascii(E) - 33 = 36
E = 10^(-3.6) = 0.000251 = 0.025%
P = 1 - 0.000251 = 99.975%

Results from inspecting our files:

  • Reads are 251 nucleotides in length.
  • Header information from the FASTQ files:
R1 head: @M01072:41:000000000-A942B:1:1101:11853:2457 1:N:0:1
R2 head: @M01072:41:000000000-A942B:1:1101:11853:2457 2:N:0:1

R1 tail: @M01072:41:000000000-A942B:1:2114:18740:28782 1:N:0:1
R2 tail: @M01072:41:000000000-A942B:1:2114:18740:28782 2:N:0:1

We can conclude that:

  • The reads are paired-end, as indicated by matching identifiers and the 1: / 2: designation for forward and reverse reads.
  • The files begin and end with matching read pairs, suggesting the data is complete and properly ordered.
  • All reads originate from the same sequencing instrument, run and flow cell.

Read Count

Next, we count how many sequences are in each FASTQ file. It is important to confirm that the number of forward reads (R1) matches the number of reverse reads (R2), since each pair should correspond to one DNA fragment.

In FASTA files, we count reads by counting lines starting with >. In FASTQ files, each record spans four lines with the header starting with @. The challenge is that @ also appears in quality score lines, so simply counting @ is unreliable.

## First attempt - counts all @ signs, not just headers
zcat C-1_R1.fastq.gz | grep "@" -c
# N = 203,083

Challenge 1: Spot the problem with counting @ signs

The command above gives 203,083 for R1. Run the equivalent command for R2 and compare the result. Can you explain why the counts differ, even though the files should have the same number of reads?

Solution
zgrep -c "@" C-1_R1.fastq.gz  # N = 203,083
zgrep -c "@" C-1_R2.fastq.gz  # N = 239,369

The counts differ because the ASCII character @ encodes Phred quality score 31 and can appear in quality score lines as well as headers. Both types of line are being counted. To verify this in R:

coderange  <- c(33:74)
asciitable <- data.frame(coderange, coderange-33,
               row.names = rawToChar(as.raw(coderange), multiple = TRUE))
colnames(asciitable) <- c("ASCII","PhredScore")
asciitable

To see which lines contain @ in a quality context:

zcat < C-1_R1.fastq.gz | grep "?@" --color -B 3

Challenge 2: Count FASTQ records correctly

Find a reliable way to count the number of records in a FASTQ file. Test your solution on both R1 and R2 and verify the counts match.

Solution

Several approaches work, with different trade-offs:

Solution A: count lines starting with @ (still not fully reliable)

zgrep -c "^@" C-1_R1.fastq.gz  # 145,297
zgrep -c "^@" C-1_R2.fastq.gz  # 146,160

Still not matching, because some quality lines also begin with @.

Solution B: match the instrument name (works here, not universal)

zcat C-1_R1.fastq.gz | head -n 1
# @M01072:41:000000000-A942B:1:1101:11853:2457 1:N:0:1

zcat C-1_R1.fastq.gz | grep "@M01072" -c  # N = 144,738
zcat C-1_R2.fastq.gz | grep "@M01072" -c  # N = 144,738

Counts match. Requires knowing the instrument name in advance.

Solution C: divide total line count by 4 (universal)

zcat C-1_R1.fastq.gz | wc -l
echo "$(zcat C-1_R1.fastq.gz | wc -l) / 4" | bc  # N = 144,738

Works for any valid FASTQ file.

Solution D: count separator lines (universal)

zgrep -c "^+$" C-1_R1.fastq.gz  # N = 144,738

Works as long as the separator line on line 3 has not been modified (some tools write the read name there too).

Verify on a known subset:

## Subset: first 100 records = 400 lines
zcat C-1_R1.fastq.gz | head -n 400 | grep "@" -c       # N = 142 (wrong)
zcat C-1_R1.fastq.gz | head -n 400 | grep "^@" -c      # N = 100 (correct)
zcat C-1_R1.fastq.gz | head -n 400 | grep "@M01072" -c # N = 100 (correct)
zcat C-1_R1.fastq.gz | head -n 400 | grep -c "^+$"     # N = 100 (correct)

Dummy Data

If you are unsure whether a command is correct, test it on a well-defined subset where you know the expected answer. This is also a good way to broaden your command repertoire and double-check results with alternative approaches.

Technical Bias and Instrument ID Checking

Sequencing reads include metadata in their headers, including the instrument name, which helps trace the origin of the data. If reads in a single FASTQ file come from multiple instruments or sequencing runs, this may indicate unintended sample pooling, run-to-run variation, or the introduction of technical bias. If detected early, such effects can be accounted for statistically, for example by modelling batch effects.

## Extract full header lines (every 4th line)
zcat C-1_R1.fastq.gz | awk 'NR % 4 == 1' | head -n 20

## Extract only the instrument name from each header
zcat C-1_R1.fastq.gz | awk -F":" 'NR % 4 == 1 { print $1 }' | sort -u

For a clearer summary with counts, use the provided script:

curl -O "https://www.gdc-docs.ethz.ch/GeneticDiversityAnalysis/GDA/scripts/check_ids.sh"
bash check_ids.sh <(zcat C-1_R1.fastq.gz)

If multiple instrument IDs are found, establish whether all samples contain pooled runs or only some. Include the instrument ID as a variable in downstream statistical models if needed.

Extracting Subsets

A well-chosen subset is often useful for faster exploration. For example, you might want to estimate PhiX contamination before deciding whether a filtering step is needed.

## Get first read
zcat C-1_R1.fastq.gz | head -n 4 > First_R1.fq

## Get last read
zcat C-1_R1.fastq.gz | tail -n 4 > Last_R1.fq

## Get a specific read
zgrep -A 3 "@M01072:41:000000000-A942B:1:1101:8091:3906" C-1_R1.fastq.gz > Extract_R1.fq

## Get a random read
zgrep "@M01072" C-1_R1.fastq.gz | sort -R | head -n 1
zgrep -A 3 "@M01072:41:000000000-A942B:1:1107:11792:27818 1:N:0:1" C-1_R1.fastq.gz > Random_R1.fq

## Get a random subset of reads
zgrep "@M01072" C-1_R1.fastq.gz | sort -R | head -n 10 > random10.list
zgrep -A 3 --no-group-separator -f random10.list C-1_R1.fastq.gz > Random_Subset_N10_R1.fq

A faster alternative is seqtk:

Command Not Found

The following exercises require that seqtk is installed. If you do not have it locally, run the labs on the GDC virtual server: gdc-vserver.ethz.ch.

## Extract 10 random sequences
seqtk sample C-1_R1.fastq.gz 10 > C-1_R1_subset_10.fq
seqtk sample C-1_R2.fastq.gz 10 > C-1_R2_subset_10.fq

Challenge 3: Extract matched random read pairs

Use seqtk to extract the same 10 random reads from both R1 and R2. How can you ensure the same reads are selected from both files? Verify that the extracted pairs actually match.

Solution

Use the seed option (-s) with the same value for both files to synchronise random selection:

seqtk sample -s123 C-1_R1.fastq.gz 10 > C-1_R1_subset_10_sync.fq
seqtk sample -s123 C-1_R2.fastq.gz 10 > C-1_R2_subset_10_sync.fq

Verify the pairs match by comparing headers:

grep "@" C-1_R1_subset_10_sync.fq | sort > R1_header.txt
grep "@" C-1_R2_subset_10_sync.fq | sort > R2_header.txt
diff R1_header.txt R2_header.txt

No output from diff means the headers are identical, confirming that R1 and R2 contain the same read pairs.

Challenge 4: Convert a FASTQ subset to FASTA

Extract 10 random sequences from the R1 file and convert them to FASTA format. Try at least two different approaches.

Solution

Solution A: manual extraction and conversion

## Extract headers from the random subset list
zgrep -A 1 --no-group-separator -f random10.list C-1_R1.fastq.gz > Random_Subset_N10_R1.tmp

## Replace @ with > to convert headers to FASTA format
tr "@" ">" < Random_Subset_N10_R1.tmp > Random_Subset_N10_R1.fa

## Verify
grep ">" -c Random_Subset_N10_R1.fa

Solution B: seqtk conversion

seqtk seq -a C-1_R1_subset_10.fq > C-1_R1_subset_10.fa
grep ">" -c C-1_R1_subset_10.fa

seqtk seq -a converts FASTQ to FASTA in one step, stripping quality scores and replacing @ with > in headers. This is the simpler and more robust approach.

Quality Control with FastQC

For qualitative assessment of raw data we use FastQC. It is easy to use and produces a graphically attractive report. However, care is needed when interpreting the results. FastQC is a contextual analysis designed for genomic data. When assessing quality you need to consider the type of data (RNA-Seq, AmpSeq, RADseq) and remember that a red flag is not necessarily a problem and a green flag does not mean all is well.

## Working directory
if [ ! -d "${HOME}/MDA/qc" ]; then
  mkdir -p "${HOME}/MDA/qc"
fi
cd "${HOME}/MDA/qc"

## Run FastQC on R1 and R2
fastqc --help
fastqc --version
fastqc -t 1 --kmers 8 C-1_R?.fastq.gz
# -t: number of threads

What are k-mers?

FastQC produces two output files per sequence file:

C-1_R1_fastqc.html
C-1_R1_fastqc.zip
C-1_R2_fastqc.html
C-1_R2_fastqc.zip

Download the HTML files using Cyberduck or scp and open them in your browser:

scp guest??@gdc-vserver.ethz.ch:/home/guest??/qc/C-1_R*_fastqc.html ${HOME}/qc
scp guest??@gdc-vserver.ethz.ch:/home/guest??/qc/C-1_R*_fastqc.zip ${HOME}/qc

You can also inspect the text-based summary directly from the terminal:

less C-1_R1_fastqc.zip
unzip -p C-1_R1_fastqc.zip C-1_R1_fastqc/summary.txt | less

QC Facts and Considerations

A few things worth considering before running quality control:

➼ Subset: Does it make sense to run QC on the entire dataset? Would a subset also work?
➼ Data structure: QC is based on data structure analysis. You need to know the structure of your data.
➼ Adapters: Make sure you are looking for the correct adapter sequences.
➼ Quality drop: Quality scores decrease towards the end of reads.
➼ R1 vs R2: Average quality is typically higher for the forward read (R1) than the reverse read (R2).

Read the Manual

Like all applications, FastQC has limitations and settings the user needs to understand. Knowing a few tools well is more valuable than knowing many tools superficially. The FastQC manual is a good example of genuinely helpful documentation. Among other things, it explains that some modules (such as Duplicate Sequences) use shortcuts to increase analysis speed. Understanding these limitations is essential for correct interpretation.

FastQC with R

Windows and FastQC in R

If you are using a Linux emulator, FastQC for R may not work. Rqc is a possible alternative (see below). If you have Ubuntu installed, you may need to specify the path to the FastQC installation.

## Install and load fastqcr
# install.packages("fastqcr")
library("fastqcr")

## Run FastQC
fastqc(fq.dir = "${HOME}/qc/", qc.dir = "${HOME}/qc/")

## FastQC for Windows with Ubuntu
# fastqcr::fastqc("seq.fq.gz", fastqc.path = "wsl.exe /path_to_wsl_fastqc_install/fastqc")

## QC plots
qc.C01.R1 <- qc_read(file = "~/qc/C-1_R1_fastqc.zip", modules = "all", verbose = TRUE)

qc_plot(qc.C01.R1, "Per sequence GC content")
qc_plot(qc.C01.R1, "Per base sequence quality")
qc_plot(qc.C01.R1, "Per sequence quality scores")
qc_plot(qc.C01.R1, "Per base sequence content")
qc_plot(qc.C01.R1, "Sequence duplication levels")

## Aggregate FastQC reports for multiple samples
qc <- qc_aggregate(qc.dir = "~/qc/")

## Filter for warnings and failures
library(dplyr)
qc %>%
  select(sample, module, status) %>%
  filter(status %in% c("WARN", "FAIL")) %>%
  arrange(sample)

## Generate a combined QC report
qc_report(qc.path = "~/qc/", result.file = "~/qc/GDA_QC_Report",
          experiment = "GDA - Test")

More QC Tools

Rqc (documentation) is an optimised Bioconductor tool for quality control and assessment of high-throughput sequencing data. It performs parallel processing of entire files and produces a report containing a set of high-resolution graphics for quality assessment.

library(Rqc)
library(ggplot2)
library(BiocParallel)
library(ShortRead)

Rqc::rqc(path = "/path/to/workfolder", pattern = ".fastq.gz")

MultiQC (multiqc.info) aggregates individual FastQC reports from many samples into a single interactive HTML report. This is particularly useful when working with large cohorts where reviewing individual reports would be impractical. MultiQC automatically detects FastQC output and produces summary plots across all samples, making it easy to spot outliers and batch effects at a glance.

multiqc .

FastQ Screen (documentation) allows you to screen FASTQ sequences against multiple reference databases to better understand library composition and detect unexpected contamination.

Additional Resources

Literature