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

Fix new older monocot traits for edge cases #77

Merged
merged 5 commits into from
Apr 23, 2024

Conversation

eberrigan
Copy link
Collaborator

@eberrigan eberrigan commented Apr 23, 2024

  • Check shapely geometry type before getting intersections
  • Fixes some edge cases where the intersection is not a MultiPoint object but LineString, a single point or a collection of geometry objects
  • Adds checks when nodes used for intersections are missing

Summary by CodeRabbit

  • New Features

    • Enhanced point extraction capabilities to handle more complex geometries.
    • Improved computation and validation of intersection points in geometric calculations.
  • Bug Fixes

    • Removed an invalid test case that was not representative of typical usage scenarios.
  • Tests

    • Added new tests for extracting points from various geometric shapes to ensure robust functionality.

Copy link
Contributor

coderabbitai bot commented Apr 23, 2024

Warning

Rate Limit Exceeded

@eberrigan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 28 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 5033de5 and 5a51eab.

Walkthrough

The recent updates bring significant improvements to geometry handling and intersection computations in the sleap_roots library. These changes enhance point extraction from complex geometries, ensure better validation of input shapes for intersection vectors, refine test coverage, and improve overall reliability and functionality.

Changes

Files Summary of Changes
sleap_roots/convhull.py, sleap_roots/points.py Enhanced point extraction from geometries, updated intersection point computations with input validation checks.
tests/test_convhull.py, tests/test_points.py Refined test suite by removing outdated cases and expanding tests to cover various geometric objects for comprehensive validation.

🌟🐇✨
In the world of code, under the moon's glow,
A rabbit hops, leaving traces in the snow.
Geometries merge, points finely weave,
In the magic of updates we believe.
Oh, celebrate the craft, so clever and bright,
With each line of code, we reach new heights!
🌟🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

codecov bot commented Apr 23, 2024

Codecov Report

Attention: Patch coverage is 86.36364% with 3 lines in your changes are missing coverage. Please review.

Project coverage is 74.62%. Comparing base (035b153) to head (5a51eab).

Files Patch % Lines
sleap_roots/convhull.py 75.00% 2 Missing ⚠️
sleap_roots/points.py 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #77      +/-   ##
==========================================
+ Coverage   74.58%   74.62%   +0.04%     
==========================================
  Files          13       13              
  Lines        1326     1344      +18     
==========================================
+ Hits          989     1003      +14     
- Misses        337      341       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 5

Out of diff range and nitpick comments (1)
tests/test_points.py (1)

Line range hint 512-512: Duplicate function definition for test_associate_lateral_to_primary_valid_input. Consider removing or renaming one of the implementations to avoid confusion and potential override issues.


def test_extract_from_unsupported_type():
with pytest.raises(NameError):
extract_points_from_geometry(Polygon([(0, 0), (1, 1), (1, 0)])) # Polygon is unsupported
Copy link
Contributor

Choose a reason for hiding this comment

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

The test attempts to use an unsupported Polygon type, which is not defined in the imports.

-        extract_points_from_geometry(Polygon([(0, 0), (1, 1), (1, 0)]))  # Polygon is unsupported
+        # Polygon is unsupported, consider adding support or handling this case differently.

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.

Suggested change
extract_points_from_geometry(Polygon([(0, 0), (1, 1), (1, 0)])) # Polygon is unsupported
# Polygon is unsupported, consider adding support or handling this case differently.

Comment on lines +7 to +10
from sleap_roots.points import (
extract_points_from_geometry,
get_line_equation_from_points,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Unused imports detected.

- from shapely import box, LineString, normalize, Polygon
+ from shapely import LineString

Remove the unused imports box, normalize, and Polygon to clean up the code and avoid potential confusion about their necessity.


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.

Suggested change
from sleap_roots.points import (
extract_points_from_geometry,
get_line_equation_from_points,
)
from sleap_roots.points import (
extract_points_from_geometry,
get_line_equation_from_points,
)

Comment on lines 451 to 462
Raises:
ValueError: If pts does not have the expected shape.
"""
if r0_pts.ndim == 1 or rn_pts.ndim == 1 or pts.ndim == 2:
print(
"Not enough instances or incorrect format to compute convex hull intersections."
)
return (np.array([[np.nan, np.nan]]), np.array([[np.nan, np.nan]]))

# Check for valid pts input
if not isinstance(pts, np.ndarray) or pts.ndim != 3 or pts.shape[-1] != 2:
raise ValueError("pts must be a numpy array of shape (instances, nodes, 2).")
Copy link
Contributor

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [454-468]

Ensure proper input validation.

- if r0_pts.ndim == 1 or rn_pts.ndim == 1 or pts.ndim == 2:
+ if r0_pts.ndim != 2 or rn_pts.ndim != 2 or pts.ndim != 3:

The condition for checking the dimensions of the input arrays should ensure that they meet the expected dimensions explicitly, rather than checking for what they should not be. This makes the validation more robust and understandable.

@@ -460,7 +465,7 @@
raise ValueError("rn_pts must be a numpy array of shape (instances, 2).")
# Ensure r0_pts is a numpy array of shape (instances, 2)
if not isinstance(r0_pts, np.ndarray) or r0_pts.ndim != 2 or r0_pts.shape[-1] != 2:
raise ValueError("r0_pts must be a numpy array of shape (instances, 2).")
raise ValueError(f"r0_pts must be a numpy array of shape (instances, 2).")
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unnecessary f-string.

- raise ValueError(f"r0_pts must be a numpy array of shape (instances, 2).")
+ raise ValueError("r0_pts must be a numpy array of shape (instances, 2).")

The f-string in this line does not contain any placeholders, making it unnecessary. Replace it with a regular string to avoid confusion and potential errors in future modifications.


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.

Suggested change
raise ValueError(f"r0_pts must be a numpy array of shape (instances, 2).")
raise ValueError("r0_pts must be a numpy array of shape (instances, 2).")

Comment on lines 11 to 49
def extract_points_from_geometry(geometry):
"""Extracts coordinates as a list of numpy arrays from any given Shapely geometry object.

This function supports Point, MultiPoint, LineString, and GeometryCollection types.
It recursively extracts coordinates from complex geometries and aggregates them into a single list.
For unsupported geometry types, it returns an empty list.

Parameters:
- geometry (shapely.geometry.base.BaseGeometry): A Shapely geometry object from which to extract points.

Returns:
- List[np.ndarray]: A list of numpy arrays, where each array represents the coordinates of a point.
The list will be empty if the geometry type is unsupported or contains no coordinates.

Raises:
- TypeError: If the input is not a recognized Shapely geometry type.

Example:
>>> from shapely.geometry import Point, MultiPoint, LineString, GeometryCollection
>>> point = Point(1, 2)
>>> multipoint = MultiPoint([(1, 2), (3, 4)])
>>> linestring = LineString([(0, 0), (1, 1), (2, 2)])
>>> geom_col = GeometryCollection([point, multipoint, linestring])
>>> extract_points_from_geometry(geom_col)
[array([1, 2]), array([1, 2]), array([3, 4]), array([0, 0]), array([1, 1]), array([2, 2])]
"""
if isinstance(geometry, Point):
return [np.array([geometry.x, geometry.y])]
elif isinstance(geometry, MultiPoint):
return [np.array([point.x, point.y]) for point in geometry.geoms]
elif isinstance(geometry, LineString):
return [np.array([x, y]) for x, y in zip(*geometry.xy)]
elif isinstance(geometry, GeometryCollection):
points = []
for geom in geometry.geoms:
points.extend(extract_points_from_geometry(geom))
return points
else:
raise TypeError(f"Unsupported geometry type: {type(geometry).__name__}")
Copy link
Contributor

Choose a reason for hiding this comment

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

Implement robust error handling in geometry extraction.

- raise TypeError(f"Unsupported geometry type: {type(geometry).__name__}")
+ if not isinstance(geometry, (Point, MultiPoint, LineString, GeometryCollection)):
+     raise TypeError(f"Unsupported geometry type: {type(geometry).__name__}")

Modify the error handling to check explicitly for supported types before processing the geometry. This prevents the function from attempting to process an unsupported type, which currently would only raise an error after failing to match any conditions.


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.

Suggested change
def extract_points_from_geometry(geometry):
"""Extracts coordinates as a list of numpy arrays from any given Shapely geometry object.
This function supports Point, MultiPoint, LineString, and GeometryCollection types.
It recursively extracts coordinates from complex geometries and aggregates them into a single list.
For unsupported geometry types, it returns an empty list.
Parameters:
- geometry (shapely.geometry.base.BaseGeometry): A Shapely geometry object from which to extract points.
Returns:
- List[np.ndarray]: A list of numpy arrays, where each array represents the coordinates of a point.
The list will be empty if the geometry type is unsupported or contains no coordinates.
Raises:
- TypeError: If the input is not a recognized Shapely geometry type.
Example:
>>> from shapely.geometry import Point, MultiPoint, LineString, GeometryCollection
>>> point = Point(1, 2)
>>> multipoint = MultiPoint([(1, 2), (3, 4)])
>>> linestring = LineString([(0, 0), (1, 1), (2, 2)])
>>> geom_col = GeometryCollection([point, multipoint, linestring])
>>> extract_points_from_geometry(geom_col)
[array([1, 2]), array([1, 2]), array([3, 4]), array([0, 0]), array([1, 1]), array([2, 2])]
"""
if isinstance(geometry, Point):
return [np.array([geometry.x, geometry.y])]
elif isinstance(geometry, MultiPoint):
return [np.array([point.x, point.y]) for point in geometry.geoms]
elif isinstance(geometry, LineString):
return [np.array([x, y]) for x, y in zip(*geometry.xy)]
elif isinstance(geometry, GeometryCollection):
points = []
for geom in geometry.geoms:
points.extend(extract_points_from_geometry(geom))
return points
else:
raise TypeError(f"Unsupported geometry type: {type(geometry).__name__}")
def extract_points_from_geometry(geometry):
"""Extracts coordinates as a list of numpy arrays from any given Shapely geometry object.
This function supports Point, MultiPoint, LineString, and GeometryCollection types.
It recursively extracts coordinates from complex geometries and aggregates them into a single list.
For unsupported geometry types, it returns an empty list.
Parameters:
- geometry (shapely.geometry.base.BaseGeometry): A Shapely geometry object from which to extract points.
Returns:
- List[np.ndarray]: A list of numpy arrays, where each array represents the coordinates of a point.
The list will be empty if the geometry type is unsupported or contains no coordinates.
Raises:
- TypeError: If the input is not a recognized Shapely geometry type.
Example:
>>> from shapely.geometry import Point, MultiPoint, LineString, GeometryCollection
>>> point = Point(1, 2)
>>> multipoint = MultiPoint([(1, 2), (3, 4)])
>>> linestring = LineString([(0, 0), (1, 1), (2, 2)])
>>> geom_col = GeometryCollection([point, multipoint, linestring])
>>> extract_points_from_geometry(geom_col)
[array([1, 2]), array([1, 2]), array([3, 4]), array([0, 0]), array([1, 1]), array([2, 2])]
"""
if isinstance(geometry, Point):
return [np.array([geometry.x, geometry.y])]
elif isinstance(geometry, MultiPoint):
return [np.array([point.x, point.y]) for point in geometry.geoms]
elif isinstance(geometry, LineString):
return [np.array([x, y]) for x, y in zip(*geometry.xy)]
elif isinstance(geometry, GeometryCollection):
points = []
for geom in geometry.geoms:
points.extend(extract_points_from_geometry(geom))
return points
else:
if not isinstance(geometry, (Point, MultiPoint, LineString, GeometryCollection)):
raise TypeError(f"Unsupported geometry type: {type(geometry).__name__}")

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: 1

Comment on lines +787 to +791
def test_extract_from_unsupported_type():
with pytest.raises(NameError):
extract_points_from_geometry(
Polygon([(0, 0), (1, 1), (1, 0)])
) # Polygon is unsupported
Copy link
Contributor

Choose a reason for hiding this comment

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

Handle unsupported geometry type correctly.

-        extract_points_from_geometry(Polygon([(0, 0), (1, 1), (1, 0)]))  # Polygon is unsupported
+        # Polygon is unsupported, consider adding support or handling this case differently.

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.

Suggested change
def test_extract_from_unsupported_type():
with pytest.raises(NameError):
extract_points_from_geometry(
Polygon([(0, 0), (1, 1), (1, 0)])
) # Polygon is unsupported
def test_extract_from_unsupported_type():
with pytest.raises(NameError):
# Polygon is unsupported, consider adding support or handling this case differently.

@eberrigan eberrigan merged commit deaf0d4 into main Apr 23, 2024
5 checks passed
@eberrigan eberrigan deleted the elizabeth/Fix-new-older-monocot-traits-for-edge-cases branch April 23, 2024 18:30
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