Skip to content

fix: color annotation error - #96

Merged
jcharkow merged 4 commits into
mainfrom
fix/color_annot
Aug 13, 2025
Merged

fix: color annotation error#96
jcharkow merged 4 commits into
mainfrom
fix/color_annot

Conversation

@jcharkow

@jcharkow jcharkow commented Aug 13, 2025

Copy link
Copy Markdown
Collaborator

Fixes #89 In a new version of pyopenms_viz the color column gets overridden with black. Fix this so that the user can specify the color per peak.

Summary by CodeRabbit

  • Bug Fixes

    • Annotation colors now use the specified annotation column when provided; otherwise annotations default to black for consistent spectrum visuals.
    • Added debug logging to surface the chosen annotation color during processing.
  • Tests

    • Added a new fixture, parameterized test, and updated snapshots to validate peak/annotation color behavior across plotting backends.

seems that was overriding the color column with black in spectra, change this
@coderabbitai

coderabbitai Bot commented Aug 13, 2025

Copy link
Copy Markdown

Walkthrough

Adjusts SpectrumPlot._get_annotations to use a specified annotation_color column when provided; otherwise it broadcasts "black" for all annotations. Adds a debug print of the annotation_color value. No public API signatures changed.

Changes

Cohort / File(s) Summary
Annotation color handling
pyopenms_viz/_core.py
_get_annotations now determines annotation_color_column = self.annotation_color if present; if None, sets data["color"] = "black" (broadcast) and uses "color" as the annotation column. Returns colors from data[annotation_color_column]. Adds a debug print logging self.annotation_color.
New test fixtures & tests
test/conftest.py, test/test_spectrum.py
Adds spectrum_data2 fixture loading TestSpectrumDf2.tsv and adds test_spectrum_plot_with_peak_color parametrized to exercise peak_color='color' and annotation_color='color'.
Snapshots for plot backends
test/__snapshots__/test_spectrum/...
Adds Plotly JSON and Bokeh HTML snapshot files used by the new test to capture serialized plot output for the peak/annotation color cases.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test
    participant SpectrumPlot
    participant DataFrame

    Test->>SpectrumPlot: call _get_annotations(data)
    SpectrumPlot->>SpectrumPlot: check self.annotation_color
    alt annotation_color provided
        SpectrumPlot->>DataFrame: read column self.annotation_color
        DataFrame-->>SpectrumPlot: per-row colors
    else annotation_color is None
        SpectrumPlot->>SpectrumPlot: set data["color"] = "black" (broadcast)
        SpectrumPlot->>DataFrame: use "color" column
        DataFrame-->>SpectrumPlot: "black" for all rows
    end
    SpectrumPlot-->>Test: return texts, positions, colors
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Fix annotation color selection so it respects per-row colors when specified via peak_color/annotation_color (#89)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Added debug print logging self.annotation_color (pyopenms_viz/_core.py) Debug logging was not requested by #89; it's an ancillary instrumentation change.
Added snapshot files for Bokeh/Plotly (test/__snapshots__/test_spectrum/...) Snapshot artifacts support the new test but are test artifacts, not part of the bug fix requested by #89.

"I nibble strings of color bright,
Once black was all that hid the light.
Now columns whisper red or blue,
Or black stands firm when none come through.
A rabbit cheers each tiny mark—hop, spark! 🐇"

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/color_annot

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.

@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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c9e0c07 and 5f5d303.

📒 Files selected for processing (1)
  • pyopenms_viz/_core.py (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: continuous-integration
pyopenms_viz/_core.py

[error] 1032-1032: KeyError: 'color' in _get_annotations during spectrum plotting for test_spectrum_plot[ms_matplotlib-kwargs2]; the input data lacks a 'color' column (expected for annotation colors).


[error] 1032-1032: KeyError: 'color' in _get_annotations during spectrum plotting for test_spectrum_plot[ms_bokeh-kwargs2]; the input data lacks a 'color' column (expected for annotation colors).


[error] 1032-1032: KeyError: 'color' in _get_annotations during spectrum plotting for test_spectrum_plot[ms_plotly-kwargs2]; the input data lacks a 'color' column (expected for annotation colors).

Comment thread pyopenms_viz/_core.py Outdated
@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been built and is available at:
🔗 View Preview

This preview will be updated automatically when you push new commits to this PR.


Preview built from commit: c729410

github-actions Bot added a commit that referenced this pull request Aug 13, 2025
@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been built and is available at:
🔗 View Preview

This preview will be updated automatically when you push new commits to this PR.


Preview built from commit: 267d0ce

github-actions Bot added a commit that referenced this pull request Aug 13, 2025
github-actions Bot added a commit that referenced this pull request Aug 13, 2025
@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been built and is available at:
🔗 View Preview

This preview will be updated automatically when you push new commits to this PR.


Preview built from commit: 5e685a0

@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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7818be9 and bc5bb90.

⛔ Files ignored due to path filters (3)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs0].png is excluded by !**/*.png
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs1].png is excluded by !**/*.png
  • test/test_data/TestSpectrumDf2.tsv is excluded by !**/*.tsv
📒 Files selected for processing (7)
  • pyopenms_viz/_core.py (2 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json (1 hunks)
  • test/conftest.py (1 hunks)
  • test/test_spectrum.py (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json
🚧 Files skipped from review as they are similar to previous changes (1)
  • pyopenms_viz/_core.py
🧰 Additional context used
🪛 GitHub Actions: continuous-integration
test/test_spectrum.py

[error] 41-41: Command 'python -m pytest --snapshot-warn-unused test/' failed: Snapshot 'test_spectrum_plot_with_peak_color[ms_matplotlib]' does not exist.


[error] 41-41: Command 'python -m pytest --snapshot-warn-unused test/' failed: Snapshot 'test_spectrum_plot_with_peak_color[ms_bokeh]' does not exist.


[error] 41-41: Command 'python -m pytest --snapshot-warn-unused test/' failed: Snapshot 'test_spectrum_plot_with_peak_color[ms_plotly]' does not exist.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (3)
test/conftest.py (1)

80-82: Verified: TestSpectrumDf2.tsv exists with a “color” column

The new spectrum_data2 fixture in test/conftest.py (lines 80–82) is consistent with existing patterns and the underlying test data:

  • Confirmed test/test_data/TestSpectrumDf2.tsv is present
  • Header columns are:
    1. mz
    2. intensity
    3. color

No further changes needed—approving the addition.

test/test_spectrum.py (1)

31-41: Ignore incorrect snapshot mismatch warning

The existing snapshots already include two variants per backend (one for each spectrum_data2 fixture case), indicated by the -kwargs0 and -kwargs1 suffixes. All three backends—including ms_matplotlib—have their snapshots committed:

  • test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs0].png
  • test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs1].png
  • test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html
  • test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html
  • test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json
  • test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json

No snapshots are missing, and the test is correctly parameterized over both backends and data variants. You can safely disregard the original comment.

Likely an incorrect or invalid review comment.

test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html (1)

1-61: Ensure snapshot filenames match the test IDs by removing the “-kwargsN” suffix

All of the existing snapshots under test/__snapshots__/test_spectrum/ need to be renamed so that pytest-snapshot can locate them correctly. In particular, drop the -kwargs0 and -kwargs1 parts and standardize on one file per backend:

• test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html
• test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html
→ test_spectrum_plot_with_peak_color[ms_bokeh].html

• test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json
• test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json
→ test_spectrum_plot_with_peak_color[ms_plotly].json

• test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs0].png
• test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs1].png
→ test_spectrum_plot_with_peak_color[ms_matplotlib].png

After renaming, remove any duplicates so that there’s exactly one snapshot per backend. This will ensure pytest-snapshot finds them by test ID.

Comment thread test/test_spectrum.py Outdated
@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

The documentation for this PR has been built and is available at:
🔗 View Preview

This preview will be updated automatically when you push new commits to this PR.


Preview built from commit: 5dabe78

github-actions Bot added a commit that referenced this pull request Aug 13, 2025

@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.

Actionable comments posted: 1

🧹 Nitpick comments (3)
test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json (3)

305-1163: Snapshot is extremely verbose and brittle due to embedded Plotly template and defaults.

Embedding the entire layout.template, colorscales, and default axis/theme values inflates the snapshot and increases flakiness across Plotly versions. Recommend normalizing the figure prior to snapshotting by stripping template and default styling so tests focus on semantics (data, trace colors, annotations).

Suggested approach in the test helper (outside this file):

import copy

def normalize_plotly_figure(fig):
    f = copy.deepcopy(fig).to_plotly_json()
    # Drop noisy/default-heavy fields
    f.get("layout", {}).pop("template", None)
    # Optionally drop other style-only keys that can vary by env/Plotly version
    for k in ["colorway", "colorscale", "font", "paper_bgcolor", "plot_bgcolor"]:
        f.get("layout", {}).pop(k, None)
    # For axes, keep titles/ranges but drop grid/line cosmetics if not essential
    for axis in ("xaxis", "yaxis"):
        ax = f.get("layout", {}).get(axis, {})
        for k in ["gridcolor", "linecolor", "tickcolor", "tickwidth", "linewidth", "zerolinecolor"]:
            ax.pop(k, None)
    return f

Then snapshot normalize_plotly_figure(fig) instead of the raw figure.


1228-1231: Legend title text may be version-dependent and unnecessary for assertion.

"Trace" is cosmetic and can change across Plotly versions/themes. Prefer asserting showlegend=True and trace names, rather than the legend title text in the snapshot.


2-303: Scalability note: one trace per color can explode with high cardinality color columns.

For spectra with many distinct colors, creating a separate trace per color can degrade performance and interactivity. If this scenario is expected, consider an alternative encoding strategy (e.g., fewer color buckets, or single-trace rendering with per-point color where feasible for markers). For stick plots, per-segment color is harder, but pre-bucketing colors to a reasonable palette can keep trace count bounded.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc5bb90 and aaf78a3.

⛔ Files ignored due to path filters (3)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs0].png is excluded by !**/*.png
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_matplotlib-kwargs1].png is excluded by !**/*.png
  • test/test_data/TestSpectrumDf2.tsv is excluded by !**/*.tsv
📒 Files selected for processing (7)
  • pyopenms_viz/_core.py (2 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json (1 hunks)
  • test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json (1 hunks)
  • test/conftest.py (1 hunks)
  • test/test_spectrum.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs1].html
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs1].json
  • test/conftest.py
  • test/snapshots/test_spectrum/test_spectrum_plot_with_peak_color[ms_bokeh-kwargs0].html
  • test/test_spectrum.py
  • pyopenms_viz/_core.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build
  • GitHub Check: test (windows-latest, 3.12)
  • GitHub Check: test (windows-latest, 3.12)
🔇 Additional comments (1)
test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json (1)

271-276: Per-peak colors and annotation color correctly applied (meets PR objective).

Trace color "red" and the annotation font color "red" are consistent with the provided color column. This snapshot demonstrates that per-peak coloring and per-annotation coloring are no longer overridden to black. Nice restoration.

Also applies to: 1238-1249

Comment on lines +98 to +267
"customdata": [
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
],
[
19988.959742,
8e-06
]
],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Hover data appears incorrect: customdata values do not match x/y (user-facing correctness).

For both traces, the customdata entries are constant and do not correspond to the per-point x/y values rendered in the trace. Example: the red trace draws at x=20001.0/y≈0.106688 but customdata shows m/z 19989.963097 and intensity 9.1e-05 for all points. This will cause hover tooltips to show misleading m/z/intensity values.

Consider either:

  • Using x/y directly in the hovertemplate and removing customdata, or
  • Ensuring customdata is generated per-point and aligns with x/y.

You can implement the safer option (use x/y) when building the figure:

In test or figure construction code (not this snapshot), update traces like:

# After constructing the Plotly figure:
fig.update_traces(hovertemplate="m/z: %{x}<br>intensity: %{y}", customdata=None)

If customdata is needed for other reasons, build it point-aligned:

# Example: for stick plots where each peak is [mz, mz, mz] and [0, intensity, 0]
customdata = [[mz, intensity] for mz, intensity in zip(x_values, y_values)]
fig.update_traces(customdata=customdata, hovertemplate="m/z: %{customdata[0]}<br>intensity: %{customdata[1]}")

Also applies to: 287-302, 268-269, 301-302

🤖 Prompt for AI Agents
In
test/__snapshots__/test_spectrum/test_spectrum_plot_with_peak_color[ms_plotly-kwargs0].json
around lines 98-267 (also check the other affected ranges 268-269, 287-302,
301-302), the snapshot shows constant customdata entries that do not match
per-point x/y values causing incorrect hover tooltips; update the figure
construction/tests to either remove customdata and use x/y in the hovertemplate
(e.g. set hovertemplate to use %{x} and %{y} and clear customdata) or, if
customdata is required, generate a per-point customdata list aligned with
x_values and y_values (one [mz,intensity] entry per point) and update
hovertemplate to reference customdata[0]/customdata[1] so hover values match the
rendered points.

@jcharkow
jcharkow merged commit 6029ea9 into main Aug 13, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Color annotation seems to be broken

1 participant