Package 'strainspy'

Title: Strain Level Microbiome Wide Association Studies
Description: Fits statistical models to detect microbial strains associated with a phenotype. For small sample sizes, models can be fitted using empirical Bayes maximum a posteriori (MAP) priors to improve detection power. Supports various experimental design scenarios, including repeated measures.
Authors: Gerry Tonkin-Hill [aut], Sudaraka Mallawarachchi [aut, cre] (ORCID: <https://orcid.org/0000-0001-8899-3323>)
Maintainer: Sudaraka Mallawarachchi <[email protected]>
License: MIT + file LICENSE
Version: 0.99.0
Built: 2026-09-16 10:57:09 UTC
Source: https://github.com/BiocStaging/strainspy

Help Index


abundanceFit

Description

This function fits a linear regression model using stats::lm() or lmerTest::lmer(). The latter is used for models with random effects. It takes a SummarizedExperiment object as input, along with a user-defined formula, and fits a linear model on the assay data.

Usage

abundanceFit(
  se,
  design,
  nthreads = 1,
  scale_continuous = TRUE,
  transform = NULL,
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

design

Formula. A formula to specify the fixed and random effects, e.g., ~ Group + (1|Sample).

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

scale_continuous

Logical. If TRUE, all numeric columns in colData(se) are z-score standardized (mean = 0, SD = 1). Defaults to TRUE.

transform

If data is already transformed, set to NULL (default). Supported options: arcsin transform arcsin or centered log ratio CLR. CLR requires compositions package.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Details

Generally, these linear models are useful to model compositional abundance data (e.g. Taxonomic_abundance in Sylph Profile) with appropriate transforms.

Value

A strainspy_fit object with the following components:

row_data

A DFrame with 6 slots with feature details

coefficients

A DFrame with coefficients for each feature

std_errors

A DFrame of standard errors for each feature

p_values

A DFrame of p-values for each feature

residuals

A DFrame of residual vectors for each feature

convergence

A named logical vector indicating convergence for each feature

design

Formula used in the call to abundanceFit

call

Call to abundanceFit

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")

se <- read_sylph(example_path, example_meta, 'Taxonomic_abundance')
se <- filter_by_presence(se, 20)

design <- as.formula(" ~ Case_status + Age_at_collection")
fit <- abundanceFit(se[1:10,],  design, nthreads=2, transform='CLR')
top_hits(fit, alpha = 0.5)

ani_distance

Description

This function calculates the distance between samples in a SummarizedExperiment object representing strain level ANI data.

Usage

ani_distance(
  se,
  taxonomy = NULL,
  tax_level = "Species",
  collapse_method = "representative"
)

Arguments

se

A SummarizedExperiment object.

taxonomy

An optional data.frame object containing the taxonomy information for the samples in se. The result of running read_taxonomy on the taxonomy file associated with the ANI data. If provided, the ANI values will be collapsed at the specified taxonomic level before calculating the distance matrix. (default=NULL)

tax_level

A character string specifying the taxonomic level at which to collapse the ANI values. (default="Species")

collapse_method

A character string specifying the method to use to collapse the ANI values. Must be one of 'representative', 'mean' or 'max'. (default='representative')

Value

A distance matrix.

Examples

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
tax_path <- system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path)
tax <- read_taxonomy(tax_path)
distance_matrix <- ani_distance(se)

caseControlFit

Description

This function fits a logistic regression model similar to that published in the original Sylph paper. It takes a SummarizedExperiment object as input, along with a user-defined formula.

Usage

caseControlFit(
  se,
  design,
  min_identity = 0.98,
  nthreads = 1,
  scale_continuous = TRUE,
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

design

Formula. A formula to specify the fixed and random effects, e.g., Outcome ~ Value + Covariate + (1|Sample).

min_identity

A numeric value specifying the minimum identity threshold to consider (default=0.98).

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

scale_continuous

Logical. If TRUE, all numeric columns in colData(se) are z-score standardized (mean = 0, SD = 1). Defaults to FALSE.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Value

A strainspy_fit object with the following components:

row_data

A DFrame with 6 slots with feature details

coefficients

A DFrame with coefficients for each feature

std_errors

A DFrame of standard errors for each feature

p_values

A DFrame of p-values for each feature

residuals

A DFrame of residual vectors for each feature

convergence

A named logical vector indicating convergence for each feature

design

Formula used in the call to caseControlFit

call

Call to caseControlFit

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_meta$Case_status <- factor(example_meta$Case_status)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
se <- filter_by_presence(se)

design <- as.formula("Case_status ~ Value + Age_at_collection")

fit <- caseControlFit(se[1:10,], design, nthreads=2)

Validate a progress argument

Description

Internal helper used by the fitting functions to check that progress is a single, non-missing logical value.

Usage

check_progress(progress)

Arguments

progress

The value supplied to a progress argument.

Value

progress, invisibly.


Stop if sample or feature names are not unique

Description

read_sylph(), read_metaphlan() and read_sourmash() all reduce Sample_file to a bare basename when clean_names = TRUE. Two input paths that differ only by directory (runA/S1.fastq.gz and runB/S1.fastq.gz) therefore collapse to the same name. Duplicated names are not rejected by SummarizedExperiment, and every downstream match() on sample or feature names would then silently attach the wrong metadata to the wrong column, so fail here instead.

Usage

check_unique_names(x, what, clean_names = FALSE)

Arguments

x

Character vector of names to check.

what

Character. What the names identify, used in the error message (for example "sample" or "feature").

clean_names

Logical. Whether the caller applied basename cleaning; used only to tailor the suggested remedy.

Value

x, invisibly, if every name is unique.


Automatically clean contig names for plots

Description

Automatically clean contig names for plots

Usage

clean_contig_names(contig_names, max_length = 50, return_map = FALSE)

Arguments

contig_names

Vector of contig names. These will be cleaned up. This function usually works with long sylph contigs, such as those given by top_hits(fit_ANI)$Contig_name

max_length

Numeric. Number of characters to keep (default 50)

return_map

bool. Return data.frame of original and shortened contig names for mapping

Value

A data.frame or original and shortened names, or a vector of shortened name in the same order


Compute the mean ANI differences for contigs with an identity effect and perform posthoc testing to establish support for each hit.

Description

In the zero-inflated beta model, beta effects represent changes in strain identity and are modeled on the logit scale. While this scale is effective for distinguishing phenotype groups statistically, the resulting effect sizes are not directly interpretable as differences in mean ANI. Same applies for effect sizes from the ordinal beta model.

Usage

comp_ani_diff_and_posthoc_test(
  se,
  fit,
  th = NULL,
  simplified_formula = NULL,
  beta_min_nz = 0.1,
  beta_min_ani_diff = 0.015,
  nthreads = 1L,
  reorder_hits = FALSE,
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing assay data and metadata

fit

A fitted strainspy_fitmodel

th

tibble returned by top_hits().

simplified_formula

A formula to use instead of fit@design, useful when the original design was too complex and causes emmeans to fail during ANI estimation (default NULL).

beta_min_nz

Minimum non-zero proportion per phenotype group required to consider a beta hit is well supported. Hits driven by a proportion of non zero values below this threshold at least in one phenotype group are flagged ⁠too few nonzero⁠. Default 0.1. Hits driven by less than or equal to 3 observations will be flagged automatically ⁠<3 nonzero⁠.

beta_min_ani_diff

Minimum absolute mean ANI difference required for a beta hit to be considered meaningful. Effect sizes small than this are flagged: ⁠small effect⁠. Default = 1.5e-3 corresponds to 0.15% delta ANI.

nthreads

Number of threads for parallel processing. Default 1.

reorder_hits

Logical. Return th after reordering hits to priorities best supported ones. Default FALSE.

BPPARAM

Optional BiocParallelParam object.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Details

This function converts logit-scale beta effects into response-scale mean ANI differences using marginal means and pairwise contrasts (requires emmeans). It therefore provides an interpretable estimate of the magnitude of strain-level differences between phenotype groups, along with post hoc quality checks for poorly supported beta signals.

Posthoc testing uses two approaches. First, it counts the number of non-zero observations supporting each beta effect. Second, it compares the estimated mean ANI difference against a preset threshold. A comment is added to each hit depending on the outcome.

By default, this function uses the formula from fit@design. However, if the formula contains multiple covariates, this can cause emmeans to behave unexpectedly. For example, if fit@design = ~ disease + age + sex + country + (1|study), this can cause this function to throw errors or warnings. Using a simplified_formula = ~ disease to override can be a useful approach.

This function is designed to directly work on the tibble returned from top_hits().

Value

A tibble similar to th, with added columns giving details on: Component (Beta, ZI or both), Mean ANI_Difference, Contrast, Non-Zero Counts of contrast components, and a general Comment on each hit. The commetn will be NA if the hit passes all posthoc tests.

Examples

if (requireNamespace("emmeans", quietly = TRUE)) {
  meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
  package = "strainspy"))
  meta$Case_status <- factor(meta$Case_status)
  se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
  package = "strainspy"), meta_data = meta)
  se <- filter_by_presence(se, min_nonzero = 30)[1:10, ]
  fit <- glmZiBFit(se, ~ Case_status + Age_at_collection, nthreads = 1)
  th <- top_hits(fit, coef = 2, alpha = 1)
  posthoc <- comp_ani_diff_and_posthoc_test(se, fit, th, nthreads = 1)
  head(posthoc$ANI_Difference)
}

