Part III · Population Genomics · Step 03

Mapping quality control

Evaluate whether each sample has sufficient, well-distributed and reliable read support across the shared UCE pseudoreference before SNP calling.

Objective

A completed mapping step does not guarantee that every sample is equally suitable for population-genomic inference. Samples can differ in mapping rate, duplicate content, breadth of UCE coverage, sequencing depth and mapping quality.

The goal here is to decide whether each individual has enough independent, confidently mapped sequence information across the shared pseudoreference to support downstream genotype calling.

final post-processed BAMs
        ↓
samtools flagstat
        ↓
samtools stats
        ↓
samtools coverage
        ↓
samtools depth -aa
        ↓
combine metrics across samples
        ↓
identify technical outliers
        ↓
retain / flag / investigate
        ↓
SNP calling
Core principle

No single metric should normally determine sample exclusion. Mapping percentage, duplicate fraction, breadth of coverage, depth and MAPQ should be interpreted together and later cross-checked against genotype missingness.

1. Input BAMs

This module assumes duplicate marking has already been completed during the mapping stage. The preferred inputs are therefore the final *.markdup.bam files and their indexes.

02_mapping/
├── sample_A/
│   ├── sample_A.markdup.bam
│   └── sample_A.markdup.bam.bai
├── sample_B/
│   ├── sample_B.markdup.bam
│   └── sample_B.markdup.bam.bai
└── ...

Marking duplicates is important because PCR or optical duplicates can inflate apparent depth without adding independent molecular information.

PROJECT="/path/to/my_UCE_project"

POPGEN="$PROJECT/population_genomics"
MAPPING="$POPGEN/02_mapping"
MAPPING_QC="$POPGEN/03_mapping_qc"

mkdir -p "$MAPPING_QC"

2. The main QC metrics

Mapped reads

Fraction of reads that align to the shared UCE pseudoreference. Useful, but not sufficient by itself for target-capture data.

Properly paired reads

Paired reads whose alignment configuration satisfies the mapper's proper-pair criteria.

Duplicate fraction

Reads marked as duplicates. High values indicate that a substantial fraction of sequencing effort may come from repeated molecules.

Reference breadth

Fraction of pseudoreference bases covered by at least one usable read.

Depth

Number of reads supporting each reference position. Threshold-based breadth is usually more informative than one global mean.

Mapping quality

Confidence that reads were placed at the reported reference location.

3. samtools flagstat

samtools flagstat scans the BAM and reports counts based primarily on SAM FLAG values.

samtools flagstat   sample_A.markdup.bam   > sample_A.flagstat.txt
mapped
Reads without the UNMAP flag. A moderate mapping percentage does not necessarily imply poor UCE recovery because capture libraries may contain substantial off-target sequence.
properly paired
Reads flagged as paired, proper-pair and mapped. The percentage is calculated against paired reads rather than mapped reads alone.
duplicates
Reads carrying SAM flag 0x400, set during duplicate marking.
Do not confuse two meanings of “singleton”

A singleton FASTQ generated during trimming is an orphan read whose mate was removed. In flagstat, “singletons” means a paired read that maps while its mate is unmapped. These are different concepts.

4. samtools stats

samtools stats provides broader BAM diagnostics. Because duplicates have already been marked, explicitly exclude them here:

samtools stats   -d   sample_A.markdup.bam   > sample_A.stats.txt

The -d / --remove-dups option excludes reads marked as duplicates from these statistics.

Why keep this file?

stats is a useful technical record for troubleshooting insert size, composition and general BAM behavior. The main cross-sample decisions in this workflow, however, rely mostly on mapping rate, duplicate fraction, reference breadth, depth and MAPQ.

5. Coverage across UCE loci

samtools coverage summarizes each reference sequence. In this workflow, each reference sequence corresponds to one UCE locus.

samtools coverage   sample_A.markdup.bam   > sample_A.coverage.tsv
#rname  startpos  endpos  numreads  covbases  coverage  meandepth  meanbaseq  meanmapq
numreads
Reads aligned to the UCE locus after filtering.
covbases
Reference bases with depth ≥1.
coverage
Percentage of positions in that UCE with at least one aligned base.
meandepth
Mean depth across the locus.
meanmapq
Mean mapping quality of selected reads.

By default, samtools coverage skips alignments flagged as unmapped, secondary, QC-failed or duplicate. When duplicate-marked BAMs are used, the resulting breadth and depth therefore reflect non-duplicate usable alignments.

Breadth and depth are different

A sample can have high mean depth over a subset of loci while still missing large parts of the pseudoreference. Conversely, a sample can cover most loci with only moderate depth. Both dimensions matter.

6. Why ≥1× coverage is not enough

Standard coverage tells us whether a position has at least one aligned base. For genotype calling, a single read provides weak evidence, so it is useful to measure how much of the pseudoreference reaches higher depth thresholds.

samtools depth -aa sample_A.markdup.bam

The -aa option reports every position in every reference sequence, including positions with zero depth. This allows percentages to be calculated against the complete pseudoreference.

By default, samtools depth excludes reads carrying UNMAP, SECONDARY, QCFAIL or DUP flags.

ThresholdInterpretation
≥1×Any evidence that the position was reached by sequencing.
≥3×Repeated but still shallow support; useful as an early diagnostic.
≥5×Moderate minimum-depth benchmark for evaluating usable breadth.
≥10×More conservative view of positions with substantial read support.
These are descriptive QC thresholds

3×, 5× and 10× are used here to describe the depth distribution. They are not universal SNP-calling thresholds. Variant and genotype filters will be defined explicitly later.

7. Calculate depth thresholds for one sample

samtools depth -aa sample_A.markdup.bam | awk '
BEGIN {
    OFS="\t"
}
{
    depth=$3
    total++
    sum+=depth

    if (depth >= 1)  d1++
    if (depth >= 3)  d3++
    if (depth >= 5)  d5++
    if (depth >= 10) d10++
}
END {
    mean=(total>0 ? sum/total : 0)

    printf "mean_depth\t%.2f\n", mean
    printf "pct_1x\t%.2f\n",  100*d1/total
    printf "pct_3x\t%.2f\n",  100*d3/total
    printf "pct_5x\t%.2f\n",  100*d5/total
    printf "pct_10x\t%.2f\n", 100*d10/total
}'

For multiple samples, run the same command in the loop or parallelization system appropriate to your environment and save one result per sample.

8. Consolidate results across samples

The final QC product should be a single table with one row per individual. Comparing samples side by side is far more informative than reading dozens of independent text files.

sample
total_reads
mapped_reads
mapped_percent
properly_paired_reads
properly_paired_percent
duplicate_reads
duplicate_percent
total_uce_loci
uce_loci_with_reads
reference_covered_percent
mean_depth
mean_mapq
pct_1x
pct_3x
pct_5x
pct_10x
Why one table matters

A mapping rate of 35% may look poor in isolation, yet the same sample may cover 95% of the shared UCE reference with high MAPQ and ample depth. QC is inherently comparative.

9. How to interpret each metric

Mapping percentage

This answers: what fraction of all reads aligned to the UCE pseudoreference? It is not equivalent to “what fraction of UCE loci was recovered.” Off-target reads, enrichment efficiency, contamination and divergence from the reference can all reduce this value.

Therefore, a moderate mapping percentage can still coexist with excellent UCE coverage and depth.

Reference breadth

reference_covered_percent asks: how much of the shared UCE coordinate system is represented at least once? For joint SNP discovery, this is often more informative than raw mapping percentage because all individuals ultimately need homologous coordinates.

Depth thresholds

The contrast between pct_1x, pct_5x and pct_10x shows whether coverage is merely broad or also deep enough to support reliable genotype evidence.

Pattern≥1×≥5×≥10×Interpretation
Broad, strong coverage95%90%80%Most of the reference has substantial read support.
Broad but shallow93%70%50%Most loci are reached, but many positions have limited depth.
Restricted coverage55%35%25%Large parts of the shared reference are poorly represented.

Duplicate fraction

A high duplicate fraction means that many sequenced reads do not represent independent molecules. This may reflect limited library complexity or amplification. High duplication is not automatically disqualifying if broad non-duplicate coverage and adequate depth remain after duplicate reads are ignored.

MAPQ

Mean MAPQ reflects mapping confidence. Samples with MAPQ clearly below the main dataset distribution deserve attention because they may be more divergent from the pseudoreference or contain a larger fraction of ambiguous alignments.

10. Recognizing technical outliers

Interpret QC comparatively rather than imposing one arbitrary cutoff on every project.

Observed patternPossible interpretationAction
Low mapping %, but broad coverage, good depth and high MAPQMany off-target reads, while UCE targets themselves remain well represented.Usually retain; mapping percentage alone is not enough to exclude.
High ≥1× coverage but much lower ≥5×/≥10× breadthMost loci are reached, but support is shallow.Flag for genotype-missingness evaluation.
Low reference breadth and low ≥5×/≥10× breadthLarge parts of the common coordinate system are absent or poorly sequenced.Strong QC warning.
High duplicate fraction but strong non-duplicate breadthLibrary is redundant but still contains enough independent information.Do not remove automatically.
Low MAPQ together with restricted breadthPossible sequence divergence, reference bias or ambiguous mapping.Investigate carefully.

11. Outgroups need separate interpretation

A phylogenetically distant outgroup may align poorly to a pseudoreference constructed mainly from the focal group. Low mapping percentage, reduced breadth and lower usable depth can therefore reflect real biological divergence rather than a failed library.

An outgroup useful for phylogenetic rooting may still be inappropriate for PCA, DAPC, ADMIXTURE or STRUCTURE analyses focused on fine-scale population variation.

Reference bias increases with divergence

The farther a sample is from the sequences represented in the shared pseudoreference, the more likely homologous reads are to fail to align or to align with reduced confidence. Evaluate divergent biological groups separately from technical failures within the focal group.

12. Do not remove samples too early

Mapping QC identifies warning samples, but it does not yet measure genotype completeness directly. A conservative workflow is:

mapping QC
    ↓
identify warning samples
    ↓
retain them for initial joint SNP calling
    ↓
calculate genotype missingness per individual
    ↓
compare mapping QC + genotype missingness
    ↓
make final inclusion/exclusion decisions

If the same individual is an outlier in mapping breadth, usable depth and genotype missingness, the evidence for exclusion becomes substantially stronger.

13. A practical decision framework

StatusTypical patternRecommended action
PASSBroad UCE coverage, substantial ≥5×/≥10× breadth, adequate depth and MAPQ similar to the main sample distribution.Advance to SNP calling.
QC WARNINGOne or more metrics are weaker than the central distribution, but enough evidence remains to attempt genotype calling.Retain provisionally and reassess with genotype missingness.
INVESTIGATEVery restricted breadth, weak depth and/or unusually low mapping confidence.Check sample identity, library history, divergence and contamination before final exclusion.
SEPARATE BIOLOGICAL GROUPStrongly divergent outgroup or non-focal lineage.Evaluate separately from focal population-structure analyses.
No universal cutoff

Appropriate thresholds depend on sequencing design, divergence, downstream caller and study objectives. Document the final criteria and justify them from the observed data distribution rather than presenting them as universal constants.

14. Final outputs

03_mapping_qc/
├── sample_A/
│   ├── sample_A.flagstat.txt
│   ├── sample_A.stats.txt
│   └── sample_A.coverage.tsv
├── sample_B/
│   └── ...
├── depth_thresholds/
│   ├── sample_A.depth.tsv
│   ├── sample_B.depth.tsv
│   └── depth_threshold_summary.tsv
└── mapping_qc_summary.tsv

The consolidated table becomes the mapping-QC record that accompanies the SNP dataset and supports later sample-retention decisions.

15. Pre-SNP checklist

✓ Final BAMs have duplicates marked and BAM indexes are present.
✓ flagstat was generated for every sample.
✓ stats -d was generated without duplicate reads.
✓ Reference breadth and mean depth were calculated with samtools coverage.
✓ ≥1×, ≥3×, ≥5× and ≥10× breadth were measured with samtools depth -aa.
✓ QC metrics were consolidated across all samples.
✓ Unusual samples were flagged rather than automatically discarded.
✓ Strongly divergent outgroups were interpreted separately.
✓ Final exclusion decisions are deferred until genotype missingness can also be evaluated.

References and software documentation

Samtools flagstat — official manual
Definitions of mapped, properly paired, duplicate and singleton FLAG-based categories.

Samtools stats — official manual
Comprehensive BAM statistics and the -d / --remove-dups option.

Samtools coverage — official manual
Definitions of covered bases, coverage percentage, mean depth, mean base quality and mean mapping quality.

Samtools depth — official manual
Per-position depth, -aa zero-depth reporting and default FLAG exclusions including duplicates.

← Mapping reads SNP calling →