Skip to content

refactor(summarization): Rename ref regression covariate to ref_covariate for SRM experiments - #190

Merged
tonywu1999 merged 5 commits into
develfrom
feat-turnover-2
Apr 12, 2026
Merged

tonywu1999 merged 5 commits into
develfrom
feat-turnover-2

Conversation

@tonywu1999

@tonywu1999 tonywu1999 commented Apr 12, 2026 •

Copy link
Copy Markdown
Contributor

PR Type

Bug fix, Tests


Description

  • Rename labeled reference term to ref_covariate

  • Update preparation, imputation, summarization models

  • Align dataProcess accepted input columns

  • Add regression tests for outputs and coefficients


Diagram Walkthrough

flowchart LR
  prep["Prepare labeled input"]
  cov["Create ref_covariate"]
  models["Update imputation and summarization models"]
  outputs["Process protein-level outputs"]
  tests["Add regression tests"]
  prep -- "builds" --> cov
  cov -- "feeds" --> models
  models -- "supports" --> outputs
  models -- "covered by" --> tests
  outputs -- "checked by" --> tests
Loading

File Walkthrough

Relevant files
Bug fix
dataProcess.R
Use `ref_covariate` in summarization inputs                           

R/dataProcess.R

  • Accept ref_covariate in summarization column subsets
  • Update single linear summarization input selection
  • Update TMP summarization input selection
+2/-2     
utils_imputation.R
Switch AFT models to `ref_covariate`                                         

R/utils_imputation.R

  • Replace ref with ref_covariate in AFT models
  • Update single-feature labeled survival regression
  • Update reduced and full labeled regression formulas
+3/-3     
utils_summarization.R
Update labeled linear model covariate                                       

R/utils_summarization.R

  • Use ref_covariate in labeled linear models
  • Update single-feature labeled summarization formula
  • Update multi-feature labeled summarization formula
+2/-2     
utils_summarization_prepare.R
Create `ref_covariate` during summarization preparation   

R/utils_summarization_prepare.R

  • Create ref_covariate for label-based inputs
  • Encode the covariate as a factor from RUN or 0
+1/-1     
Tests
test_dataProcess.R
Add output column regression checks                                           

inst/tinytest/test_dataProcess.R

  • Assert ProteinLevelData includes LogIntensities
  • Assert ProteinLevelData includes GROUP
  • Add regression coverage for labeled SRM outputs
+8/-0     
test_utils_summarization.R
Test labeled models with `ref_covariate`                                 

inst/tinytest/test_utils_summarization.R

  • Add helper to build labeled SRM input
  • Populate test data with ref_covariate
  • Fit .fitLinearModel on labeled input
  • Verify coefficients include ref_covariate terms
+32/-0   

Motivation and Context

This PR refactors the labeled reference term naming convention across the MSstats summarization and imputation pipeline. Previously, the reference indicator for labeled experiments was stored in a column named ref. This refactoring renames this term to ref_covariate to improve naming clarity and semantic consistency. The change propagates through data preparation, survival model fitting, and linear model fitting, ensuring that all downstream analyses correctly reference the renamed covariate in their formulas and data subsets.

Detailed Changes

Core Implementation Changes

  • R/utils_summarization_prepare.R: Modified MSstatsPrepareForSummarization() to create the ref_covariate column instead of ref by storing factor(ifelse(LABEL == "L", RUN, 0)) under the new column name.

  • R/dataProcess.R: Updated column-selection logic in MSstatsSummarizeSingleLinear() and MSstatsSummarizeSingleTMP() to replace ref with ref_covariate in the feature-level data column intersections, ensuring downstream model-fitting data includes the correctly named covariate.

  • R/utils_summarization.R: Updated .fitLinearModel() to use ref_covariate instead of ref in linear model formulas for labeled experiments (both single-feature and multi-feature cases: ABUNDANCE ~ RUN + ref_covariate and ABUNDANCE ~ FEATURE + RUN + ref_covariate).

  • R/utils_imputation.R: Updated survival regression formulas in .fitSurvival() for labeled cases to replace the ref term with ref_covariate in three labeled-case branches, resulting in formulas like ~ RUN + ref_covariate and ~ FEATURE + RUN + ref_covariate.

