Skip to content

feat: Add measurement of distance form nucleus center and border#8

Merged
Czaki merged 2 commits intomainfrom
distance_measure
Jul 9, 2025
Merged

feat: Add measurement of distance form nucleus center and border#8
Czaki merged 2 commits intomainfrom
distance_measure

Conversation

@Czaki
Copy link
Contributor

@Czaki Czaki commented Jul 8, 2025

Summary by CodeRabbit

  • New Features
    • Added new measurement options to calculate the distance from each ROI to the nucleus center and the shortest distance from each ROI to the nucleus border. These measurements are available in the analysis measurement category and require full data for calculation.

@coderabbitai
Copy link

coderabbitai bot commented Jul 9, 2025

Walkthrough

Two new measurement classes, DistanceToNucleusCenter and DistanceFromNucleusBorder, have been added to the codebase. These classes enable spatial measurements between ROI components and the nucleus, and are registered for use in the system's measurement analysis. No existing APIs or control flow were modified.

Changes

File(s) Change Summary
src/PartSeg_smfish/measurement.py Added DistanceToNucleusCenter and DistanceFromNucleusBorder measurement classes.
src/PartSeg_smfish/init.py Registered the two new measurement classes for analysis measurement.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MeasurementSystem
    participant DistanceToNucleusCenter
    participant DistanceFromNucleusBorder
    participant ROI
    participant Nucleus

    User->>MeasurementSystem: Request measurement (e.g., DistanceToNucleusCenter)
    MeasurementSystem->>DistanceToNucleusCenter: Invoke calculation
    DistanceToNucleusCenter->>ROI: Get ROI center
    DistanceToNucleusCenter->>Nucleus: Get nucleus center
    DistanceToNucleusCenter->>MeasurementSystem: Return distance

    User->>MeasurementSystem: Request measurement (DistanceFromNucleusBorder)
    MeasurementSystem->>DistanceFromNucleusBorder: Invoke calculation
    DistanceFromNucleusBorder->>ROI: Get ROI center
    DistanceFromNucleusBorder->>Nucleus: Get nucleus border points
    DistanceFromNucleusBorder->>MeasurementSystem: Return min distance
Loading

Poem

In the land of code where nuclei dwell,
Two new measures ring the bell—
From center to border, distances found,
With math and logic tightly bound.
Now rabbits can hop and cheer,
For spatial insights have appeared!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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

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

@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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 45c945c and 46a5b75.

📒 Files selected for processing (2)
  • src/PartSeg_smfish/__init__.py (1 hunks)
  • src/PartSeg_smfish/measurement.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/PartSeg_smfish/__init__.py (1)
src/PartSeg_smfish/measurement.py (2)
  • DistanceToNucleusCenter (37-81)
  • DistanceFromNucleusBorder (84-142)
⏰ 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). (8)
  • GitHub Check: macos-latest py3.12
  • GitHub Check: windows-latest py3.11
  • GitHub Check: ubuntu-latest py3.12
  • GitHub Check: macos-latest py3.10
  • GitHub Check: windows-latest py3.12
  • GitHub Check: ubuntu-latest py3.10
  • GitHub Check: ubuntu-latest py3.11
  • GitHub Check: windows-latest py3.10
🔇 Additional comments (2)
src/PartSeg_smfish/measurement.py (1)

9-10: LGTM: New imports are properly added.

The imports for get_border and symbols are correctly added to support the new measurement classes.

src/PartSeg_smfish/__init__.py (1)

29-36: LGTM: New measurement classes are properly registered.

The two new measurement classes are correctly registered under the analysis_measurement category, following the same pattern as the existing ComponentType measurement. This will integrate them into the measurement framework without affecting existing functionality.

Comment on lines +37 to +82
class DistanceToNucleusCenter(MeasurementMethodBase):
text_info = (
"Distance to nucleus center",
"Distance to nucleus center in units",
)

@classmethod
def get_fields(cls):
return []

@classmethod
def need_full_data(cls):
return True

@classmethod
def get_starting_leaf(cls):
return Leaf(
name=cls.text_info[0],
area=AreaType.ROI,
per_component=PerComponent.Yes,
)