Constructor for strainspy_priors using empirical Bayes estimation

Description

Fits fast binomial and beta models to estimate MAP prior SDs for use in zero-inflated and ordinal beta models fitted using GLMMTMB.

Usage

compute_eb_priors(
  se,
  design,
  nthreads = 1L,
  BPPARAM = NULL,
  low_cutoff = 0.1,
  high_cutoff = 10,
  est_disperion_prior = FALSE,
  progress = TRUE
)

Arguments

se

A SummarizedExperiment object with count matrix and colData.

design

A fixed-effects-only formula (e.g., ~ group + age + sex).

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

low_cutoff

Ceiling for small SD estimates. Default 0.1

high_cutoff

Floor for large SD estimates. Default 10

est_disperion_prior

Estimate a prior for disperion (default = FALSE)

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Value

An object of class strainspy_priors.

Examples

if (requireNamespace("fastglm", quietly = TRUE) && 
requireNamespace("betareg", quietly = TRUE)) {
  meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
  package = "strainspy"))
  meta$Case_status <- factor(meta$Case_status)
  se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
  package = "strainspy"), meta_data = meta)
  se <- filter_by_presence(se, min_nonzero = 30)
  pri <- compute_eb_priors(se[1:10, ], 
  ~ Case_status + Age_at_collection, nthreads = 1)
  class(pri)
}

Constructor for strainspy_priors using preset or user defined priors

Description

Constructor for strainspy_priors using preset or user defined priors

Usage

define_priors(
  se,
  design,
  method = "preset_weak",
  add_dispersion_prior = FALSE,
  priors_df = NULL
)

Arguments

se

A SummarizedExperiment object with count matrix and colData.

design

A fixed-effects-only formula (e.g., ~ group + age + sex).

method

Prior type ("preset_weak", "preset_strong", "manual"). To compute empirical priors, use compute_eb_priors(). Default preset_weak.

add_dispersion_prior

Add a prior of normal(0,1) to the dispersion parameter. Default False

priors_df

NULL if method == 'preset_weak' | 'preset_strong', else a data.frame of priors suitable for glmmTMB model fitting. See ?glmmTMB::priors for more details. Default NULL.

Value

An object of class strainspy_priors.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz",
 package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
pri <- suppressWarnings(define_priors(se[1:10, ], 
~ Case_status + Age_at_collection, method = "preset_weak"))
class(pri)

Estimate beta diversity from ANI

Description

Estimate beta diversity from ANI

Usage

estimate_beta_diversity(
  se,
  method = "manhattan",
  distance_only = FALSE,
  ani_threshold = 95,
  phenotype = NULL,
  show_plots = FALSE,
  return_plots = FALSE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

method

Distance method: "manhattan" (default) or "jaccard"

distance_only

Logical. If TRUE, stop after computing distance matrix

ani_threshold

Numeric. Threshold for presence/absence determination if method == jaccard (default 95)

phenotype

Any factor variable in colnames(se@colData). Not required if distance_only == FALSE

show_plots

Logical. If TRUE, shows the plots (default = FALSE)

return_plots

Logical. If TRUE, returns ggplot2 objects (default = FALSE)

Value

If distance_only = TRUE, returns distance object. Otherwise a list with:

  • distance — distance matrix

  • nmds — NMDS object

  • ordination — NMDS coordinates with group

  • permanova — PERMANOVA results

  • betadisper — betadisper object

  • plots — list of ggplot2 objects (if return_plots = TRUE)

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
se <- filter_by_presence(se, min_nonzero = 30)
d <- estimate_beta_diversity(se[1:15, ], distance_only = TRUE)

Estimate species richness and coverage of reference strains using ANI

Description

This function estimates sample-level species richness and strain coverage using ANI-based presence/absence. A strain is considered present if ANI > ani_threshold.

Usage

estimate_sample_richness(
  se,
  taxonomy,
  ani_threshold = 95,
  report_strain_richness = FALSE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

taxonomy

An optional taxonomy file read using strainspy::read_taxonomy().

ani_threshold

Numeric ANI threshold used to define presence (default: 95).

report_strain_richness

Return the estimated strain_richness count. See description (default: FALSE)

Details

Species richness is defined as the number of species with at least one strain exceeding the ANI threshold. This requires taxonomy data, which can be read in using read_taxonomy().

Experimental Strain coverage is a database-dependent, normalised score that increases with the number of reference strains detected within a species. When only one strain is present for a species, it contributes 1 towards strain coverage. Asmore strains are detected, the contribution increases toward 2, reaching 2 when all reference strains are detected. Although this is designed to prevent inflation for species with many reference strains, this measures the coverage of reference strain space in the database, not true biological strain richness. Therefore, this value is not returned by default.

The strain coverage metric is computed as:

1+(k−1)/N1 + (k - 1) / N

where kk is the number of reference strains detected for a species and NN is the total number of reference strains for that species in the database.

This approach does not resolve true strain multiplicity and may overestimate coverage when a single biological strain matches many highly similar reference genomes. Alternative approaches are being investigated.

Value

A named list with:

species_richness

Integer vector giving the number of species detected per sample.

strain_coverage

NA or Numeric vector giving the database-normalised strain coverage per sample.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
tax <- read_taxonomy(system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy"))
rich <- estimate_sample_richness(se[1:20, ], tax)

Access fixef priors needed for ordinal beta regression

Description

Access fixef priors needed for ordinal beta regression

Usage

extract_fixef_priors(object)

## S4 method for signature 'strainspy_priors'
extract_fixef_priors(object)

Arguments

object

A strainspy_priors object.

Value

A data frame of prior parameters for fixed effects.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
pri <- suppressWarnings(define_priors(se[1:10, ], 
~ Case_status + Age_at_collection, method = "preset_weak"))
head(extract_fixef_priors(pri))

Extract data from a StrainSpy SummarizedExperiment object in long format

Description

Extract data from a StrainSpy SummarizedExperiment object in long format

Usage

extract_strainspy(
  se,
  variables = NULL,
  contigs = NULL,
  taxonomy = NULL,
  drop_zeros = FALSE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

variables

One or multiple variables in colnames(se@colData), except Sample_File.

contigs

A vector of contigs to generate violin plots

taxonomy

An optional taxonomy file read using strainspy::read_taxonomy (default=NULL).

drop_zeros

Bool. If TRUE, ANI or Abundance 0 values will not be included in the violin plot. Default FALSE.

Value

A long-format data.frame with sample metadata, contig identity columns, ANI values, row-level annotations, and optional taxonomy columns.

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
# Change variable from character to factor
example_meta$Case_status = factor(example_meta$Case_status)

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)

tax_path <- system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy")
tax <- read_taxonomy(tax_path)

extract_strainspy(se, variables = c("Case_status", "Age_at_collection"), 
contigs = rownames(se)[1:5], taxonomy=tax)

Identify per-feature model fits that failed

Description

The fitting backends signal failure in two different ways. glmObFit(), glmQBFit() and abundanceFit() return NULL for a feature that could not be fitted, so the failure shows up as a zero-length entry. Both glmZiBFit() backends instead return a fully-populated list whose coefficient matrices are NA and whose log_likelihood is NA, so the zero-length test never fires there and the NA log-likelihood is the only signal.

Usage

failed_fit_index(results)

Arguments

results

A list of per-feature fit results, one element per feature, in the same order as rowData(se).

Details

Detecting only one of the two leaves failed fits in the results, and applying the log_likelihood test blindly is worse: glmQBFit() does not report a log-likelihood at all, so every successful fit would look like a failure. This helper handles both protocols by treating a log-likelihood that is absent from every result as "not reported" rather than "all failed".

It deliberately uses vapply() rather than unlist(). unlist() silently drops the NULL log-likelihood of a zero-length entry, which shortens the vector and shifts every later index, so the returned positions would no longer line up with results or with rowData().

Value

An increasing integer vector of positions in results that should be dropped, or integer(0) if every fit succeeded.


filter_by_presence

Description

This function filters a SummarizedExperiment object to keep only rows (features/strains) that are present in a specified number of samples. The same rows are filtered from all assays in the SummarizedExperiment.

Usage

filter_by_presence(se, min_nonzero = 10)

Arguments

se

A SummarizedExperiment object.

min_nonzero

Integer. The minimum number of non-zero entries required to retain a row. Default is 10.

Value

A filtered SummarizedExperiment object with only the rows that meet the criteria.

Examples

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path)

# Filter to keep only rows with >20 non-zero entries 
filtered_se <- filter_by_presence(se, min_nonzero = 20)

filter_by_presence_with_rescale_abundance

Description

This function is copied from filter_by_presence(). Additionally, it rescales abundances such that each sample sums back to 100. Since this behaviour is not useful for association testing, this function is not exported.

Usage

filter_by_presence_and_rescale(se, min_nonzero = 10, rescale_abundance = FALSE)

Arguments

se

A SummarizedExperiment object.

min_nonzero

Integer. The minimum number of non-zero entries required to retain a row. Default is 10.

rescale_abundance

bool. Instead of containment ANI (e.g. sylph), if assay(se) contains relative abundance (e.g. metaphlan), set rescale_abundance=TRUE. After filtering, this rescales the remaining abundances to ensure they sum to 100.

Value

A filtered SummarizedExperiment object with only the rows that meet the criteria.

Examples

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path)

# Filter to keep only rows with at least 10 non-zero entries in the assay
filtered_se <- filter_by_presence(se)

# View the filtered object
filtered_se

Filter strains based on subject and time aware manner - useful for longitudinal datasets

Description

FThis function filters a SummarizedExperiment object to keep only rows (features/strains) present in at least min_subjects individuals and at least min_timepoints timepoints per subject.

Usage

filter_by_presence_longitudinal(
  se,
  min_subjects = 3,
  min_timepoints = 2,
  subject_col = "subject",
  time_col = "time"
)

Arguments

se

A SummarizedExperiment object.

min_subjects

Integer. Minimum number of subjects that must have the strain.

min_timepoints

Integer. Minimum number of non-zero timepoints per subject.Default is 3.

subject_col

Character. Column name in colData(se) corresponding to subject IDs. Default is 2.

time_col

Character. Column name in colData(se) corresponding to timepoints.

Value

A filtered SummarizedExperiment object with only the rows that meet the criteria.


Fit a linear model for a Single Feature

Description

Fits a simple linear model for functions without random effects using stats::lm()

Usage

fit_lm(se_subset, col_data, combined_formula)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

Value

A list with model coefficients, zero-inflation coefficients, residuals, log-likelihood, and convergence status.


Fit a linear model with random effects for a single feature

Description

Fits a linear model for a single feature in an assay using lmerTest::lmer()

Usage

fit_lmer(se_subset, col_data, combined_formula)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

Value

A list with model coefficients, zero-inflation coefficients, residuals, log-likelihood, and convergence status.


Fit Logistic Regression for a Single Feature

Description

Fits a logistic regression for a single feature in an assay using glmmTMB.

Usage

fit_logit_model(se_subset, col_data, design, fixed_priors, min_identity)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

design

Formula. A formula to specify the fixed and random effects, e.g., ~ Group + (1|Sample).

fixed_priors

Optional priors for the model.

min_identity

A numeric value specifying the minimum identity threshold to consider (default=0.98).

Value

A list with model coefficients, zero-inflation coefficients, residuals, log-likelihood, and convergence status.


Fit Ordinal Beta Regression for a Single Feature

Description

Fits a zero-inflated beta regression for a single feature in an assay using glmmTMB.

Usage

fit_ob_model(se_subset, col_data, combined_formula, fixed_priors, family)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

fixed_priors

Optional priors for the model.

family

A glmmTMB family object. Defaults to glmmTMB::ordbeta().

Value

A list where each element contains per-feature fitted coefficients, residuals, and convergence status.


Fit quasibinomial regression for a Single Feature

Description

Fits a quasibinomial regression for a single feature in an assay using stats::glm().

Usage

fit_qb_model(se_subset, col_data, combined_formula)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

Value

A list where each element contains per-feature fitted coefficients, residuals, and convergence status.


Fit Zero-Inflated Beta Regression for a Single Feature

Description

Fits a zero-inflated beta regression for a single feature in an assay using glmmTMB.

Usage

fit_zero_inflated_beta(
  se_subset,
  col_data,
  combined_formula,
  design,
  fixed_priors
)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

design

The formula for the zero-inflation model.

fixed_priors

Optional priors for the model.

Value

A list with model coefficients, zero-inflation coefficients, residuals, log-likelihood, and convergence status.


Fit Zero-Inflated Beta Regression for a Single Feature using the gamlss package

Description

Fits a zero-inflated beta regression for a single feature in an assay using gamlss.

Usage

fit_zero_inflated_beta_gamlss(
  se_subset,
  col_data,
  combined_formula,
  design,
  fixed_priors,
  progress = TRUE
)

Arguments

se_subset

A SummarizedExperiment object containing the assay data.

col_data

A data frame containing the design matrix and additional covariates.

combined_formula

The formula for the conditional mean model.

design

The formula for the zero-inflation model.

fixed_priors

Optional priors for the model.

progress

Logical. If TRUE (default), a progress message is printed.

Value

A list with model coefficients, zero-inflation coefficients, residuals, log-likelihood, and convergence status.


Generate colours for Manhattan plots

Description

This function generates a vector of colours for plotting, prioritising a fixed palette of 21 distinct colours. If more than 21 colours are required, additional colours are generated using grDevices::rainbow().

Usage

get_colors(n)

Arguments

n

Integer. The number of colours needed.

Value

A character vector of n colour hex codes.


Generate a confusion matrix for a fitted model

Description

Generate a confusion matrix for a fitted model

Usage

get_confusion_mx(top_hits, gt_contigs, all_contigs, print_cm = TRUE)

Arguments

top_hits

Output from tophits(fit)

gt_contigs

Vector of ground truth contigs

all_contigs

Vector of all contigs

print_cm

logical. Print the confusion matrix (default = TRUE)

Value

Confusion Matrix.


Get Contig names in a fit object

Description

Gets the ordered list of fitted contig names in a strainspy_fit

Usage

getContigNames(object)

## S4 method for signature 'strainspy_fit'
getContigNames(object)

Arguments

object

An object of class strainspy_fit.

Value

A vector of contig names

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
head(getContigNames(fit))

Access False Discovery Rates (FDR)

Description

Returns the false discovery rates (FDR) from a strainspy_fit object, if available.

Usage

getFDR(object)

## S4 method for signature 'strainspy_fit'
getFDR(object)

Arguments

object

An object of class strainspy_fit.

Value

A DataFrame or NULL containing FDR values.

Examples

methods::hasMethod("getFDR", "strainspy_fit")

Get Genomes in a fit object

Description

Gets the ordered list of fitted genomes in a strainspy_fit

Usage

getGenomes(object)

## S4 method for signature 'strainspy_fit'
getGenomes(object)

Arguments

object

An object of class strainspy_fit.

Value

A vector of fitted genomes

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
head(getGenomes(fit))

Access Residuals

Description

Returns the residuals from a strainspy_fit object.

Usage

getResiduals(object)

## S4 method for signature 'strainspy_fit'
getResiduals(object)

Arguments

object

An object of class strainspy_fit.

Value

A DataFrame containing residuals.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
class(getResiduals(fit))

Get Sample names in a fit object

Description

Gets the ordered list of samples used in strainspy_fit

Usage

getSamples(object)

## S4 method for signature 'strainspy_fit'
getSamples(object)

Arguments

object

An object of class strainspy_fit.

Value

A vector of fitted sample names

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
head(getSamples(fit))

Access Zero-Inflation Coefficients

Description

Returns the zero-inflation coefficients from a strainspy_fit object.

Usage

getZICoefficients(object)

## S4 method for signature 'strainspy_fit'
getZICoefficients(object)

Arguments

object

An object of class strainspy_fit.

Value

A DataFrame containing zero-inflation coefficients.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
class(getZICoefficients(fit))

glmObFit

Description

TODO: Implement return of vcov info. Patched for compatibility (returns NULL)

Usage

glmObFit(
  se,
  design,
  nthreads = 1L,
  scale_continuous = TRUE,
  MAP_prior = "preset_weak",
  family = glmmTMB::ordbeta(),
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

design

Formula. A formula to specify the fixed and random effects, e.g., ~ Group + (1|Sample).

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

scale_continuous

Logical. If TRUE, all numeric columns in colData(se) are z-score standardized (mean = 0, SD = 1). Defaults to FALSE.

MAP_prior

One of strainspy_priors object, character string (⁠"preset_weak", "preset_strong"⁠), a data.frame of priors, or NULL. Default "preset_weak". See Details.

family

A glmmTMB family object. Defaults to glmmTMB::ordbeta(). For general use, leave this at default Advanced users can experiment with others families in ?glmmTMB::family_glmmTMB

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Details

This function fits a ordinalbeta regression model using the glmmTMB package. It takes a SummarizedExperiment object as input, along with a user-defined formula, and fits an ordinal beta regression model on the assay data.

For robust model fitting, it is recommended to use maximum a posteriori (MAP) estimation. Emprical Bayes MAP priors can be computed using strainspy::compute_eb_priors(). They can also be manually defined using strainspy::define_priors(). The resulting strainspy_priors object can be passed to the MAP_prior argument.

Alternatively, a character string ("preset_weak" or "preset_strong") or a valid prior data.frame (see ?glmmTMB::priors) can be provided instead. This will result in a call to strainspy::define_priors() to generate priors. To disable MAP estimation and perform standard REML fitting, set MAP_prior = NULL.

Value

A strainspy_fit object with the following components:

row_data

A DFrame with 6 slots with feature details

coefficients

A DFrame with coefficients for each feature

std_errors

A DFrame of standard errors for each feature

p_values

A DFrame of p-values for each feature

residuals

A DFrame of residual vectors for each feature

convergence

A named logical vector indicating convergence for each feature

design

Formula used in the call to glmObFit

call

Call to glmObFit

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
se <- filter_by_presence(se)

design <- as.formula(" ~ Case_status + Age_at_collection")

fit <- glmObFit(se[1:10,],  design, family=glmmTMB::ordbeta())

glmQBFit TODO: Implement return of vcov info. Patched for compatibility (returns NULL)

Description

This function fits a quasibinomial regression model using stats::glm().

Usage

glmQBFit(
  se,
  design,
  nthreads = 1L,
  scale_continous = TRUE,
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

design

Formula. A formula to specify fixed effects, e.g., ~ Age + BMI.

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

scale_continous

Logical. If TRUE, all numeric columns in colData(se) are z-score standardized (mean = 0, SD = 1). Default FALSE.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Details

It takes a SummarizedExperiment object as input, along with a user-defined formula containing only fixed effect parameters, and fits a quasibinomial regression model on the assay data.

Value

A strainspy_fit object with the following components:

row_data

A DFrame with 6 slots with feature details

coefficients

A DFrame with coefficients for each feature

std_errors

A DFrame of standard errors for each feature

p_values

A DFrame of p-values for each feature

residuals

A DFrame of residual vectors for each feature

convergence

A named logical vector indicating convergence for each feature

design

Formula used in the call to glmQBFit

call

Call to glmQBFit

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz",
package = "strainspy")
se <- read_sylph(example_path, example_meta)
se <- filter_by_presence(se)

design <- as.formula(" ~ Case_status")

fit <- glmQBFit(se[1:10,], design, nthreads=2)

glmZiBFit

Description

This function fits a zero-inflated beta regression model using either glmmTMB or gamlss packages. It takes a SummarizedExperiment object as input, along with a user-defined formula, and fits a zero-inflated beta regression model on the assay data.

Usage

glmZiBFit(
  se,
  design,
  nthreads = 1,
  scale_continuous = TRUE,
  MAP_prior = "preset_weak",
  BPPARAM = NULL,
  method = "glmmTMB",
  return_vcov = TRUE,
  progress = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

design

Formula. A formula to specify the fixed and random effects, e.g., ~ Group + (1|Sample).

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to one 1.

scale_continuous

Logical. If TRUE, all numeric columns in colData(se) are z-score standardized (mean = 0, SD = 1). Defaults to TRUE.

MAP_prior

One of strainspy_priors object, character string (⁠"preset_weak", "preset_strong"⁠), a data.frame of priors, or NULL. Default "preset_weak". See Details.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

method

Character. The method to use for fitting the model. Either 'glmmTMB' (default) or 'gamlss'.

return_vcov

Logical. Return variance-covariance matrices for each model, required for estimate_effect_sizes(). Disabling will result in a much smaller strainspy_fit object that is useful for most analyses. Defaults to TRUE.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Value

A strainspy_fit object with the following components:

row_data

A DFrame with 6 slots with feature details

coefficients

A DFrame with coefficients for each feature

std_errors

A DFrame of standard errors for each feature

p_values

A DFrame of p-values for each feature

zi_coefficients

A DFrame of zero inflated coefficients for each feature

zi_std_errors

A DFrame of zero inflated standard errors for each feature

zi_p_values

A DFrame of zero inflated p-values for each feature

residuals

A DFrame of residual vectors for each feature

convergence

A named logical vector indicating convergence for each feature

design

Formula used in the call to glmZiBFit

call

Call to glmZiBFit

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
se <- filter_by_presence(se)

design <- as.formula(" ~ Case_status")

fit <- glmZiBFit(se[1:10,], design, nthreads=2)

Performs hierarchical taxonomy aware adjustment of p-values.

Description

This function performs multiple testing adjustment on the results of a betaGLM object integrating taxonomic information. Various correction methods are available, including Harmonic Mean P-value (HMP), Bonferroni and Benjamini-Hochberg (BH).

Usage

hadjust(object, coef = 2, method = "HMP", taxonomy = NULL, index_range = FALSE)

Arguments

object

A strainspy_fit object.

coef

The coefficient to use for p-value adjustment. Defaults to 2.

method

The method for p-value adjustment. Options include "bonferroni" and Harmonic Mean P-value (HMP).

taxonomy

A taxonomy data.table object. If provided, the p-values will be adjusted at each taxonomic level.

index_range

This option is only used to generate Manhattan plot segments for higher taxonomic levels

Value

A tibble with original and adjusted p-values.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
se <- filter_by_presence(se, min_nonzero = 30)
tax <- read_taxonomy(system.file("extdata", "example_taxonomy.tsv.gz",
package = "strainspy"))
fit <- glmZiBFit(se[1:10, ], ~ Case_status + Age_at_collection, 
nthreads = 1, return_vcov = FALSE)
out <- hadjust(fit, coef = 2, taxonomy = tax)
head(out)

merge_metaphlan_files

Description

Merge MetaPhlAn >=4.0 profiles into a single file to use with read_metaphlan() and generate the taxonomy file required for downstream analysis.

Usage

merge_metaphlan_files(
  metaphlan_files,
  output_folder,
  output_filename = "metaphlan",
  sgb_database = TRUE
)

Arguments

metaphlan_files

A character vector of file paths to merge. Optionally, if the input is named, names(metaphlan_files) will be used as sample identifiers in place of the filename.

output_folder

Folder path to save outputs.

output_filename

File name for the two outputs. By default, the two files will be saved as metaphlan_merged.tsv.gz and metaphlan_taxonomy.tsv.gz

sgb_database

bool. Specify whether the default sgb database was used for profiling. Set to FALSE if sgb_to_gtdb_profile.py was run on the profiles as a post processing step. Default TRUE

Value

Invisibly returns NULL. The function writes two files to output_folder: a merged profile table (⁠*_merged.tsv.gz⁠) and a taxonomy table (⁠*_taxonomy.tsv.gz⁠).

Examples

files <- character(0)
is.character(files)

merge_sourmash_files

Description

Merge the outputs of ⁠sourmash search⁠ or ⁠sourmash gather⁠ into a single file. The output of this function is suitable to use in read_sourmash()

Usage

merge_sourmash_files(
  sourmash_files,
  manifest_file = NULL,
  output,
  strip_unusable = TRUE
)

Arguments

sourmash_files

A character vector of file paths to merge.

manifest_file

If one or several indexed databases were used for searching or gathering, required genome column can be missing. The path to the output of ⁠sourmash sig manifest⁠ can be provided to try and add back the data automatically (Default = NULL). If provided, columns md5, name and filename are required. This function uses name and md5 to match the manifest data with sourmash outputs. In the final output, filename will be used to identify each hit. If the filename is a path, the basename without extensions will be used instead.

output

Save path for the output file. Internally, data.table::fwrite is used, provide the extension gz to save a compressed file.

strip_unusable

Remove columns containing data not useful for further analysis. Default TRUE.

Details

Refer to sourmash documentation for more information.

Value

Invisibly returns NULL. The merged sourmash table is written to output.

Examples

# Split the bundled sourmash output into two per-query files, then merge them.
hits <- data.table::fread(
  system.file("extdata", "example_sourmash.csv.gz", package = "strainspy")
)
queries <- head(unique(hits$query_name), 2)
parts <- vapply(queries, function(q) {
  f <- tempfile(fileext = ".csv")
  data.table::fwrite(hits[hits$query_name == q, ], f)
  f
}, character(1))

merged <- tempfile(fileext = ".csv.gz")
merge_sourmash_files(parts, output = merged)

sm <- read_sourmash(merged)
dim(sm)

merge_sylph_files

Description

Merge the outputs of ⁠sylph query⁠ or ⁠sylph profile⁠ into a single file. The output of this function is suitable to use in read_sylph()

Usage

merge_sylph_files(sylph_files, output)

Arguments

sylph_files

A character vector of sylph output file paths to merge.

output

Save path for the output file. Internally, data.table::fwrite is used, provide the extension gz to save a compressed file.

Value

Invisibly returns NULL. The merged sylph table is written to output.

Examples

# Split the bundled profile into two per-sample files, then merge them back.
profile <- data.table::fread(
  system.file("extdata", "example_sylph_profile.tsv.gz", package = "strainspy")
)
samples <- head(unique(profile$Sample_file), 2)
parts <- vapply(samples, function(s) {
  f <- tempfile(fileext = ".tsv")
  data.table::fwrite(profile[profile$Sample_file == s, ], f, sep = "\t")
  f
}, character(1))

merged <- tempfile(fileext = ".tsv.gz")
merge_sylph_files(parts, merged)

# The merged file carries one header and both samples
se <- read_sylph(merged)
dim(se)

Add or modify metadata in a SummarizedExperiment object

Description

This function adds or modifies metadata in a SummarizedExperiment object.

Usage

modify_metadata(se, meta_data, replace = FALSE, convert = TRUE)

Arguments

se

A SummarizedExperiment object.

meta_data

A data.frame with sample metadata. The first column must contain all samples returned by colnames(se).

replace

Logical. If TRUE, replaces existing colData. Default FALSE.

convert

Logical. If TRUE, attempts to auto-convert types as suited for model fitting (int to numeric, char to factor). Disable if meta_data is fully configured for model fitting. Default TRUE. See Details.

Details

If convert = TRUE, character columns with less than 5 unique (non-NA) values will be automatically converted to factors, with levels ordered alphabetically. For meaningful association testing, however, factor levels should reflect the intended reference level. It is recommended to manually convert such variables to factors with explicitly set levels before calling modify_metadata().

Value

Updated SummarizedExperiment object.

Examples

# Add or modify metadata subsequently
  example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
  package = "strainspy")
  example_meta <- read.csv(example_meta_path)
  example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
  package = "strainspy")
  se <- read_sylph(example_path)
  se <- modify_metadata(se, example_meta)

Remove random effects from model

Description

nobars_ copied from https://github.com/bbolker/reformulas This function can work with formulas like ~cohort + timepoint + (1 + timepoint | patientID), above fails We can either use it like this, or add reformulas (or lme4) as a dependency

Usage

nobars_(term)

Arguments

term

Formula object

Value

A formula without mixed components


Offset ANI by a fixed value

Description

This function reduces all non-zero ANI values by eps

Usage

offset_ANI(x, eps = 0.01)

Arguments

x

Vector of ANI values in (0,1)

eps

offset value (default 1e-2)

Value

Adjusted ANI vector


Generate a violin or box plot for a subset of contigs for a categorical phenotype.

Description

Generate a violin or box plot for a subset of contigs for a categorical phenotype.

Usage

plot_ani_dist(
  se,
  phenotype,
  contigs,
  facet_phenotype = NULL,
  contig_names = NULL,
  show_zero_plot = TRUE,
  show_points = TRUE,
  plot = TRUE,
  plot_type = "box"
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

phenotype

Any factor variable in colnames(se@colData).

contigs

A vector of contigs to generate distribution plots

facet_phenotype

Any factor variable in colnames(se@colData), except phenotype. If provided, this will be used to facet the plot. See ?ggplot2::facet_wrap(). Default NULL.

contig_names

Optional character vector to replace long contig names in the plot. Must match the length and order of contigs. If NULL (default), shortening will be attempted automatically.

show_zero_plot

Bool. If TRUE, distribution of the proportion of zeros will also be plotted. Default TRUE

show_points

Bool. If TRUE, points will be overlaid with jitter using ggforce::geom_sina(). Default TRUE

plot

If set to false, the function will return a tibble with data used to generate the plot.

plot_type

Specify whether box or violin plot is required. Default box.

Value

If plot = TRUE, returns a ggplot object (or a combined patchwork plot when show_zero_plot = TRUE). If plot = FALSE, returns a long-format table used to generate the ANI distribution plot.

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", package = "strainspy")
example_meta <- read.csv(example_meta_path)
# Change variable from character to factor
example_meta$Case_status = factor(example_meta$Case_status)

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", package = "strainspy")
se <- read_sylph(example_path, example_meta)

plot_ani_dist(se, phenotype = "Case_status", contigs = rownames(se)[1:5])

Generate a histogram for a single contig for a categorical phenotype.

Description

Generate a histogram for a single contig for a categorical phenotype.

Usage

plot_histogram(
  se,
  phenotype,
  contig,
  bins = 250,
  drop_zeros = FALSE,
  show_quantiles = TRUE,
  fit_spline = FALSE,
  fit_control = 100,
  separate_facets = TRUE
)

Arguments

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

phenotype

One variable in colnames(se@colData), except Sample_File. The selected variable must be categorical

contig

Contig name to visualise

bins

Numeric. Number of bins to plot the histogram. This parameter should be adjusted to properly visualise the ANI differences. Default 250

drop_zeros

Bool. If TRUE, ANI or Abundance 0 values will not be included in the violin plot. Default FALSE

show_quantiles

Bool. If TRUE, min, max, etc. will be shown as vertical lines. Default TRUE

fit_spline

Bool. If TRUE, a spline will be fitted to each histogram. Default FALSE

fit_control

Numeric. Smaller values increase the smoothness of the fitted spline. Default 100

separate_facets

Bool. If TRUE, each category of the phenotype will be plotted in a separate facet. Default TRUE

Value

A ggplot histogram object. A summary table of per-group statistics is attached as attr(plot, "summary_table").

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
# Change variable from character to factor
example_meta$Case_status = factor(example_meta$Case_status)

example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)

plot_histogram(se, phenotype = "Case_status", contig = rownames(se)[1])

Generate a strain Manhattan plot from a strainspy_fit object

Description

This function can generate multiple Manhattan plots from a strainspy_fit object.

Usage

plot_manhattan(
  object,
  coef = 2,
  taxonomy = NULL,
  aggregate_by_taxa = NULL,
  method = "holm",
  alpha = 0.05,
  tax_levels = c("Phylum", "Genus", "Species", "Strain"),
  plot = TRUE
)

Arguments

object

A strainspy_fit object.

coef

The number of the coefficient from which to generate the plot (default=2).

taxonomy

An optional taxonomy file read using strainspy::read_taxonomy (default=NULL).

aggregate_by_taxa

Logical. If TRUE, aggregate p-values across tax_levels and visualise as a stacked segment plot. Requires taxonomy. If NULL (default), the function automatically sets it to TRUE when taxonomy is provided.

method

Character. Multiple testing correction method for p-values (e.g., "holm"). Defaults to "holm". Only applicable if aggregate_by_taxa = TRUE.

alpha

Numeric. Significance threshold for adjusted p-values. Defaults to 0.05.

tax_levels

Character vector. Subset of taxonomic levels: c("Domain", "Phylum", "Class", "Order", "Family", "Genus", "Species", "Strain") to include in the plot. Defaults to c("Phylum", "Genus", "Species", "Strain"). Provided levels will be reordered by the standard hierarchy and the highest level is used for colouring. If it has >30 categories, the legend is replaced by a named vector. Only applicable with aggregate_by_taxa = TRUE.

plot

If set to false, the function will return a tibble with data used to generate the plot. NOTE: Will be disregarded if taxonomy is provided with the option aggregate_by_taxa = FALSE.

Details

The generated plot will be more informative if taxonomic information is provided. Two types of plots can be generated with taxonomic information.

  1. Set aggregate_by_taxa = TRUE to aggregate p-values across taxonomic levels specified by tax_levels. This generates a stacked segment Manhattan plot. In this plot, -log10 p-values adjusted using method will be plotted in taxonomic ordering. Significance threshold will be alpha.

  2. Set aggregate_by_taxa = FALSE to generate a traditional Manhattan plot for all strains coloured by phylum. Unadjusted p-values will be plotted and Bonferroni significance thresholds (0.05, 0.01) will be shown. Strains will be in taxonomic ordering and a tree showing the taxonomic relationship between strains will be plotted below the Manhattan plot.

If taxonomic information is not provided (taxonomy = NULL), a plot with -log10 p-values adjusted using method will be generated. Strains will be plotted in alphabetical order. Significance threshold will be alpha.

If Zero-Inflated Beta regression was used to model object, separate facets will be used for zero-inflated and beta components of the model.

Value

A ggplot object showing the Manhattan plot if plot = TRUE, else a data.frame with plot data.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
se <- filter_by_presence(se, min_nonzero = 30)
tax <- read_taxonomy(system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy"))
fit <- glmZiBFit(se[1:10, ], ~ Case_status + Age_at_collection, 
nthreads = 1, return_vcov = FALSE)
mh_data <- plot_manhattan(fit, taxonomy = tax, plot = FALSE)
head(mh_data)

Generate a Manhattan plot from a strainspy_fit object, with the option to add ground truth

Description

This function is copied from plot_manhattan()

Usage

plot_manhattan_gt(
  object,
  coef = 2,
  taxonomy = NULL,
  method = "HMP",
  alpha = 0.05,
  levels = c("Phylum", "Genus", "Species", "Strain"),
  colour_level = "Phylum",
  plot = TRUE,
  ground_truth = NULL
)

Arguments

object

A strainspy_fit object.

coef

The number of the coefficient from which to generate the plot (default=2).

taxonomy

An optional taxonomy file read using strainspy::read_taxonomy (default=NULL).

method

Character. Multiple testing correction method for p-values (e.g., "holm"). Defaults to "holm".

alpha

Numeric. Significance threshold for adjusted p-values. Defaults to 0.05.

levels

Character vector. Taxonomic levels to include in the plot when taxonomy is provided. Defaults to c("Phylum", "Genus", "Species", "Strain").

colour_level

Character. Taxonomic level used for coloring the plot segments. Defaults to "Phylum".

plot

If set to false, the function will return a tibble with data used to generate the plot.

ground_truth

A vector of ground truth contigs

Value

A ggplot object showing the Manhattan plot.


Generate a conventional Manhattan plot for the strain all strains.

Description

Generate a conventional Manhattan plot for the strain all strains.

Usage

plot_manhattan_tree(object, taxonomy, coef = 2)

Arguments

object

A strainspy_fit object.

taxonomy

Taxonomy file read using strainspy::read_taxonomy (default=NULL).

coef

The number of the coefficient from which to generate the plot (default=2).

Value

A ggplot object showing the Manhattan plot combined with the taxonomic tree


Plot MDS of ANI data

Description

Performs classical multidimensional scaling (MDS) on a SummarizedExperiment object and plots the result, optionally colored by a phenotype.

Usage

plot_mds(
  se,
  coef = 2,
  taxonomy = NULL,
  palette = c("#DAA520", "#3CB371", "#483D8B"),
  plot = TRUE
)

Arguments

se

A SummarizedExperiment object containing ANI data.

coef

Integer. Index of the column in colData(se) to use as the grouping or color variable (default is 2).

taxonomy

Optional taxonomy table to use in distance calculation.

palette

A vector of color hex codes for numeric phenotype gradients. Defaults to viridis palette.

plot

Logical. If TRUE, returns a ggplot object. If FALSE, returns the underlying MDS coordinates as a tibble.

Value

A ggplot object showing the MDS plot, or a tibble of MDS coordinates if plot = FALSE.

Examples

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
plot_mds(se, coef = 2)

plot_pca_biplot

Description

Perform PCA and Generate a Biplot

Usage

plot_pca_biplot(se, phenotype, plot = TRUE)

Arguments

se

A SummarizedExperiment object containing expression data.

phenotype

A character string specifying the name of a phenotype or an integer specifying the column number in colData(se)

plot

A logical value indicating whether to return the PCA plot (TRUE) or PCA data (FALSE). Default is TRUE.

Details

This function performs Principal Component Analysis (PCA) on a SummarizedExperiment object and generates a PCA biplot colored by a specified phenotype.

Value

If plot = TRUE, returns a ggplot2 PCA plot. If plot = FALSE, returns a tibble with PCA results.

Examples

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
plot_pca_biplot(se, phenotype = 3)

Plot method for strainspy_priors objects

Description

Plot method for strainspy_priors objects

Usage

plot_prior_bootstrap(object, prior)

## S4 method for signature 'strainspy_priors'
plot_prior_bootstrap(object, prior)

Arguments

object

An object of class strainspy_priors that has bootstrap information

prior

Prior to be plotted

Value

Invisibly returns the object

Examples

methods::hasMethod("plot_prior_bootstrap", "strainspy_priors")

Generate a Volcano Plot from a betaGLM Object

Description

This function creates a volcano plot from the results of a betaGLM analysis, highlighting the relationship between effect size (coefficients) and statistical significance (-log10 p-values).

Usage

plot_volcano(
  object,
  coef = 2,
  alpha = 0.05,
  method = "holm",
  palette = rev(viridis::viridis(3)),
  label = FALSE,
  contig_names = NULL,
  plot = TRUE
)

Arguments

object

A strainspy_fit object containing model results.

coef

Integer, specifying the phenotype index of the betaGLM to extract p values and effect size for plotting. Default is 2.

alpha

Float indicating signficance level. Default is 0.05

method

The method for p-value adjustment. For available options, see ?top_hits(). Default holm.

palette

A vector of user defined palette to colour plot. Default is the viridis palette.

label

Logical, whether to label most signifcant points of the plot with Species name.

contig_names

Optional character vector to replace long contig names in the plot. Must match the length and order of top_hits(object, coef = coef, alpha = alpha)$Contig_name. If NULL (default), shortening will be attempted automatically.

plot

Logical, whether to return a ggplot object (default: TRUE). If FALSE, returns the processed data.

Value

A ggplot2 object if plot = TRUE, otherwise a dataframe containing the relevant statistics.

Examples

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
se <- read_sylph(example_path, example_meta)
se <- filter_by_presence(se)
design <- as.formula(" ~ Case_status + Sex")
fit <- glmZiBFit(se[1:10,], design, nthreads=2)
plot_volcano(fit, coef = 2, label = TRUE)

Prepare a caret-compatible prediction data frame from a SummarizedExperiment

Description

Formats strain-level data and optional covariates into a data.frame object ready for modeling with caret. The function extracts selected contigs from the sy assay matrix, combines them with the specified outcome and optional covariates from the metadata, and performs basic validation and cleaning. Metadata is pulled from SummarizedExperiement::colData(sy), and generally assumes strainspy::modify_metadata() was used upstream.

Usage

prep_for_prediction(
  sy,
  outcome,
  contigs,
  covariates = NULL,
  use_genome_names = TRUE
)

Arguments

sy

A SummarizedExperiment A SummarizedExperiment object containing the assay data and metadata.

outcome

Character string giving the name of the outcome variable present in colData(sy). This is usually the left-hand side of the prediction model formula.

contigs

Character vector of contigs (feature) to include as predictors. Must be present in rownames(sy).

covariates

Optional character vector of additional metadata variables to include as covariates. Default NULL for no covariates.

use_genome_names

Bool. Use Genome_file instead of Contig_name in colnames(output). Genome_file is extracted from SummarizedExperiemnt::elementMetadata(sy). If not available, Contig_name will be used. Default True.

Details

Character variables are automatically converted to factors. Numeric variables are returned unchanged. For pre processing, refer to caret::train().

Value

A data.frame containing the specified outcome variable, optional covariates, and selected contig features. The object is ready for direct use in caret functions such as caret::train().

Examples

library(strainspy)

example_meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
example_meta <- read.csv(example_meta_path)
example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
sy <- read_sylph(example_path, example_meta)
contigs <- rownames(sy)[1:10]
df <- prep_for_prediction(
  sy = sy,
  outcome = "Case_status",
  contigs = contigs,
  covariates = c("Sex", "BMI")
)

read_metaphlan

Description

This function reads a merged MetaPhlAn profile output and create a SummarizedExperiment object. An optional metadata table can be provided and added directly to colData via an internal call to modify_metadata().

Usage

read_metaphlan(
  file_path,
  meta_data = NULL,
  variable = "relative_abundance",
  clean_names = TRUE
)

Arguments

file_path

Character. Path to the merged metaphlan output file.

meta_data

data.frame. An optional tibble or data frame containing sample metadata. See Details

variable

Character. Name of the input variable to import. Defaults to relative_abundance.

clean_names

Logical. If TRUE, file paths will be stripped of their directory path and file extension, leaving only the base file name. Defaults to TRUE.

Value

A SummarizedExperiment object with the following components:

assays

A matrix containing numeric features such as relative_abundance

rowData

DataFrame containing metadata for each sequence, such as Contig_name and Genome_file.

colData

DataFrame containing information for each sample (derived from the Sample_file field).

Note

Since MetaPhlAn profiles are usually generated per sample, first use merge_metaphlan_files() to merge and generate the input for this function.

#' If metadata is provided, it must meet the input requirements described in modify_metadata(). If appending metadata fails due to pre processing requirements, this function will issue a detailed warning and still return the SummarizedExperiment object without metadata. In that case, apply necessary fixes and subsequently call modify_metadata().

Examples

# Read a merged metaphlan profile file into a SummarizedExperiment object
  example_path <- system.file("extdata", "metaphlan_merged.tsv.gz", 
  package = "strainspy")
  mp <- read_metaphlan(example_path)

read_sourmash

Description

This function reads a ⁠sourmash gather⁠ or ⁠sourmash search⁠ -like output CSV file and create a SummarizedExperiment object. An optional metadata table can be provided and added directly to colData via an internal call to modify_metadata().

Usage

read_sourmash(
  file_path,
  meta_data = NULL,
  variable = "match_containment_ani",
  clean_names = TRUE
)

Arguments

file_path

Character. Path to the sourmash gather file (CSV format).

meta_data

data.frame. A tibble or data frame containing sample metadata. Metadata requirements are identical to read_sylph().

variable

Character. Name of the input variable to import. Defaults to match_containment_ani.

clean_names

Logical. If TRUE, file paths will be stripped of their directory path and file extension, leaving only the base file name. Defaults to TRUE.

Value

A SummarizedExperiment object with the following components:

assays

A matrix containing numeric features such as Adjusted_ANI, Taxonomic_abundance, Median_cov, etc.

rowData

DataFrame containing metadata for each sequence, such as Contig_name and Genome_file.

colData

DataFrame containing information for each sample (derived from the Sample_file field).

Note

Some of sourmash subcommands like gather are designed to take exactly one query file. To merge and save a CSV file suitable to use with this function, use merge_sourmash_files() #' If metadata is provided, it must meet the input requirements described in modify_metadata(). If appending metadata fails due to pre processing requirements, this function will issue a detailed warning and still return the SummarizedExperiment object without metadata. In that case, apply necessary fixes and subsequently call modify_metadata().

Examples

# Read a merged sourmash file into a SummarizedExperiment object
  example_path <- system.file("extdata", "example_sourmash.csv.gz", 
  package = "strainspy")
  sm <- read_sourmash(example_path)

Read Sylph query or profile output file and create a SummarizedExperiment object

Description

This function reads a Sylph output file (either query or profile), parses the data, and returns a SummarizedExperiment object. An optional metadata table can be provided and added directly to colData via an internal call to modify_metadata().

Usage

read_sylph(
  file_path,
  meta_data = NULL,
  variable = "Adjusted_ANI",
  min_identity = 95,
  clean_names = TRUE
)

Arguments

file_path

Character. Path to the Sylph query or profile output file(s) in tsv format. A single merged sylph output file processed with merge_sylph_files(), or a character vector of paths to individual sylph output files can be provided. If multiple files are provided, they will be merged internally and saved to a temporary file. If the internal merging fails, use merge_sylph_files() to merge the files externally and provide the merged file path.

meta_data

data.frame. An optional tibble or data frame containing sample metadata. See Details

variable

Character. Name of the input variable to import. Defaults to Adjusted_ANI, other options can include Naive_ANI, Taxonomic_abundance and Sequence_abundance.

min_identity

Numeric. Minimum identity threshold for filtering ANI values. Defaults to 95.

clean_names

Logical. If TRUE, file paths will be stripped of their directory path and file extension, leaving only the base file name. Defaults to TRUE.

Details

If metadata is provided, it must meet the input requirements described in modify_metadata(). If appending metadata fails due to pre processing requirements, this function will issue a detailed warning and still return the SummarizedExperiment object without metadata. In that case, apply necessary fixes and subsequently call modify_metadata().

Value

A SummarizedExperiment object with the following components:

assays

A matrix containing numeric features such as Adjusted_ANI, Taxonomic_abundance, Median_cov, etc.

rowData

DataFrame containing metadata for each sequence, such as Contig_name and Genome_file.

colData

DataFrame containing information for each sample (derived from the Sample_file field).

Examples

# Read a Sylph file 
  example_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
  package = "strainspy")
  sy <- read_sylph(example_path)

Read and process a taxonomy file in Sylph format

Description

This function reads a taxonomy file in Sylph format.

Usage

read_taxonomy(file_path)

Arguments

file_path

Path to the taxonomy file.

Value

A data.table containing parsed taxonomy information.

Examples

tax <- read_taxonomy(system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy"))
head(tax)

Transform ANI Data to Simulate a Treatment Effect

Description

This function applies a simple linear transformation to simulate a treatment effect.

Usage

rescale_beta(x, beta = 0.98, zi = 0.1)

Arguments

x

a vector of sequence identity values to transform

beta

simulate a decreased in identiy by factor of beta (default=0.95)

zi

simulate an increased shift in the proportion of zeros by zi (default=0.1)

Value

a vector of transformed values


Resolve and construct priors for model fitting

Description

Ensures MAP_prior is interpreted correctly and returns a valid strainspy_priors object or NULL (for unpenalised ML fits).

Usage

resolve_priors(MAP_prior, se, design)

Arguments

MAP_prior

One of: NULL, a character string ("preset_weak", "preset_strong"), a prior data.frame, or a strainspy_priors object.

se

A SummarizedExperiment object.

design

A fixed-effects-only formula.

Value

A strainspy_priors object or NULL.


Show Method for strainspy_fit

Description

Displays a summary of a strainspy_fit object, including model design, convergence, and coefficient matrix dimensions.

Usage

## S4 method for signature 'strainspy_fit'
show(object)

Arguments

object

An object of class strainspy_fit.

Value

Invisibly returns NULL after printing a compact summary.


Show method for strainspy_priors objects

Description

Show method for strainspy_priors objects

Usage

## S4 method for signature 'strainspy_priors'
show(object)

Arguments

object

An object of class strainspy_priors

Value

Invisibly returns the object


Strainspy Wrapper

Description

A wrapper to run a full strainspy workflow with explicit input validation.

Usage

strainspy(
  meta_path,
  sylph_path,
  design_formula,
  coef,
  min_nonzero = NULL,
  taxonomy_path = NULL,
  output_path = NULL,
  alpha = 0.05,
  p_adjust_method = "holm",
  model_method = "glmmTMB",
  scale_continuous = TRUE,
  nthreads = 2,
  return_vcov = FALSE,
  attach_taxonomy = TRUE,
  overwrite = TRUE,
  progress = TRUE
)

Arguments

meta_path

Path to the metadata file (CSV format).

sylph_path

Path to the sylph output file (TSV format).

design_formula

One-sided formula (or string coercible to formula) for the design matrix, e.g. ~ Condition + Age + (1|Subject).

coef

Coefficient index to report in top_hits(). This determines which design term is tested.

min_nonzero

Minimum number of samples for strain presence filtering. If NULL (default), this is set to ceiling(0.10 * n_samples).

taxonomy_path

Optional path to a taxonomy file (TSV format). If provided, taxonomy columns are appended to top hits.

output_path

Optional path to save top hits as CSV. If NULL, no file is written.

alpha

Significance threshold used by top_hits().

p_adjust_method

Multiple-testing correction method for top_hits().

model_method

Backend used by glmZiBFit(): "glmmTMB" or "gamlss".

scale_continuous

If TRUE, continuous metadata covariates are z-scored by glmZiBFit().

nthreads

Number of threads for parallel processing (default: all available cores).

return_vcov

If TRUE, include per-feature variance-covariance matrices in fit.

attach_taxonomy

If TRUE and taxonomy_path is provided, append taxonomy columns to top hits.

overwrite

If FALSE, abort when output_path already exists.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Value

A data frame of top hits. If taxonomy_path is supplied and attach_taxonomy = TRUE, taxonomy columns are appended.

Examples

meta_path <- system.file("extdata", "example_metadata.csv.gz", 
package = "strainspy")
sylph_path <- system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy")
taxonomy_path <- system.file("extdata", "example_taxonomy.tsv.gz", 
package = "strainspy")

# Decision 1: choose predictors for the design formula
# Decision 2: choose which coefficient index to report in top_hits()
# For ~ Case_status + Age_at_collection, coef = 2 corresponds to Case_status

out <- strainspy(
  meta_path = meta_path,
  sylph_path = sylph_path,
  design_formula = "~ Case_status + Age_at_collection",
  coef = 2,
  taxonomy_path = taxonomy_path,
  output_path = tempfile(fileext = ".csv"),
  nthreads = 2,
  alpha = 1
)
head(out)

strainspy_fit: A Class for storing fit data from all strainspy models

Description

The strainspy_fit class is designed to store the results of strainspy

Slots

row_data

A DataFrame containing row data.

priors

A strainspy_priors object or NULL for REML.

scale_continuous

A logical indicating whether all numeric columns were z-score standardized

coefficients

A DataFrame containing model coefficients.

std_errors

A DataFrame containing standard errors of the coefficients.

p_values

A DataFrame containing p-values for the coefficients.

vcov

A DataFrame containing the variance-covariance matrix.

zi_coefficients

A DataFrame containing zero-inflation coefficients.

zi_std_errors

A DataFrame containing zero-inflation standard errors.

zi_p_values

A DataFrame containing zero-inflation p-values.

zi_vcov

A DataFrame containing the zero-inflated variance-covariance matrix.

residuals

A DataFrame containing residuals from the model.

convergence

A logical indicating whether model fitting converged.

design

A matrix representing the design matrix of the model.

call

The matched call of the model.

family

The family of the fit.


strainspy_priors: A Class for storing model fitting priors

Description

The strainspy_priors class is designed to store MAP priors used for ordinal and zero-inflated beta model fitting using glmmTMB.

Slots

method

Character. Prior estimation method used ("preset_weak", "preset_strong", "empirical", "manual").

priors_df

Data frame. Data frame containing prior parameters.

boot_fixef

Numeric matrix. Bootstrap SD values for fixed effect priors

boot_fixef_ZI

Numeric matrix. Bootstrap SD values for zero inflated fixed effect priors

boot_disp

Numeric matrix. Bootstrap mean and SD values for the dispersion term of beta component.

design

The formula with with effect terms used

call

The matched call of the model.


Summary Method for strainspy_fit

Description

Provides a high-level summary of a strainspy_fit object, including its call, coefficients, zero-inflation coefficients, dispersion, and the availability of FDR and residuals.

Usage

## S4 method for signature 'strainspy_fit'
summary(object)

Arguments

object

An object of class strainspy_fit.

Value

A list summarizing the strainspy_fit object.


Provides the top results of a strainspy_fit object, sorted by adjusted p-value.

Description

This function performs multiple testing adjustment on the results of a strainspy_fit object integrating taxonomic information. Various correction methods are available, including Harmonic Mean P-value (HMP), Bonferroni and Benjamini-Hochberg (BH).

Usage

top_hits(fit, coef = 2, method = "holm", alpha = 0.05)

Arguments

fit

A strainspy_fit object.

coef

The coefficient to report and use for p-value adjustment. Defaults to 2.

method

The method for p-value adjustment. Available methods are a subset of those in p.adjust, specifically those valid for dependent tests. Common choices include "holm", "hochberg", "hommel", and "BH" (Benjamini-Hochberg) and "BY".

alpha

Numeric. Significance threshold for adjusted p-values. Defaults to 0.05.

Value

A tibble with the top hits, sorted by adjusted p-value.

Examples

meta <- read.csv(system.file("extdata", "example_metadata.csv.gz",
 package = "strainspy"))
meta$Case_status <- factor(meta$Case_status)
se <- read_sylph(system.file("extdata", "example_sylph_profile.tsv.gz", 
package = "strainspy"), meta_data = meta)
fit <- glmZiBFit(filter_by_presence(se, min_nonzero = 30)[1:10, ], 
~ Case_status + Age_at_collection, nthreads = 1, return_vcov = FALSE)
top_hits(fit, coef = 2, alpha = 1)

Update the model fit by calling the specified fit function only a subset of features. Same design will be fitted.

Description

Update the model fit by calling the specified fit function only a subset of features. Same design will be fitted.

Usage

update_fit(
  fit,
  update_idx,
  se,
  scale_continuous = TRUE,
  min_identity = 0.98,
  method = "glmmTMB",
  family = glmmTMB::ordbeta(),
  nthreads = 1,
  BPPARAM = NULL,
  progress = TRUE
)

Arguments

fit

A strainspy_fit object

update_idx

Vector of indices that need to be updated

se

SummarizedExperiment. A SummarizedExperiment object containing the assay data and metadata.

scale_continuous

Binary specifying whether to rescale numeric values. Default T

min_identity

Only for caseControlFit(). A numeric value specifying the minimum identity threshold to consider (default=0.98).

method

Character. The method to use for fitting the model. Either 'glmmTMB' (default) or 'gamlss'. Only applicable for glmZiBFit().

family

A glmmTMB family object. Defaults to glmmTMB::ordbeta(). Only applicable for glmZiBFit()

nthreads

An integer specifying the number of (CPUs or workers) to use. Defaults to 1.

BPPARAM

Optional BiocParallelParam object. If not provided, the function will configure an appropriate backend automatically.

progress

Logical. If TRUE (default), progress bars and progress messages are printed. Set to FALSE to silence them.

Value

Updated version of the fit object