Test Coverage

  • inst/tinytest/test_dataProcess.R: Added two regression assertions validating that dataProcess(SRMRawData, use_log_file = FALSE)$ProteinLevelData contains expected columns LogIntensities and GROUP.

  • inst/tinytest/test_utils_summarization.R: Added make_srm_input() helper function that constructs synthetic test data with ref_covariate as a categorical column, along with a new test assertion verifying that .fitLinearModel() produces coefficients containing "ref_covariate" terms when fitting labeled experiments.

  • inst/tinytest/test_utils_imputation.R: New comprehensive test file with helper functions for generating labeled and unlabeled survival model test datasets across single-feature and multi-feature scenarios:

    • make_surv_labeled_single(), make_surv_labeled_multi_welldetermined(), make_surv_labeled_underdetermined() for labeled cases
    • make_surv_unlabeled_single(), make_surv_unlabeled_multi_welldetermined() for unlabeled cases
    • coef_names() helper for extracting coefficient names from fitted models
    • Assertions verifying presence/absence of ref_covariate and FEATURE terms in fitted models based on scenario type.
  • inst/tinytest/test_utils_summarization_prepare.R: New test file verifying ref_covariate creation in MSstatsPrepareForSummarization() for both labeled and label-free datasets, confirming the column is created as a factor with correct mappings (heavy rows → "0", light rows → corresponding RUN identifiers) for labeled input and absent for label-free input.

Unit Tests Added or Modified

  • test_dataProcess.R: 2 new assertions (8 lines added)
  • test_utils_summarization.R: 1 new helper function and 1 new test call with assertion (32 lines added)
  • test_utils_imputation.R: New file with 6 helper functions and comprehensive assertions across labeled/unlabeled and single/multi-feature scenarios (133 lines added)
  • test_utils_summarization_prepare.R: New file with thorough validation of ref_covariate column creation and mapping for labeled and label-free datasets (72 lines added)

Coding Guidelines

No coding guideline violations identified in the provided changes. The refactoring maintains consistent naming conventions, preserves existing control flow and logic, and includes comprehensive test coverage across all modified code paths.

@coderabbitai

coderabbitai Bot commented Apr 12, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Replaces the ref indicator with a new ref_covariate column across data preparation, model-fitting formulas, and column-selection logic for labeled experiments; updates/adds tests to assert presence and use of ref_covariate and related output columns.

Changes

Cohort / File(s) Summary
Data preparation
R/utils_summarization_prepare.R
Writes the two-label indicator into a new ref_covariate column (factor of ifelse(LABEL == "L", RUN, 0)) instead of ref.
Model fitting / column selection
R/dataProcess.R, R/utils_imputation.R, R/utils_summarization.R
Replaces uses of ref with ref_covariate in column-intersection logic and in survival/linear model formulas for labeled branches (single- and multi-feature cases).
Tests / fixtures / helpers
inst/tinytest/test_dataProcess.R, inst/tinytest/test_utils_summarization.R, inst/tinytest/test_utils_imputation.R, inst/tinytest/test_utils_summarization_prepare.R
Adds/updates tests and synthetic-data helpers to generate labeled/unlabeled fixtures using ref_covariate; asserts model coefficients include ref_covariate where expected and checks presence of output columns like LogIntensities, GROUP, and ref_covariate behavior.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • devonjkohler
  • mstaniak
  • anshuman-raina

Poem

🐰 I hopped through code both near and far,
Swapped ref for ref_covariate — a shiny star.
Factors placed and tests made neat,
Models now greet the new covariate's beat.
🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description includes motivation, changes overview, and diagram, but lacks the structured template format with detailed bullet points and testing details. Reorganize the description to match the template structure: add 'Motivation and Context' section with problem summary, expand 'Changes' with detailed bullet points for each file, and add explicit 'Testing' section documenting added tests.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title accurately describes the main change: renaming a regression covariate from 'ref' to 'ref_covariate' across summarization code for SRM experiments, which is reflected consistently across all modified files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-turnover-2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ No major issues detected

@github-actions

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Preserve run labels correctly

ifelse() strips the factor metadata from RUN, so this can encode light rows with the
underlying integer level ids instead of the run names. Convert RUN to character
before branching so ref_covariate keeps the intended labels and the labeled-model
design matrix is correct.

R/utils_summarization_prepare.R [36]

-input[, ref_covariate := factor(ifelse(LABEL == "L", RUN, 0))]
+input[, ref_covariate := {
+    ref_values <- ifelse(LABEL == "L", as.character(RUN), "0")
+    factor(ref_values, levels = c("0", as.character(unique(RUN))))
+}]
Suggestion importance[1-10]: 8

__

Why: This is a valid correctness issue: ifelse() can coerce factor-valued RUN entries to their underlying integer codes, which would make ref_covariate incorrect for labeled data. The proposed change is directly applicable to ref_covariate construction and would prevent downstream model terms from being misencoded.

