Skip to contents

This vignette walks through a complete functional profiling workflow with sra2lab: setting up an analysis directory and the conda environments, listing the SRA runs of a BioProject, profiling their KEGG Orthology (KO) content with funprofiler_runs(), and combining and comparing the profiles 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 runs are profiled taxonomically in vignette("sylph-workflow", package = "sra2lab").

fmh-funprofiler (funcprofiler) translates a metagenome’s reads into protein k-mers, sketches them with sourmash, and compares the sketch with sketches of KEGG Orthology groups (KOs) to report which KOs are present and their relative abundance. funprofiler_runs() downloads each SRA run in turn, profiles it, and deletes the reads before moving on, so only one run’s reads are on disk at a time.

Before you start

You need:

  • conda, for example Miniconda. sra2lab looks for ~/miniconda3/bin/conda by default; see ?conda_bin if yours is elsewhere.
  • A KO reference sketch. Pre-built KO sketches are at https://zenodo.org/records/10045253. This vignette uses KOs_sketched_scaled_1000.sig.zip (about 100 MB), which has protein k-mer sizes 7, 11 and 15 at scaled = 1000.
  • Internet access to NCBI, and enough disk space in the analysis directory for one run’s download, its reads, and the temporary files fasterq-dump writes while extracting them (several times the download’s size).

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 profiles go under data/, and environment specifications under methods/. By default, funprofiler_runs() looks for the KO sketch one level above the working directory, so a layout like this keeps one copy of the database for many analyses:

