Part III · Population Genomics · Step 02

Mapping reads to the shared UCE pseudoreference

Align the original cleaned sequencing reads from every individual against the same locus-wise UCE pseudoreference, producing coordinate-sorted and indexed BAM files suitable for mapping quality control and downstream SNP calling.

Objective

The shared pseudoreference created in the previous module establishes a common coordinate system across all sampled individuals. In this step, the cleaned reads from each sample are mapped back to that same reference with BWA-MEM2.

cleaned reads
    │
    ├── paired-end R1 + R2
    │
    └── optional singleton reads
            ↓
      BWA-MEM2 mapping
            ↓
      coordinate sorting
            ↓
       merge read sets
            ↓
       BAM validation
            ↓
        BAM indexing
            ↓
sample.sorted.bam
sample.sorted.bam.bai
Why map every sample to the same pseudoreference?

Joint population-genomic analyses require homologous variants to be represented using the same locus and position coordinates in every individual. Mapping all samples against one shared UCE reference provides that common coordinate system.

1. Activate the population-genomics environment

The uce-popgen Conda environment was created once at the beginning of the population-genomics workflow. Reuse the same environment here rather than creating a new one.

conda activate uce-popgen

Confirm that the mapping tools are available:

bwa-mem2 version
samtools --version
Keep the analysis environment consistent

Reusing the same environment across the population-genomics workflow makes software versions easier to track and avoids unnecessary duplication between modules.

2. Define the project paths

The examples below use generic shell variables. Adapt only the paths and file naming pattern to your project.

# Root directory of the UCE project.
PROJECT="/path/to/my_UCE_project"

# Shared pseudoreference produced in the previous module.
PSEUDO="$PROJECT/population_genomics/01_pseudoreference"
PSEUDOREF="$PSEUDO/shared_uce_pseudoref.fasta"

# Directory containing cleaned reads.
CLEAN_FASTQ="$PROJECT/clean-fastq"

# Output directory for mapped reads.
MAPPING="$PROJECT/population_genomics/02_mapping"

mkdir -p "$MAPPING"

A simple cleaned-read layout could look like this:

clean-fastq/
├── sample_A/
│   └── split-adapter-quality-trimmed/
│       ├── sample_A-READ1.fastq.gz
│       ├── sample_A-READ2.fastq.gz
│       ├── sample_A-READ-singleton.fastq.gz
│       └── sample_A-READ-singleton-R2.fastq.gz
│
├── sample_B/
│   └── split-adapter-quality-trimmed/
│       ├── sample_B-READ1.fastq.gz
│       └── sample_B-READ2.fastq.gz
│
└── ...

Singleton files are optional. If the read-processing workflow did not generate them, simply omit the singleton mapping steps below.

3. Index the shared pseudoreference

BWA-MEM2 requires its own mapping index. Samtools also benefits from a FASTA .fai index for downstream operations.

bwa-mem2 index "$PSEUDOREF"

samtools faidx "$PSEUDOREF"

Inspect the resulting files:

ls -lh "$PSEUDOREF"*

The exact BWA-MEM2 index filenames depend on the implementation, but the reference FASTA should now be accompanied by BWA-MEM2 index files and a .fai file produced by Samtools.

4. Map one paired-end sample

Start by defining one sample and its read files. Testing one individual before processing the full dataset is strongly recommended.

SAMPLE="sample_A"

READ_DIR="$CLEAN_FASTQ/$SAMPLE/split-adapter-quality-trimmed"

R1="$READ_DIR/${SAMPLE}-READ1.fastq.gz"
R2="$READ_DIR/${SAMPLE}-READ2.fastq.gz"

OUTDIR="$MAPPING/$SAMPLE"
TMPDIR="$OUTDIR/tmp"

mkdir -p "$OUTDIR" "$TMPDIR"

Define a read group before mapping:

RG="@RG\tID:${SAMPLE}\tSM:${SAMPLE}\tLB:${SAMPLE}\tPL:ILLUMINA"
ID
Read-group identifier. It should be unique within the BAM.
SM
Biological sample name. This field is particularly important for downstream genotype calling.
LB
Library identifier. Here it is set to the sample identifier for a simple one-library-per-sample design.
PL
Sequencing platform. Use the value appropriate for the data; ILLUMINA is shown here as a common UCE example.

Map and coordinate-sort the paired reads in a single stream:

PAIRED_BAM="$TMPDIR/${SAMPLE}.paired.bam"

bwa-mem2 mem \
  -t 4 \
  -R "$RG" \
  "$PSEUDOREF" \
  "$R1" \
  "$R2" \
| samtools sort \
    -@ 2 \
    -T "$TMPDIR/paired_sort" \
    -o "$PAIRED_BAM" \
    -

Piping directly from BWA-MEM2 to samtools sort avoids writing a large intermediate SAM file.

5. Optional: map singleton reads

Adapter trimming and paired-read cleaning can leave reads whose mate was discarded. These surviving reads may still contain useful UCE sequence and can be mapped as single-end reads.

SINGLE1="$READ_DIR/${SAMPLE}-READ-singleton.fastq.gz"
SINGLE2="$READ_DIR/${SAMPLE}-READ-singleton-R2.fastq.gz"

Map the first singleton file if it exists:

SINGLE1_BAM="$TMPDIR/${SAMPLE}.singleton1.bam"

if [[ -s "$SINGLE1" ]]; then
  bwa-mem2 mem \
    -t 4 \
    -R "$RG" \
    "$PSEUDOREF" \
    "$SINGLE1" \
  | samtools sort \
      -@ 2 \
      -T "$TMPDIR/singleton1_sort" \
      -o "$SINGLE1_BAM" \
      -
fi

Do the same for the second singleton file if present:

SINGLE2_BAM="$TMPDIR/${SAMPLE}.singleton2.bam"

if [[ -s "$SINGLE2" ]]; then
  bwa-mem2 mem \
    -t 4 \
    -R "$RG" \
    "$PSEUDOREF" \
    "$SINGLE2" \
  | samtools sort \
      -@ 2 \
      -T "$TMPDIR/singleton2_sort" \
      -o "$SINGLE2_BAM" \
      -
fi
Do not invent singleton filenames

Read-processing tools differ in how singleton reads are named and stored. Include only files that actually exist in your workflow.

6. Merge mapped read sets

If paired-end and singleton reads were mapped separately, merge the coordinate-sorted BAM files into one final BAM for the sample.

FINAL_BAM="$OUTDIR/${SAMPLE}.sorted.bam"

BAMS=("$PAIRED_BAM")

[[ -s "$SINGLE1_BAM" ]] && BAMS+=("$SINGLE1_BAM")
[[ -s "$SINGLE2_BAM" ]] && BAMS+=("$SINGLE2_BAM")