@staticmethod
def calculate_property(
area_array,
roi_alternative: dict[str, np.ndarray],
help_dict: dict,
result_scalar: float,
voxel_size: tuple[float, float, float],
**kwargs,
):
if "nucleus_center" not in help_dict:
nucleus = roi_alternative["nucleus"]
help_dict["nucleus_center"] = (
af.density_mass_center(nucleus, voxel_size) * result_scalar
)
nucleus_center = help_dict["nucleus_center"]
roi_center = (
af.density_mass_center(area_array, voxel_size) * result_scalar
)
return np.sqrt(np.sum((nucleus_center - roi_center) ** 2))

@classmethod
def get_units(cls, ndim):
return symbols("{}")

Copy link

@coderabbitai coderabbitai bot Jul 9, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix the units method to return proper units.

The DistanceToNucleusCenter class implementation is correct for calculating Euclidean distance with good caching optimization. However, the get_units method returns an empty symbolic unit which likely isn't intended.

 @classmethod
 def get_units(cls, ndim):
-    return symbols("{}")
+    return symbols("μm")  # or appropriate unit symbol

The distance calculation logic is sound - it computes the Euclidean distance between the density mass centers of the ROI and nucleus, with proper scaling by result_scalar.

📝 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
class DistanceToNucleusCenter(MeasurementMethodBase):
text_info = (
"Distance to nucleus center",
"Distance to nucleus center in units",
)
@classmethod
def get_fields(cls):
return []
@classmethod
def need_full_data(cls):
return True
@classmethod
def get_starting_leaf(cls):
return Leaf(
name=cls.text_info[0],
area=AreaType.ROI,
per_component=PerComponent.Yes,
)
@staticmethod
def calculate_property(
area_array,
roi_alternative: dict[str, np.ndarray],
help_dict: dict,
result_scalar: float,
voxel_size: tuple[float, float, float],
**kwargs,
):
if "nucleus_center" not in help_dict:
nucleus = roi_alternative["nucleus"]
help_dict["nucleus_center"] = (
af.density_mass_center(nucleus, voxel_size) * result_scalar
)
nucleus_center = help_dict["nucleus_center"]
roi_center = (
af.density_mass_center(area_array, voxel_size) * result_scalar
)
return np.sqrt(np.sum((nucleus_center - roi_center) ** 2))
@classmethod
def get_units(cls, ndim):
return symbols("{}")
@classmethod
def get_units(cls, ndim):
- return symbols("{}")
+ return symbols("μm") # or appropriate unit symbol
🤖 Prompt for AI Agents
In src/PartSeg_smfish/measurement.py between lines 37 and 82, the get_units
method in the DistanceToNucleusCenter class currently returns an empty symbolic
unit which is incorrect. Update this method to return the appropriate unit for
distance measurement, such as a length unit symbol, to correctly represent the
units of the calculated distance.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The unit is determined by result_scalar and the proper text value is set using str.format when printing reesult.

Copy link

Choose a reason for hiding this comment

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

@Czaki Thank you for the clarification! You're absolutely right - I misunderstood how the unit system works in this codebase. The symbols("{}") creates a placeholder that gets filled in later using str.format when the results are printed, with the actual unit determined by the result_scalar. This is a much more flexible approach than hardcoding the unit symbol.

I appreciate you taking the time to explain this implementation detail!


✏️ Learnings added
Learnt from: Czaki
PR: 4DNucleome/PartSeg-smfish#8
File: src/PartSeg_smfish/measurement.py:37-82
Timestamp: 2025-07-09T23:03:57.430Z
Learning: In PartSeg measurement classes, the `get_units()` method returns `symbols("{}")` as a placeholder that gets filled in later using `str.format` when printing results. The actual unit is determined by the `result_scalar` parameter, making the unit system dynamic and flexible.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +84 to +142
class DistanceFromNucleusBorder(MeasurementMethodBase):
text_info = (
"Distance from nucleus border",
"Distance from nucleus border in units",
)

@classmethod
def get_fields(cls):
return []

@classmethod
def need_full_data(cls):
return True

@classmethod
def get_starting_leaf(cls):
return Leaf(
name=cls.text_info[0],
area=AreaType.ROI,
per_component=PerComponent.Yes,
)

@staticmethod
def calculate_property(
area_array,
roi_alternative: dict[str, np.ndarray],
help_dict: dict,
result_scalar: float,
roi_annotation: dict,
_component_num: int,
voxel_size: tuple[float, float, float],
**kwargs,
):
if "nucleus_border" not in help_dict:
nucleus = roi_alternative["nucleus"]
area_pos = np.transpose(np.nonzero(get_border(nucleus))).astype(
float
)
area_pos += 0.5
for i, val in enumerate(
(x * result_scalar for x in reversed(voxel_size)), start=1
):
area_pos[:, -i] *= val
help_dict["nucleus_border"] = area_pos

