Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better heatmap range handling #4865

Merged
merged 3 commits into from
Sep 30, 2024
Merged

Conversation

benjaminpkane
Copy link
Contributor

@benjaminpkane benjaminpkane commented Sep 30, 2024

What changes are proposed in this pull request?

When heatmap values are above the range, consider them the max range value. When they are below the range, consider them like a 0 with no coloring (background)

import fiftyone as fo
from fiftyone.core.state import build_color_scheme
import fiftyone.zoo as foz


color_scheme = build_color_scheme()
color_scheme.default_colorscale = {
    "name": None,
    "list": [
        {"color": "rgb(48, 18, 59)", "value": 0.0},
        {"color": "rgb(69, 90, 205)", "value": 0.003},
        {"color": "rgb(62, 155, 254)", "value": 0.008},
        {"color": "rgb(25, 214, 204)", "value": 0.0181},
        {"color": "rgb(70, 248, 132)", "value": 0.0473},
        {"color": "rgb(163, 253, 60)", "value": 0.0994},
        {"color": "rgb(225, 221, 55)", "value": 0.1825},
        {"color": "rgb(254, 165, 49)", "value": 0.3049},
        {"color": "rgb(240, 91, 18)", "value": 0.4756},
        {"color": "rgb(196, 37, 3)", "value": 0.741},
        {"color": "rgb(122, 4, 3)", "value": 1.0},
    ],
}


dataset = foz.load_zoo_dataset("quickstart", max_samples=1)
dataset.app_config.color_scheme = color_scheme
dataset.save()

sample = dataset.first()
sample["heatmap_over"] = fo.Heatmap(
    map_path="/path/to/heatmap.png",
    range=[38768.0, 39864.0],
)
sample["heatmap_under"] = fo.Heatmap(
    map_path="/path/to/heatmap.png",
    range=[30768.0, 31864.0],
)
sample.save()
Screen.Recording.2024-09-30.at.9.26.54.AM.mov

66d21819553de2e89ff93430

How is this patch tested? If it is not, please explain why.

Unit test

Release Notes

  • Fixed heatmap rendering for values outside of the range attribute

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • New Features
    • Improved color indexing logic for heatmap rendering.
    • Introduced a new clampedIndex function to handle index calculations.
  • Bug Fixes
    • Enhanced robustness of color retrieval in heatmaps, ensuring valid colors are returned even for out-of-bounds values.
  • Tests
    • Added a new test suite for verifying the behavior of the clampedIndex function.
  • Refactor
    • Streamlined control flow in the Heatmap method and refined color assignment logic in the Segmentation method.

@benjaminpkane benjaminpkane added bug Bug fixes app Issues related to App features labels Sep 30, 2024
@benjaminpkane benjaminpkane requested a review from a team September 30, 2024 13:30
@benjaminpkane benjaminpkane self-assigned this Sep 30, 2024
Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Walkthrough

The changes involve significant updates to the HeatmapOverlay class in the heatmap.ts file, enhancing the color indexing logic through the introduction of a clampedIndex function. Additionally, modifications to the PainterFactory functions improve the handling of color assignments in heatmap and segmentation methods. A new test suite is added to validate the functionality of the clampedIndex function. Overall, the updates focus on refining color retrieval processes and ensuring robust heatmap rendering.

Changes

Files Change Summary
app/packages/looker/src/overlays/heatmap.ts Updated getColor method to use clampedIndex for index calculation; adjusted return values. Reintroduced isShown method.
app/packages/looker/src/worker/painter.test.ts Added a new test suite for clampedIndex function, verifying its behavior for various input values.
app/packages/looker/src/worker/painter.ts Modified Heatmap and Segmentation methods for clarity; introduced clampedIndex function for index handling.

Poem

In the fields where colors bloom,
A heatmap dances, dispelling gloom.
With clamped indices, bright and clear,
Our overlays shine, bringing cheer.
Hopping along, we celebrate,
A vibrant world we create! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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.

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 543ecf3 and 7e82c80.

📒 Files selected for processing (3)
  • app/packages/looker/src/overlays/heatmap.ts (3 hunks)
  • app/packages/looker/src/worker/painter.test.ts (1 hunks)
  • app/packages/looker/src/worker/painter.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
app/packages/looker/src/overlays/heatmap.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/painter.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/painter.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (3)
app/packages/looker/src/overlays/heatmap.ts (1)

208-212: Correct use of 'clampedIndex' function

The updated use of clampedIndex ensures that the index for color retrieval is properly clamped within the valid range, enhancing the robustness of the heatmap rendering.

app/packages/looker/src/worker/painter.ts (2)

209-230: Improved handling of zero and out-of-range heatmap values

The updated logic correctly skips processing when value === 0, and appropriately handles values outside the specified range using the new clampedIndex function. This ensures that heatmap rendering aligns with the PR objectives for better range handling.


394-396: Efficient iteration using for...of loop