Medium
Keep legacy column working

This rename drops legacy ref columns entirely, which can break labeled summarization
for already-prepared tables or cached objects that still use the old name. Normalize
ref to ref_covariate before selecting columns so the refactor stays backward
compatible during rollout.

R/dataProcess.R [367-370]

+if (!"ref_covariate" %in% colnames(single_protein) && "ref" %in% colnames(single_protein)) {
+  data.table::setnames(single_protein, "ref", "ref_covariate")
+}
 cols = intersect(
   colnames(single_protein),
   c("newABUNDANCE", "cen", "RUN", "FEATURE", "ref_covariate")
 )
Suggestion importance[1-10]: 5

__

Why: This is a reasonable backward-compatibility improvement because the PR consistently switches from ref to ref_covariate, and older prepared inputs could otherwise stop working. Its impact is moderate rather than critical, since the new code path appears internally consistent and this mainly helps legacy or cached single_protein objects.

Low

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
inst/tinytest/test_utils_summarization.R (1)

75-78: Strengthen the assertion to require a non-aliased ref_covariate effect.

Right now the test passes if the term name exists even when all ref_covariate coefficients are NA (aliased). Consider asserting at least one non-NA ref_covariate coefficient.

Suggested test hardening
-expect_true(
-    any(grepl("ref_covariate", names(coef(lm_fit)))),
-    info = "ref_covariate: model coefficients must include 'ref_covariate' terms"
-)
+coef_vals <- coef(lm_fit)
+ref_terms <- coef_vals[grepl("^ref_covariate", names(coef_vals))]
+expect_true(
+    length(ref_terms) > 0 && any(!is.na(ref_terms)),
+    info = "ref_covariate: model must retain at least one estimable ref_covariate coefficient"
+)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@inst/tinytest/test_utils_summarization.R` around lines 75 - 78, The test
currently only checks that a term named "ref_covariate" appears in coef(lm_fit);
change the assertion to require at least one non-NA coefficient for that effect
by extracting coef(lm_fit)[grepl("ref_covariate", names(coef(lm_fit)))],
checking its length > 0 and that any(!is.na(...)) is true, and update the
expect_* call (e.g., expect_true or expect_false with appropriate info) so the
test fails when all ref_covariate coefficients are aliased (NA).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@inst/tinytest/test_utils_summarization.R`:
- Around line 75-78: The test currently only checks that a term named
"ref_covariate" appears in coef(lm_fit); change the assertion to require at
least one non-NA coefficient for that effect by extracting
coef(lm_fit)[grepl("ref_covariate", names(coef(lm_fit)))], checking its length >
0 and that any(!is.na(...)) is true, and update the expect_* call (e.g.,
expect_true or expect_false with appropriate info) so the test fails when all
ref_covariate coefficients are aliased (NA).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d7c2ee8c-e026-4c58-bd0e-d712a2f45273

📥 Commits

Reviewing files that changed from the base of the PR and between d9418ed and bba1d31.

📒 Files selected for processing (6)
  • R/dataProcess.R
  • R/utils_imputation.R
  • R/utils_summarization.R
  • R/utils_summarization_prepare.R
  • inst/tinytest/test_dataProcess.R
  • inst/tinytest/test_utils_summarization.R

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
inst/tinytest/test_utils_imputation.R (2)

19-20: Consider extracting shared ref_covariate construction.

The same transformation is repeated in three fixtures. A tiny helper would reduce drift risk in future renames.

♻️ Suggested refactor
+add_ref_covariate <- function(dt, runs) {
+    ref_vals <- ifelse(dt$LABEL == "L", as.character(dt$RUN), "0")
+    dt[["ref_covariate"]] <- factor(ref_vals, levels = c("0", runs))
+    dt
+}
+
 make_surv_labeled_single <- function() {
@@
-    ref_vals <- ifelse(dt$LABEL == "L", as.character(dt$RUN), "0")
-    dt[["ref_covariate"]] <- factor(ref_vals, levels = c("0", runs))
-    dt
+    add_ref_covariate(dt, runs)
 }