nucleus_border = help_dict["nucleus_border"]
roi_center = (
af.density_mass_center(area_array, voxel_size) * result_scalar
)
res = np.sqrt(
np.min(np.sum((nucleus_border - roi_center) ** 2, axis=1))
)
if roi_annotation[_component_num].get("type") == "Nucleus":
return -res
return res

@classmethod
def get_units(cls, ndim):
return symbols("{}")
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Fix the units method and verify coordinate scaling logic.

The DistanceFromNucleusBorder class implements a complex but correct distance calculation. The coordinate scaling logic appears sound, but the units issue needs fixing.

 @classmethod
 def get_units(cls, ndim):
-    return symbols("{}")
+    return symbols("μm")  # or appropriate unit symbol

The implementation correctly:

  • Caches nucleus border coordinates for efficiency
  • Scales coordinates by voxel size and result_scalar
  • Finds minimum distance to border points
  • Returns negative distance for "Nucleus" ROI type (indicating inside the nucleus)

Please verify that the coordinate scaling logic in lines 123-126 correctly handles the dimensionality and ordering:


🏁 Script executed:

#!/bin/bash
# Verify the coordinate scaling logic matches the expected dimensionality
ast-grep --pattern 'for i, val in enumerate($$$):
    area_pos[:, -i] *= val'

Length of output: 397


🏁 Script executed:

#!/bin/bash
head -n 40 src/PartSeg_smfish/measurement.py

Length of output: 1062


🏁 Script executed:

#!/bin/bash
rg -n "def get_units" src/PartSeg_smfish/measurement.py -B3 -A3

Length of output: 500


Fix the units for DistanceFromNucleusBorder

The coordinate-scaling loop (Lines 123–126) correctly applies voxel_size and result_scalar to each axis in reverse order. Only the get_units method needs updating to reflect a physical length unit.

File: src/PartSeg_smfish/measurement.py

@@ class DistanceFromNucleusBorder(MeasurementMethodBase):
 @classmethod
 def get_units(cls, ndim):
-    return symbols("{}")
+    # Return the physical length unit, e.g., micrometers
+    return symbols("µm")
📝 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
class DistanceFromNucleusBorder(MeasurementMethodBase):
text_info = (
"Distance from nucleus border",
"Distance from nucleus border in units",
)
@classmethod
def get_fields(cls):
return []
@classmethod
def need_full_data(cls):
return True
@classmethod
def get_starting_leaf(cls):
return Leaf(
name=cls.text_info[0],
area=AreaType.ROI,
per_component=PerComponent.Yes,
)
@staticmethod
def calculate_property(
area_array,
roi_alternative: dict[str, np.ndarray],
help_dict: dict,
result_scalar: float,
roi_annotation: dict,
_component_num: int,
voxel_size: tuple[float, float, float],
**kwargs,
):
if "nucleus_border" not in help_dict:
nucleus = roi_alternative["nucleus"]
area_pos = np.transpose(np.nonzero(get_border(nucleus))).astype(
float
)
area_pos += 0.5
for i, val in enumerate(
(x * result_scalar for x in reversed(voxel_size)), start=1
):
area_pos[:, -i] *= val
help_dict["nucleus_border"] = area_pos
nucleus_border = help_dict["nucleus_border"]
roi_center = (
af.density_mass_center(area_array, voxel_size) * result_scalar
)
res = np.sqrt(
np.min(np.sum((nucleus_border - roi_center) ** 2, axis=1))
)
if roi_annotation[_component_num].get("type") == "Nucleus":
return -res
return res
@classmethod
def get_units(cls, ndim):
return symbols("{}")
@classmethod
def get_units(cls, ndim):
- return symbols("{}")
+ # Return the physical length unit, e.g., micrometers
+ return symbols("µm")
🤖 Prompt for AI Agents
In src/PartSeg_smfish/measurement.py around lines 84 to 142, the get_units
method currently returns an empty symbol string, which does not reflect the
physical length units used in the distance calculation. Update the get_units
method to return the appropriate physical length unit symbol, such as "µm" or
"um", to correctly represent the units of the distance from the nucleus border.

@Czaki Czaki merged commit 9f9dee4 into main Jul 9, 2025
11 checks passed
@Czaki Czaki deleted the distance_measure branch July 10, 2025 08:01
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.

1 participant