Taxonomic, functional and resistance gene profiling in one pass with multiprocess_runs()
Source:vignettes/multiprocess-workflow.Rmd
multiprocess-workflow.RmdThis vignette walks through a complete multi-pathway workflow with
sra2lab: setting up an analysis directory, the conda
environments and the three reference databases, listing the SRA runs of
a BioProject, and processing each run with
multiprocess_runs(), which downloads it once and then:
- profiles its taxa with sylph,
- profiles its KEGG Orthology groups (KOs) with fmh-funprofiler, and
- finds its antibiotic resistance genes with RGI and the Comprehensive Antibiotic Resistance Database (CARD).
It then combines the three kinds of results in R.
The example BioProject is PRJNA1556220,
“Microbiome changes in the peri-heart transplant setting”: 67 paired-end
Illumina shotgun metagenomes from skin (axilla and groin) and gut
(perirectal and stool) swabs. The same 8 runs are processed one pathway
at a time in vignette("sylph-workflow"),
vignette("funprofiler-workflow") and
vignette("rgi-workflow"), which go into each kind of result
in more detail.
Why one pass?
Running sylph_runs(), funprofiler_runs()
and rgi_runs() one after another downloads every run three
times. Downloading usually takes far longer than the analyses
themselves, so multiprocess_runs() downloads each run once,
runs every chosen pathway on it, and deletes the reads before moving on.
Its outputs are exactly the files the single-pathway functions write,
with the same names and in the same directories, so the two approaches
can be mixed: either one skips outputs the other has already made.
Before you start
You need:
-
conda, for example Miniconda.
sra2lab looks for
~/miniconda3/bin/condaby default; see?conda_binif yours is elsewhere. -
Three reference databases, one per pathway (step
3):
- a sylph database, here the GTDB r232 two-stage
database
gtdb-r232-c200-dbv2.syl2db(about 20 GB); - a KO database for fmh-funprofiler, here
KOs_sketched_scaled_1000.sig.zip; -
CARD’s reference data, loaded with RGI into a
localDBdirectory. This is essential: RGI ships without any reference data.
- a sylph database, here the GTDB r232 two-stage
database
-
Internet access to NCBI, and enough disk space in
the analysis directory for one run’s download, its reads, the temporary
files
fasterq-dumpwrites while extracting them (several times the download’s size), and the results.
1. Set up an analysis directory
Keep each analysis in its own directory. sra2lab’s functions
write to paths relative to the working directory: run metadata and
results go under data/, and environment specifications
under methods/. By default,
multiprocess_runs() looks for all three databases one level
above the working directory, so a layout like this keeps one
copy of each database for many analyses:
~/projects/
├── gtdb-r232-c200-dbv2.syl2db <- sylph database (shared)
├── KOs_sketched_scaled_1000.sig.zip <- KO database (shared)
├── localDB/ <- CARD data, loaded by RGI (shared)
└── PRJNA1556220/ <- analysis directory (working directory)
├── data/
│ ├── PRJNA1556220_runs.csv <- run metadata (step 4)
│ ├── sylph/ <- taxonomic profiles (step 5)
│ ├── funprofiler/ <- KO profiles (step 5)
│ └── rgi/ <- resistance genes (step 5)
└── methods/
└── *_env.yml <- environment specifications (step 2)
Create the analysis directory and make it the working directory (or create an RStudio project there, which does the same):
library(sra2lab)
analysis_dir <- "~/projects/PRJNA1556220"
dir.create(analysis_dir, recursive = TRUE, showWarnings = FALSE)
setwd(analysis_dir)2. Set up and document the conda environments
Each tool runs in its own conda environment. For these three
pathways, multiprocess_runs() uses sra_env
(the SRA Toolkit and EDirect), sylph_env,
funprofiler_env and rgi_env. Each only needs
to be created once per computer:
setup_conda_sra(yes = TRUE)
setup_conda_sylph(yes = TRUE)
setup_conda_funprofiler(yes = TRUE)
setup_conda_rgi(yes = TRUE)If an environment already exists, these calls stop with an error and
leave it untouched (use overwrite = TRUE to rebuild it).
Adding "smash" to process_path (step 5) also
needs setup_conda_sourmash().
Then record the exact environments used for this analysis, with every package’s version and build:
document_conda_sra(write_yml = TRUE)
document_conda_sylph(write_yml = TRUE)
document_conda_funprofiler(write_yml = TRUE)
document_conda_rgi(write_yml = TRUE)
#> Wrote methods/sra_env.yml
#> ...
#> Wrote methods/sylph_env.yml
#> ...
#> Wrote methods/funprofiler_env.yml
#> ...
#> Wrote methods/rgi_env.yml
#> ...
list.files("methods")
#> [1] "funprofiler_env.yml" "rgi_env.yml" "sra_env.yml"
#> [4] "sylph_env.yml"Keeping these files with the analysis lets you report the tool
versions (here sylph 1.0.0, fmh-funprofiler 1.1.1 with sourmash 4.9.4,
and RGI 6.0.8 with KMA 1.7.1) and recreate each environment later with
conda env create -f methods/<env>.yml.
3. Get the reference databases
Each pathway needs its own reference database. Download them once, into the directory above your analysis directories.
sylph. Pre-built databases are listed at https://sylph-docs.github.io/pre%E2%80%90built-databases/.
This vignette uses the GTDB r232 two-stage database
(gtdb-r232-c200-dbv2.syl2db). The matching GTDB taxonomy,
metadata and trees are at https://gtdb.ecogenomic.org/downloads.
fmh-funprofiler. The pre-sketched KO databases are
on Zenodo, at https://zenodo.org/records/10045253. This vignette uses
KOs_sketched_scaled_1000.sig.zip, sketched with k = 11 and
scaled = 1000, which must match funprofiler_k and
funprofiler_scaled.
RGI (essential: don’t skip this). RGI is installed without any reference data, so download CARD’s data and load it with RGI. In a terminal:
cd ~/projects # the directory above the analysis
# 1. download the latest CARD data and extract card.json
wget https://card.mcmaster.ca/latest/data
tar -xvf data ./card.json
# 2. make RGI's reference sequences from it
conda run -n rgi_env rgi card_annotation -i card.json
# 3. load them into ./localDB
conda run -n rgi_env rgi load -i card.json --local \
--card_annotation card_database_v4.0.2.fasta \
--card_annotation_all_models card_database_v4.0.2_all.fasta
# record the CARD version for your methods
conda run -n rgi_env rgi database --version --local
#> 4.0.2rgi card_annotation names its files after the CARD
version (here 4.0.2), so check the names it writes and use them in
rgi load. vignette("rgi-workflow") explains
each step.
Before downloading any reads, multiprocess_runs() checks
every chosen pathway’s database and environment: that the sylph and KO
databases exist, that the KO database was sketched with
funprofiler_k and funprofiler_scaled, and that
localDB holds the CARD data RGI needs. A missing database
stops it straight away, with the argument to fix:
multiprocess_runs(to_process, process_path = c("sylph", "funprofiler", "rgi"),
rgi_card_db = "../CARD/localDB")
#> Error: CARD database not found: ../CARD/localDB. Load CARD with `rgi load --local` (see ?rgi_runs).4. List the SRA runs in the BioProject
get_bioproject_runs() queries NCBI for every run in the
BioProject and returns one row per run (SRR ID), with its sequencing
details and the BioSample metadata the submitters provided:
runs <- get_bioproject_runs("PRJNA1556220")
#> Querying NCBI SRA for PRJNA1556220 ...
dir.create("data", showWarnings = FALSE)
write.csv(runs, "data/PRJNA1556220_runs.csv", row.names = FALSE)The run table from that query is saved as
data/PRJNA1556220_runs.csv, so it can be read back in later
steps (or sessions) without querying NCBI again:
runs <- read.csv("data/PRJNA1556220_runs.csv")
dim(runs)
#> [1] 67 31
table(runs$isolation_source, runs$organism)
#>
#> human gut metagenome human skin metagenome
#> Axilla Swab 0 5
#> Groin Swab 0 15
#> Perirectal Swab 24 0
#> Stool Swab 23 0
summary(runs$size / 1e9) # run sizes, GB
#> Min. 1st Qu. Median Mean 3rd Qu. Max.
#> 0.3779 0.5793 0.9983 0.9239 1.1129 1.9082All 67 runs are paired-end shotgun metagenomes
(library_strategy WGS), from 18 subjects
(host_subject_id). The whole BioProject is about 62 GB of
reads. For this example, pick the two smallest runs of each swab
type:
runs <- runs[order(runs$size), ]
to_process <- do.call(rbind, lapply(split(runs, runs$isolation_source),
head, 2))
rownames(to_process) <- NULL
to_process[, c("run_accession", "isolation_source", "host_subject_id",
"size")]
#> run_accession isolation_source host_subject_id size
#> 1 SRR41520897 Axilla Swab GOL_015 569543795
#> 2 SRR41520919 Axilla Swab GOL_016 1036597186
#> 3 SRR41520874 Groin Swab GOL_034 560547549
#> 4 SRR41520873 Groin Swab GOL_017 571965183
#> 5 SRR41520878 Perirectal Swab GOL_017 377877890
#> 6 SRR41520882 Perirectal Swab GOL_017 551256914
#> 7 SRR41520894 Stool Swab GOL_018 489008698
#> 8 SRR41520884 Stool Swab GOL_003 493557313To process the whole BioProject instead, pass runs
itself (or any filtered version of it) to
multiprocess_runs().
5. Process the runs with multiprocess_runs()
process_path chooses the pathways, from
"smash" (sourmash sketches), "sylph",
"funprofiler" and "rgi"; each runs in the
order given. Each pathway’s options are the arguments of its
single-pathway function, with the pathway’s name as a prefix:
sylph_database; funprofiler_database,
funprofiler_k, funprofiler_scaled and
threshold_bp; rgi_card_db,
rgi_aligner, rgi_include_wildcard,
rgi_include_other_models and rgi_keep_bam; and
sylph_outdir, funprofiler_outdir and
rgi_outdir for where the results go. The defaults are the
same as the single-pathway functions’, so the call below spells out only
the databases:
res <- multiprocess_runs(
to_process,
process_path = c("sylph", "funprofiler", "rgi"),
sylph_database = "../gtdb-r232-c200-dbv2.syl2db",
funprofiler_database = "../KOs_sketched_scaled_1000.sig.zip",
rgi_card_db = "../localDB",
threads = 6, quiet = TRUE
)
#> [1/8] SRR41520897: downloading (prefetch) ...
#> [1/8] SRR41520897: extracting and compressing reads (fasterq-dump) ...
#> [1/8] SRR41520897: profiling ...
#> [1/8] SRR41520897: profiling (k=11, scaled=1000) ...
#> [1/8] SRR41520897: mapping reads to CARD (kma) ...
#> [1/8] SRR41520897: wrote data/sylph/SRR41520897_profiling.tsv, data/funprofiler/SRR41520897_k11_scale1000_ko_profiles.csv, data/rgi/SRR41520897_kma.gene_mapping_data.txt
#> [2/8] SRR41520919: downloading (prefetch) ...
#> [2/8] SRR41520919: extracting and compressing reads (fasterq-dump) ...
#> ...
#> [8/8] SRR41520884: wrote data/sylph/SRR41520884_profiling.tsv, data/funprofiler/SRR41520884_k11_scale1000_ko_profiles.csv, data/rgi/SRR41520884_kma.gene_mapping_data.txt
#> Done: 16 profiled, 8 mapped, 0 skipped, 0 failed.For each run, multiprocess_runs() downloads the run with
prefetch, extracts its reads with
fasterq-dump, then profiles them with sylph, profiles their
KOs with fmh-funprofiler, maps them to CARD with rgi bwt,
and writes each tool’s results to its own directory under
data/. In the progress messages, the first “profiling” line
is sylph and the second, with k and scaled, is
fmh-funprofiler; the “wrote” line lists each pathway’s main output:
| Pathway | Output (per run) |
|---|---|
| sylph | data/sylph/<SRR>_profiling.tsv |
| funprofiler | data/funprofiler/<SRR>_k11_scale1000_ko_profiles.csv |
| rgi |
data/rgi/<SRR>_kma.gene_mapping_data.txt, with
RGI’s other outputs |
These 8 runs (about 4.7 GB) took about 2.4 hours in all, mostly
downloading. Processed one pathway at a time, in the other three
vignettes, the same runs took about 6 hours, because each was downloaded
three times. The results are the same either way: the files
multiprocess_runs() wrote match those of the single-pathway
runs, apart from the order of a few rows. Download speed depends on your
connection and on NCBI.
quiet = TRUE hides the tools’ own progress output,
including fasterq-dump’s, which keeps the console readable
on a long job. It also hides the first sign of a slow or failing
download: a large run can show nothing after “downloading (prefetch) …”
or “extracting and compressing reads (fasterq-dump) …” for many minutes.
For a first run, or on an unreliable connection, leave
quiet at its default (FALSE). Either way, a
run that fails is reported straight away, with a line such as
[2/8] SRR41520919: FAILED: fasterq-dump failed (exit status N). ...;
the reason is kept in the result’s message column, and
running the same call again retries only the failed runs.
Running the pathways in parallel
By default, each run’s pathways go one after another. With
parallel = TRUE, they all start as soon as the run is
downloaded, each in its own R process, reading the same
working_data.fastq.gz; the next run starts when all of them
have finished. Here it is on one of the runs (SRR41520878, 378 MB), with
all four pathways, in a fresh data/ directory:
one_run <- to_process[to_process$run_accession == "SRR41520878", ]
res <- multiprocess_runs(
one_run,
process_path = c("smash", "sylph", "funprofiler", "rgi"),
sylph_database = "../gtdb-r232-c200-dbv2.syl2db",
funprofiler_database = "../KOs_sketched_scaled_1000.sig.zip",
rgi_card_db = "../localDB",
threads = 6, parallel = TRUE, quiet = TRUE
)
#> [1/1] SRR41520878: downloading (prefetch) ...
#> [1/1] SRR41520878: extracting and compressing reads (fasterq-dump) ...
#> [1/1] SRR41520878 [smash]: sketching ...
#> [1/1] SRR41520878 [sylph]: profiling ...
#> [1/1] SRR41520878 [funprofiler]: profiling (k=11, scaled=1000) ...
#> [1/1] SRR41520878 [rgi]: mapping reads to CARD (kma) ...
#> [1/1] SRR41520878: wrote data/smash/SRR41520878_k31_scale1000_seed42_abund.sig, data/sylph/SRR41520878_profiling.tsv, data/funprofiler/SRR41520878_k11_scale1000_ko_profiles.csv, data/rgi/SRR41520878_kma.gene_mapping_data.txt
#> Done: 1 sketched, 2 profiled, 1 mapped, 0 skipped, 0 failed.Each progress message names its pathway, because the pathways’
messages arrive together. The outputs were the same as with
parallel = FALSE, and the whole run took 586 seconds,
against 697 seconds with the pathways one after another; both include
roughly 5 minutes of downloading, which parallel does not
change. The saving is larger when the tools take longer than the
download, for example with several values of funprofiler_k
or rgi_aligner.
Some things to know before turning it on:
-
Processors and memory. The tools compete for the
computer: each still uses
threadsthreads, and the memory needed is that of all of them at once, including sylph’s database and RGI’s CARD index. Use a smallerthreadsif the tools slow each other down, andparallel = FALSEif memory is short. -
Console output. The tools’ own output is mixed
together, so use
quiet = TRUE. -
Failures and interrupts. A pathway that fails, or
whose process is killed (for example, for running out of memory), is
marked
"failed", and the others carry on. An interrupt (Esc or Ctrl-C) stops every pathway’s tools, keeps the outputs of pathways that had already finished, and the same call later makes the rest. -
Windows. R cannot fork processes on Windows, so
there
parallel = TRUEgives a warning and runs the pathways one after another. -
IDEs: run from a terminal instead. Some IDEs do not
allow R to fork. Positron refuses it, and RStudio advises against it. In
Positron,
parallel = TRUEfails every sample with “Can’t fork the R session in Positron” as itsmessage, after downloading its reads. Withparallel = TRUE, put the call in a script and run it withRscriptfrom a terminal, outside the IDE; in the IDE’s console, keepparallel = FALSE.
For example, save the call as run_pathways.R:
library(sra2lab)
runs <- get_bioproject_runs("PRJNA1556220")
res <- multiprocess_runs(
runs,
process_path = c("smash", "sylph", "funprofiler", "rgi"),
sylph_database = "../gtdb-r232-c200-dbv2.syl2db",
funprofiler_database = "../KOs_sketched_scaled_1000.sig.zip",
rgi_card_db = "../localDB",
threads = 6, parallel = TRUE, quiet = TRUE
)
saveRDS(res, "run_pathways_result.rds")and run it from a terminal in the project’s folder:
For a long job that should keep going after the terminal is closed, send the messages to a log file instead:
The result is saved to run_pathways_result.rds, so you
can read it back in the IDE with readRDS() and look at any
failed outputs’ message.
multiprocess_local() takes parallel as
well.
The result table
The result has one row per run and output file, so here 8 runs × 3
pathways = 24 rows. process names the pathway;
k, scaled, method and
aligner record the options each output was made with
(NA where they don’t apply); output is the
file; and status and message say what
happened:
res
#> # A tibble: 24 × 9
#> run_accession process k scaled method aligner output status message
#> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <chr> <chr>
#> 1 SRR41520897 sylph NA NA <NA> <NA> data/sylph/SRR41520897_prof… profi… <NA>
#> 2 SRR41520897 funprofiler 11 1000 <NA> <NA> data/funprofiler/SRR4152089… profi… <NA>
#> 3 SRR41520897 rgi NA NA <NA> kma data/rgi/SRR41520897_kma.ge… mapped <NA>
#> 4 SRR41520919 sylph NA NA <NA> <NA> data/sylph/SRR41520919_prof… profi… <NA>
#> 5 SRR41520919 funprofiler 11 1000 <NA> <NA> data/funprofiler/SRR4152091… profi… <NA>
#> 6 SRR41520919 rgi NA NA <NA> kma data/rgi/SRR41520919_kma.ge… mapped <NA>
#> ...
#> # ℹ 14 more rowsIt is easy to summarise, for example to check that every output was made:
table(res$process, res$status)
#>
#> mapped profiled
#> funprofiler 0 8
#> rgi 8 0
#> sylph 0 8Restarting and failures
-
Restarting. Outputs that already exist are skipped, and a run is only downloaded if at least one of its outputs is missing. An interrupted job can be restarted with the same call (
overwrite = TRUEmakes every output again). Running the same call again here downloads nothing, and takes seconds:res2 <- multiprocess_runs(to_process, process_path = c("sylph", "funprofiler", "rgi"), quiet = TRUE) #> [1/8] SRR41520897: data/sylph/SRR41520897_profiling.tsv, data/funprofiler/SRR41520897_k11_scale1000_ko_profiles.csv, data/rgi/SRR41520897_kma.gene_mapping_data.txt exist, skipping. #> ... #> [8/8] SRR41520884: data/sylph/SRR41520884_profiling.tsv, data/funprofiler/SRR41520884_k11_scale1000_ko_profiles.csv, data/rgi/SRR41520884_kma.gene_mapping_data.txt exist, skipping. #> Done: 0 profiled, 0 mapped, 24 skipped, 0 failed.The same holds across functions: a later
multiprocess_runs()call withprocess_path = c("sylph", "funprofiler", "rgi", "smash"), for example, downloads each run once more only to make the sourmash sketches. Failures. Each failure is reported as it happens, with a
FAILEDline giving the reason. If a run fails to download, all its outputs are marked"failed". If one pathway fails, only that pathway’s outputs are marked"failed", with the reason inmessage, and the run’s other pathways still go ahead. Either way the remaining runs carry on, and a later call retries only the missing outputs.Storage. Only one run’s reads are on disk at a time, as
working_data.fastq.gz, which is deleted at the end. Useworking_file = "working_data.fastq"to skip compressing the reads, which is faster if there is disk space for several times as much. On WSL2, keep the analysis directory in the Linux file system (under~), not on a Windows drive under/mnt/, which is much slower.
multiprocess_local() does the same for paired-end reads
already on disk, found by specimen ID; see
?multiprocess.
6. Read the results
Each pathway’s results are read just as in its own vignette. First
the sylph profiles, one row per genome detected in a run, with a rough
genus label taken from the organism name in
Contig_name:
sylph_files <- list.files(file.path("data", "sylph"),
pattern = "_profiling[.]tsv$", full.names = TRUE)
taxa <- do.call(rbind, lapply(sylph_files, read.delim))
taxa$run_accession <- taxa$Sample_file
organism <- sub("^\\S+\\s+", "", taxa$Contig_name) # drop accession
organism <- sub("^(MAG( TPA_asm)?: )?(TPA_asm: )?", "", organism)
organism <- sub("^(uncultured )?(Candidatus )?", "", organism)
organism <- gsub("\\[|\\]", "", organism)
taxa$genus <- vapply(strsplit(organism, " "), `[`, character(1), 1)
dim(taxa)
#> [1] 235 17Then the KO profiles, one row per KO found in a run, with its relative abundance:
ko_files <- list.files(file.path("data", "funprofiler"),
pattern = "_ko_profiles[.]csv$", full.names = TRUE)
kos <- do.call(rbind, lapply(ko_files, function(f) {
profile <- read.csv(f)
profile$run_accession <- sub("_k[0-9]+_scale[0-9]+_ko_profiles[.]csv$", "",
basename(f))
profile
}))
dim(kos)
#> [1] 16865 3And the resistance genes, one row per CARD gene with mapped reads in
a run. As in vignette("rgi-workflow"), normalise the read
counts to reads per kilobase of gene per million reads (RPKM), using
each run’s total read count from overall_mapping_stats.txt,
and keep genes covered along at least half their length:
gene_files <- list.files(file.path("data", "rgi"),
pattern = "_kma[.]gene_mapping_data[.]txt$",
full.names = TRUE)
amr <- do.call(rbind, lapply(gene_files, function(f) {
genes <- read.delim(f, check.names = FALSE)
genes$run_accession <- sub("_kma[.].*$", "", basename(f))
genes
}))
stats_files <- list.files(file.path("data", "rgi"),
pattern = "_kma[.]overall_mapping_stats[.]txt$",
full.names = TRUE)
total_reads <- vapply(stats_files, function(f) {
line <- grep("^Total reads:", readLines(f), value = TRUE)
as.numeric(sub("^Total reads:\\s+([0-9]+).*$", "\\1", line))
}, numeric(1))
names(total_reads) <- sub("_kma[.].*$", "", basename(stats_files))
amr$rpkm <- amr[["All Mapped Reads"]] / (amr[["Reference Length"]] / 1e3) /
(total_reads[amr$run_accession] / 1e6)
amr <- amr[amr[["Average Percent Coverage"]] >= 50, ]
dim(amr)
#> [1] 352 287. Combine and compare the three views
Because all three pathways ran on the same reads, their results line up by run accession. One table summarises each sample from all three views:
sample_order <- to_process$run_accession[order(to_process$isolation_source)]
genus_pct <- function(genus) {
pct <- tapply(taxa$Taxonomic_abundance * (taxa$genus == genus),
taxa$run_accession, sum)
round(pct[sample_order], 1)
}
summary_table <- data.frame(
run_accession = sample_order,
swab = sub(" Swab$", "", to_process$isolation_source[
match(sample_order, to_process$run_accession)]),
genomes = as.vector(table(taxa$run_accession)[sample_order]),
staph_pct = genus_pct("Staphylococcus"),
ecoli_pct = genus_pct("Escherichia"),
kos = as.vector(table(kos$run_accession)[sample_order]),
amr_genes = as.vector(table(amr$run_accession)[sample_order]),
amr_rpkm = round(as.vector(tapply(amr$rpkm, amr$run_accession,
sum)[sample_order])),
row.names = NULL
)
summary_table
#> run_accession swab genomes staph_pct ecoli_pct kos amr_genes amr_rpkm
#> 1 SRR41520897 Axilla 7 96.6 0.0 1253 26 7988
#> 2 SRR41520919 Axilla 7 75.0 0.0 1689 23 14801
#> 3 SRR41520874 Groin 8 89.9 0.0 1566 41 117934
#> 4 SRR41520873 Groin 16 94.1 0.0 1246 35 105823
#> 5 SRR41520878 Perirectal 68 0.0 14.7 3690 76 1945
#> 6 SRR41520882 Perirectal 69 0.0 22.5 4034 82 2823
#> 7 SRR41520894 Stool 20 0.0 0.0 2066 53 277
#> 8 SRR41520884 Stool 40 0.0 0.0 1321 16 42The views tell a consistent story. The skin swabs hold few genomes, almost all Staphylococcus (75–97%), few KOs, and a small set of resistance genes at very high abundance (8,000 to 118,000 RPKM), led by staphylococcal genes such as ermC, mecA and qacA. The perirectal swabs, the most diverse samples, with Escherichia coli the most abundant genome, have the most KOs and the most resistance genes, though at far lower abundance (about 2,000 to 3,000 RPKM). The stool swabs have the lowest resistance gene abundance.
Do the three views agree on which samples are alike?
For each view, compute the Bray–Curtis dissimilarity between every pair of samples, from relative abundances: of genomes (sylph), of KOs (funprofiler), and of resistance genes (RPKM, rescaled to sum to 1 in each sample). Bray–Curtis is 0 for identical profiles and 1 for profiles with nothing in common:
bray_curtis <- function(m) {
m <- m / rowSums(m)
as.matrix(dist(m, method = "manhattan")) / 2
}
taxa_matrix <- unclass(xtabs(Taxonomic_abundance ~ run_accession +
Genome_file, data = taxa))
ko_matrix <- unclass(xtabs(abundance ~ run_accession + ko_id, data = kos))
amr_matrix <- unclass(xtabs(rpkm ~ run_accession + `ARO Term`, data = amr))
bray <- list(
Taxa = bray_curtis(taxa_matrix[sample_order, ]),
KOs = bray_curtis(ko_matrix[sample_order, ]),
`Resistance genes` = bray_curtis(amr_matrix[sample_order, ])
)A principal coordinates analysis (PCoA) of each view places the samples so that their distances reflect these dissimilarities:
swab <- summary_table$swab
swab_types <- sort(unique(swab))
cols <- hcl.colors(4, "Dark 3")
op <- par(mfrow = c(1, 3), mar = c(4, 4, 2, 0.5), mgp = c(2.2, 0.7, 0),
oma = c(2, 0, 0, 0))
for (view in names(bray)) {
pcoa <- cmdscale(as.dist(bray[[view]]), k = 2, eig = TRUE)
explained <- round(100 * pcoa$eig[1:2] / sum(pcoa$eig[pcoa$eig > 0]))
plot(pcoa$points, col = cols[match(swab, swab_types)], pch = 19,
cex = 1.4, main = view, cex.main = 1, cex.axis = 0.8,
xlab = paste0("PCoA 1 (", explained[1], "%)"),
ylab = paste0("PCoA 2 (", explained[2], "%)"))
}
par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0),
new = TRUE)
plot.new()
legend("bottom", legend = swab_types, col = cols, pch = 19, bty = "n",
horiz = TRUE, cex = 0.9)
par(op)In all three views the first axis separates the skin swabs from the gut swabs. How closely do the views agree? Correlating the pairwise dissimilarities of each pair of views (the statistic of a Mantel test) gives:
pairwise <- sapply(bray, function(d) d[lower.tri(d)])
round(cor(pairwise, method = "spearman"), 2)
#> Taxa KOs Resistance genes
#> Taxa 1.00 0.91 0.81
#> KOs 0.91 1.00 0.76
#> Resistance genes 0.81 0.76 1.00Samples that are alike in their taxa are mostly alike in their
functions and their resistance genes too, as expected when the genes
come from the organisms present. With only 8 samples this is a
description, not a test; for a Mantel test with a p-value, use for
example vegan::mantel() on more samples.
Linking resistance genes to the taxa that carry them
The staphylococcal resistance genes should be most abundant where Staphylococcus is. Compare each sample’s Staphylococcus abundance (sylph) with its RPKM of a few genes typical of staphylococci (RGI):
staph_genes <- c("mecA", "PC1 beta-lactamase (blaZ)", "qacA", "dfrC",
"norA")
staph_rpkm <- tapply(amr$rpkm * (amr[["ARO Term"]] %in% staph_genes),
amr$run_accession, sum)
data.frame(summary_table[, c("run_accession", "swab", "staph_pct")],
staph_gene_rpkm = round(as.vector(staph_rpkm[sample_order])))
#> run_accession swab staph_pct staph_gene_rpkm
#> 1 SRR41520897 Axilla 96.6 4358
#> 2 SRR41520919 Axilla 75.0 2166
#> 3 SRR41520874 Groin 89.9 1810
#> 4 SRR41520873 Groin 94.1 2173
#> 5 SRR41520878 Perirectal 0.0 0
#> 6 SRR41520882 Perirectal 0.0 0
#> 7 SRR41520894 Stool 0.0 0
#> 8 SRR41520884 Stool 0.0 0These genes are found only in the skin swabs, where Staphylococcus dominates. RGI’s read-level results can’t say which organism a gene came from, but agreement like this between the taxonomic and resistance gene profiles is a first check; contig-level analysis (below) can link genes to the genomes that carry them.
A note on the RGI results
multiprocess_runs(), like rgi_runs(), gives
read-level resistance gene results: rgi bwt aligns
each read to CARD with KMA, a k-mer-based aligner, and counts reads per
gene. It does not assemble contigs or run rgi main, the
contig-based analysis that applies RGI’s Perfect/Strict/Loose criteria
(the options of CARD’s RGI web portal).
Pipelines such as CZ ID’s (AMR
Pipeline Workflow) combine read-level alignment with contig assembly
and rgi main. Use these results for screening and
abundance, and confirm genes of interest at the contig level; see
vignette("rgi-workflow") for more.
Next steps
- Process the rest of the BioProject with the same call on
runs; outputs already made are skipped. - Add sourmash sketches (
"smash"inprocess_path, withsmash_k,smash_scaledandsmash_method), for comparing samples or searching them against other databases. - Process reads you already have on disk with
multiprocess_local(). - For more on each kind of result, see
vignette("sylph-workflow"),vignette("funprofiler-workflow")andvignette("rgi-workflow").
References
Shaw J, Yu YW. Rapid species-level metagenome profiling and containment estimation with sylph. Nature Biotechnology. 2025;43(8):1348–1359. https://doi.org/10.1038/s41587-024-02412-y
Hera MR, Liu S, Wei W, Rodriguez JS, Ma C, Koslicki D. Metagenomic functional profiling: to sketch or not to sketch? Bioinformatics. 2024;40(Suppl 2):ii165–ii173. https://doi.org/10.1093/bioinformatics/btae397
Irber L, Pierce-Ward NT, Abuelanin M, et al. sourmash v4: A multitool to quickly search, compare, and analyze genomic and metagenomic data sets. Journal of Open Source Software. 2024;9(98):6830. https://doi.org/10.21105/joss.06830
Alcock BP, Huynh W, Chalil R, et al. CARD 2023: expanded curation, support for machine learning, and resistome prediction at the Comprehensive Antibiotic Resistance Database. Nucleic Acids Research. 2023;51(D1):D690–D699. https://doi.org/10.1093/nar/gkac920
RGI: Resistance Gene Identifier (source code and documentation). https://github.com/arpcard/rgi
CARD. Resistance Gene Identifier (RGI) web portal. https://card.mcmaster.ca/analyze/rgi
CZ ID Help Center. AMR Pipeline Workflow. https://chanzuckerberg.zendesk.com/hc/en-us/articles/15091031482644-AMR-Pipeline-Workflow