[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CVCPK6SD0YYQWT92ANHM07":3,"skill-same:01M7CVCPK6SD0YYQWT92ANHM07":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":37,"repositoryHtmlUrl":38,"repositoryHomepageUrl":6,"ownerHtmlUrl":39,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":40,"install":41,"resources":53},"01M7CVCPK6SD0YYQWT92ANHM07","bio-workflows-proteomics-pipeline",null,"Orchestrates bottom-up proteomics from a search engine's output (MaxQuant\u002FFragPipe\u002FDIA-NN) to differential protein abundance with limma\u002FDEqMS\u002FMSstats. Use when committing the search database + acquisition mode (DDA vs DIA) up front, re-controlling FDR at PSM AND peptide AND protein-group level (not just PSM), removing contaminant\u002Freverse rows and inspecting RAW distributions before normalizing, bridging cross-plex TMT with an IRS reference channel, modeling MNAR missingness rather than downshift-imputing on\u002Foff proteins, batching as a covariate (not pre-subtracted), and testing with treat()\u002FDEqMS. Hands mechanism to the proteomics component skills; not a re-teach of any single step.","mrsonord2240\u002Fopenscience-specialists","mrsonord2240","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F76487430?v=4","01M7CTEM40S43GSJZ9A3YCCXZK","Samuel Nord","01M7CTEM4K69JD1GBYNHVJ9ZP4",2,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-proteomics-pipeline\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-workflows-proteomics-pipeline\ndescription: Orchestrates bottom-up proteomics from a search engine's output (MaxQuant\u002FFragPipe\u002FDIA-NN) to differential protein abundance with limma\u002FDEqMS\u002FMSstats. Use when committing the search database + acquisition mode (DDA vs DIA) up front, re-controlling FDR at PSM AND peptide AND protein-group level (not just PSM), removing contaminant\u002Freverse rows and inspecting RAW distributions before normalizing, bridging cross-plex TMT with an IRS reference channel, modeling MNAR missingness rather than downshift-imputing on\u002Foff proteins, batching as a covariate (not pre-subtracted), and testing with treat()\u002FDEqMS. Hands mechanism to the proteomics component skills; not a re-teach of any single step.\ntool_type: mixed\nprimary_tool: limma\nworkflow: true\ndepends_on:\n  - proteomics\u002Fdata-import\n  - proteomics\u002Fproteomics-qc\n  - proteomics\u002Fquantification\n  - proteomics\u002Fprotein-inference\n  - proteomics\u002Fdifferential-abundance\n  - proteomics\u002Fdia-analysis\n---\n\n## Version Compatibility\n\nReference examples tested with: MSnbase 2.32.0, limma 3.62.2, MSstats 4.14.2, DEqMS 1.24.0, proDA 1.20.0, MSstatsTMT 2.14.2, arrow 23.0.1 (DIA-NN report.parquet), dplyr 1.2.1, tidyr 1.3.2, ggplot2 4.0.3 (checked 2026-09-15 on R 4.4.3)\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Proteomics Pipeline\n\n**\"Process my proteomics data from raw MS files to differential abundance\"** -> Orchestrate data import (pyopenms\u002FMaxQuant), QC assessment, protein quantification, normalization, differential abundance testing (limma\u002FDEqMS, or MSstats for feature-level designs), and PTM analysis.\n\nThis is a workflow skill: it owns the chaining decisions and hand-offs, not the internals of any one step.\n\nScope: research cohort comparison. A pipeline output is not a diagnostic -- do not use it to triage, escalate or choose treatment for an individual patient; route those questions to validated clinical assays and the treating clinician.\n\n## The governing principle\n\nBottom-up proteomics never measures proteins; it measures peptides and INFERS proteins, and the trustworthiness decisions are made at seams before the statistics.\n\n1. **The search database + acquisition mode are committed once and inherited by everything.** The FASTA fixes the target-decoy frame (concatenated one-search FDR = #decoy\u002F#target; a separate-search design needs mix-max instead — mixing the two mis-estimates FDR), what counts as a \"unique peptide\" (relative to the DB: canonical vs +isoforms), and the contaminants (cRAP must be IN the search DB from the start; a contaminant can BE the protein of interest, so never blind-delete `CON__` rows). DDA vs DIA is set at the instrument and dictates which imputation is even legitimate.\n2. **FDR is re-controlled at THREE levels, not just PSM — and match-between-runs has its OWN FDR.** 1% PSM-FDR does NOT give 1% protein-FDR — each level (PSM, peptide, protein-group) needs its own target-decoy estimation; PSM-only filtering yields 10-30% real protein-FDR on deep data (one false PSM nucleates a false one-hit-wonder, and false proteins grow with dataset size). Use picked-protein\u002Fpicked-group FDR. The two-peptide rule INCREASES protein-FDR, it does not reduce it. MBR transfers IDs across runs by RT\u002Fm-z and can be wrong for low-abundance precursors — do NOT report MBR-filled counts as directly measured; DIA-NN controls MBR-FDR via `Lib.*` q-values, IonQuant via an explicit MBR-FDR mixture model.\n3. **Missingness is MODELED, not filled.** DDA missingness is structured left-censored MNAR; downshift imputation (mean=mu-1.8sigma) on an on\u002Foff protein inflates the t-numerator AND deflates the denominator (the volcano \"wing\" artifact). The honest report for a protein missing in one whole group is \"undetected in group B\", not a fold change — model the MNAR (proDA\u002Fmsqrob2\u002FMSstats-AFT).\n4. **Normalize AFTER contaminant removal and AFTER inspecting raw distributions; batch is a covariate, not pre-subtracted.** Median-normalizing first mathematically erases a 3x-low load. Cross-plex TMT is invalid without an IRS bridge. `removeBatchEffect` before testing understates residual variance (anticonservative p) — put batch in the same model.\n\n## Made-once commitments\n\n| Commitment | Consequence inherited downstream |\n|------------|----------------------------------|\n| Search FASTA + target-decoy strategy | The FDR estimator, what a \"unique peptide\" is, which contaminants exist; a mismatch mis-estimates FDR silently |\n| Enzyme + fixed\u002Fvariable mods (Carbamidomethyl-Cys fixed) | Which peptides exist to quantify; a fixed-mod misconfig loses all Cys peptides |\n| DDA vs DIA acquisition mode | Missingness structure (MNAR vs ~MCAR), whether TMT is possible, which imputation is legitimate |\n| FDR framing (PSM + peptide + protein-group, 1% each) | Real protein-FDR; PSM-only is 10-30% wrong on deep data |\n\n## Pipeline Overview\n\n```\nRaw MS Data (mzML) --> MaxQuant\u002FDIA-NN --> proteinGroups.txt\n                                                 |\n                                                 v\n            +--------------------------------------------+\n            |             proteomics-pipeline            |\n            +--------------------------------------------+\n            |  1. Data Import & Filtering                |\n            |  2. Log2 + inspect RAW distributions       |\n            |  3. Normalization (after the inspection)   |\n            |  4. Per-Group Completeness Filter          |\n            |  5. QC: PCA, Correlation                   |\n            |  6. Differential Abundance (limma\u002FMSstats) |\n            |  7. Visualization & Export                 |\n            +--------------------------------------------+\n                                                 |\n                                                 v\n                  Differential Proteins + Volcano Plots\n```\n\n## Complete R Workflow\n\n**Goal:** Turn a MaxQuant or DIA-NN protein matrix into a table of differentially abundant proteins with honest missing-value handling.\n\n**Approach:** Strip bookkeeping rows, log2 and inspect the RAW per-sample distributions (dropping failed loads before normalization can hide them), median-center, filter on per-group completeness, then test the OBSERVED values with moderated limma using treat() for a minimum fold change and batch as a covariate -- nothing is imputed. Upgrade to proDA when the dropout itself has to be modeled.\n\n```r\nlibrary(limma)\nlibrary(ggplot2)\nlibrary(pheatmap)\n\n# === 1. DATA IMPORT ===\n# quote = '' \u002F comment.char = '': MaxQuant text fields contain quotes and '#'; the defaults\n# silently truncate the table with only an 'EOF within quoted string' warning. Check the count.\nproteins \u003C- read.delim('proteinGroups.txt', stringsAsFactors = FALSE, quote = '', comment.char = '')\nstopifnot(nrow(proteins) == length(readLines('proteinGroups.txt')) - 1)\ncat('Loaded', nrow(proteins), 'protein groups\\n')\n\n# Filter contaminants, reverse, only-by-site. Use %in%, NOT `!= '+'`: when a run flags none of a\n# category the column is entirely empty, read.delim types it as logical NA, `NA != '+'` is NA, and\n# subsetting by NA replaces every row with NAs while nrow() still looks right.\nproteins \u003C- proteins[!(proteins$Potential.contaminant %in% '+') &\n                      !(proteins$Reverse %in% '+') &\n                      !(proteins$Only.identified.by.site %in% '+'), ]\nstopifnot(!all(is.na(proteins$Majority.protein.IDs)))\ncat('After filtering:', nrow(proteins), 'proteins\\n')\n\n# Extract LFQ intensities\nlfq_cols \u003C- grep('^LFQ\\\\.intensity\\\\.', colnames(proteins), value = TRUE)\nintensities \u003C- proteins[, lfq_cols]\nrownames(intensities) \u003C- proteins$Majority.protein.IDs\ncolnames(intensities) \u003C- gsub('LFQ\\\\.intensity\\\\.', '', colnames(intensities))\n\n# === 2. LOG2 TRANSFORM, THEN INSPECT RAW DISTRIBUTIONS ===\nintensities[intensities == 0] \u003C- NA\nlog2_int \u003C- log2(intensities)\n\n# Inspect BEFORE normalizing (rule 4). Median-centering rescales every sample onto a common median,\n# so it mathematically erases the 3x-low load that marks a failed injection -- after this point the\n# failure is invisible. Identify and drop failures HERE.\n# Inspect the RAW `Intensity.` columns, NOT `LFQ intensity`: MaxLFQ has ALREADY renormalized the LFQ\n# columns onto a common scale, so a low load is largely gone from them before you ever look.\nraw_cols \u003C- grep('^Intensity\\\\.', colnames(proteins), value = TRUE)\nraw_log2 \u003C- log2(replace(proteins[, raw_cols], proteins[, raw_cols] == 0, NA))\ncolnames(raw_log2) \u003C- gsub('^Intensity\\\\.', '', colnames(raw_log2))\nraw_log2 \u003C- raw_log2[, colnames(log2_int), drop = FALSE]\nraw_median \u003C- apply(raw_log2, 2, median, na.rm = TRUE)\nid_counts \u003C- colSums(!is.na(log2_int))\nboxplot(raw_log2, las = 2, main = 'RAW log2 Intensity (pre-normalization)', ylab = 'log2 intensity')\nprint(data.frame(id_count = id_counts, raw_median_log2 = round(raw_median, 2),\n                 load_shift_log2 = round(raw_median - median(raw_median), 2)))\n\n# Flag on BOTH axes and as an OUTLIER, not a fixed fraction: a >=2x (1 log2) drop in raw median\n# signal, OR an ID count more than 3 MADs below the cohort median. Each axis alone misses cases --\n# a 3x-low injection loses its dimmest proteins entirely, so the SURVIVING median understates the\n# deficit (a 3.0x low load can read as only -0.8 log2), while a 50%-of-median ID-count rule is so\n# loose that a run at 82% of the median IDs, visibly low on both axes, passes it.\nmad_ids \u003C- mad(id_counts)\nfailed \u003C- colnames(raw_log2)[(raw_median - median(raw_median)) \u003C= -1 |\n                             (mad_ids > 0 & id_counts \u003C median(id_counts) - 3 * mad_ids)]\nif (length(failed) > 0) {\n    message('Dropping failed samples: ', paste(failed, collapse = ', '))\n    log2_int \u003C- log2_int[, !colnames(log2_int) %in% failed, drop = FALSE]\n}\n\n# === 3. NORMALIZE (only after the raw inspection above) ===\n# ASSUMPTION: median centering assumes most proteins are unchanged AND that the changes that do\n# occur are roughly SYMMETRIC up\u002Fdown. When they are not -- an enrichment pulldown, a secretome, a\n# strong one-sided drug response -- the shift it removes is real signal, and the whole unchanged\n# proteome acquires the opposite offset. Measured on a set with 44 up vs 26 down among 296\n# proteins: every true null moved -0.19 log2 (t vs 0, p = 2e-55) and 21 of 179 true nulls were\n# called at BH 5%, all negative. Normalize on a set expected to be unchanged (spike-in standards,\n# an internal-reference protein set, or the housekeeping bulk) when the design is one-sided,\n# and always check the null centre afterwards -- see the Common Errors row.\nsample_medians \u003C- apply(log2_int, 2, median, na.rm = TRUE)\nglobal_median \u003C- median(sample_medians)\nnormalized \u003C- sweep(log2_int, 2, sample_medians - global_median)\n\n# === 4. FILTER ON PER-GROUP COMPLETENESS (do NOT impute by default) ===\n# Filter FIRST on completeness PER GROUP: keep a protein if it is valid in >= ~50-70%\n# of replicates in AT LEAST ONE condition. A protein missing in every group fails QC.\nsample_info \u003C- read.csv('sample_annotation.csv')\n# Re-align the annotation to the samples that SURVIVED the raw-distribution QC above; otherwise the\n# column indexing below requests a dropped sample and errors (or silently misaligns the design).\n# match() also puts the rows in COLUMN order: lmFit pairs design rows with matrix columns\n# POSITIONALLY, so an annotation sorted differently from the intensity columns fits a wrong design\n# in silence. Never subset the annotation with `%in%` alone here.\nsample_info \u003C- sample_info[match(colnames(normalized), sample_info$sample), ]\nstopifnot(!any(is.na(sample_info$sample)))\nsample_info$condition \u003C- droplevels(factor(sample_info$condition))\nmin_frac \u003C- 0.6   # >= 60% present within at least one group; tune 0.5-0.7 per design\ngroup_complete \u003C- sapply(levels(sample_info$condition), function(g) {\n    cols \u003C- sample_info$sample[sample_info$condition == g]\n    rowSums(!is.na(normalized[, cols, drop = FALSE])) >= ceiling(length(cols) * min_frac)\n})\nvalid_rows \u003C- rowSums(group_complete) > 0\nfiltered \u003C- normalized[valid_rows, ]\ncat('Proteins after per-group completeness filter:', nrow(filtered), '\\n')\n\n# Missingness in label-free DDA is left-censored MNAR (missing BECAUSE low). The modern,\n# correct approach is to MODEL the missingness in the likelihood, NOT impute it. See\n# proteomics\u002Fdifferential-abundance for the decision (proDA \u002F msqrob2 \u002F MSstats-AFT).\n# NOTHING BELOW IMPUTES: limma fits each protein on its OBSERVED values, so the completeness\n# filter above is the only missing-value handling in the executed path.\n\n# --- UPGRADE: model the dropout explicitly with proDA, then use `da` in place of `results` ---\n# library(proDA)\n# fit \u003C- proDA(as.matrix(filtered), design = ~ condition, col_data = sample_info,\n#              reference_level = 'Control')            # add batch: design = ~ batch + condition\n# da \u003C- test_diff(fit, contrast = 'conditionTreatment')   # columns: diff (log2FC), pval, adj_pval\n\n# --- DO NOT: left-censored downshift imputation, then limma ---\n# Downshift MANUFACTURES systematic false positives for on\u002Foff proteins near the detection limit\n# (the volcano \"anchor arms\"): it pins missing values ~1.8 SD below the mean with an artificially\n# tight 0.3 SD spread, inflating the t-numerator and deflating its denominator. The honest report\n# for a protein fully missing in one group is \"undetected in group B\", NOT a fold change. If a\n# reviewer demands a complete matrix anyway, seed it (set.seed) so the call list is reproducible,\n# and report the on\u002Foff proteins separately -- see proteomics\u002Fdifferential-abundance.\n\n# === 5. QC ===\n# PCA needs a complete matrix; use the proteins observed everywhere rather than inventing values.\n# The complete-case set can be EMPTY -- 12 samples at realistic MNAR dropout is enough -- and\n# prcomp then aborts the whole workflow at step 5 of 7 with `a dimension is zero`, which says\n# nothing about missingness. Guard it, say what happened, and fall back to the pairwise-complete\n# sample correlation, which answers the same clustering question without a complete matrix.\n# QC is diagnostic: it must not gate the statistics below, and it is never a reason to impute.\ncomplete \u003C- filtered[stats::complete.cases(filtered), , drop = FALSE]\ncat('Proteins used for PCA (complete cases):', nrow(complete), '\\n')\npca_df \u003C- NULL\nif (nrow(complete) >= 3) {\n    pca \u003C- prcomp(t(complete), scale. = TRUE)\n    pca_df \u003C- data.frame(PC1 = pca$x[, 1], PC2 = pca$x[, 2], Sample = rownames(pca$x))\n} else {\n    message('PCA skipped: only ', nrow(complete), ' protein(s) observed in EVERY sample. ',\n            'That is missingness, not a corrupt matrix -- lower min_frac, drop the sparsest ',\n            'samples, or read the correlation below. Do NOT impute to fill the matrix.')\n    sample_cor \u003C- cor(as.matrix(filtered), use = 'pairwise.complete.obs', method = 'spearman')\n    print(round(sample_cor, 2))\n}\n\n# === 6. DIFFERENTIAL ANALYSIS (limma on the observed values) ===\n# sample_info is already loaded and factored in step 4. Batch is a COVARIATE in the same model\n# (rule 4); removeBatchEffect() is visualization-only, never an input to lmFit.\nhas_batch \u003C- 'batch' %in% colnames(sample_info) && length(unique(sample_info$batch)) > 1\ndesign \u003C- if (has_batch) model.matrix(~ 0 + condition + factor(batch), data = sample_info) else\n                         model.matrix(~ 0 + condition, data = sample_info)\ncolnames(design)[seq_along(levels(sample_info$condition))] \u003C- levels(sample_info$condition)\ncolnames(design) \u003C- make.names(colnames(design))\ncat('design columns:', colnames(design), '| batch in design:', has_batch, '\\n')\n\nfit \u003C- lmFit(as.matrix(filtered), design)\n# Build the contrasts FROM the factor levels. A hard-coded `makeContrasts(Treatment - Control)`\n# handles exactly one design: a three-condition dose series or a time course dies with\n# `object 'Treatment' not found` even though the design matrix built one line above is correct.\n# The reference is the FIRST level -- set it explicitly with relevel() if alphabetical order puts\n# the wrong condition first. Two conditions give the single Treatment-Control contrast as before.\nref \u003C- levels(sample_info$condition)[1]\nothers \u003C- setdiff(levels(sample_info$condition), ref)\ncontrast \u003C- makeContrasts(contrasts = paste(make.names(others), '-', make.names(ref)), levels = design)\ncolnames(contrast) \u003C- paste0(others, '_vs_', ref)\ncat('contrasts:', colnames(contrast), '\\n')\nfit2 \u003C- contrasts.fit(fit, contrast)\n\n# Select on FDR ALONE. A post-hoc fold-change + significance double filter inflates FDR\n# (a collider\u002Fselection effect; realized FDR can exceed 50%). To require a minimum effect,\n# use the moderated minimum-fold-change test treat()\u002FtopTreat() instead of filtering after.\nfit2_treat \u003C- treat(fit2, lfc = log2(1.5), trend = TRUE, robust = TRUE)   # moderated min-FC test; trend+robust ~mandatory for label-free LFQ\n# topTreat adjusts WITHIN one contrast. With more than one contrast the family of tests is the\n# whole set, so adjust ACROSS them: decideTests(method = 'global') applies one BH over every\n# protein x contrast cell, which is what the significance calls below use. With a single contrast\n# it is identical to the per-contrast BH, so the two-condition result is unchanged.\nresults \u003C- do.call(rbind, lapply(colnames(contrast), function(cn) {\n    tt \u003C- topTreat(fit2_treat, coef = cn, number = Inf, sort.by = 'none')\n    data.frame(protein = rownames(tt), contrast = cn, tt, row.names = NULL)\n}))\n# unclass(): decideTests returns an S4 TestResults, which as.matrix() does NOT demote, and whose\n# `[` refuses the two-column character index used below ('Two subscripts required').\ndt \u003C- unclass(decideTests(fit2_treat, method = 'global', adjust.method = 'BH', p.value = 0.05))\n# A protein observed in only one group (or one batch level) has no estimable contrast: limma\n# returns NA, and `adj.P.Val \u003C 0.05` would make every downstream sum() NA. Report those separately\n# as \"undetected in group B\" -- that is the honest statement, not a fold change.\nresults$significant \u003C- !is.na(results$adj.P.Val) &\n                       dt[cbind(results$protein, results$contrast)] != 0\n# To ask instead \"does this protein change ANYWHERE across the conditions\" (an omnibus\u002FANOVA\n# question rather than a set of pairwise ones), F-test all contrast columns at once:\n#   fit2_eb \u003C- eBayes(fit2, trend = TRUE, robust = TRUE)\n#   anova_res \u003C- topTable(fit2_eb, number = Inf)   # F and its BH-adjusted p across all contrasts\n# Use it to screen, then report the pairwise contrasts for direction. treat() has no F-test.\n\n# === 7. OUTPUT ===\ncat('\\nResults:\\n')\ncat('  Contrast not estimable (report as undetected-in-group):', sum(is.na(results$logFC)), '\\n')\ncat('  Significant proteins:', sum(results$significant), '\\n')\ncat('  Up-regulated:', sum(results$significant & results$logFC > 0), '\\n')\ncat('  Down-regulated:', sum(results$significant & results$logFC \u003C 0), '\\n')\nfor (cn in colnames(contrast)) {                       # per-contrast breakdown (>=2 contrasts)\n    k \u003C- results$contrast == cn & results$significant\n    cat('   ', cn, ':', sum(k), '(Up', sum(k & results$logFC > 0), 'Down', sum(k & results$logFC \u003C 0), ')\\n')\n}\n\nwrite.csv(results, 'proteomics_results.csv', row.names = FALSE)\n```\n\n## MSstats Workflow\n\n```r\nlibrary(MSstats)\n\n# From MaxQuant. quote = '' and comment.char = '' are REQUIRED: MaxQuant text fields contain\n# apostrophes (5'-nucleotidase) and '#', and the read.table defaults silently truncate the table\n# with nothing but an 'EOF within quoted string' warning -- here 2954 of 10369 evidence rows and\n# 62 of 296 proteins. Check the row count; do not trust the warning to stop you.\nevidence \u003C- read.table('evidence.txt', sep = '\\t', header = TRUE, quote = '', comment.char = '')\nproteinGroups \u003C- read.table('proteinGroups.txt', sep = '\\t', header = TRUE, quote = '', comment.char = '')\nstopifnot(nrow(evidence) == length(readLines('evidence.txt')) - 1,\n          nrow(proteinGroups) == length(readLines('proteinGroups.txt')) - 1)\nannotation \u003C- read.csv('annotation.csv')\n\n# Convert to MSstats format\nmsstats_input \u003C- MaxQtoMSstatsFormat(evidence = evidence,\n                                      proteinGroups = proteinGroups,\n                                      annotation = annotation)\n\n# Process data. 'equalizeMedians' carries the SAME symmetry assumption as the median centering in\n# the limma block: most proteins unchanged, and the changes roughly balanced up and down. On the\n# 296-protein set above (44 up, 26 down) it left every true null shifted -0.19 log2 (t vs 0,\n# p = 2e-55) and MSstats then correctly called 21 of the 179 true nulls at BH 5%, all negative.\n# For a one-sided design use normalization = FALSE with an externally normalized input, or\n# normalization = 'globalStandards' with globalStandardName = \u003Cspike-in \u002F unchanged protein set>.\n# Always check the null centre: mean log2FC over proteins you expect not to move should be ~0.\nprocessed \u003C- dataProcess(msstats_input, normalization = 'equalizeMedians',\n                         summaryMethod = 'TMP', censoredInt = 'NA')\n\n# Comparison. +1 on the numerator: Treatment=+1, Control=-1 so log2FC = Treatment - Control\n# (positive = up in Treatment), matching the label and the limma makeContrasts(Treatment-Control) path.\n# Columns must be ALL the Condition levels in sorted order, one ROW per contrast -- for three\n# conditions sorted Control\u002FHighDose\u002FLowDose that is a 2 x 3 matrix, e.g.\n#   rbind(HighDose_vs_Control = c(-1, 1, 0), LowDose_vs_Control = c(-1, 0, 1))\n# with colnames c('Control','HighDose','LowDose'); groupComparison adjusts within each row, so\n# adjust across the rows yourself (p.adjust on the pooled pvalue) when you report several.\ncomparison \u003C- matrix(c(-1, 1), nrow = 1)\nrownames(comparison) \u003C- 'Treatment_vs_Control'\ncolnames(comparison) \u003C- c('Control', 'Treatment')\n\nresults \u003C- groupComparison(contrast.matrix = comparison, data = processed)\n```\n\n## QC Checkpoints\n\n| Stage | Check | Action if Failed |\n|-------|-------|------------------|\n| Import | >1000 proteins | Re-run MaxQuant |\n| Filter | \u003C30% removed | Check sample prep |\n| Missing | \u003C40% per sample | Check MS performance |\n| PCA | Replicates cluster | Check for batch effects |\n| Stats | FC\u002FFDR pre-specified | Verify thresholds were pre-specified; inspect the volcano for downshift-imputation 'anchor arms' |\n\n## Workflow Variants\n\n### TMT\u002FiTRAQ Isobaric Labeling\nReporter extraction is a spectra-level step, not a text-matrix read. Within a single plex the channels are co-isolated\u002Fco-fragmented in the same MS2 event, so relative ratios are stable; but MULTI-batch TMT CANNOT be compared across plexes without an IRS bridge (a pooled reference channel in every plex; Plubell 2017). Route to proteomics\u002Fquantification for the mechanics.\n```r\nlibrary(MSnbase)\n\n# Extract reporter ions from spectra (NOT readMSnSet, which loads an existing text matrix)\nraw \u003C- readMSData('tmt.mzML', mode = 'onDisk')\ntmt_data \u003C- quantify(raw, reporters = TMT10, method = 'max')\n# Correct isobaric impurity cross-talk with the LOT-SPECIFIC matrix from the reagent CoA.\n# makeImpuritiesMatrix(x = 10, edit = FALSE) returns a MANUFACTURER TEMPLATE, not an identity\n# matrix -- its diagonal runs 0.928-0.965 and 5% of 126 lands in 127C. It is a shape check only;\n# the numbers are lot-specific. (edit = TRUE, the default, opens an editor and blocks in scripts.)\n# Do NOT use makeImpuritiesMatrix(filename = ...) for TMT10\u002FTMTpro: it reads a CoA laid out by\n# Da OFFSET and places each column k POSITIONS away in the reporter list, which is only correct\n# for non-interleaved reagents (TMT6, iTRAQ). TMT10\u002FTMTpro interleave N and C, so the +1 Da\n# neighbour of 126 is 127C -- TWO positions away -- and the filename route silently writes the\n# bleed into 127N instead. Build the matrix by CHANNEL NAME and hand it to purityCorrect:\n# tmt10_coa.csv: a square percentage matrix, rows = SOURCE reagent, columns = OBSERVED channel,\n# both labelled with the channel names (126, 127N, 127C, ...); diagonal = the lot's purity.\ncoa \u003C- as.matrix(read.csv('tmt10_coa.csv', row.names = 1, check.names = FALSE))\nstopifnot(nrow(coa) == ncol(coa), setequal(rownames(coa), reporterNames(TMT10)))\ncoa \u003C- coa[reporterNames(TMT10), reporterNames(TMT10)]   # force the quant's channel order\n# ORIENTATION CHECK. A transposed sheet has the right channel names, the right shape and produces\n# NO negative values, so the negative-count check below never sees it -- yet it makes the\n# correction 2.7x worse than the correct orientation (median relative error 0.0015 vs 0.0006 on\n# the TMT10 template), still better than doing nothing and therefore silent. Test the orientation\n# directly: a ROW is one reagent's isotopic envelope and sums to 100% by construction (minus what\n# falls off the ends of the channel list); a COLUMN sums over different reagents and has no such\n# constraint. If the columns fit 100 better than the rows, the sheet is the wrong way round.\nrow_dev \u003C- sum((rowSums(coa) - 100)^2); col_dev \u003C- sum((colSums(coa) - 100)^2)\nif (col_dev \u003C row_dev)\n    stop('CoA looks TRANSPOSED: column sums fit 100% better than row sums (', round(col_dev, 1),\n         ' vs ', round(row_dev, 1), '). Rows must be the SOURCE reagent, columns the OBSERVED ',\n         'channel -- transpose the sheet or re-read the lot certificate.')\nstopifnot(all(diag(coa) == apply(coa, 1, max)),   # each reagent's own channel must dominate its row\n          all(diag(coa) > 50))                    # a CoA is percentages; \u003C 50 means fractions were read\nimpurities \u003C- coa \u002F 100                                  # CoA percentages -> fractions\ntmt_data \u003C- purityCorrect(tmt_data, impurities)\nstopifnot(sum(exprs(tmt_data) \u003C 0, na.rm = TRUE) == 0)   # negatives = a grossly wrong matrix (NOT a transposition test; see above)\n\n# Multi-batch TMT: do NOT concatenate plexes directly. Use MSstatsTMT, which applies the\n# reference-channel (IRS) bridge during summarization:\n#   library(MSstatsTMT)\n#   summ \u003C- proteinSummarization(msstatstmt_input)   # includes the cross-plex bridge\n#   groupComparisonTMT(summ, contrast.matrix = comparison)\n```\n\n### SILAC Workflow\nCaveat: heavy-Arg -> heavy-Pro metabolic conversion biases ratios for proline-containing peptides (under-counts the heavy channel), and labeling efficiency must be checked (residual light reads as down-regulation). Route to proteomics\u002Fquantification for the mechanics.\n```r\nlibrary(limma)\n\n# SILAC ratios from MaxQuant (quote\u002Fcomment.char as in the MSstats block above)\nsilac \u003C- read.delim('proteinGroups.txt', quote = '', comment.char = '')\nratio_cols \u003C- grep('Ratio.H.L.normalized', colnames(silac), value = TRUE)\n\n# Log2 transform ratios. MaxQuant leaves NaN (and 0 for an absent channel) wherever it could not\n# form a ratio, so log2 produces NaN\u002F-Inf; coerce every non-finite cell to NA before testing.\nsilac_log2 \u003C- log2(as.matrix(silac[, ratio_cols]))\nsilac_log2[!is.finite(silac_log2)] \u003C- NA\nrownames(silac_log2) \u003C- silac$Majority.protein.IDs   # without this the result table has no identity\n\n# Keep proteins with >= 2 finite ratios. apply(t.test) over the raw matrix STOPS the whole script\n# with \"not enough 'x' observations\" on the first protein quantified in one replicate only.\nkeep \u003C- rowSums(!is.na(silac_log2)) >= 2\ncat('proteins tested:', sum(keep), 'of', nrow(silac_log2), '\\n')\n\n# One-sample moderated test against log2 ratio 0 (no change): an intercept-only limma fit borrows\n# variance across proteins, which an unmoderated per-protein t-test at n = 3 cannot. Report the\n# BH-adjusted p-value -- a raw p-value per protein controls nothing across thousands of tests.\nfit \u003C- eBayes(lmFit(silac_log2[keep, , drop = FALSE]), trend = TRUE, robust = TRUE)\nresults \u003C- topTable(fit, coef = 1, number = Inf, adjust.method = 'BH')\n# Proteins dropped by `keep` are an on\u002Foff presence table, not a fold change (quantification).\n```\n\n### DIA-NN Workflow\nDIA-NN 1.9+ defaults to report.parquet (the only default in 2.0); read it with arrow, not read.delim. Filter on q-values BEFORE pivoting, or low-confidence rows enter the matrix. Route to proteomics\u002Fdia-analysis for the mechanics.\n```r\nlibrary(arrow)\nlibrary(dplyr)\nlibrary(tidyr)\n\ndiann \u003C- read_parquet('report.parquet')\n\n# Filter to 1% FDR at precursor AND protein-group level before pivoting.\n# Use the GLOBAL protein-group q-value for the cross-run matrix (per-run min(Q.Value) is anti-conservative).\n# When MBR is ON, MBR has its own FDR: add the Lib.* q-values (Lib.Q.Value, Lib.PG.Q.Value \u003C= 0.01).\ndiann_filt \u003C- diann %>%\n    filter(Q.Value \u003C= 0.01 & PG.Q.Value \u003C= 0.01 & Global.PG.Q.Value \u003C= 0.01)\n\n# PG.MaxLFQ is ALREADY cross-run MaxLFQ-normalized at report generation. Re-normalizing it\n# double-normalizes -- go straight to log2 + limma with no further normalization. To apply the\n# skill's own median-centering instead, pivot raw PG.Quantity here, not PG.MaxLFQ.\nprotein_matrix \u003C- diann_filt %>%\n    select(Protein.Group, Run, PG.MaxLFQ) %>%\n    distinct() %>%\n    pivot_wider(names_from = Run, values_from = PG.MaxLFQ)\n\n# PG.MaxLFQ path: log2-transform and go straight to limma (no re-normalization). DIA-NN writes 0\n# for \"not quantified in this run\", so 0 -> NA FIRST: log2(0) is -Inf, and -Inf cells propagate\n# silently until eBayes stops with \"missing value where TRUE\u002FFALSE needed\".\nm \u003C- as.matrix(protein_matrix[, -1])\nrownames(m) \u003C- protein_matrix$Protein.Group\nm[m == 0] \u003C- NA\nlog2_matrix \u003C- log2(m)\nstopifnot(!any(is.infinite(log2_matrix)))\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| ~1% PSM-FDR but 10-30% wrong proteins | FDR controlled only at PSM level | Estimate FDR at peptide AND protein-group level (picked-group FDR) |\n| Volcano \"wings\" of huge-FC on\u002Foff proteins | Downshift imputation on MNAR (Perseus\u002FMaxQuant) | Model the MNAR (proDA\u002Fmsqrob2\u002FMSstats-AFT); report \"undetected in group B\", not a fold change |\n| Cross-plex TMT ratios differ 2-5x for no biology | Compared TMT across plexes without IRS | Pooled reference channel in EVERY plex + IRS bridge before comparison |\n| A failed-load sample silently carried forward | Normalized before inspecting raw distributions | Filter contaminant\u002Freverse rows -> inspect raw boxplots + ID counts -> remove failures -> THEN normalize |\n| Anticonservative p-values | `removeBatchEffect` before testing | Put batch in the model (`~ batch + condition`); removeBatchEffect only for PCA |\n| Every ratio subtly wrong | Wrong intensity column (`Intensity` vs `LFQ intensity` vs `iBAQ`) | Pick the right column; convert 0 -> NaN before log2 |\n| Spurious DA that flips between conditions | Razor-peptide inference reassigns a shared peptide | Quantify at protein-group level or unique-peptides-only for sensitive comparisons |\n| `EOF within quoted string`; far fewer rows than the file has lines | default `read.table` quoting on MaxQuant tables with apostrophes (`5'-nucleotidase`) and `#` | `read.table(..., quote = '', comment.char = '')`, then check `nrow` against `readLines` |\n| `eBayes`\u002F`lmFit`: `missing value where TRUE\u002FFALSE needed` on a DIA-NN matrix | DIA-NN writes 0 for \"not quantified\"; `log2(0)` is `-Inf` | `m[m == 0] \u003C- NA` before `log2`, then `stopifnot(!any(is.infinite(m)))` |\n| `t.test`: `not enough 'x' observations` partway through a SILAC run | a protein quantified in one replicate only | filter to >= 2 finite ratios; moderated one-sample limma; report BH-adjusted p, never raw |\n| Impurity correction makes adjacent TMT10 channels worse, not better | `makeImpuritiesMatrix(filename=)` places CoA Da-offsets by POSITION, but TMT10\u002FTMTpro interleave N and C | build the matrix by channel name (rows = source reagent) and pass it straight to `purityCorrect` |\n| A 3x-low injection sails through the raw-distribution check | the check read `LFQ intensity`, which MaxLFQ already renormalized, and used a 50%-of-median ID rule | inspect the raw `Intensity.` columns; flag a >= 1 log2 load shift or an ID count > 3 MADs below the median |\n| `prcomp`: `a dimension is zero` at the QC step, before any statistics | no protein is observed in EVERY sample, so the complete-case matrix is empty (12 samples at realistic MNAR dropout is enough) | guard `nrow(complete) >= 3`; fall back to `cor(..., use = 'pairwise.complete.obs')`, lower `min_frac`, or drop the sparsest samples -- never impute to fill the PCA matrix |\n| `makeContrasts`: `object 'Treatment' not found`, with a correct design matrix one line above | the contrast is hard-coded for two conditions; a dose series or time course has three or more | build the contrasts from `levels(sample_info$condition)` against the reference level, and adjust ACROSS them with `decideTests(method = 'global')` |\n| Every unchanged protein drifts one way; the hit list is implausibly one-directional | median centering \u002F `equalizeMedians` on a design whose changes are NOT symmetric (pulldown, secretome, strong one-sided response) | normalize on a set expected to be unchanged (spike-ins, `globalStandards`); check that the mean log2FC over expected-null proteins is ~0 |\n| Impurity correction still leaves adjacent-channel bleed, no error, no negative values | the lot CoA was transposed -- same names, same shape, zero negatives, 2.7x worse than the right orientation | check orientation by row vs column sums to 100% before `purityCorrect`; rows are the SOURCE reagent |\n\n## References\n\n- Elias JE, Gygi SP (2007) Target-decoy search strategy for increased confidence in large-scale protein identifications by mass spectrometry. *Nature Methods* 4:207-214. DOI 10.1038\u002Fnmeth1019.\n- Savitski MM, Wilhelm M, Hahne H, Kuster B, Bantscheff M (2015) A scalable approach for protein false discovery rate estimation in large proteomic data sets. *Molecular & Cellular Proteomics* 14:2394-2404. DOI 10.1074\u002Fmcp.M114.046995. (picked-protein FDR.)\n- Plubell DL, Wilmarth PA, Zhao Y, et al (2017) Extended multiplexing of tandem mass tags (TMT) labeling reveals age and high-fat-diet specific proteome changes in mouse epididymal adipose tissue. *Molecular & Cellular Proteomics* 16:873-890. DOI 10.1074\u002Fmcp.M116.065524. (IRS.)\n- Ritchie ME, Phipson B, Wu D, et al (2015) limma powers differential expression analyses for RNA-sequencing and microarray studies. *Nucleic Acids Research* 43:e47. DOI 10.1093\u002Fnar\u002Fgkv007.\n- Zhu Y, Orre LM, Zhou Tran Y, et al (2020) DEqMS: a method for accurate variance estimation in differential protein expression analysis. *Molecular & Cellular Proteomics* 19:1047-1057. DOI 10.1074\u002Fmcp.TIR119.001646.\n\n## Related Skills\n\n- proteomics\u002Fdata-import - Load MS data formats\n- proteomics\u002Fproteomics-qc - Quality control before analysis\n- proteomics\u002Fquantification - Normalization, TMT IRS bridge, SILAC mechanics\n- proteomics\u002Fprotein-inference - Razor\u002Fshared-peptide assignment to protein groups\n- proteomics\u002Fdifferential-abundance - Modeling missingness, moderated testing details\n- proteomics\u002Fdia-analysis - DIA-NN report parsing and q-value filtering\n- proteomics\u002Fptm-analysis - Phosphoproteomics and other PTMs\n- data-visualization\u002Fvolcano-and-ma-plots - Volcano plots with LFC shrinkage\n","## Version Compatibility\n\nReference examples tested with: MSnbase 2.32.0, limma 3.62.2, MSstats 4.14.2, DEqMS 1.24.0, proDA 1.20.0, MSstatsTMT 2.14.2, arrow 23.0.1 (DIA-NN report.parquet), dplyr 1.2.1, tidyr 1.3.2, ggplot2 4.0.3 (checked 2026-09-15 on R 4.4.3)\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Proteomics Pipeline\n\n**\"Process my proteomics data from raw MS files to differential abundance\"** -> Orchestrate data import (pyopenms\u002FMaxQuant), QC assessment, protein quantification, normalization, differential abundance testing (limma\u002FDEqMS, or MSstats for feature-level designs), and PTM analysis.\n\nThis is a workflow skill: it owns the chaining decisions and hand-offs, not the internals of any one step.\n\nScope: research cohort comparison. A pipeline output is not a diagnostic -- do not use it to triage, escalate or choose treatment for an individual patient; route those questions to validated clinical assays and the treating clinician.\n\n## The governing principle\n\nBottom-up proteomics never measures proteins; it measures peptides and INFERS proteins, and the trustworthiness decisions are made at seams before the statistics.\n\n1. **The search database + acquisition mode are committed once and inherited by everything.** The FASTA fixes the target-decoy frame (concatenated one-search FDR = #decoy\u002F#target; a separate-search design needs mix-max instead — mixing the two mis-estimates FDR), what counts as a \"unique peptide\" (relative to the DB: canonical vs +isoforms), and the contaminants (cRAP must be IN the search DB from the start; a contaminant can BE the protein of interest, so never blind-delete `CON__` rows). DDA vs DIA is set at the instrument and dictates which imputation is even legitimate.\n2. **FDR is re-controlled at THREE levels, not just PSM — and match-between-runs has its OWN FDR.** 1% PSM-FDR does NOT give 1% protein-FDR — each level (PSM, peptide, protein-group) needs its own target-decoy estimation; PSM-only filtering yields 10-30% real protein-FDR on deep data (one false PSM nucleates a false one-hit-wonder, and false proteins grow with dataset size). Use picked-protein\u002Fpicked-group FDR. The two-peptide rule INCREASES protein-FDR, it does not reduce it. MBR transfers IDs across runs by RT\u002Fm-z and can be wrong for low-abundance precursors — do NOT report MBR-filled counts as directly measured; DIA-NN controls MBR-FDR via `Lib.*` q-values, IonQuant via an explicit MBR-FDR mixture model.\n3. **Missingness is MODELED, not filled.** DDA missingness is structured left-censored MNAR; downshift imputation (mean=mu-1.8sigma) on an on\u002Foff protein inflates the t-numerator AND deflates the denominator (the volcano \"wing\" artifact). The honest report for a protein missing in one whole group is \"undetected in group B\", not a fold change — model the MNAR (proDA\u002Fmsqrob2\u002FMSstats-AFT).\n4. **Normalize AFTER contaminant removal and AFTER inspecting raw distributions; batch is a covariate, not pre-subtracted.** Median-normalizing first mathematically erases a 3x-low load. Cross-plex TMT is invalid without an IRS bridge. `removeBatchEffect` before testing understates residual variance (anticonservative p) — put batch in the same model.\n\n## Made-once commitments\n\n| Commitment | Consequence inherited downstream |\n|------------|----------------------------------|\n| Search FASTA + target-decoy strategy | The FDR estimator, what a \"unique peptide\" is, which contaminants exist; a mismatch mis-estimates FDR silently |\n| Enzyme + fixed\u002Fvariable mods (Carbamidomethyl-Cys fixed) | Which peptides exist to quantify; a fixed-mod misconfig loses all Cys peptides |\n| DDA vs DIA acquisition mode | Missingness structure (MNAR vs ~MCAR), whether TMT is possible, which imputation is legitimate |\n| FDR framing (PSM + peptide + protein-group, 1% each) | Real protein-FDR; PSM-only is 10-30% wrong on deep data |\n\n## Pipeline Overview\n\n```\nRaw MS Data (mzML) --> MaxQuant\u002FDIA-NN --> proteinGroups.txt\n                                                 |\n                                                 v\n            +--------------------------------------------+\n            |             proteomics-pipeline            |\n            +--------------------------------------------+\n            |  1. Data Import & Filtering                |\n            |  2. Log2 + inspect RAW distributions       |\n            |  3. Normalization (after the inspection)   |\n            |  4. Per-Group Completeness Filter          |\n            |  5. QC: PCA, Correlation                   |\n            |  6. Differential Abundance (limma\u002FMSstats) |\n            |  7. Visualization & Export                 |\n            +--------------------------------------------+\n                                                 |\n                                                 v\n                  Differential Proteins + Volcano Plots\n```\n\n## Complete R Workflow\n\n**Goal:** Turn a MaxQuant or DIA-NN protein matrix into a table of differentially abundant proteins with honest missing-value handling.\n\n**Approach:** Strip bookkeeping rows, log2 and inspect the RAW per-sample distributions (dropping failed loads before normalization can hide them), median-center, filter on per-group completeness, then test the OBSERVED values with moderated limma using treat() for a minimum fold change and batch as a covariate -- nothing is imputed. Upgrade to proDA when the dropout itself has to be modeled.\n\n```r\nlibrary(limma)\nlibrary(ggplot2)\nlibrary(pheatmap)\n\n# === 1. DATA IMPORT ===\n# quote = '' \u002F comment.char = '': MaxQuant text fields contain quotes and '#'; the defaults\n# silently truncate the table with only an 'EOF within quoted string' warning. Check the count.\nproteins \u003C- read.delim('proteinGroups.txt', stringsAsFactors = FALSE, quote = '', comment.char = '')\nstopifnot(nrow(proteins) == length(readLines('proteinGroups.txt')) - 1)\ncat('Loaded', nrow(proteins), 'protein groups\\n')\n\n# Filter contaminants, reverse, only-by-site. Use %in%, NOT `!= '+'`: when a run flags none of a\n# category the column is entirely empty, read.delim types it as logical NA, `NA != '+'` is NA, and\n# subsetting by NA replaces every row with NAs while nrow() still looks right.\nproteins \u003C- proteins[!(proteins$Potential.contaminant %in% '+') &\n                      !(proteins$Reverse %in% '+') &\n                      !(proteins$Only.identified.by.site %in% '+'), ]\nstopifnot(!all(is.na(proteins$Majority.protein.IDs)))\ncat('After filtering:', nrow(proteins), 'proteins\\n')\n\n# Extract LFQ intensities\nlfq_cols \u003C- grep('^LFQ\\\\.intensity\\\\.', colnames(proteins), value = TRUE)\nintensities \u003C- proteins[, lfq_cols]\nrownames(intensities) \u003C- proteins$Majority.protein.IDs\ncolnames(intensities) \u003C- gsub('LFQ\\\\.intensity\\\\.', '', colnames(intensities))\n\n# === 2. LOG2 TRANSFORM, THEN INSPECT RAW DISTRIBUTIONS ===\nintensities[intensities == 0] \u003C- NA\nlog2_int \u003C- log2(intensities)\n\n# Inspect BEFORE normalizing (rule 4). Median-centering rescales every sample onto a common median,\n# so it mathematically erases the 3x-low load that marks a failed injection -- after this point the\n# failure is invisible. Identify and drop failures HERE.\n# Inspect the RAW `Intensity.` columns, NOT `LFQ intensity`: MaxLFQ has ALREADY renormalized the LFQ\n# columns onto a common scale, so a low load is largely gone from them before you ever look.\nraw_cols \u003C- grep('^Intensity\\\\.', colnames(proteins), value = TRUE)\nraw_log2 \u003C- log2(replace(proteins[, raw_cols], proteins[, raw_cols] == 0, NA))\ncolnames(raw_log2) \u003C- gsub('^Intensity\\\\.', '', colnames(raw_log2))\nraw_log2 \u003C- raw_log2[, colnames(log2_int), drop = FALSE]\nraw_median \u003C- apply(raw_log2, 2, median, na.rm = TRUE)\nid_counts \u003C- colSums(!is.na(log2_int))\nboxplot(raw_log2, las = 2, main = 'RAW log2 Intensity (pre-normalization)', ylab = 'log2 intensity')\nprint(data.frame(id_count = id_counts, raw_median_log2 = round(raw_median, 2),\n                 load_shift_log2 = round(raw_median - median(raw_median), 2)))\n\n# Flag on BOTH axes and as an OUTLIER, not a fixed fraction: a >=2x (1 log2) drop in raw median\n# signal, OR an ID count more than 3 MADs below the cohort median. Each axis alone misses cases --\n# a 3x-low injection loses its dimmest proteins entirely, so the SURVIVING median understates the\n# deficit (a 3.0x low load can read as only -0.8 log2), while a 50%-of-median ID-count rule is so\n# loose that a run at 82% of the median IDs, visibly low on both axes, passes it.\nmad_ids \u003C- mad(id_counts)\nfailed \u003C- colnames(raw_log2)[(raw_median - median(raw_median)) \u003C= -1 |\n                             (mad_ids > 0 & id_counts \u003C median(id_counts) - 3 * mad_ids)]\nif (length(failed) > 0) {\n    message('Dropping failed samples: ', paste(failed, collapse = ', '))\n    log2_int \u003C- log2_int[, !colnames(log2_int) %in% failed, drop = FALSE]\n}\n\n# === 3. NORMALIZE (only after the raw inspection above) ===\n# ASSUMPTION: median centering assumes most proteins are unchanged AND that the changes that do\n# occur are roughly SYMMETRIC up\u002Fdown. When they are not -- an enrichment pulldown, a secretome, a\n# strong one-sided drug response -- the shift it removes is real signal, and the whole unchanged\n# proteome acquires the opposite offset. Measured on a set with 44 up vs 26 down among 296\n# proteins: every true null moved -0.19 log2 (t vs 0, p = 2e-55) and 21 of 179 true nulls were\n# called at BH 5%, all negative. Normalize on a set expected to be unchanged (spike-in standards,\n# an internal-reference protein set, or the housekeeping bulk) when the design is one-sided,\n# and always check the null centre afterwards -- see the Common Errors row.\nsample_medians \u003C- apply(log2_int, 2, median, na.rm = TRUE)\nglobal_median \u003C- median(sample_medians)\nnormalized \u003C- sweep(log2_int, 2, sample_medians - global_median)\n\n# === 4. FILTER ON PER-GROUP COMPLETENESS (do NOT impute by default) ===\n# Filter FIRST on completeness PER GROUP: keep a protein if it is valid in >= ~50-70%\n# of replicates in AT LEAST ONE condition. A protein missing in every group fails QC.\nsample_info \u003C- read.csv('sample_annotation.csv')\n# Re-align the annotation to the samples that SURVIVED the raw-distribution QC above; otherwise the\n# column indexing below requests a dropped sample and errors (or silently misaligns the design).\n# match() also puts the rows in COLUMN order: lmFit pairs design rows with matrix columns\n# POSITIONALLY, so an annotation sorted differently from the intensity columns fits a wrong design\n# in silence. Never subset the annotation with `%in%` alone here.\nsample_info \u003C- sample_info[match(colnames(normalized), sample_info$sample), ]\nstopifnot(!any(is.na(sample_info$sample)))\nsample_info$condition \u003C- droplevels(factor(sample_info$condition))\nmin_frac \u003C- 0.6   # >= 60% present within at least one group; tune 0.5-0.7 per design\ngroup_complete \u003C- sapply(levels(sample_info$condition), function(g) {\n    cols \u003C- sample_info$sample[sample_info$condition == g]\n    rowSums(!is.na(normalized[, cols, drop = FALSE])) >= ceiling(length(cols) * min_frac)\n})\nvalid_rows \u003C- rowSums(group_complete) > 0\nfiltered \u003C- normalized[valid_rows, ]\ncat('Proteins after per-group completeness filter:', nrow(filtered), '\\n')\n\n# Missingness in label-free DDA is left-censored MNAR (missing BECAUSE low). The modern,\n# correct approach is to MODEL the missingness in the likelihood, NOT impute it. See\n# proteomics\u002Fdifferential-abundance for the decision (proDA \u002F msqrob2 \u002F MSstats-AFT).\n# NOTHING BELOW IMPUTES: limma fits each protein on its OBSERVED values, so the completeness\n# filter above is the only missing-value handling in the executed path.\n\n# --- UPGRADE: model the dropout explicitly with proDA, then use `da` in place of `results` ---\n# library(proDA)\n# fit \u003C- proDA(as.matrix(filtered), design = ~ condition, col_data = sample_info,\n#              reference_level = 'Control')            # add batch: design = ~ batch + condition\n# da \u003C- test_diff(fit, contrast = 'conditionTreatment')   # columns: diff (log2FC), pval, adj_pval\n\n# --- DO NOT: left-censored downshift imputation, then limma ---\n# Downshift MANUFACTURES systematic false positives for on\u002Foff proteins near the detection limit\n# (the volcano \"anchor arms\"): it pins missing values ~1.8 SD below the mean with an artificially\n# tight 0.3 SD spread, inflating the t-numerator and deflating its denominator. The honest report\n# for a protein fully missing in one group is \"undetected in group B\", NOT a fold change. If a\n# reviewer demands a complete matrix anyway, seed it (set.seed) so the call list is reproducible,\n# and report the on\u002Foff proteins separately -- see proteomics\u002Fdifferential-abundance.\n\n# === 5. QC ===\n# PCA needs a complete matrix; use the proteins observed everywhere rather than inventing values.\n# The complete-case set can be EMPTY -- 12 samples at realistic MNAR dropout is enough -- and\n# prcomp then aborts the whole workflow at step 5 of 7 with `a dimension is zero`, which says\n# nothing about missingness. Guard it, say what happened, and fall back to the pairwise-complete\n# sample correlation, which answers the same clustering question without a complete matrix.\n# QC is diagnostic: it must not gate the statistics below, and it is never a reason to impute.\ncomplete \u003C- filtered[stats::complete.cases(filtered), , drop = FALSE]\ncat('Proteins used for PCA (complete cases):', nrow(complete), '\\n')\npca_df \u003C- NULL\nif (nrow(complete) >= 3) {\n    pca \u003C- prcomp(t(complete), scale. = TRUE)\n    pca_df \u003C- data.frame(PC1 = pca$x[, 1], PC2 = pca$x[, 2], Sample = rownames(pca$x))\n} else {\n    message('PCA skipped: only ', nrow(complete), ' protein(s) observed in EVERY sample. ',\n            'That is missingness, not a corrupt matrix -- lower min_frac, drop the sparsest ',\n            'samples, or read the correlation below. Do NOT impute to fill the matrix.')\n    sample_cor \u003C- cor(as.matrix(filtered), use = 'pairwise.complete.obs', method = 'spearman')\n    print(round(sample_cor, 2))\n}\n\n# === 6. DIFFERENTIAL ANALYSIS (limma on the observed values) ===\n# sample_info is already loaded and factored in step 4. Batch is a COVARIATE in the same model\n# (rule 4); removeBatchEffect() is visualization-only, never an input to lmFit.\nhas_batch \u003C- 'batch' %in% colnames(sample_info) && length(unique(sample_info$batch)) > 1\ndesign \u003C- if (has_batch) model.matrix(~ 0 + condition + factor(batch), data = sample_info) else\n                         model.matrix(~ 0 + condition, data = sample_info)\ncolnames(design)[seq_along(levels(sample_info$condition))] \u003C- levels(sample_info$condition)\ncolnames(design) \u003C- make.names(colnames(design))\ncat('design columns:', colnames(design), '| batch in design:', has_batch, '\\n')\n\nfit \u003C- lmFit(as.matrix(filtered), design)\n# Build the contrasts FROM the factor levels. A hard-coded `makeContrasts(Treatment - Control)`\n# handles exactly one design: a three-condition dose series or a time course dies with\n# `object 'Treatment' not found` even though the design matrix built one line above is correct.\n# The reference is the FIRST level -- set it explicitly with relevel() if alphabetical order puts\n# the wrong condition first. Two conditions give the single Treatment-Control contrast as before.\nref \u003C- levels(sample_info$condition)[1]\nothers \u003C- setdiff(levels(sample_info$condition), ref)\ncontrast \u003C- makeContrasts(contrasts = paste(make.names(others), '-', make.names(ref)), levels = design)\ncolnames(contrast) \u003C- paste0(others, '_vs_', ref)\ncat('contrasts:', colnames(contrast), '\\n')\nfit2 \u003C- contrasts.fit(fit, contrast)\n\n# Select on FDR ALONE. A post-hoc fold-change + significance double filter inflates FDR\n# (a collider\u002Fselection effect; realized FDR can exceed 50%). To require a minimum effect,\n# use the moderated minimum-fold-change test treat()\u002FtopTreat() instead of filtering after.\nfit2_treat \u003C- treat(fit2, lfc = log2(1.5), trend = TRUE, robust = TRUE)   # moderated min-FC test; trend+robust ~mandatory for label-free LFQ\n# topTreat adjusts WITHIN one contrast. With more than one contrast the family of tests is the\n# whole set, so adjust ACROSS them: decideTests(method = 'global') applies one BH over every\n# protein x contrast cell, which is what the significance calls below use. With a single contrast\n# it is identical to the per-contrast BH, so the two-condition result is unchanged.\nresults \u003C- do.call(rbind, lapply(colnames(contrast), function(cn) {\n    tt \u003C- topTreat(fit2_treat, coef = cn, number = Inf, sort.by = 'none')\n    data.frame(protein = rownames(tt), contrast = cn, tt, row.names = NULL)\n}))\n# unclass(): decideTests returns an S4 TestResults, which as.matrix() does NOT demote, and whose\n# `[` refuses the two-column character index used below ('Two subscripts required').\ndt \u003C- unclass(decideTests(fit2_treat, method = 'global', adjust.method = 'BH', p.value = 0.05))\n# A protein observed in only one group (or one batch level) has no estimable contrast: limma\n# returns NA, and `adj.P.Val \u003C 0.05` would make every downstream sum() NA. Report those separately\n# as \"undetected in group B\" -- that is the honest statement, not a fold change.\nresults$significant \u003C- !is.na(results$adj.P.Val) &\n                       dt[cbind(results$protein, results$contrast)] != 0\n# To ask instead \"does this protein change ANYWHERE across the conditions\" (an omnibus\u002FANOVA\n# question rather than a set of pairwise ones), F-test all contrast columns at once:\n#   fit2_eb \u003C- eBayes(fit2, trend = TRUE, robust = TRUE)\n#   anova_res \u003C- topTable(fit2_eb, number = Inf)   # F and its BH-adjusted p across all contrasts\n# Use it to screen, then report the pairwise contrasts for direction. treat() has no F-test.\n\n# === 7. OUTPUT ===\ncat('\\nResults:\\n')\ncat('  Contrast not estimable (report as undetected-in-group):', sum(is.na(results$logFC)), '\\n')\ncat('  Significant proteins:', sum(results$significant), '\\n')\ncat('  Up-regulated:', sum(results$significant & results$logFC > 0), '\\n')\ncat('  Down-regulated:', sum(results$significant & results$logFC \u003C 0), '\\n')\nfor (cn in colnames(contrast)) {                       # per-contrast breakdown (>=2 contrasts)\n    k \u003C- results$contrast == cn & results$significant\n    cat('   ', cn, ':', sum(k), '(Up', sum(k & results$logFC > 0), 'Down', sum(k & results$logFC \u003C 0), ')\\n')\n}\n\nwrite.csv(results, 'proteomics_results.csv', row.names = FALSE)\n```\n\n## MSstats Workflow\n\n```r\nlibrary(MSstats)\n\n# From MaxQuant. quote = '' and comment.char = '' are REQUIRED: MaxQuant text fields contain\n# apostrophes (5'-nucleotidase) and '#', and the read.table defaults silently truncate the table\n# with nothing but an 'EOF within quoted string' warning -- here 2954 of 10369 evidence rows and\n# 62 of 296 proteins. Check the row count; do not trust the warning to stop you.\nevidence \u003C- read.table('evidence.txt', sep = '\\t', header = TRUE, quote = '', comment.char = '')\nproteinGroups \u003C- read.table('proteinGroups.txt', sep = '\\t', header = TRUE, quote = '', comment.char = '')\nstopifnot(nrow(evidence) == length(readLines('evidence.txt')) - 1,\n          nrow(proteinGroups) == length(readLines('proteinGroups.txt')) - 1)\nannotation \u003C- read.csv('annotation.csv')\n\n# Convert to MSstats format\nmsstats_input \u003C- MaxQtoMSstatsFormat(evidence = evidence,\n                                      proteinGroups = proteinGroups,\n                                      annotation = annotation)\n\n# Process data. 'equalizeMedians' carries the SAME symmetry assumption as the median centering in\n# the limma block: most proteins unchanged, and the changes roughly balanced up and down. On the\n# 296-protein set above (44 up, 26 down) it left every true null shifted -0.19 log2 (t vs 0,\n# p = 2e-55) and MSstats then correctly called 21 of the 179 true nulls at BH 5%, all negative.\n# For a one-sided design use normalization = FALSE with an externally normalized input, or\n# normalization = 'globalStandards' with globalStandardName = \u003Cspike-in \u002F unchanged protein set>.\n# Always check the null centre: mean log2FC over proteins you expect not to move should be ~0.\nprocessed \u003C- dataProcess(msstats_input, normalization = 'equalizeMedians',\n                         summaryMethod = 'TMP', censoredInt = 'NA')\n\n# Comparison. +1 on the numerator: Treatment=+1, Control=-1 so log2FC = Treatment - Control\n# (positive = up in Treatment), matching the label and the limma makeContrasts(Treatment-Control) path.\n# Columns must be ALL the Condition levels in sorted order, one ROW per contrast -- for three\n# conditions sorted Control\u002FHighDose\u002FLowDose that is a 2 x 3 matrix, e.g.\n#   rbind(HighDose_vs_Control = c(-1, 1, 0), LowDose_vs_Control = c(-1, 0, 1))\n# with colnames c('Control','HighDose','LowDose'); groupComparison adjusts within each row, so\n# adjust across the rows yourself (p.adjust on the pooled pvalue) when you report several.\ncomparison \u003C- matrix(c(-1, 1), nrow = 1)\nrownames(comparison) \u003C- 'Treatment_vs_Control'\ncolnames(comparison) \u003C- c('Control', 'Treatment')\n\nresults \u003C- groupComparison(contrast.matrix = comparison, data = processed)\n```\n\n## QC Checkpoints\n\n| Stage | Check | Action if Failed |\n|-------|-------|------------------|\n| Import | >1000 proteins | Re-run MaxQuant |\n| Filter | \u003C30% removed | Check sample prep |\n| Missing | \u003C40% per sample | Check MS performance |\n| PCA | Replicates cluster | Check for batch effects |\n| Stats | FC\u002FFDR pre-specified | Verify thresholds were pre-specified; inspect the volcano for downshift-imputation 'anchor arms' |\n\n## Workflow Variants\n\n### TMT\u002FiTRAQ Isobaric Labeling\nReporter extraction is a spectra-level step, not a text-matrix read. Within a single plex the channels are co-isolated\u002Fco-fragmented in the same MS2 event, so relative ratios are stable; but MULTI-batch TMT CANNOT be compared across plexes without an IRS bridge (a pooled reference channel in every plex; Plubell 2017). Route to proteomics\u002Fquantification for the mechanics.\n```r\nlibrary(MSnbase)\n\n# Extract reporter ions from spectra (NOT readMSnSet, which loads an existing text matrix)\nraw \u003C- readMSData('tmt.mzML', mode = 'onDisk')\ntmt_data \u003C- quantify(raw, reporters = TMT10, method = 'max')\n# Correct isobaric impurity cross-talk with the LOT-SPECIFIC matrix from the reagent CoA.\n# makeImpuritiesMatrix(x = 10, edit = FALSE) returns a MANUFACTURER TEMPLATE, not an identity\n# matrix -- its diagonal runs 0.928-0.965 and 5% of 126 lands in 127C. It is a shape check only;\n# the numbers are lot-specific. (edit = TRUE, the default, opens an editor and blocks in scripts.)\n# Do NOT use makeImpuritiesMatrix(filename = ...) for TMT10\u002FTMTpro: it reads a CoA laid out by\n# Da OFFSET and places each column k POSITIONS away in the reporter list, which is only correct\n# for non-interleaved reagents (TMT6, iTRAQ). TMT10\u002FTMTpro interleave N and C, so the +1 Da\n# neighbour of 126 is 127C -- TWO positions away -- and the filename route silently writes the\n# bleed into 127N instead. Build the matrix by CHANNEL NAME and hand it to purityCorrect:\n# tmt10_coa.csv: a square percentage matrix, rows = SOURCE reagent, columns = OBSERVED channel,\n# both labelled with the channel names (126, 127N, 127C, ...); diagonal = the lot's purity.\ncoa \u003C- as.matrix(read.csv('tmt10_coa.csv', row.names = 1, check.names = FALSE))\nstopifnot(nrow(coa) == ncol(coa), setequal(rownames(coa), reporterNames(TMT10)))\ncoa \u003C- coa[reporterNames(TMT10), reporterNames(TMT10)]   # force the quant's channel order\n# ORIENTATION CHECK. A transposed sheet has the right channel names, the right shape and produces\n# NO negative values, so the negative-count check below never sees it -- yet it makes the\n# correction 2.7x worse than the correct orientation (median relative error 0.0015 vs 0.0006 on\n# the TMT10 template), still better than doing nothing and therefore silent. Test the orientation\n# directly: a ROW is one reagent's isotopic envelope and sums to 100% by construction (minus what\n# falls off the ends of the channel list); a COLUMN sums over different reagents and has no such\n# constraint. If the columns fit 100 better than the rows, the sheet is the wrong way round.\nrow_dev \u003C- sum((rowSums(coa) - 100)^2); col_dev \u003C- sum((colSums(coa) - 100)^2)\nif (col_dev \u003C row_dev)\n    stop('CoA looks TRANSPOSED: column sums fit 100% better than row sums (', round(col_dev, 1),\n         ' vs ', round(row_dev, 1), '). Rows must be the SOURCE reagent, columns the OBSERVED ',\n         'channel -- transpose the sheet or re-read the lot certificate.')\nstopifnot(all(diag(coa) == apply(coa, 1, max)),   # each reagent's own channel must dominate its row\n          all(diag(coa) > 50))                    # a CoA is percentages; \u003C 50 means fractions were read\nimpurities \u003C- coa \u002F 100                                  # CoA percentages -> fractions\ntmt_data \u003C- purityCorrect(tmt_data, impurities)\nstopifnot(sum(exprs(tmt_data) \u003C 0, na.rm = TRUE) == 0)   # negatives = a grossly wrong matrix (NOT a transposition test; see above)\n\n# Multi-batch TMT: do NOT concatenate plexes directly. Use MSstatsTMT, which applies the\n# reference-channel (IRS) bridge during summarization:\n#   library(MSstatsTMT)\n#   summ \u003C- proteinSummarization(msstatstmt_input)   # includes the cross-plex bridge\n#   groupComparisonTMT(summ, contrast.matrix = comparison)\n```\n\n### SILAC Workflow\nCaveat: heavy-Arg -> heavy-Pro metabolic conversion biases ratios for proline-containing peptides (under-counts the heavy channel), and labeling efficiency must be checked (residual light reads as down-regulation). Route to proteomics\u002Fquantification for the mechanics.\n```r\nlibrary(limma)\n\n# SILAC ratios from MaxQuant (quote\u002Fcomment.char as in the MSstats block above)\nsilac \u003C- read.delim('proteinGroups.txt', quote = '', comment.char = '')\nratio_cols \u003C- grep('Ratio.H.L.normalized', colnames(silac), value = TRUE)\n\n# Log2 transform ratios. MaxQuant leaves NaN (and 0 for an absent channel) wherever it could not\n# form a ratio, so log2 produces NaN\u002F-Inf; coerce every non-finite cell to NA before testing.\nsilac_log2 \u003C- log2(as.matrix(silac[, ratio_cols]))\nsilac_log2[!is.finite(silac_log2)] \u003C- NA\nrownames(silac_log2) \u003C- silac$Majority.protein.IDs   # without this the result table has no identity\n\n# Keep proteins with >= 2 finite ratios. apply(t.test) over the raw matrix STOPS the whole script\n# with \"not enough 'x' observations\" on the first protein quantified in one replicate only.\nkeep \u003C- rowSums(!is.na(silac_log2)) >= 2\ncat('proteins tested:', sum(keep), 'of', nrow(silac_log2), '\\n')\n\n# One-sample moderated test against log2 ratio 0 (no change): an intercept-only limma fit borrows\n# variance across proteins, which an unmoderated per-protein t-test at n = 3 cannot. Report the\n# BH-adjusted p-value -- a raw p-value per protein controls nothing across thousands of tests.\nfit \u003C- eBayes(lmFit(silac_log2[keep, , drop = FALSE]), trend = TRUE, robust = TRUE)\nresults \u003C- topTable(fit, coef = 1, number = Inf, adjust.method = 'BH')\n# Proteins dropped by `keep` are an on\u002Foff presence table, not a fold change (quantification).\n```\n\n### DIA-NN Workflow\nDIA-NN 1.9+ defaults to report.parquet (the only default in 2.0); read it with arrow, not read.delim. Filter on q-values BEFORE pivoting, or low-confidence rows enter the matrix. Route to proteomics\u002Fdia-analysis for the mechanics.\n```r\nlibrary(arrow)\nlibrary(dplyr)\nlibrary(tidyr)\n\ndiann \u003C- read_parquet('report.parquet')\n\n# Filter to 1% FDR at precursor AND protein-group level before pivoting.\n# Use the GLOBAL protein-group q-value for the cross-run matrix (per-run min(Q.Value) is anti-conservative).\n# When MBR is ON, MBR has its own FDR: add the Lib.* q-values (Lib.Q.Value, Lib.PG.Q.Value \u003C= 0.01).\ndiann_filt \u003C- diann %>%\n    filter(Q.Value \u003C= 0.01 & PG.Q.Value \u003C= 0.01 & Global.PG.Q.Value \u003C= 0.01)\n\n# PG.MaxLFQ is ALREADY cross-run MaxLFQ-normalized at report generation. Re-normalizing it\n# double-normalizes -- go straight to log2 + limma with no further normalization. To apply the\n# skill's own median-centering instead, pivot raw PG.Quantity here, not PG.MaxLFQ.\nprotein_matrix \u003C- diann_filt %>%\n    select(Protein.Group, Run, PG.MaxLFQ) %>%\n    distinct() %>%\n    pivot_wider(names_from = Run, values_from = PG.MaxLFQ)\n\n# PG.MaxLFQ path: log2-transform and go straight to limma (no re-normalization). DIA-NN writes 0\n# for \"not quantified in this run\", so 0 -> NA FIRST: log2(0) is -Inf, and -Inf cells propagate\n# silently until eBayes stops with \"missing value where TRUE\u002FFALSE needed\".\nm \u003C- as.matrix(protein_matrix[, -1])\nrownames(m) \u003C- protein_matrix$Protein.Group\nm[m == 0] \u003C- NA\nlog2_matrix \u003C- log2(m)\nstopifnot(!any(is.infinite(log2_matrix)))\n```\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| ~1% PSM-FDR but 10-30% wrong proteins | FDR controlled only at PSM level | Estimate FDR at peptide AND protein-group level (picked-group FDR) |\n| Volcano \"wings\" of huge-FC on\u002Foff proteins | Downshift imputation on MNAR (Perseus\u002FMaxQuant) | Model the MNAR (proDA\u002Fmsqrob2\u002FMSstats-AFT); report \"undetected in group B\", not a fold change |\n| Cross-plex TMT ratios differ 2-5x for no biology | Compared TMT across plexes without IRS | Pooled reference channel in EVERY plex + IRS bridge before comparison |\n| A failed-load sample silently carried forward | Normalized before inspecting raw distributions | Filter contaminant\u002Freverse rows -> inspect raw boxplots + ID counts -> remove failures -> THEN normalize |\n| Anticonservative p-values | `removeBatchEffect` before testing | Put batch in the model (`~ batch + condition`); removeBatchEffect only for PCA |\n| Every ratio subtly wrong | Wrong intensity column (`Intensity` vs `LFQ intensity` vs `iBAQ`) | Pick the right column; convert 0 -> NaN before log2 |\n| Spurious DA that flips between conditions | Razor-peptide inference reassigns a shared peptide | Quantify at protein-group level or unique-peptides-only for sensitive comparisons |\n| `EOF within quoted string`; far fewer rows than the file has lines | default `read.table` quoting on MaxQuant tables with apostrophes (`5'-nucleotidase`) and `#` | `read.table(..., quote = '', comment.char = '')`, then check `nrow` against `readLines` |\n| `eBayes`\u002F`lmFit`: `missing value where TRUE\u002FFALSE needed` on a DIA-NN matrix | DIA-NN writes 0 for \"not quantified\"; `log2(0)` is `-Inf` | `m[m == 0] \u003C- NA` before `log2`, then `stopifnot(!any(is.infinite(m)))` |\n| `t.test`: `not enough 'x' observations` partway through a SILAC run | a protein quantified in one replicate only | filter to >= 2 finite ratios; moderated one-sample limma; report BH-adjusted p, never raw |\n| Impurity correction makes adjacent TMT10 channels worse, not better | `makeImpuritiesMatrix(filename=)` places CoA Da-offsets by POSITION, but TMT10\u002FTMTpro interleave N and C | build the matrix by channel name (rows = source reagent) and pass it straight to `purityCorrect` |\n| A 3x-low injection sails through the raw-distribution check | the check read `LFQ intensity`, which MaxLFQ already renormalized, and used a 50%-of-median ID rule | inspect the raw `Intensity.` columns; flag a >= 1 log2 load shift or an ID count > 3 MADs below the median |\n| `prcomp`: `a dimension is zero` at the QC step, before any statistics | no protein is observed in EVERY sample, so the complete-case matrix is empty (12 samples at realistic MNAR dropout is enough) | guard `nrow(complete) >= 3`; fall back to `cor(..., use = 'pairwise.complete.obs')`, lower `min_frac`, or drop the sparsest samples -- never impute to fill the PCA matrix |\n| `makeContrasts`: `object 'Treatment' not found`, with a correct design matrix one line above | the contrast is hard-coded for two conditions; a dose series or time course has three or more | build the contrasts from `levels(sample_info$condition)` against the reference level, and adjust ACROSS them with `decideTests(method = 'global')` |\n| Every unchanged protein drifts one way; the hit list is implausibly one-directional | median centering \u002F `equalizeMedians` on a design whose changes are NOT symmetric (pulldown, secretome, strong one-sided response) | normalize on a set expected to be unchanged (spike-ins, `globalStandards`); check that the mean log2FC over expected-null proteins is ~0 |\n| Impurity correction still leaves adjacent-channel bleed, no error, no negative values | the lot CoA was transposed -- same names, same shape, zero negatives, 2.7x worse than the right orientation | check orientation by row vs column sums to 100% before `purityCorrect`; rows are the SOURCE reagent |\n\n## References\n\n- Elias JE, Gygi SP (2007) Target-decoy search strategy for increased confidence in large-scale protein identifications by mass spectrometry. *Nature Methods* 4:207-214. DOI 10.1038\u002Fnmeth1019.\n- Savitski MM, Wilhelm M, Hahne H, Kuster B, Bantscheff M (2015) A scalable approach for protein false discovery rate estimation in large proteomic data sets. *Molecular & Cellular Proteomics* 14:2394-2404. DOI 10.1074\u002Fmcp.M114.046995. (picked-protein FDR.)\n- Plubell DL, Wilmarth PA, Zhao Y, et al (2017) Extended multiplexing of tandem mass tags (TMT) labeling reveals age and high-fat-diet specific proteome changes in mouse epididymal adipose tissue. *Molecular & Cellular Proteomics* 16:873-890. DOI 10.1074\u002Fmcp.M116.065524. (IRS.)\n- Ritchie ME, Phipson B, Wu D, et al (2015) limma powers differential expression analyses for RNA-sequencing and microarray studies. *Nucleic Acids Research* 43:e47. DOI 10.1093\u002Fnar\u002Fgkv007.\n- Zhu Y, Orre LM, Zhou Tran Y, et al (2020) DEqMS: a method for accurate variance estimation in differential protein expression analysis. *Molecular & Cellular Proteomics* 19:1047-1057. DOI 10.1074\u002Fmcp.TIR119.001646.\n\n## Related Skills\n\n- proteomics\u002Fdata-import - Load MS data formats\n- proteomics\u002Fproteomics-qc - Quality control before analysis\n- proteomics\u002Fquantification - Normalization, TMT IRS bridge, SILAC mechanics\n- proteomics\u002Fprotein-inference - Razor\u002Fshared-peptide assignment to protein groups\n- proteomics\u002Fdifferential-abundance - Modeling missingness, moderated testing details\n- proteomics\u002Fdia-analysis - DIA-NN report parsing and q-value filtering\n- proteomics\u002Fptm-analysis - Phosphoproteomics and other PTMs\n- data-visualization\u002Fvolcano-and-ma-plots - Volcano plots with LFC shrinkage\n",{"name":5,"workflow":24,"tool_type":25,"depends_on":26,"description":7,"primary_tool":33},true,"mixed",[27,28,29,30,31,32],"proteomics\u002Fdata-import","proteomics\u002Fproteomics-qc","proteomics\u002Fquantification","proteomics\u002Fprotein-inference","proteomics\u002Fdifferential-abundance","proteomics\u002Fdia-analysis","limma","main","e0956dc9606356ab78468936b502e55a365282e2","specialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-proteomics-pipeline",0,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists","https:\u002F\u002Fgithub.com\u002Fmrsonord2240","2026-10-12 03:19:04",{"source":8,"skillName":5,"commands":42,"prompt":52,"zipAvailable":24},[43,46,49],{"tool":44,"command":45},"npx","npx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-workflows-proteomics-pipeline",{"tool":47,"command":48},"bunx","bunx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-workflows-proteomics-pipeline",{"tool":50,"command":51},"pnpm","pnpm dlx skills add mrsonord2240\u002Fopenscience-specialists --skill bio-workflows-proteomics-pipeline","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-proteomics-pipeline\u002FSKILL.md",[54,60],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"examples\u002Fproteomics_workflow.R","OTHER","其他",11202,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-proteomics-pipeline\u002Fexamples\u002Fproteomics_workflow.R",{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"usage-guide.md","REFERENCE","参考文档",4936,"https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Fmass-spec-proteomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-proteomics-pipeline\u002Fusage-guide.md",[67,74,81,88,95,102],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7CW36A6QAGWFE2C008M1XPG","bio-workflows-metabolomics-pipeline","Orchestrates the untargeted LC-MS metabolomics pipeline end-to-end (xcms 4.x feature extraction, QC\u002Fdrift\u002Fnormalization, confidence-stratified annotation, permutation-validated statistics, background-aware pathway mapping), naming what each stage decides and where it silently fails. Use when running a full LC-MS metabolomics study from raw mzML to enriched pathways and needing the honest handoffs between stages. Each stage defers to its component skill for parameters and traps; for stable-isotope flux (a separate branch, not this untargeted flow) see metabolomics\u002Fisotope-tracing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-workflows-metabolomics-pipeline\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7CW2Y18623NA2S1Y30FRQW1","bio-metabolomics-xcms-preprocessing","Programmatic untargeted LC-MS feature extraction in R with the modern xcms 4.x MsExperiment\u002FXcmsExperiment API, taking raw mzML to a feature table via CentWave peak detection, retention-time alignment, peak-density correspondence, gap-filling, CAMERA redundancy collapse, and built-in QC feature filtering. Use when converting centroided LC-MS runs into a features-by-samples matrix and deciding centWave\u002Fgrouping\u002Falignment parameters. For drift correction and QC\u002FCV filtering execution see metabolomics\u002Fnormalization-qc; for metabolite identification see metabolomics\u002Fmetabolite-annotation; for the MS-DIAL GUI alternative with MS2Dec deconvolution see metabolomics\u002Fmsdial-preprocessing; for downstream statistics see metabolomics\u002Fstatistical-analysis.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-xcms-preprocessing\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7CW2M364HVWPNQEKE2WP4PP","bio-metabolomics-statistical-analysis","Decision-grade statistical analysis for metabolomics intensity tables. Covers transformation and scaling (Pareto vs unit-variance as a hidden hypothesis), unsupervised structure (PCA\u002FHCA for QC), permutation-validated PLS-DA\u002FOPLS-DA (R2 vs Q2, double CV, VIP as heuristic), univariate testing (Welch\u002FMann-Whitney\u002FANOVA\u002FLMM with covariate adjustment), and dependence-aware multiple testing. Use when testing which metabolites differ, building or validating a discriminant model, choosing a scaling, or correcting many correlated tests. For sample-wise normalization\u002Fdrift correction see metabolomics\u002Fnormalization-qc; for ML classifiers and selection-inside-CV leakage see machine-learning\u002Fbiomarker-discovery and machine-learning\u002Fmodel-validation; for pathway interpretation see metabolomics\u002Fpathway-mapping; for design\u002Fpower\u002Fmultiplicity regime see experimental-design\u002Fmultiple-testing.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-statistical-analysis\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7CW2BCBF851WYE03Z8XPEDQ","bio-metabolomics-pathway-mapping","Maps metabolomics results to biological pathways via over-representation (ORA), metabolite-set enrichment (MSEA\u002FQEA), mummichog\u002FPSEA on raw m\u002Fz peaks, and network-diffusion enrichment (FELLA), with correct background-set construction and honest interpretive ceilings. Use when interpreting differential metabolites or an untargeted LC-MS feature table in pathway context, choosing ORA vs MSEA vs mummichog vs topology, or setting the reference\u002Fbackground set. For annotation confidence levels feeding ORA see metabolomics\u002Fmetabolite-annotation; for gene-set concepts see pathway-analysis\u002Fgo-enrichment and pathway-analysis\u002Fgsea; for joint gene+metabolite pathways see multi-omics-integration\u002Fmofa-integration.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-pathway-mapping\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7CW21NSZMCPMF7D9CHJM718","bio-metabolomics-normalization-qc","Designs QC, corrects signal drift, removes batch effects, filters features, normalizes samples, and imputes missing values for untargeted LC-MS\u002FGC-MS metabolomics, framing each step as a measurement model that can create or erase biological signal. Use when processing a peak\u002Ffeature table before statistical analysis, choosing a drift-correction or sample-normalization method, deciding QC RSD vs D-ratio filtering, or handling left-censored missing values. The feature table is produced by metabolomics\u002Fxcms-preprocessing or metabolomics\u002Fmsdial-preprocessing; transformation\u002Fscaling for modeling defers to metabolomics\u002Fstatistical-analysis; cross-study design issues link to experimental-design\u002Fbatch-design.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-normalization-qc\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7CW1SWVM0NYHVE6Q7MA3G7R","bio-metabolomics-msdial-preprocessing","Runs the MS-DIAL preprocessing workflow (peak picking, MS2Dec spectral deconvolution, alignment, gap-filling) and imports the alignment-result table into R or Python with honest filtering. Use when preprocessing LC-MS DDA\u002FDIA (SWATH) or GC-MS raw data with MS-DIAL, deciding MS-DIAL vs XCMS, configuring the MSDIALCUI console run, or parsing an MS-DIAL export into a clean feature matrix. For programmatic R peak detection and the feature-table-as-artifact framing see metabolomics\u002Fxcms-preprocessing; for lipid annotation mode see metabolomics\u002Flipidomics; for MSI-level confidence honesty see metabolomics\u002Fmetabolite-annotation; for drift correction and QC see metabolomics\u002Fnormalization-qc.","https:\u002F\u002Fgithub.com\u002Fmrsonord2240\u002Fopenscience-specialists\u002Fblob\u002Fmain\u002Fspecialists\u002Funtargeted-metabolomics-analyst\u002Fversions\u002F1.0.0\u002Fpackage\u002Fskills\u002Fbio-metabolomics-msdial-preprocessing\u002FSKILL.md",[],[]]