~/projects/
├── KOs_sketched_scaled_1000.sig.zip   <- KO reference sketch (shared)
└── PRJNA1556220/                      <- analysis directory (working directory)
    ├── data/
    │   ├── PRJNA1556220_runs.csv      <- run metadata (step 3)
    │   └── funprofiler/               <- one KO profile per run (step 4)
    └── methods/
        └── funprofiler_env.yml        <- environment specification (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

funprofiler_runs() uses two environments: sra_env (the SRA Toolkit, to download reads, and EDirect, to query NCBI) and funprofiler_env (fmh-funprofiler and its dependencies, including sourmash). Each only needs to be created once per computer:

setup_conda_funprofiler() installs the dependencies from conda and then fmh-funprofiler itself from GitHub with pip. If an environment already exists, these calls stop with an error and leave it untouched (use overwrite = TRUE to rebuild it).

Then record the exact environment used for this analysis, with every package’s version and build:

document_conda_sra(write_yml = TRUE)
document_conda_funprofiler(write_yml = TRUE)
#> Wrote methods/funprofiler_env.yml
#> name: funprofiler_env
#> channels:
#>   - conda-forge
#>   - bioconda
#>   - defaults
#> dependencies:
#>   ...
#>   - pandas=3.1.1=np2py315h5900ff1_0
#>   - python=3.15.2=h3dc335a_103_cp315
#>   - sourmash=4.9.4=hdfd78af_0
#>   ...
#>   - pip:
#>       - fmh-funprofiler==1.1.1
#>   ...

Keeping these files with the analysis lets you report the tool versions and recreate the environment later with conda env create -f methods/funprofiler_env.yml.

3. 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.9082

All 67 runs are paired-end shotgun metagenomes (library_strategy WGS), about 62 GB of reads in all. For this example, pick the two smallest runs of each swab type:

runs <- runs[order(runs$size), ]
to_profile <- do.call(rbind, lapply(split(runs, runs$isolation_source),
                                    head, 2))
rownames(to_profile) <- NULL
to_profile[, 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  493557313

To profile the whole BioProject instead, pass runs itself (or any filtered version of it) to funprofiler_runs().

4. Profile the runs with funprofiler

funprofiler_runs() takes the run table (it needs only the run_accession column) and, for each run, downloads the run with prefetch, extracts its reads with fasterq-dump, runs funcprofiler on them against the KO sketch, and writes data/funprofiler/<SRR>_k<k>_scale<scaled>_ko_profiles.csv:

res <- funprofiler_runs(to_profile,
                        database = "../KOs_sketched_scaled_1000.sig.zip",
                        k = 11, scaled = 1000, quiet = TRUE)
#> [1/8] SRR41520897: downloading (prefetch) ...
#> [1/8] SRR41520897: extracting and compressing reads (fasterq-dump) ...
#> [1/8] SRR41520897: profiling (k=11, scaled=1000) ...
#> [1/8] SRR41520897: wrote data/funprofiler/SRR41520897_k11_scale1000_ko_profiles.csv
#> [2/8] SRR41520919: downloading (prefetch) ...
#> [2/8] SRR41520919: extracting and compressing reads (fasterq-dump) ...
#> ...
#> [8/8] SRR41520884: wrote data/funprofiler/SRR41520884_k11_scale1000_ko_profiles.csv
#> Done: 8 profiled, 0 skipped, 0 failed.

res
#> # A tibble: 8 × 6
#>   run_accession     k scaled profile                                    status   message
#>   <chr>         <dbl>  <dbl> <chr>                                      <chr>    <chr>
#> 1 SRR41520897      11   1000 data/funprofiler/SRR41520897_k11_scale100… profiled <NA>
#> 2 SRR41520919      11   1000 data/funprofiler/SRR41520919_k11_scale100… profiled <NA>
#> ...

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.

The settings:

  • k is the protein k-mer size: 7, 11 or 15 (DNA k-mer sizes 21, 33 and 45). k = 11 is the setting used in the fmh-funprofiler examples.
  • scaled is the sketch’s scaled value, and must not be smaller than the database’s (1000 here). Sketches at other scaled values are at https://zenodo.org/records/10981414.
  • threshold_bp (default 1000) is the minimum estimated overlap, in base pairs, for a KO to be reported.

Several values of k or scaled give one profile per combination. Before downloading anything, funprofiler_runs() checks that the database has each requested k and that scaled is not too small, and stops with an error if not.

These 8 runs (about 4.7 GB) took about two and a half hours, mostly downloading (with a second download job running at the same time for part of it); funcprofiler itself took a few minutes per run. As with the other *_runs() functions, runs whose profile already exists are skipped, so an interrupted job can be restarted with the same call; a run that fails is reported and the rest still go ahead; and only one run’s reads are on disk at a time.

5. Combine the profiles

Each profile is a CSV file with two columns: ko_id (the KO, e.g. ko:K02004) and abundance (its relative abundance, summing to 1 across the KOs found in the sample). The file names carry the run accession, so read them all into one table and add it:

profile_files <- list.files(file.path("data", "funprofiler"),
                            pattern = "_ko_profiles[.]csv$",
                            full.names = TRUE)
length(profile_files)
#> [1] 8

kos <- do.call(rbind, lapply(profile_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     3
head(kos)
#>       ko_id    abundance run_accession
#> 1 ko:K00001 0.0004214075   SRR41520873
#> 2 ko:K00003 0.0004214075   SRR41520873
#> 3 ko:K00008 0.0008428150   SRR41520873
#> 4 ko:K00013 0.0004214075   SRR41520873
#> 5 ko:K00014 0.0004214075   SRR41520873
#> 6 ko:K00016 0.0004214075   SRR41520873

Add the run metadata, so each KO carries its sample’s swab type, and group the swabs into skin (axilla, groin) and gut (perirectal, stool) sites:

kos <- merge(kos, runs[, c("run_accession", "isolation_source",
                           "host_subject_id")],
             by = "run_accession")
kos$site <- ifelse(kos$isolation_source %in% c("Axilla Swab", "Groin Swab"),
                   "skin", "gut")

6. Inspect the profiles

How many KOs were found in each sample? The perirectal swabs, with the richest communities in the sylph profiles, have the most (about 3,700 and 4,000); the skin and stool swabs have about 1,250 to 2,100:

ko_richness <- aggregate(ko_id ~ run_accession + isolation_source,
                         data = kos, FUN = length)
names(ko_richness)[3] <- "kos_detected"
ko_richness[order(ko_richness$isolation_source), ]
#>   run_accession isolation_source kos_detected
#> 1   SRR41520897      Axilla Swab         1253
#> 2   SRR41520919      Axilla Swab         1689
#> 3   SRR41520873       Groin Swab         1246
#> 4   SRR41520874       Groin Swab         1566
#> 5   SRR41520878  Perirectal Swab         3690
#> 6   SRR41520882  Perirectal Swab         4034
#> 7   SRR41520884       Stool Swab         1321
#> 8   SRR41520894       Stool Swab         2066

For comparisons between samples, reshape the profiles into a runs × KOs matrix, with 0 for KOs not found in a run:

ko_matrix <- unclass(xtabs(abundance ~ run_accession + ko_id, data = kos))
dim(ko_matrix)
#> [1]    8 5398
site <- ifelse(to_profile$isolation_source[match(rownames(ko_matrix),
                                                 to_profile$run_accession)]
               %in% c("Axilla Swab", "Groin Swab"), "skin", "gut")

How many KOs are shared by every sample, and how many are found only in skin or only in gut samples?

present <- ko_matrix > 0
c(all_samples = sum(colSums(present) == nrow(present)),
  skin_only = sum(colSums(present[site == "skin", ]) > 0 &
                    colSums(present[site == "gut", ]) == 0),
  gut_only = sum(colSums(present[site == "gut", ]) > 0 &
                   colSums(present[site == "skin", ]) == 0))
#> all_samples   skin_only    gut_only 
#>         286         673        2511

Comparing samples

Bray–Curtis dissimilarity compares two samples’ KO abundances: 0 when they are identical, 1 when they share no KOs. Because each profile sums to 1, it is half the sum of absolute differences:

bray <- as.matrix(dist(ko_matrix, method = "manhattan")) / 2
round(bray, 2)
#>             SRR41520873 SRR41520874 SRR41520878 SRR41520882 SRR41520884
#> SRR41520873        0.00        0.46        0.56        0.56        0.59
#> SRR41520874        0.46        0.00        0.51        0.50        0.55
#> SRR41520878        0.56        0.51        0.00        0.15        0.49
#> SRR41520882        0.56        0.50        0.15        0.00        0.50
#> SRR41520884        0.59        0.55        0.49        0.50        0.00
#> SRR41520894        0.63        0.51        0.46        0.46        0.53
#> SRR41520897        0.44        0.44        0.56        0.57        0.61
#> SRR41520919        0.43        0.52        0.64        0.64        0.69
#>             SRR41520894 SRR41520897 SRR41520919
#> SRR41520873        0.63        0.44        0.43
#> SRR41520874        0.51        0.44        0.52
#> SRR41520878        0.46        0.56        0.64
#> SRR41520882        0.46        0.57        0.64
#> SRR41520884        0.53        0.61        0.69
#> SRR41520894        0.00        0.63        0.70
#> SRR41520897        0.63        0.00        0.53
#> SRR41520919        0.70        0.53        0.00

A principal coordinates analysis (PCoA) places the samples so that their distances reflect these dissimilarities:

pcoa <- cmdscale(as.dist(bray), k = 2, eig = TRUE)
explained <- round(100 * pcoa$eig[1:2] / sum(pcoa$eig[pcoa$eig > 0]))
swab <- to_profile$isolation_source[match(rownames(ko_matrix),
                                          to_profile$run_accession)]
swab_types <- sort(unique(swab))
cols <- hcl.colors(4, "Dark 3")[match(swab, swab_types)]

# label above each point, or below one that nearly overlaps another
near <- as.matrix(dist(pcoa$points)) < 0.05 & lower.tri(diag(nrow(bray)))
label_pos <- ifelse(rowSums(near) > 0, 1, 3)

plot(pcoa$points, col = cols, pch = 19, cex = 1.5,
     xlim = range(pcoa$points[, 1]) + c(-0.06, 0.06),
     ylim = range(pcoa$points[, 2]) + c(-0.08, 0.08),
     xlab = paste0("PCoA 1 (", explained[1], "%)"),
     ylab = paste0("PCoA 2 (", explained[2], "%)"))
text(pcoa$points, labels = rownames(pcoa$points), pos = label_pos,
     cex = 0.6)
legend("bottomright", legend = swab_types, col = hcl.colors(4, "Dark 3"),
       pch = 19, bty = "n", cex = 0.8)

PCoA of Bray-Curtis dissimilarities between KO profiles; skin samples separate from gut samples along the first axis.

The first axis separates the skin swabs from the gut swabs. The two perirectal swabs, both from subject GOL_017, are functionally almost identical (Bray–Curtis 0.15), while the two stool swabs differ more.

KOs that differ between sites

Which KOs differ most in mean relative abundance between skin and gut samples?

mean_skin <- colMeans(ko_matrix[site == "skin", ])
mean_gut <- colMeans(ko_matrix[site == "gut", ])
difference <- mean_skin - mean_gut

site_kos <- data.frame(
  ko_id = names(difference),
  mean_skin = signif(mean_skin, 2),
  mean_gut = signif(mean_gut, 2),
  row.names = NULL
)
higher_in_skin <- head(site_kos[order(difference, decreasing = TRUE), ], 5)
higher_in_gut <- head(site_kos[order(difference), ], 5)
higher_in_skin
#>          ko_id mean_skin mean_gut
#> 2111 ko:K05020    0.0025  5.4e-05
#> 2157 ko:K05565    0.0023  8.2e-05
#> 1830 ko:K03657    0.0046  2.5e-03
#> 4000 ko:K14195    0.0022  2.4e-04
#> 4488 ko:K17686    0.0027  7.3e-04
higher_in_gut
#>          ko_id mean_skin mean_gut
#> 5033 ko:K21572   0.00110   0.0046
#> 5034 ko:K21573   0.00036   0.0032
#> 550  ko:K01190   0.00099   0.0038
#> 992  ko:K02014   0.00039   0.0026
#> 2127 ko:K05349   0.00039   0.0024

With 4 samples per site this is only a description; a real comparison would use more samples and a statistical test suited to compositional data.

Naming the KOs

The profiles give KO IDs only. KEGG’s REST API returns their names. The API is free for academic use (see https://www.kegg.jp/kegg/rest/), and needs internet access, so it is not run here:

# KEGG names for a vector of KO IDs (e.g. "ko:K05020"), 10 per request
kegg_names <- function(ko_ids) {
  batches <- split(ko_ids, ceiling(seq_along(ko_ids) / 10))
  named <- do.call(rbind, lapply(batches, function(ids) {
    url <- paste0("https://rest.kegg.jp/list/", paste(ids, collapse = "+"))
    batch <- read.delim(url, header = FALSE, col.names = c("ko", "name"),
                        quote = "")
    data.frame(ko_id = paste0("ko:", batch$ko), name = batch$name)
  }))
  rownames(named) <- NULL
  named
}

kegg_names(c(higher_in_skin$ko_id, higher_in_gut$ko_id))
#>        ko_id                                                        name
#> 1  ko:K05020                 opuD, betL; glycine betaine transporter
#> 2  ko:K05565        mnhA, mrpA; multicomponent Na+:H+ antiporter subunit A
#> 3  ko:K03657   uvrD, pcrA, SRS2; ATP-dependent DNA helicase UvrD/PcrA/SRS2 [EC:5.6.2.4]
#> 4  ko:K14195                                       sasG; surface protein G
#> 5  ko:K17686          copA, ctpA, ATP7; P-type Cu+ transporter [EC:7.2.2.8]
#> 6  ko:K21572  susD; starch-binding outer membrane protein, SusD/RagB family
#> 7  ko:K21573  susC; TonB-dependent starch-binding outer membrane protein SusC
#> 8  ko:K01190                    lacZ; beta-galactosidase [EC:3.2.1.23]
#> 9  ko:K02014           TC.FEV.OM; iron complex outermembrane recepter protein
#> 10 ko:K05349                     bglX; beta-glucosidase [EC:3.2.1.21]

The skin-enriched KOs fit the Staphylococcus-dominated skin communities seen in the sylph vignette: a glycine betaine transporter (osmoprotection on salty skin), a Na+/H+ antiporter, and the staphylococcal surface protein SasG. The gut-enriched KOs include the SusC/SusD starch-binding proteins of Bacteroides and enzymes that break down dietary sugars (beta-galactosidase, beta-glucosidase).

Next steps

  • Profile the rest of the BioProject with funprofiler_runs(runs); already profiled runs are skipped.
  • Profile reads you already have on disk with funprofiler_local(), which finds each specimen’s R1 and R2 files by specimen ID.
  • Get taxonomic profiles or sourmash signatures from the same downloads with multiprocess_runs(), e.g. multiprocess_runs(runs, process_path = c("sylph", "funprofiler")).
  • For other formats, the fmh-funprofiler documentation shows how to convert a KO profile to BIOM format with biom convert.

References

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