Model differential protein abundance
The condition coefficient estimates a relative abundance difference between the resistant derivative and parental SKBR3. The biological observations are cultures. Peptides improve the measurement of a protein group but do not increase the number of independent cultures in its model.
The main analysis uses accepted groups with two group-unique peptide sequences and at least two measured cultures per condition. It fits observed normalized log2 abundance without filling missing entries.
The linear regression lesson introduces coefficients and residual assumptions. The multiple testing lesson explains hypothesis families and BH correction.
Declare the contrast
Section titled “Declare the contrast”The design contains an intercept and a resistant-condition indicator. Parental is the reference, so a positive coefficient means higher relative abundance in the resistant derivative. Equal replicate numbers across the two conditions do not define paired samples.
The design has no additional measured batch factor. Adding a guessed batch from filename order would invent information about sample preparation or acquisition. A verified batch that is completely confounded with condition would prevent the model from separating those effects.
Each group has its own observed sample subset. The fit checks that both conditions remain represented and that the residual degrees of freedom are positive. The output retains the number of measured cultures per condition beside the effect estimate.
Use limma for the primary inference
Section titled “Use limma for the primary inference”The R analysis fits the condition model with limma and applies empirical Bayes variance moderation with trend = TRUE and robust = TRUE. It uses Winsorization tail proportions of 0.05 and 0.10. The prior differential proportion is 0.01; that option affects the B-statistic, which this lesson does not interpret. Moderation borrows information across protein groups to estimate residual variability; it does not add biological replicates.
The result table retains the log2 fold change, standard error, test statistic, p-value, BH-adjusted p-value, and full group membership. The BH family contains the eligible fitted groups defined before the significance threshold is applied.
An effect estimate remains useful when its adjusted p-value exceeds the decision threshold. Conversely, a small adjusted p-value does not establish a large effect or a mechanism of resistance. The comparison concerns this parental line and this resistant derivative.
Compare only equivalent calculations
Section titled “Compare only equivalent calculations”The paired Python example independently fits ordinary least squares to the same observed values and design. It compares ordinary coefficients, standard errors, degrees of freedom, test statistics, and p-values with their R counterparts.
Those checks establish numerical agreement for the shared linear model. They do not make Python’s ordinary p-values equivalent to limma’s moderated p-values. The primary inference remains the explicitly identified R result.
The output keeps both calculations so readers can inspect how variance moderation changes inference without confusing that change with a sample-order error.
Report sensitivity and scope
Section titled “Report sensitivity and scope”The sensitivity tables compare complete cases and unnormalized abundance with the main result. Shared complete-case groups retain exactly the same values, median offsets, and design, so their effects are identical by construction. Their diagonal effect plot follows from those unchanged inputs and adds no independent evidence of stability. The complete-case sensitivity assesses eligibility, the fitted variance prior, and the BH family. A discovery count from a different population does not by itself measure stability.
The visualization lesson shows culture-level measurements for selected groups alongside the volcano plot. The pathway lesson then uses only defensible group annotations and the declared tested background.
Fit and compare the declared models
Section titled “Fit and compare the declared models”The shared source verifies fixture hashes and the recorded sample review before it fits limma. Its ordinary calculation uses the observed difference in condition means, pooled residual variance, and residual degrees of freedom equal to the observation count minus two. Groups with zero residual variance remain in the output with a specific exclusion reason.
Both sensitivity models refit limma. The complete-case model uses the primary median offsets and changes only row eligibility. The model without sample scaling uses the original log2 abundance and the primary eligibility rule. Each fit estimates its own variance prior and applies BH to its own tested family, so the table compares shared effects as well as discovery counts.
Interpret this cohort
Section titled “Interpret this cohort”The primary moderated analysis tests 463 groups and reports 171 BH findings at the declared threshold. The ordinary comparison reports 131 findings.
The analysis without sample scaling retains the same effect direction for 370 of 463 shared fits. Interpret each result with the normalization sensitivity and condition-specific detection patterns.
library(ggplot2)library(jsonlite)source("/shared/ms_common.R")source("/shared/ms_models.R")data <- PrepareMsAnalysis(LoadMsData())ordinary <- FitMsOrdinary(data)primary <- FitMsLimma(data)unscaled <- FitMsLimma(data, matrix = data$log_abundance)complete <- FitMsLimma(data, eligible = data$complete)primary$members <- data$groups$memberswrite.csv(primary, "outputs/primary_limma_r.csv", row.names = FALSE, na = "NA")variants <- list(primary = primary, no_sample_scaling = unscaled, complete_cases = complete)ordinary_variants <- list( primary = ordinary, no_sample_scaling = FitMsOrdinary(data, matrix = data$log_abundance), complete_cases = FitMsOrdinary(data, eligible = data$complete))summaries <- list()comparison_rows <- list()for (name in names(variants)) { result <- variants[[name]] write.csv(result, paste0("outputs/limma_", name, "_r.csv"), row.names = FALSE, na = "NA") write.csv(ordinary_variants[[name]], paste0("outputs/ordinary_", name, "_r.csv"), row.names = FALSE, na = "NA") shared <- primary$tested & result$tested summaries[[name]] <- data.frame( model = name, tested = sum(result$tested), significant = sum(result$adjusted_p_value < 0.05, na.rm = TRUE), shared_tested = sum(shared), median_effect_difference = median(abs( result$log2_fold_change[shared] - primary$log2_fold_change[shared] )), same_effect_direction = sum( sign(result$log2_fold_change[shared]) == sign(primary$log2_fold_change[shared]) ) ) if (name != "primary") { comparison_rows[[name]] <- data.frame( group_id = result$group_id[shared], model = name, primary_effect = primary$log2_fold_change[shared], alternative_effect = result$log2_fold_change[shared] ) }}sensitivity <- do.call(rbind, summaries)write.csv(sensitivity, "outputs/sensitivity_r.csv", row.names = FALSE)comparisons <- do.call(rbind, comparison_rows)write.csv(comparisons, "outputs/effect_comparisons_r.csv", row.names = FALSE)metrics <- list( tested_groups = sum(primary$tested), ordinary_significant = sum(ordinary$adjusted_p_value < 0.05, na.rm = TRUE), moderated_significant = sum(primary$adjusted_p_value < 0.05, na.rm = TRUE), complete_case_tested = sum(complete$tested))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)WriteMsModelProvenance("outputs/model_provenance_r.json")cat("Tested protein groups:", metrics$tested_groups, "\n")cat("Ordinary BH discoveries:", metrics$ordinary_significant, "\n")cat("Moderated BH discoveries:", metrics$moderated_significant, "\n")cat("Complete-case tested groups:", metrics$complete_case_tested, "\n")Tested protein groups: 463Ordinary BH discoveries: 131Moderated BH discoveries: 171Complete-case tested groups: 341ma_rows <- rbind( data.frame(model = "Median offsets", ordinary[ordinary$tested, ]), data.frame(model = "No sample scaling", ordinary_variants$no_sample_scaling[ ordinary_variants$no_sample_scaling$tested, ]))ma_plot <- ggplot(ma_rows, aes(mean_log2_abundance, log2_fold_change)) + geom_hline(yintercept = 0, color = "gray60") + geom_point(alpha = 0.35, size = 0.7, color = "#287c8e") + facet_wrap(~model) + labs(x = "Mean observed log2 abundance", y = "Resistant minus parental log2 effect") + theme_minimal(base_size = 11)ggsave("outputs/ma_models_r.png", ma_plot, width = 10, height = 4.5, dpi = 160, bg = "white")sensitivity_plot <- ggplot(comparisons, aes(primary_effect, alternative_effect)) + geom_abline(slope = 1, intercept = 0, color = "gray60") + geom_point(alpha = 0.35, size = 0.7, color = "#287c8e") + facet_wrap(~model) + labs(x = "Primary log2 effect", y = "Sensitivity log2 effect") + theme_minimal(base_size = 11)ggsave("outputs/model_sensitivity_r.png", sensitivity_plot, width = 10, height = 4.5, dpi = 160, bg = "white")

import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
modules = {}for name in ["ms_common", "ms_models"]: spec = importlib.util.spec_from_file_location(name, f"/shared/{name}.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) modules[name] = modulems, models = modules["ms_common"], modules["ms_models"]data = ms.prepare_ms_analysis(ms.load_ms_data())if data["provenance"]["scientific_sample_review_complete"] is not True: raise ValueError("The scientific sample review is incomplete")ordinary = models.fit_ordinary(data)variants = { "primary": ordinary, "no_sample_scaling": models.fit_ordinary( data, matrix=data["log_abundance"]), "complete_cases": models.fit_ordinary(data, eligible=data["complete"]),}for name, result in variants.items(): expected = pd.read_csv(f"outputs/ordinary_{name}_r.csv") pd.testing.assert_frame_equal(result, expected, check_dtype=False, rtol=1e-10, atol=1e-10) result.to_csv(f"outputs/ordinary_{name}_python.csv", index=False, na_rep="NA")primary = pd.read_csv("outputs/primary_limma_r.csv")if not primary["group_id"].equals(ordinary["group_id"]): raise ValueError("The primary and ordinary group orders differ")np.testing.assert_array_equal(primary["tested"], ordinary["tested"])np.testing.assert_allclose(primary["log2_fold_change"], ordinary["log2_fold_change"], atol=1e-10, rtol=1e-10, equal_nan=True)metrics = { "tested_groups": int(ordinary["tested"].sum()), "ordinary_significant": int(ordinary["adjusted_p_value"].lt(0.05).sum()), "moderated_significant": int(primary["adjusted_p_value"].lt(0.05).sum()), "complete_case_tested": int(variants["complete_cases"]["tested"].sum()),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Tested protein groups:", metrics["tested_groups"])print("Ordinary BH discoveries:", metrics["ordinary_significant"])print("R moderated BH discoveries:", metrics["moderated_significant"])print("Complete-case tested groups:", metrics["complete_case_tested"])Tested protein groups: 463Ordinary BH discoveries: 131R moderated BH discoveries: 171Complete-case tested groups: 341figure, axes = plt.subplots(1, 2, figsize=(10, 4.5), sharey=True)for axis, name in zip(axes, ["primary", "no_sample_scaling"]): result = variants[name].loc[variants[name]["tested"]] axis.axhline(0, color="gray", linewidth=0.8) axis.scatter(result["mean_log2_abundance"], result["log2_fold_change"], s=4, alpha=0.35, color="#287c8e") axis.set_title(name.replace("_", " ")) axis.set_xlabel("Mean observed log2 abundance")axes[0].set_ylabel("Resistant minus parental log2 effect")figure.tight_layout()figure.savefig("outputs/ma_models_python.png", dpi=160, facecolor="white")plt.close(figure)figure, axes = plt.subplots(1, 2, figsize=(10, 4.5))comparisons = []for axis, name in zip(axes, ["no_sample_scaling", "complete_cases"]): result = variants[name] shared = ordinary["tested"] & result["tested"] table = pd.DataFrame({ "group_id": result.loc[shared, "group_id"], "model": name, "primary_effect": ordinary.loc[shared, "log2_fold_change"], "alternative_effect": result.loc[shared, "log2_fold_change"], }) comparisons.append(table) axis.axline((0, 0), slope=1, color="gray", linewidth=0.8) axis.scatter(table["primary_effect"], table["alternative_effect"], s=4, alpha=0.35, color="#287c8e") axis.set_title(name.replace("_", " ")) axis.set_xlabel("Primary log2 effect") axis.set_ylabel("Sensitivity log2 effect")comparison = pd.concat(comparisons, ignore_index=True)pd.testing.assert_frame_equal( comparison, pd.read_csv("outputs/effect_comparisons_r.csv"), check_dtype=False, rtol=1e-10, atol=1e-10)comparison.to_csv("outputs/effect_comparisons_python.csv", index=False)figure.tight_layout()figure.savefig("outputs/model_sensitivity_python.png", dpi=160, facecolor="white")plt.close(figure)

The Python tab reads the moderated results from the fresh R run only for their explicitly labeled discovery count. It independently computes every ordinary statistic and both effect comparisons. A changed moderated discovery count therefore describes the variance model, not a second independent confirmation of the biology.
Further reading
Section titled “Further reading”The limma linear model reference describes the design matrix, coefficient estimates, and residual quantities returned by lmFit. The R linear model reference provides the corresponding ordinary regression definitions used for the comparison.
The R p-value adjustment reference distinguishes BH false discovery rate control from procedures that control the probability of any false rejection. It explains the adjustment applied across the protein hypotheses.