Comparing sketches across subjects, sources and time
Source:vignettes/smash-compare.Rmd
smash-compare.RmdThe point of a sketch is comparison. Two sketches that share most of their hashes come from similar sequence: at k = 31, genomes of the same species, or similar communities; at k = 51, the same strain. Comparing every pair of samples in a study, and asking which pairs are more alike than expected, is how sketches point to persistence within a subject and to transmission between subjects.
sourmash compare does this from the command line.
smash2lab does it in R: smash_compare() computes the same
similarities from the hashes that smash_aggregate() read,
so sourmash is not needed to compare sketches, only to
make them. If you prefer sourmash’s own numbers, or already have its
output, smash_read_compare() reads them (below). Either way,
smash_compare_plot() plots the comparisons.
Files you need
smash2lab works on files you already have: sourmash signatures (usually made with sra2lab) and the samples’ metadata. Unlike taxonomic or functional profiles, sketches need no reference database to read, combine or compare. A typical analysis directory looks like this:
~/projects/
└── PRJNA1556220/ <- analysis directory (working directory)
└── data/
├── PRJNA1556220_runs.csv <- run metadata
└── smash/ <- one .sig per run and sketch setting
├── SRR41520862_k31_scale1000_seed42_abund.sig
├── SRR41520862_k51_scale1000_seed42_abund.sig
└── ...
The signatures come from
sra2lab::smash_runs(), smash_stream(),
smash_local() or multiprocess_runs(), which
run sourmash sketch dna in sra2lab’s smash_env
conda environment (made by
sra2lab::setup_conda_sourmash()). They write one
<id>_k<k>_scale<scaled>_seed<seed>_<method>.sig
per sample and setting:
runs <- sra2lab::get_bioproject_runs("PRJNA1556220")
write.csv(runs, "data/PRJNA1556220_runs.csv", row.names = FALSE)
# k = 31 for species-level comparisons, k = 51 for strains
sra2lab::smash_runs(runs, k = c(31, 51), scaled = 1000, method = "abund")Any other sourmash signature files work too (.sig,
.sig.gz or .zip collections, e.g. from
sourmash sketch run by hand), as long as they hold
FracMinHash (scaled) sketches. smash2lab reads them in R;
sourmash is needed only to make them, and optionally to compare them
(see vignette("smash-compare")).
Run metadata: isolates and metagenomes.
sra2lab::get_bioproject_runs() returns one row per SRA run,
with the BioSample attributes the submitters gave. Its columns depend on
the BioSample package the BioProject used, the two packages that lv2sra prepares submissions
for:
| BioSample package | BioSampleModel |
What was sequenced | Key attributes |
|---|---|---|---|
| Metagenome or environmental | Metagenome or environmental |
a specimen’s whole microbial community |
organism (a metagenome type, e.g. “human gut
metagenome”), isolation_source,
host_subject_id, collection_date
|
| Microbe | Microbe, viral or environmental |
a cultured isolate |
organism (the isolate’s species, e.g. “Klebsiella
pneumoniae”), isolate or strain,
isolation_source (the specimen it was cultured from),
host_subject_id, collection_date
|
smash_aggregate() uses these to record, for every
sketch, whether it is of an isolate or a metagenome, its source, and for
an isolate its species. For local reads sketched with
sra2lab::smash_local(), use your own specimen table
instead, with one row per specimen ID.
The example data
smash2lab ships sourmash signatures of 18 runs from BioProject PRJNA1556220,
“Microbiome changes in the peri-heart transplant setting”: skin, stool
and perirectal swab metagenomes from 7 subjects, five of whom have two
to six samples. They are the same runs as the example data of sylph2lab, funprofiler2lab and
rgi2lab. The runs were
sketched with sra2lab::smash_stream() at k = 31 and k = 51
(scaled = 1000, seed = 42, with abundances). To keep the package small,
the shipped sketches keep only k-mers seen at least twice and are
downsampled to scaled = 10000; that is, they are what
smash_aggregate(min_abundance = 2, downsample = 10000)
would make of the originals, and are named for their parameters (e.g.
SRR41520862_k31_scale10000_seed42_abund.sig.gz). The
package also ships the run table for all 67 runs of the BioProject.
smash_example() gives their paths, which stand in for
data/smash and data/PRJNA1556220_runs.csv
below.
The isolate example data
smash2lab also ships sourmash signatures of 30 cultured bacterial
isolates from BioProject PRJNA1570337,
“Bacterial isolates from human subjects with a history of MDRO infection
and their healthcare environment”, and the run table of all 239 of its
runs, all Microbe BioSamples. The 30 isolates are of six species, from
five subjects: from each subject’s throat, stool and perirectal swabs,
from environmental swabs linked to the subject
(environmental swab), and, for four subjects, the isolate
recorded with the source Bacterial Cell Iso, collected
before the others. They were sketched with
sra2lab::smash_stream() at k = 31 and k = 51, with scaled =
100 to resolve strains (seed = 42, with abundances); the shipped
sketches are filtered and downsampled as described in
vignette("smash-aggregate").
smash_example("isolates") and
smash_example("isolate_runs") give their paths.
Some examples also use small made-up tables, marked as such, to show isolates and metagenomes side by side.
Compare every pair of samples
Comparisons need one sketch per sample, all with the same k-mer size,
so choose a setting in smash_aggregate(). For sketches of
reads, drop the k-mers of sequencing errors with
min_abundance (see
vignette("smash-aggregate")); the example sketches already
are.
library(smash2lab)
sketches <- smash_aggregate(smash_example("signatures"),
metadata = smash_example("runs"), k = 31)
cmp <- smash_compare(sketches)
cmp
#> # A tibble: 306 × 24
#> sample_1 sample_2 n_hashes_1 n_hashes_2 n_shared jaccard containment
#> <chr> <chr> <int> <int> <dbl> <dbl> <dbl>
#> 1 SRR41520862 SRR41520863 15752 10090 1423 0.0583 0.0903
#> 2 SRR41520862 SRR41520865 15752 13620 2077 0.0761 0.132
#> 3 SRR41520862 SRR41520867 15752 14592 1579 0.0549 0.100
#> 4 SRR41520862 SRR41520868 15752 12638 5720 0.252 0.363
#> 5 SRR41520862 SRR41520869 15752 12422 1260 0.0468 0.0800
#> 6 SRR41520862 SRR41520870 15752 4485 553 0.0281 0.0351
#> 7 SRR41520862 SRR41520873 15752 1806 10 0.000570 0.000635
#> 8 SRR41520862 SRR41520874 15752 1579 28 0.00162 0.00178
#> 9 SRR41520862 SRR41520876 15752 15637 1575 0.0528 0.1000
#> 10 SRR41520862 SRR41520878 15752 7538 1129 0.0509 0.0717
#> # ℹ 296 more rows
#> # ℹ 17 more variables: max_containment <dbl>, avg_containment <dbl>,
#> # angular_similarity <dbl>, jaccard_ani <dbl>, containment_ani <dbl>,
#> # max_containment_ani <dbl>, avg_containment_ani <dbl>, sample_type_1 <chr>,
#> # sample_type_2 <chr>, species_1 <chr>, species_2 <chr>,
#> # sample_source_1 <chr>, sample_source_2 <chr>, host_subject_id_1 <chr>,
#> # host_subject_id_2 <chr>, collection_date_1 <date>, …There is one row per ordered pair of samples, so each pair
appears twice (sample_1–sample_2 and
sample_2–sample_1), and the samples’ subject,
date, type, species and source are carried along with the suffixes
_1 and _2. The similarities are those of
sourmash compare:
| Column | sourmash compare |
Meaning |
|---|---|---|
jaccard |
--ignore-abundance |
shared hashes / all hashes of the two |
angular_similarity |
(default, with abundances) | similarity of the k-mer abundance profiles |
containment |
--containment |
fraction of sample_1’s hashes found in
sample_2
|
max_containment, avg_containment
|
--max-containment, --avg-containment
|
the larger, or the mean, of the two containments |
jaccard_ani, containment_ani,
max_containment_ani, avg_containment_ani
|
with --ani
|
the average nucleotide identity (ANI) estimated from each |
n_shared is the number of hashes in common, and
n_hashes_1 and n_hashes_2 the sizes of the two
sketches.
Comparisons are computed with a sparse matrix of hashes, so thousands
of isolate sketches compare in seconds. Large metagenome sketches are
slower: downsample in smash_aggregate() makes
them smaller.
Which similarity?
-
Metagenomes:
angular_similarity(which weighs each k-mer by its abundance, so dominant organisms count most) orjaccard(presence only, so rare organisms count as much as dominant ones). Containment of one metagenome in another is rarely useful, because each holds many k-mers of its own. -
Isolates: an ANI estimate. Isolates of the same
species typically share 95% ANI or more, and of the same strain 99.5% or
more (99.9% or more for recent transmission).
max_containment_aniis robust to differences in genome size, such as plasmids carried by one isolate only. Strain-level comparisons are best at k = 51, with isolates sketched at a smallscaled(e.g. 100), so that each sketch holds thousands of hashes. -
An isolate against a metagenome:
containmentof the isolate in the metagenome (sample_1the isolate,sample_2the metagenome), the fraction of the isolate’s genome found in the community.
A matrix of similarities
The default plot is a samples x samples matrix. With
subject, the samples are grouped into blocks by subject,
and ordered by time within them, so comparisons within a
subject sit on the diagonal blocks:
smash_compare_plot(cmp, "angular_similarity", subject = "host_subject_id",
time = "collection_date")
smash_compare_matrix() gives the same as a plain matrix,
laid out as sourmash compare lays it out, e.g. for
clustering:
m <- smash_compare_matrix(cmp, "angular_similarity")
round(m[1:4, 1:4], 3)
#> SRR41520862 SRR41520863 SRR41520865 SRR41520867
#> SRR41520862 1.000 0.106 0.087 0.184
#> SRR41520863 0.106 1.000 0.278 0.144
#> SRR41520865 0.087 0.278 1.000 0.116
#> SRR41520867 0.184 0.144 0.116 1.000
plot(hclust(as.dist(1 - m), method = "average"), xlab = "", sub = "",
main = "Angular distance, average linkage")
Within and between subjects
type = "distribution" plots the similarity of every pair
of samples as a histogram, split into pairs from the same subject and
pairs from different subjects, with the median of each. If samples from
the same subject are more alike than samples from different subjects,
the two distributions separate:
smash_compare_plot(cmp, "angular_similarity", type = "distribution",
subject = "host_subject_id")
Here pairs of samples from the same subject have a median angular similarity of about 0.22, against 0.05 for pairs from different subjects: each subject’s microbiome is, at the level of 31-mers, largely its own.
group compares like with like: a panel for each group,
using only pairs of samples from the same group. For metagenomes, the
source (a stool swab is best compared with other stool swabs); for
isolates, the species, so that same-strain pairs stand out against the
background of same-species pairs:
smash_compare_plot(cmp, "angular_similarity", type = "distribution",
subject = "host_subject_id", group = "sample_source")
The dashed line is the threshold (by default the 95th
percentile of the similarity, or 0.995 for ANI estimates); set it to a
value that means something for your question, such as a strain-level ANI
cutoff.
Ordination
type = "ordination" places the samples by a principal
coordinates analysis (PCoA) of the distances 1 - similarity, coloured by
subject. Samples from the same subject that sit together share more of
their k-mers than with other subjects’ samples:
smash_compare_plot(cmp, "angular_similarity", type = "ordination",
subject = "host_subject_id", shape = "sample_source")
With group, each group gets its own ordination, in its
own panel; for isolates, group = "species" gives one PCoA
per species, as in a figure of within-species strain structure.
A network of similar pairs
type = "network" joins samples whose similarity is at
least threshold: candidate shared strains, or transmission
events. By default samples are placed by the PCoA, but the most similar
samples then sit almost on top of one another, hiding the lines between
them; layout = "circle" spreads them out:
smash_compare_plot(cmp, "angular_similarity", type = "network",
subject = "host_subject_id", shape = "sample_source",
layout = "circle")
#> Joining samples with angular_similarity >= 0.74 (set `threshold` to change).
Of the eight pairs joined here, two are GOL_017’s own stool and
perirectal swabs, but four are skin (groin and axilla) swabs from
different subjects, and two join skin swabs to a small perirectal
sketch. The skin swabs have the smallest sketches (under 2,500 hashes at
this scaled), and look alike across subjects in their
abundance profiles: a reminder to compare like with like
(group), and to read high similarity between low-biomass
samples with care.
For the directional containment and
containment_ani, arrows point from each sample to the
samples it is contained in: from an isolate to the metagenomes that hold
its genome, for example.
Isolates, strains and transmission
For a study of isolates, the same steps answer the transmission
question. With a run table of a Microbe BioProject,
smash_aggregate() gives each isolate its species, and a
typical analysis is:
isolates <- smash_aggregate("data/smash", metadata = "data/runs.csv",
k = 51, min_abundance = 3)
cmp <- smash_compare(isolates)
# same-strain pairs: ANI of 99.5% or more
strain_pairs <- cmp[cmp$species_1 == cmp$species_2 &
cmp$max_containment_ani >= 0.995 &
cmp$sample_1 < cmp$sample_2, ]
# within-species distributions: same subject versus different subjects
smash_compare_plot(cmp, "max_containment_ani", type = "distribution",
subject = "host_subject_id", group = "species",
threshold = 0.995)
# one PCoA per species, coloured by subject
smash_compare_plot(cmp, "jaccard", type = "ordination",
subject = "host_subject_id", group = "species")
# candidate transmission: isolates joined at strain-level ANI
smash_compare_plot(cmp, "max_containment_ani", type = "network",
subject = "host_subject_id", shape = "species",
threshold = 0.995, sample_label = "sample_source")Pairs from different subjects above the strain threshold are the
candidate transmissions; check their dates
(collection_date_1, collection_date_2) and
sources against smash_timeline()
(vignette("smash-timeline")), and their shared hashes with
smash_heatmap()
(vignette("smash-heatmap")).
The isolate example data
Here are those steps on the isolate example data: 30 isolates of six
species from five subjects, sketched at k = 51 and cleaned of sequencing
errors (see vignette("smash-aggregate")):
isolates <- smash_aggregate(smash_example("isolates"),
metadata = smash_example("isolate_runs"), k = 51)
iso_cmp <- smash_compare(isolates)
# each pair once, isolates of the same species
same_species <- iso_cmp[iso_cmp$species_1 == iso_cmp$species_2 &
iso_cmp$sample_1 < iso_cmp$sample_2, ]
same_species$same_subject <-
same_species$host_subject_id_1 == same_species$host_subject_id_2
aggregate(max_containment_ani ~ species_1 + same_subject, same_species,
function(x) round(c(pairs = length(x), min = min(x),
median = median(x), max = max(x)), 4))
#> species_1 same_subject max_containment_ani.pairs
#> 1 Enterococcus faecium FALSE 40.0000
#> 2 Pseudomonas aeruginosa FALSE 3.0000
#> 3 Staphylococcus aureus FALSE 16.0000
#> 4 Enterococcus faecium TRUE 38.0000
#> 5 Klebsiella aerogenes TRUE 6.0000
#> 6 Pseudomonas aeruginosa TRUE 3.0000
#> 7 Staphylococcus aureus TRUE 12.0000
#> max_containment_ani.min max_containment_ani.median max_containment_ani.max
#> 1 0.9941 0.9952 0.9965
#> 2 0.9940 0.9940 0.9946
#> 3 0.9981 0.9982 0.9988
#> 4 0.9959 0.9991 0.9999
#> 5 0.9998 0.9998 0.9999
#> 6 0.9999 1.0000 1.0000
#> 7 0.9993 0.9996 0.9999Isolates of different species are far apart (ANI below 0.91, so not in the table). Within a species, pairs from the same subject have ANI of 0.999 or more: all of them for Klebsiella aerogenes, Pseudomonas aeruginosa and Staphylococcus aureus, and most for Enterococcus faecium (the exceptions are below). But pairs from different subjects are close too: Staphylococcus aureus from P008 and P027 at 0.998, and Enterococcus faecium from P007 and P011 at 0.994 to 0.997, as expected of hospital-adapted lineages. A cutoff of 0.995 would call many of them the same strain; in these data, 0.999 separates the pairs within subjects from those between them. The distributions show this, per species:
smash_compare_plot(iso_cmp, "max_containment_ani", type = "distribution",
subject = "host_subject_id", group = "species",
threshold = 0.999)
Choose a strain threshold from such distributions, for each species, rather than from a rule of thumb. The network joins isolates at that threshold, labelled by source:
smash_compare_plot(iso_cmp, "max_containment_ani", type = "network",
subject = "host_subject_id", shape = "species",
threshold = 0.999, layout = "circle",
sample_label = "sample_source")
strain_pairs <- same_species[same_species$max_containment_ani >= 0.999, ]
table(strain_pairs$host_subject_id_1, strain_pairs$species_1)
#>
#> Enterococcus faecium Klebsiella aerogenes Pseudomonas aeruginosa
#> P005 0 6 0
#> P007 18 0 3
#> P008 0 0 0
#> P011 6 0 0
#> P027 0 0 0
#>
#> Staphylococcus aureus
#> P005 0
#> P007 0
#> P008 6
#> P011 0
#> P027 6All 45 pairs at 0.999 or more are within a subject, so these isolates show no transmission between the five subjects. Within subjects, they show spread to the environment. P007’s Enterococcus faecium from the first isolate, from the subject’s throat, perirectal and stool swabs, and from environmental swabs over two weeks in November, are one strain (ANI of 0.9989 or more between every pair, 18 of the 21 pairs at 0.999 or more); the subject’s stool isolate three months later is not (ANI of at most 0.997 to any other isolate), a different strain, about as far from P007’s earlier isolates as from P011’s. P011’s throat isolate, too, is a little apart from the subject’s other four (ANI of 0.998 to 0.999):
feb <- iso_cmp[iso_cmp$sample_1 == "SRR42080285" &
iso_cmp$species_2 == "Enterococcus faecium", ]
head(feb[order(-feb$max_containment_ani),
c("sample_2", "host_subject_id_2", "sample_source_2",
"collection_date_2", "max_containment_ani")])
#> # A tibble: 6 × 5
#> sample_2 host_subject_id_2 sample_source_2 collection_date_2
#> <chr> <chr> <chr> <date>
#> 1 SRR42080207 P011 Bacterial Cell Iso 2025-02-20
#> 2 SRR42080279 P011 throat swab 2025-03-04
#> 3 SRR42080290 P007 environmental swab 2024-11-10
#> 4 SRR42080287 P007 throat swab 2024-11-14
#> 5 SRR42080293 P007 Perirectal Swab 2024-11-08
#> 6 SRR42080266 P007 environmental swab 2024-11-16
#> # ℹ 1 more variable: max_containment_ani <dbl>vignette("smash-heatmap") shows the hashes that tell
these strains apart.
Using sourmash compare
If you prefer sourmash compare itself, run it in the
smash_env conda environment that sra2lab made for sketching
(sra2lab::setup_conda_sourmash()), from R with
system2(), and read its CSV with
smash_read_compare(). This chunk runs only where sra2lab
and its smash_env are installed:
conda <- sra2lab::conda_bin()
sigs <- list.files(smash_example("signatures"), pattern = "_k31_",
full.names = TRUE)
out <- tempfile(fileext = ".csv")
system2(conda, c("run", "-n", "smash_env",
"sourmash", "-q", "compare", "-k", "31",
"--ignore-abundance", "--csv", out, sigs),
stdout = FALSE, stderr = FALSE) # drop sourmash's progress output
sm <- smash_read_compare(out, metric = "jaccard", data = sketches)
smdata matches sourmash’s signature names to the samples,
and carries their metadata along, so sm plots exactly like
cmp. The two agree to machine precision:
both <- merge(sm, cmp[, c("sample_1", "sample_2", "jaccard")],
by = c("sample_1", "sample_2"), suffixes = c("_sourmash", "_r"))
max(abs(both$jaccard_sourmash - both$jaccard_r))Other options of sourmash compare map to
metric as in the table above: drop
--ignore-abundance for "angular_similarity",
use --containment for "containment" (or
--max-containment, --avg-containment), and add
--ani for the ANI estimates
("containment_ani", …). For --distance-matrix
output, add distance = TRUE.
Customising and saving
All plots are ggplots, with the plotted values in their
data element:
p <- smash_compare_plot(cmp, "angular_similarity", type = "ordination",
subject = "host_subject_id")
ggplot2::ggsave("figs/pcoa_k31.pdf", p, width = 7, height = 5)
# the comparisons themselves
readr::write_csv(cmp, "data/smash_compare_k31.csv")