Skip to content

fixing of bug in msstats_tmt.R (Issue: Error in the msstats_tmt.R function parse_contrasts #577) - #578

Merged
ypriverol merged 2 commits into
bigbio:devfrom
kai-lawsonmcdowall:dev
Aug 24, 2025
Merged

ypriverol merged 2 commits into
bigbio:devfrom
kai-lawsonmcdowall:dev

Conversation

@kai-lawsonmcdowall

@kai-lawsonmcdowall kai-lawsonmcdowall commented Aug 20, 2025 •

Copy link
Copy Markdown

User description

PR checklist

  • This comment contains a description of changes (with reason).
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added a new tool - have you followed the pipeline conventions in the contribution docs
  • If necessary, also make a PR on the bigbio/quantms branch on the nf-core/test-datasets repository.
  • Make sure your code lints (nf-core pipelines lint).
  • Ensure the test suite passes (nextflow run . -profile test,docker --outdir <OUTDIR>).
  • Check for unexpected warnings in debug mode (nextflow run . -profile debug,test,docker --outdir <OUTDIR>).
  • Usage Documentation in docs/usage.md is updated.
  • Output Documentation in docs/output.md is updated.
  • CHANGELOG.md is updated.
  • README.md is updated (including new tool citations and authors/contributors).

PR Type

Bug fix


Description

  • Fixed critical bug in contrast parsing logic

  • Corrected variable references in control condition handling

  • Applied consistent code formatting throughout R script


Diagram Walkthrough

flowchart LR
  A["parse_contrasts function"] --> B["Fixed variable reference bug"]
  B --> C["comparison[control] instead of comparison[i]"]
  C --> D["Corrected contrast naming"]
  D --> E["Fixed error message typo"]
Loading

File Walkthrough

Relevant files
Bug fix
msstats_tmt.R
Fix contrast parsing bug and code formatting                         

bin/msstats_tmt.R

  • Fixed critical bug where comparison[i] was incorrectly used instead of
    comparison[control]
  • Corrected contrast naming to compare j vs. control instead of i vs. j
  • Fixed typo in error message (missing newline character)
  • Applied consistent code formatting and spacing throughout the file
+409/-328

@coderabbitai

coderabbitai Bot commented Aug 20, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Possible Issue

In .makeVolcano, aesthetics map y to a dynamic variable name via aes_string using the log_adjp string, but the data column created is named with single_label[[log_adjp]]; verify that the resulting column actually exists in the data frame (not a data.table nonstandard eval issue) and that ggplot picks it up as intended. A mismatch would yield a blank/errored plot.

.makeVolcano <- function(
    input, label_name, log_base_FC, log_base_pval, x.lim, ProteinName, dot.size,
    y.limdown, y.limup, text.size, FCcutoff, sig, x.axis.size, y.axis.size,
    legend.size, log_adjp) {
    Protein <- NULL

    plot <- ggplot(
        aes_string(
            x = "logFC",
            y = log_adjp,
            color = "colgroup",
            label = "Protein"
        ),
        data = input
    ) +
        geom_point(size = dot.size) +
        scale_colour_manual(
            values = c("gray65", "blue", "red"),
            limits = c("black", "blue", "red"),
            breaks = c("black", "blue", "red"),
            labels = c("No regulation", "Down-regulated", "Up-regulated")
        ) +
        scale_y_continuous(paste0("-Log", log_base_pval, " (adjusted p-value)"),
            limits = c(y.limdown, y.limup)
        ) +
        labs(title = unique(label_name))
    plot <- plot +
        scale_x_continuous(paste0("Log", log_base_pval, " fold change"),
            limits = c(-x.lim, x.lim)
        )
    if (ProteinName) {
        if (!(length(unique(input$colgroup)) == 1 & any(unique(input$colgroup) == "black"))) {
Edge Case

parse_contrasts now sets comparison[control] <- -1 and names contrasts as j-control; confirm sign convention aligns with downstream MSstatsTMT expectations (e.g., logFC direction). If previous outputs or documentation expect control vs. treatment, this flip could invert interpretation.

control <- which(as.character(lvls) == control_str)
if (length(control) == 0) {
    stop("Control condition not part of found levels.\n", call. = FALSE)
}
contrast_mat <- matrix(nrow = l - 1, ncol = l, dimnames = list(Contrasts = rep(NA, l - 1), Levels = lvls))
c <- 1
for (j in setdiff(1:l, control)) {
    comparison <- rep(0, l)
    comparison[control] <- -1 # Fixed: use 'control' instead of 'i'
    comparison[j] <- 1
    contrast_mat[c, ] <- comparison
    rownames(contrast_mat)[c] <- paste0(lvls[j], "-", lvls[control]) # Fixed: compare j vs. control
    c <- c + 1
}
Plot File Naming

savePlot builds file names based on existing files in the CWD. Regex patterns differ for 'ProfilePlot' vs others; ensure they won’t collide across multiple runs with different prefixes and that directories in name_base are handled (list.files(".") ignores nested paths).

savePlot <- function(name_base, file_name, width, height) {
    if (name_base != FALSE) {
        all_files <- list.files(".")
        if (file_name == "ProfilePlot") {
            num_same_name <- sum(grepl(paste0("^", name_base, file_name, "_[0-9]?"), all_files))
        } else {
            num_same_name <- sum(grepl(paste0("^", name_base, file_name, "[0-9]?"), all_files))
        }
        if (num_same_name > 0) {
            file_name <- paste(file_name, num_same_name + 1, sep = "_")
        }
        file_path <- paste0(name_base, file_name, ".pdf")
        pdf(file_path, width = width, height = height)
    }

@qodo-code-review

qodo-code-review Bot commented Aug 20, 2025 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Validate contrast orientation

The fix changes contrast naming and the sign convention (j vs. control), but
there’s no validation that downstream consumers (groupComparisonTMT, plotting,
or external expectations) interpret positive/negative logFC consistently with
this new orientation. Add a single, explicit sanity check (e.g., on a miniature
example) or a guard that ensures the constructed contrast matrix aligns with
MSstatsTMT’s expected directionality to avoid silently flipped biological
interpretations.

Examples:

bin/msstats_tmt.R [98-105]
            for (j in setdiff(1:l, control)) {
                comparison <- rep(0, l)
                comparison[control] <- -1 # Fixed: use 'control' instead of 'i'
                comparison[j] <- 1
                contrast_mat[c, ] <- comparison
                rownames(contrast_mat)[c] <- paste0(lvls[j], "-", lvls[control]) # Fixed: compare j vs. control
                c <- c + 1
            }

Solution Walkthrough:

Before:

# bin/msstats_tmt.R
...
for (j in setdiff(1:l, control)) {
    comparison <- rep(0, l)
    comparison[control] <- -1 # Fixed: use 'control' instead of 'i'
    comparison[j] <- 1
    contrast_mat[c, ] <- comparison
    rownames(contrast_mat)[c] <- paste0(lvls[j], "-", lvls[control]) # Fixed: compare j vs. control
    c <- c + 1
}
...

After:

# bin/msstats_tmt.R
...
for (j in setdiff(1:l, control)) {
    comparison <- rep(0, l)
    # Assuming groupComparisonTMT interprets a contrast of `A-B` with +1 for A and -1 for B.
    # This will yield a positive logFC if A > B.
    comparison[control] <- -1
    comparison[j] <- 1
    contrast_mat[c, ] <- comparison
    rownames(contrast_mat)[c] <- paste0(lvls[j], "-", lvls[control])
    c <- c + 1
}
...
Suggestion importance[1-10]: 9

__

Why: This suggestion addresses a critical potential flaw where fixing a crash might have introduced silently inverted results, as the orientation of contrasts in parse_contrasts must match the expectation of groupComparisonTMT.

High
Possible issue
Replace positional with named indexing

Using input[, 3] is brittle and can silently break if column order changes.
Index the log fold-change column by name to ensure correctness. This prevents
accidental use of the wrong column in the heatmap thresholding logic.

bin/msstats_tmt.R [510-514]

 if (is.numeric(FCcutoff)) {
-    input$adj.pvalue <- ifelse(input[, 3] < log(FCcutoff, log_base_FC) & input[, 3] > -log(FCcutoff, log_base_FC),
-        1, input$adj.pvalue
-    )
+    # determine FC column by name (supports log2FC or log10FC)
+    fc_col <- intersect(colnames(input), c("log2FC", "log10FC"))
+    if (length(fc_col) != 1) stop("Could not uniquely identify logFC column for FCcutoff filtering.")
+    logfc_vals <- input[[fc_col]]
+    cutoff <- log(FCcutoff, log_base_FC)
+    input$adj.pvalue <- ifelse(logfc_vals < cutoff & logfc_vals > -cutoff, 1, input$adj.pvalue)
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that using positional indexing input[, 3] is brittle and improves code robustness by using named indexing, which prevents potential bugs if column order changes.

Low
General
Fix typo in user errors

There is a typo in the error messages ("Cannnot"). Fixing it improves clarity
and avoids repeated misspelling in user-facing errors. Keep messages consistent
across branches.

bin/msstats_tmt.R [703-711]

 if (address == FALSE) {
     if (which.Comparison == "all") {
         if (length(unique(input$Label)) > 1) {
-            stop("** Cannnot generate all volcano plots in a screen. Please set one comparison at a time.")
+            stop("** Cannot generate all volcano plots on screen. Please set one comparison at a time.")
         }
     } else if (length(which.Comparison) > 1) {
-        stop("** Cannnot generate multiple volcano plots in a screen. Please set one comparison at a time.")
+        stop("** Cannot generate multiple volcano plots on screen. Please set one comparison at a time.")
     }
 }

[Suggestion processed]

Suggestion importance[1-10]: 3

__

Why: The suggestion correctly identifies and fixes a typo ("Cannnot") in a user-facing error message, which improves the professionalism and clarity of the tool's output.

Low
  • Update

@ypriverol
ypriverol requested a review from Copilot August 20, 2025 16:13

This comment was marked as outdated.

@ypriverol
ypriverol requested a review from Copilot August 24, 2025 15:06

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot wasn't able to review any files in this pull request.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread bin/msstats_tmt.R
Comment on lines 705 to 710
if (length(unique(input$Label)) > 1) {
stop('** Cannnot generate all volcano plots in a screen. Please set one comparison at a time.')
stop("** Cannnot generate all volcano plots in a screen. Please set one comparison at a time.")
}
} else if (length(which.Comparison) > 1) {
stop( '** Cannnot generate multiple volcano plots in a screen. Please set one comparison at a time.' )
stop("** Cannnot generate multiple volcano plots in a screen. Please set one comparison at a time.")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: Fix typo in user errors

Suggested change
if (length(unique(input$Label)) > 1) {
stop('** Cannnot generate all volcano plots in a screen. Please set one comparison at a time.')
stop("** Cannnot generate all volcano plots in a screen. Please set one comparison at a time.")
}
} else if (length(which.Comparison) > 1) {
stop( '** Cannnot generate multiple volcano plots in a screen. Please set one comparison at a time.' )
stop("** Cannnot generate multiple volcano plots in a screen. Please set one comparison at a time.")
}
if (length(unique(input$Label)) > 1) {
stop("** Cannot generate all volcano plots on screen. Please set one comparison at a time.")
}
} else if (length(which.Comparison) > 1) {
stop("** Cannot generate multiple volcano plots on screen. Please set one comparison at a time.")
}

@ypriverol
ypriverol self-requested a review August 24, 2025 15:08
@ypriverol
ypriverol merged commit e2c7807 into bigbio:dev Aug 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants