This workshop follows a workflow for assembling mixed microbial sequence data, examining the resulting contigs, grouping them into genome bins and assessing bin quality.
Bash commands are run in the Terminal. R commands are run in the R Console or R chunks. All chunks below are displayed without executing during knitting.
cd ~/mb5370-workshops/raw_data
ln -s /pvol/data/metagenome_assembly/reads_R10_0.5.fastq.gz raw_reads.fastq.gz
cd ..
ls -l raw_data
ln -s creates a symbolic link rather than duplicating
the large input file. ls -l shows the link and its target,
allowing the path to be checked.
Run this from the project root.
cd ~/mb5370-workshops
zcat raw_data/raw_reads.fastq.gz |
head -n 40000 |
bioawk -c fastx '{print $name,length($seq)}' > read_lengths.txt
head read_lengths.txt
wc -l read_lengths.txt
zcat decompresses the input to standard output. The pipe
passes that output to head, which retains the first 40,000
lines. For four-line FASTQ records, this represents 10,000 reads.
bioawk prints each read identifier and sequence length.
The > operator writes the results to a file, replacing
an existing file of that name.
A broken-pipe message can occur because head stops
before zcat finishes reading. The output should still be
checked using head and wc -l rather than
assuming success.
library(tidyverse)
rl_data <- read_tsv(
"~/mb5370-workshops/read_lengths.txt",
col_names = c("id", "length"),
show_col_types = FALSE
)
ggplot(rl_data, aes(x = length / 1000)) +
geom_histogram(binwidth = 2) +
labs(
x = "Read length (kb)",
y = "Number of reads"
) +
theme_minimal()
read_tsv() imports the two-column file. Dividing length
by 1,000 converts bases to kilobases, and the histogram groups reads
into 2 kb intervals.
total_len <- sum(rl_data$length)
read_n50 <- rl_data |>
arrange(desc(length)) |>
mutate(cumulative_length = cumsum(length)) |>
filter(cumulative_length >= total_len / 2) |>
slice_head(n = 1)
read_n50
Reads are sorted from longest to shortest, then their lengths are accumulated. N50 is the length of the read at which the cumulative total first reaches at least half of all sampled bases.
This calculation describes the sampled reads, not necessarily the full input dataset.
cd ~/mb5370-workshops/flye_metagenome
Save the following as run_flye.sh inside this
folder.
#!/bin/bash
#SBATCH --time=360
#SBATCH --cpus-per-task=4 --mem=6gb
echo "Starting flye in $(pwd) at $(date)"
flye --nano-hq ../raw_data/raw_reads.fastq.gz \
--threads 4 \
--out-dir mock \
--meta
echo "Finished flye in $(pwd) at $(date)"
The Slurm directives request a time limit, CPUs and memory.
--nano-hq specifies high-quality Nanopore reads, while
--meta selects the metagenome assembly mode. Outputs are
written into mock.
sbatch run_flye.sh
squeue -u "$USER"
tail -f slurm-XXX.out
Replace XXX with the submitted job number. Submit the
job only once.
squeue reports queued and running jobs.
tail -f watches the log until interrupted with Ctrl+C;
stopping the viewer does not cancel the Slurm job.
After the job ends, check the log for errors and confirm that final output files exist. The script’s final echo message alone does not demonstrate success.
ls -lh mock
tail -n 20 mock/flye.log
Important outputs include:
assembly.fasta: assembled sequences.assembly_graph.gfa: graph for visualisation.assembly_info.txt: contig statistics.Download mock/assembly_graph.gfa, load it in Bandage and
draw the graph. Enable node names, lengths and depths to inspect large
components.
bioawk -c fastx '{print $name, length($seq)}' \
mock/assembly.fasta |
sort -nr -k2 |
head
The first row identifies the longest assembled sequence. Length, coverage and graph structure provide clues about genome recovery, but cannot independently confirm taxonomic identity.
Save the following Bioawk program as gc.awk in the
project root. This is file content, not a command to run directly in the
shell.
BEGIN {
OFS="\t"
}
{
l=length($seq)
ngc=gsub("[cgCG]","",$seq)
nat=gsub("[taTA]","",$seq)
print $name,l,ngc/(ngc+nat)
}
The program prints the sequence name, total length and GC fraction. GC fraction is calculated among A, C, G and T bases, excluding other symbols from the denominator.
cd ~/mb5370-workshops
ls /pvol/data/mg/refs/*.fna
cat /pvol/data/mg/refs/*.fna |
bioawk -c fastx -f gc.awk
These values provide reference characteristics for comparison with assembled sequences. Similar GC content alone does not establish that two sequences belong to the same organism.
Wait for Flye to finish before running this step.
cd ~/mb5370-workshops/assembly_check
cat ../flye_metagenome/mock/assembly.fasta |
bioawk -c fastx -f ../gc.awk > assembly.gc.tsv
The same script is applied to assembled contigs, producing a tab-separated file.
gc <- read_tsv(
"~/mb5370-workshops/assembly_check/assembly.gc.tsv",
col_names = c("#seq_name", "length", "GC"),
show_col_types = FALSE
)
info <- read_tsv(
"~/mb5370-workshops/flye_metagenome/mock/assembly_info.txt",
show_col_types = FALSE
)
gc_info <- info |>
left_join(gc, by = c("#seq_name", "length"))
The join matches sequence identifiers and lengths, attaching GC content to the corresponding assembly information.
The full paths avoid confusion if the R Console’s working directory differs from the Terminal’s location.
ggplot(gc_info, aes(x = GC)) +
geom_histogram(bins = 30) +
labs(
x = "GC fraction",
y = "Number of contigs"
) +
theme_minimal()
Each contig contributes one observation. The histogram is therefore not weighted by sequence length or organism abundance.
library(ggrepel)
gc_info |>
filter(GC < 0.8, cov. < 25) |>
ggplot(aes(x = GC, y = cov.)) +
geom_point(aes(size = length)) +
geom_label_repel(aes(label = `#seq_name`)) +
labs(
x = "GC fraction",
y = "Coverage depth (×)",
size = "Contig length (bp)"
) +
theme_minimal()
Point position represents GC fraction and coverage, while point size represents sequence length. Similar values may help identify candidate groups for further investigation.
The filters restrict this visualisation; they do not delete sequences from the assembly or prove that excluded sequences are errors.
cd ~/mb5370-workshops
cat /pvol/data/mg/refs/*.fna |
bioawk -c fastx -f gc.awk |
awk '{sum+=$2} END {print sum}'
The final awk command sums the sequence lengths.
sum(gc_info$length)
Compare this with the exact reference total printed above. A similar total length does not establish that every reference region was recovered: missing regions, duplicated sequences and errors can affect the comparison.
characteristics.
cd ~/mb5370-workshops/metabat
cat ../flye_metagenome/mock/assembly_info.txt |
grep -v '#' |
awk 'BEGIN {OFS="\t"} {print $1,$3}' > depths.txt
grep -v excludes matching lines, removing the header
here. awk extracts the sequence identifier and coverage
columns.
awk '{print $1}' depths.txt |
xargs samtools faidx ../flye_metagenome/mock/assembly.fasta \
> assembly_ordered.fasta
The identifiers are passed to samtools faidx, which
retrieves the sequences in the requested order.
metabat2 -i assembly_ordered.fasta \
-a depths.txt \
--cvExt \
-o bins/metabat \
--seed 5
grep '>' bins/metabat.*.fa
MetaBAT2 uses sequence-composition and coverage information to group contigs into candidate genome bins. The seed records a setting relevant to reproducibility.
The header listing shows which sequences were assigned to each bin. Bins are hypotheses about genome membership; their number need not equal the number of species, and some sequences may remain unbinned.
cd ~/mb5370-workshops/checkm
cp ../metabat/bins/metabat.*.fa bins/
cp copies the MetaBAT FASTA files into the CheckM input
directory.
bioawk -c fastx '{print $name, length($seq)}' \
../flye_metagenome/mock/assembly.fasta |
sort -nr -k2 |
head -n 5
The first row is the longest contig. Its identifier must be checked against the actual bin headers before adding it separately.
grep -H -E '^>contig_43([[:space:]]|$)' bins/metabat.*.fa
If this prints a match, the contig is already in a bin and should not be added again. If there is no match and the files were searched successfully, extract it as a separate candidate bin:
samtools faidx ../flye_metagenome/mock/assembly.fasta contig_43 \
> bins/contig_43.fa
Save this as run_checkm.sh in the checkm
folder.
#!/bin/bash
#SBATCH --time=60
#SBATCH --cpus-per-task=4 --mem=40gb
echo "Starting checkm in $(pwd) at $(date)"
shopt -s expand_aliases
alias checkm='apptainer run -B /pvol/:/pvol /pvol/data/sif/checkm.sif checkm'
checkm lineage_wf bins out -t 4 -x fa -f checkm_results.txt
echo "Finished checkm in $(pwd) at $(date)"
CheckM is run through the supplied Apptainer container. The bind
option makes /pvol accessible inside it. shopt
enables alias expansion in this Bash script.
lineage_wf runs the lineage-based assessment,
-x fa identifies the input file extension and
-f names the summary file.
sbatch run_checkm.sh
squeue -u "$USER"
tail -f slurm-XXX.out
Replace XXX with the actual job number. After successful
completion:
cat checkm_results.txt
CheckM uses lineage-specific marker genes to estimate genome completeness and contamination. Duplicated markers can indicate mixed genome content, although biological duplication and strain mixtures complicate interpretation.
Strain heterogeneity helps assess whether duplicated markers are similar enough to suggest closely related strains. It is not a direct percentage of all reads belonging to different strains.
These estimates should be interpreted alongside contig composition, coverage and graph evidence. Marker lineage is not necessarily a species-level identification.
Workshop guide: https://mb5370.bioinformatics.guide/workshop3.html