Replacing the forEach loop with a for...of loop in convertMaskColorsToObject enhances performance, especially for large arrays. This change conforms with best practices in TypeScript for array iteration.

Comment on lines +67 to +75
describe("heatmap utils", () => {
it("clamps for heatmaps", async () => {
// A value below a heatmap range returns -1
expect(painter.clampedIndex(1, 2, 3, 4)).toBe(-1);

// A value above a heatmap range return the max
expect(painter.clampedIndex(4, 2, 3, 4)).toBe(3);
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage and improve test structure

The new test suite for the clampedIndex function is a good addition. However, consider the following improvements:

  1. Split the current test case into two separate test cases for better clarity and easier debugging:

    • One for testing values below the range
    • Another for testing values above the range
  2. Add more test cases to cover:

    • Edge cases (e.g., values exactly at the min and max of the range)
    • Values within the range
    • Invalid inputs (if applicable)
  3. Make the test descriptions more specific about what is being tested.

Here's an example of how you could restructure the tests:

describe("heatmap utils", () => {
  describe("clampedIndex", () => {
    it("returns -1 for values below the range", () => {
      expect(painter.clampedIndex(1, 2, 3, 4)).toBe(-1);
    });

    it("returns the max index for values above the range", () => {
      expect(painter.clampedIndex(4, 2, 3, 4)).toBe(3);
    });

    it("returns the correct index for values within the range", () => {
      expect(painter.clampedIndex(2.5, 2, 3, 4)).toBe(1); // Assuming linear scale
    });

    it("handles edge cases correctly", () => {
      expect(painter.clampedIndex(2, 2, 3, 4)).toBe(0);
      expect(painter.clampedIndex(3, 2, 3, 4)).toBe(3);
    });
  });
});

This structure provides better organization and more comprehensive coverage of the clampedIndex function's behavior.

Comment on lines +224 to +226
const result = Math.min(max, Math.abs(value)) / max;

return get32BitColor(color, value / max);
return get32BitColor(color, result / max);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Possible double division by 'max' in alpha computation

In the calculation of result, you already divide by max:

const result = Math.min(max, Math.abs(value)) / max;

Then in the return statement, you're dividing result by max again:

return get32BitColor(color, result / max);

This means you're dividing by max twice, which may not be intended and could result in incorrect alpha values for the color.

Apply this diff to correct the calculation:

- return get32BitColor(color, result / max);
+ return get32BitColor(color, result);

Comment on lines +399 to +413

export const clampedIndex = (
value: number,
start: number,
stop: number,
length: number
) => {
if (value < start) {
return -1;
}
const clamped = Math.min(value, stop);
return Math.round(
(Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential division by zero in clampedIndex when start equals stop

In the clampedIndex function, if start equals stop, the expression stop - start will be zero, leading to a division by zero error. This could cause a runtime exception or unexpected behavior.

Apply this diff to prevent division by zero:

 export const clampedIndex = (
   value: number,
   start: number,
   stop: number,
   length: number
+ ): number => {
+  if (stop === start) {
+    return -1;
+  }
   if (value < start) {
     return -1;
   }
   const clamped = Math.min(value, stop);
   return Math.round(
     (Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
   );
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const clampedIndex = (
value: number,
start: number,
stop: number,
length: number
) => {
if (value < start) {
return -1;
}
const clamped = Math.min(value, stop);
return Math.round(
(Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
);
};
export const clampedIndex = (
value: number,
start: number,
stop: number,
length: number
): number => {
if (stop === start) {
return -1;
}
if (value < start) {
return -1;
}
const clamped = Math.min(value, stop);
return Math.round(
(Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
);
};

🛠️ Refactor suggestion

Specify return types for exported functions

For better type safety and clarity, it's recommended to explicitly specify the return types of exported functions in TypeScript.

Add explicit return types to the function declarations:

 export const clampedIndex = (
   value: number,
   start: number,
   stop: number,
   length: number
- ) => {
+ ): number => {

Similarly, for convertMaskColorsToObject:

 const convertMaskColorsToObject = (array: MaskColorInput[])
- => {
+ : { [key: string]: string } => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const clampedIndex = (
value: number,
start: number,
stop: number,
length: number
) => {
if (value < start) {
return -1;
}
const clamped = Math.min(value, stop);
return Math.round(
(Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
);
};
export const clampedIndex = (
value: number,
start: number,
stop: number,
length: number
): number => {
if (value < start) {
return -1;
}
const clamped = Math.min(value, stop);
return Math.round(
(Math.max(clamped - start, 0) / (stop - start)) * (length - 1)
);
};

@benjaminpkane benjaminpkane merged commit 5ab32f7 into release/v1.0.0 Sep 30, 2024
11 checks passed
@benjaminpkane benjaminpkane deleted the bugfix/scope-heatmap-scale branch September 30, 2024 15:51
@coderabbitai coderabbitai bot mentioned this pull request Dec 30, 2024
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
app Issues related to App features bug Bug fixes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants