--- title: "All modelling methods at a glance" author: - name: Witold E. Wolski affiliation: Functional Genomics Center Zurich (FGCZ), ETH Zurich and University of Zurich package: prolfqua output: BiocStyle::html_document vignette: > %\VignetteIndexEntry{4. All modelling methods at a glance} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) ``` # Purpose `build_contrast_analysis()` selects the model with its `method` argument. This vignette runs every method listed by `list_facades()` on one small simulated dataset and shows one line of output per method. Plots and a discussion of the methods are in the article [Comparing modelling methods on one dataset](https://fgcz.github.io/prolfqua/articles/ComparingMethods.html). ```{r factory, echo = FALSE, purl = FALSE, out.width = "100%", fig.cap = "build_contrast_analysis() is a factory: the method key selects the model, and every model rolls out with the same interface."} knitr::include_graphics("../man/figures/prolfqua_factory.png") ``` # Data We simulate peptide intensities for 20 proteins in three groups and compare group `A` with the control. ```{r simulate} library(prolfqua) sim <- sim_lfq_data(level = "peptide", n_proteins = 20, seed = 42) lfq_peptide <- LFQData$new(sim$data, sim$config) lfq_peptide <- transform_lfqdata(lfq_peptide, "log2") lfq_protein <- lfq_peptide$get_Aggregator()$aggregate() lfq_limpa <- lfq_peptide$get_Aggregator("limpa", prefix = "protein")$aggregate() contrasts <- c(A_vs_Ctrl = "group_A - group_Ctrl") ``` Each method declares the input it needs: - `aggregated`: protein-level input, here `lfq_protein` aggregated with median polish. `limpa` takes `lfq_limpa`, aggregated by `AggregateLimpa`, which adds the per-protein standard errors it needs. - `nested`: peptide-level input, `lfq_peptide`. The method models the peptides and reports protein-level contrasts. # Fit all methods ```{r fit, results = "hide"} facades <- list_facades() input_for <- function(method) { if (method == "limpa") { return(lfq_limpa) } if (facades[[method]]$needs == "nested") lfq_peptide else lfq_protein } model_for <- function(method) { if (method == "lmer_nested") "~ group_ + (1 | peptide_Id) + (1 | sampleName)" else "~ group_" } analyses <- lapply(names(facades), function(method) { build_contrast_analysis(input_for(method), model_for(method), contrasts, method = method) }) names(analyses) <- names(facades) results <- lapply(analyses, function(fa) fa$get_contrasts()) ``` The warnings come from single proteins: `lmer_nested` cannot fit a protein with one peptide, because its random peptide effect needs at least two; `rlm` stops at its iteration limit for one protein; `ropeca_nested` cannot fit a peptide observed in one group only; and the DEqMS moderation reports its note on the variance fit. Each analysis keeps the other proteins and records the failures, which `$provenance()` lists: ```{r provenance} analyses$lmer_nested$provenance() ``` # One line per method ```{r summary} about <- c( lm = "linear model per protein", lm_impute = "lm; groups without observations imputed at the limit of detection (LOD)", rlm = "robust linear model (MASS::rlm)", rfit = "rank-based regression (Rfit)", rfit_impute = "rfit with LOD imputation", limma = "limma, empirical-Bayes moderated variances", limma_impute = "limma with LOD imputation", limma_voom = "limma with vooma precision weights", limma_voom_impute = "limma_voom with LOD imputation", deqms = "limma with DEqMS peptide-count variance moderation", deqms_voom = "deqms with vooma precision weights", limpa = "limma on limpa DPC-quantified proteins", limpa_nested = "limpa, DPC quantification from peptides", firth = "Firth logistic regression, protein detection", binomial_nested = "quasibinomial model, peptide detection counts", binomial_firth_nested = "binomial_nested with Firth bias reduction", hurdle_nested = "lm_impute intensity + binomial_firth_nested detection", lmer_nested = "mixed model, peptide and sample random effects", ropeca_nested = "peptide fold changes summarised per protein (ROPECA)", ropecaV2_nested = "ROPECA with an exact, correlation-aware null for the median peptide z-score" ) overview <- data.frame( method = names(results), input = vapply(facades, function(x) x$needs, character(1)), proteins = vapply(results, nrow, integer(1)), FDR_lt_0.1 = vapply(results, function(x) sum(x$FDR < 0.1, na.rm = TRUE), integer(1)), model = about[names(results)] ) knitr::kable(overview, row.names = FALSE) ``` The detection models (`firth`, `binomial_nested`, `binomial_firth_nested`) test differences in how often a protein or its peptides are observed. The simulated data has few missing values, so they find little. # Missing values An `NA` intensity is a missing observation, and the method decides what happens to it: - dropped in each per-protein fit: `lm`, `rlm`, `rfit`, `limma`, `limma_voom`, `deqms`, `lmer_nested`, `ropeca_nested` - imputed at the limit of detection where a whole group is missing: the `_impute` methods - modelled as detection: `firth`, `binomial_nested`, `binomial_firth_nested`, and `hurdle_nested` together with the intensities - filled from the fitted models after the analysis: `impute_from_model()` The `log2()` transform turns zero intensities, which mean "not detected", into `NA`. `Inf`, `-Inf` and `NaN` intensities, and `NA` in protein, peptide, group or sample columns, stop the analysis with a classed error. What happened on the way is recorded: `$provenance()` of the analysis lists the values set to `NA`, removed rows, failed or singular fits, missing responses dropped per fit, and the proteins absent from a contrast with the reason. # One protein, all methods All methods return the same columns. Here is the protein with the smallest `lm` p-value. For the detection models `diff` is a log odds ratio, not a log2 fold change. This protein is detected in every sample, so the detection models report `diff` 0 and a p-value of 1 or `NaN`. ```{r one-protein} top <- results$lm$protein_Id[which.min(results$lm$p.value)] one <- lapply(results, function(x) x[x$protein_Id == top, c("diff", "p.value", "FDR")]) one <- dplyr::bind_rows(one, .id = "method") knitr::kable(one, digits = 3) ``` # Comparing methods `ContrastsComparison` aligns the results of several methods on protein and contrast. It shows which protein and contrast pairs each method estimates (`$coverage()`, `$upset()`) and where the methods contradict each other at an FDR threshold (`$conflicts()`): significant in opposite directions, significant in one method but not in another that tested the pair, or significant in one method and not estimated by another. Results of other tools can be compared too, as a `contrasts_table()` with a `ContrastConfiguration` that names their columns. Here one protein has no observations in group `A`: `lm` and `limma` cannot estimate its contrast, the `_impute` methods estimate it at the limit of detection. ```{r compare-methods} protein_data <- lfq_protein$data_long() gap <- sort(unique(protein_data$protein_Id))[1] lfq_gap <- lfq_protein$get_copy() lfq_gap$set_data(protein_data[!(protein_data$protein_Id == gap & protein_data$group_ == "A"), ]) methods <- c("lm", "limma", "lm_impute", "limma_impute") gap_analyses <- lapply(stats::setNames(methods, methods), function(method) { build_contrast_analysis(lfq_gap, "~ group_", contrasts, method = method) }) comparison <- ContrastsComparison$new(gap_analyses, fdr_threshold = 0.1) knitr::kable(comparison$coverage()) conflicts <- comparison$conflicts() flagged <- conflicts$sign_conflict | conflicts$significance_conflict | conflicts$coverage_conflict knitr::kable(conflicts[flagged, ]) ``` # Inspecting a fitted analysis The fitted analysis supports standard R methods. `print()` gives the model specification, fit counts, a one-line provenance summary and a coefficient preview without calculating contrasts. `summary()` evaluates the contrasts and counts estimated, missing and significant results; the significance defaults are FDR < 0.05 and absolute effect > 1. ```{r inspect-analysis} analysis <- build_contrast_analysis(lfq_protein, "~ group_", contrasts, method = "lm") print(analysis) summary(analysis) analysis$provenance() head(coef(analysis)) head(vcov(analysis)) head(confint(analysis)) formula(analysis) head(nobs(analysis)) head(fitted(analysis)) head(residuals(analysis)) plot(analysis) plot(analysis, type = "volcano") ``` Coefficient tables describe the fitted model; requested comparisons remain available through `analysis$get_contrasts()`. Confidence intervals are Wald t intervals, with moderated standard errors and degrees of freedom for limma and normal Wald intervals for the Firth logistic backend. ROPECA coefficient tables are keyed by protein and peptide because those methods fit peptide-level models. `vcov()` returns the coefficient covariance as a long table keyed by subject, `term` and `term2`. LOD-refitted models use their borrowed covariance; matrix models use the moderated variance and each subject's weighted design. The default plot shows observed responses and fitted group means with confidence intervals for the six subjects with the smallest FDR in the first contrast. Select other subjects with `plot(analysis, subject = top, level = 0.9)`. Points and intervals share the modelled response scale; detection models show probabilities, and mixed models use fixed-effect means with Satterthwaite intervals. For multiple factors, the plotted means correspond to factor combinations. ROPECA plots have one panel per peptide of each selected protein. Volcano and MA plots remain available through `type = "volcano"` and `type = "ma"`; combined hurdle analyses default to volcano and require selecting an intensity or detection component for a fitted plot. The modelling call retains its input, and the fitted-value and residual accessors retain observed modelled responses. Internal child-feature aggregation and detection encoding have no inverse. Preceding LFQData transformations retain their original input columns; they are not recorded as a new transformation-history object. See `?build_contrast_analysis` for the affected methods and output scales. Fitted values and residuals retain sample, factor and available child-feature identifiers. They include observed responses from successful fits and a subject-level `imputed` flag; rows filled during LOD imputation are excluded. The values use the fitting scale: log2 intensity here, and probabilities for detection models. Binomial detection responses are the adjusted proportions used in fitting; response residuals equal response minus fitted probability. `nobs()` excludes imputed observations. Hurdle results combine two fitted models. Their print, summary and plot methods describe the combined analysis; use `analysis$contrast$intensity` or `analysis$contrast$detection` for coefficients, formula, observation counts, fitted values and residuals. # Session info ```{r session-info} sessionInfo() ```