if [[ ${#BAMS[@]} -eq 1 ]]; then
  mv "${BAMS[0]}" "$FINAL_BAM"
else
  samtools merge \
    -@ 2 \
    -f \
    -c \
    -o "$FINAL_BAM" \
    "${BAMS[@]}"
fi

Because the input BAMs were coordinate-sorted against the same reference, Samtools can preserve that coordinate order while merging them. The -c option is useful here because the BAM chunks intentionally share the same read-group identifier.

7. Validate and index the final BAM

Perform a fast structural check before indexing:

samtools quickcheck -v "$FINAL_BAM"

No output is expected when the BAM passes this quick integrity check. Then create the BAM index:

samtools index -@ 2 "$FINAL_BAM"

Confirm the final files:

ls -lh "$FINAL_BAM" "${FINAL_BAM}.bai"
02_mapping/
└── sample_A/
    ├── sample_A.sorted.bam
    └── sample_A.sorted.bam.bai

8. Portable script for one sample

The steps above can be combined into a reusable Bash script. It accepts the sample ID as its first argument and does not depend on any workload manager.

#!/usr/bin/env bash

set -euo pipefail

SAMPLE="$1"

PROJECT="/path/to/my_UCE_project"
PSEUDOREF="$PROJECT/population_genomics/01_pseudoreference/shared_uce_pseudoref.fasta"
CLEAN_FASTQ="$PROJECT/clean-fastq"
MAPPING="$PROJECT/population_genomics/02_mapping"

READ_DIR="$CLEAN_FASTQ/$SAMPLE/split-adapter-quality-trimmed"

R1="$READ_DIR/${SAMPLE}-READ1.fastq.gz"
R2="$READ_DIR/${SAMPLE}-READ2.fastq.gz"

SINGLE1="$READ_DIR/${SAMPLE}-READ-singleton.fastq.gz"
SINGLE2="$READ_DIR/${SAMPLE}-READ-singleton-R2.fastq.gz"

OUTDIR="$MAPPING/$SAMPLE"
TMPDIR="$OUTDIR/tmp"

mkdir -p "$OUTDIR" "$TMPDIR"

FINAL_BAM="$OUTDIR/${SAMPLE}.sorted.bam"
PAIRED_BAM="$TMPDIR/${SAMPLE}.paired.bam"

RG="@RG\tID:${SAMPLE}\tSM:${SAMPLE}\tLB:${SAMPLE}\tPL:ILLUMINA"

if [[ ! -s "$R1" || ! -s "$R2" ]]; then
  echo "ERROR: paired reads not found for $SAMPLE" >&2
  exit 1
fi

bwa-mem2 mem -t 4 -R "$RG" "$PSEUDOREF" "$R1" "$R2" \
| samtools sort -@ 2 -T "$TMPDIR/paired_sort" -o "$PAIRED_BAM" -

BAMS=("$PAIRED_BAM")

if [[ -s "$SINGLE1" ]]; then
  SINGLE1_BAM="$TMPDIR/${SAMPLE}.singleton1.bam"

  bwa-mem2 mem -t 4 -R "$RG" "$PSEUDOREF" "$SINGLE1" \
  | samtools sort -@ 2 -T "$TMPDIR/singleton1_sort" -o "$SINGLE1_BAM" -

  BAMS+=("$SINGLE1_BAM")
fi

if [[ -s "$SINGLE2" ]]; then
  SINGLE2_BAM="$TMPDIR/${SAMPLE}.singleton2.bam"

  bwa-mem2 mem -t 4 -R "$RG" "$PSEUDOREF" "$SINGLE2" \
  | samtools sort -@ 2 -T "$TMPDIR/singleton2_sort" -o "$SINGLE2_BAM" -

  BAMS+=("$SINGLE2_BAM")
fi

if [[ ${#BAMS[@]} -eq 1 ]]; then
  mv "${BAMS[0]}" "$FINAL_BAM"
else
  samtools merge -@ 2 -f -c -o "$FINAL_BAM" "${BAMS[@]}"
fi

samtools quickcheck -v "$FINAL_BAM"
samtools index -@ 2 "$FINAL_BAM"

rm -rf "$TMPDIR"

echo "Mapping completed: $SAMPLE"
echo "BAM: $FINAL_BAM"

Run it with:

bash map_one_sample.sh sample_A

9. Process multiple samples without a scheduler

A simple sample list makes the workflow portable across workstations, servers and other Unix-like environments.

printf "%s\n" \
  sample_A \
  sample_B \
  sample_C \
  > mapping_samples.txt

Run the mapping sequentially:

while read -r SAMPLE; do
  bash map_one_sample.sh "$SAMPLE"
done < mapping_samples.txt
Parallel execution is environment-specific

The biological workflow does not depend on a particular scheduler. On HPC systems, containers, cloud platforms or multicore workstations, parallelize the same per-sample command using the resource manager appropriate to that environment.

10. What this step produces

At the end of mapping, every individual should have one coordinate-sorted BAM and its index, all aligned against the same shared UCE pseudoreference:

population_genomics/
├── 01_pseudoreference/
│   └── shared_uce_pseudoref.fasta
│
└── 02_mapping/
    ├── sample_A/
    │   ├── sample_A.sorted.bam
    │   └── sample_A.sorted.bam.bai
    ├── sample_B/
    │   ├── sample_B.sorted.bam
    │   └── sample_B.sorted.bam.bai
    └── ...

These BAM files are the direct input for the next stage: mapping quality control. Variant calling should not begin until mapping success, coverage and depth have been evaluated across samples and UCE loci.

11. Pre-flight check

✓ Every sample was mapped to the same shared UCE pseudoreference.
✓ The pseudoreference was indexed with BWA-MEM2 and Samtools.
✓ Paired-end reads were supplied as R1 and R2 from the same sample.
✓ Read groups include at least ID, SM, LB and PL fields.
✓ Singleton reads were included only when they actually existed.
✓ BAM files were coordinate-sorted before indexing.
✓ The final BAM passed samtools quickcheck.
✓ Every final BAM has its corresponding index file.

References and software documentation

BWA-MEM2 — official repository and usage documentation
Reference indexing and paired- or single-end read mapping with the BWA-MEM2 algorithm.

Samtools sort — official manual
Coordinate sorting of SAM/BAM/CRAM alignments before indexing.

Samtools merge — official manual
Merging coordinate-sorted alignment files while preserving their sort order.

Samtools — official manual
Documentation for faidx, quickcheck, index and related alignment utilities.

Boundary of this module

samtools quickcheck is used here only as a basic file-integrity check. Mapping rate, properly paired reads, locus coverage, depth and mapping-quality diagnostics belong to the next module: Mapping Quality Control.

← Building a UCE pseudoreference Next: Mapping quality control →