Also applies to: 33-34, 55-56

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@inst/tinytest/test_utils_imputation.R` around lines 19 - 20, Extract the
repeated construction of ref_vals and dt[["ref_covariate"]] into a small helper
(e.g., make_ref_covariate) and call it from the three fixtures instead of
duplicating the logic; specifically, move the logic that builds ref_vals <-
ifelse(dt$LABEL == "L", as.character(dt$RUN), "0") and dt[["ref_covariate"]] <-
factor(ref_vals, levels = c("0", runs)) into that helper, accept dt and runs as
parameters, return the modified dt (or the factor), and replace the three inline
occurrences (the blocks constructing ref_vals and setting dt[["ref_covariate"]])
with calls to make_ref_covariate.

83-133: Assertions are strong, but one branch is still untested.

Given .fitSurvival in R/utils_imputation.R has a distinct unlabeled underdetermined fallback (~ RUN), add one fixture/assertion pair for that case to lock behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@inst/tinytest/test_utils_imputation.R` around lines 83 - 133, Add a test case
for the unlabeled underdetermined branch by calling MSstats:::.fitSurvival with
a fixture like make_surv_unlabeled_underdetermined() (mirror the pattern of
surv_labeled_under and surv_unlabeled_multi_wd) and assert that the resulting
coef names do NOT contain "ref_covariate" and do NOT contain "^FEATURE" (i.e.,
add two expect_false checks similar to the other unlabeled assertions,
referencing the new variable e.g. surv_unlabeled_under to locate the test).
inst/tinytest/test_utils_summarization_prepare.R (1)

21-21: Add teardown to restore logging settings.

MSstatsConvert::MSstatsLogsSettings(FALSE) on line 21 changes global behavior and is never restored. This will disable logging for all subsequent tests executed in the same R session. Add a corresponding restoration call (e.g., MSstatsConvert::MSstatsLogsSettings(TRUE)) at the end of the file to prevent unintended side effects on other tests.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@inst/tinytest/test_utils_summarization_prepare.R` at line 21, The test file
calls MSstatsConvert::MSstatsLogsSettings(FALSE) which mutates global logging
state and is never restored; add a teardown to reset it (e.g., call
MSstatsConvert::MSstatsLogsSettings(TRUE)) at the end of the file or register a
cleanup/on.exit handler so logging is restored after tests finish; reference the
existing call to MSstatsConvert::MSstatsLogsSettings(FALSE) when adding the
restoration to ensure the global setting is returned to TRUE.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@inst/tinytest/test_utils_imputation.R`:
- Around line 19-20: Extract the repeated construction of ref_vals and
dt[["ref_covariate"]] into a small helper (e.g., make_ref_covariate) and call it
from the three fixtures instead of duplicating the logic; specifically, move the
logic that builds ref_vals <- ifelse(dt$LABEL == "L", as.character(dt$RUN), "0")
and dt[["ref_covariate"]] <- factor(ref_vals, levels = c("0", runs)) into that
helper, accept dt and runs as parameters, return the modified dt (or the
factor), and replace the three inline occurrences (the blocks constructing
ref_vals and setting dt[["ref_covariate"]]) with calls to make_ref_covariate.
- Around line 83-133: Add a test case for the unlabeled underdetermined branch
by calling MSstats:::.fitSurvival with a fixture like
make_surv_unlabeled_underdetermined() (mirror the pattern of surv_labeled_under
and surv_unlabeled_multi_wd) and assert that the resulting coef names do NOT
contain "ref_covariate" and do NOT contain "^FEATURE" (i.e., add two
expect_false checks similar to the other unlabeled assertions, referencing the
new variable e.g. surv_unlabeled_under to locate the test).

In `@inst/tinytest/test_utils_summarization_prepare.R`:
- Line 21: The test file calls MSstatsConvert::MSstatsLogsSettings(FALSE) which
mutates global logging state and is never restored; add a teardown to reset it
(e.g., call MSstatsConvert::MSstatsLogsSettings(TRUE)) at the end of the file or
register a cleanup/on.exit handler so logging is restored after tests finish;
reference the existing call to MSstatsConvert::MSstatsLogsSettings(FALSE) when
adding the restoration to ensure the global setting is returned to TRUE.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f5405e57-b85e-4a95-b9d6-6f7071c18424

📥 Commits

Reviewing files that changed from the base of the PR and between bba1d31 and 3a6c712.

📒 Files selected for processing (2)
  • inst/tinytest/test_utils_imputation.R
  • inst/tinytest/test_utils_summarization_prepare.R

@tonywu1999 tonywu1999 changed the title refactor(summarization): Rename ref regression covariate to ref_covariate refactor(summarization): Rename ref regression covariate to ref_covariate for SRM experiments Apr 12, 2026
@tonywu1999
tonywu1999 merged commit df6f005 into devel Apr 12, 2026
1 check passed
@tonywu1999
tonywu1999 deleted the feat-turnover-2 branch April 12, 2026 22:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant