Skip to content

Conversation

@pm-dimagi
Copy link
Contributor

@pm-dimagi pm-dimagi commented Jun 19, 2025

Product Description

Link
this is the XPath implementation of function
-is-point-inside-polygon
-closest-point-of-polygon

purpose is to keep earth curvature in mind to calculate the closest point
used Gavaghan Geodesy lib to do so

Technical Summary

Safety Assurance

Safety story

Automated test coverage

QA Plan

Special deploy instructions

  • This PR can be deployed after merge with no further considerations.

Rollback instructions

  • This PR can be reverted after deploy with no further considerations.

Review

  • The set of people pinged as reviewers is appropriate for the level of risk of the change.

Duplicate PR

Automatically duplicate this PR as defined in contributing.md.

Summary by CodeRabbit

  • New Features
    • Polygon calculations now use geodesic (ellipsoid-aware) methods, improving accuracy for geographic data.
    • New support for finding the closest point on a polygon boundary using geodesic calculations.
  • Bug Fixes
    • Improved validation for latitude and longitude inputs.
  • Refactor
    • Replaced previous planar geometry library with a geodesy library for all polygon-related computations.
  • Tests
    • Enhanced test cases with higher precision expected results and added tests for larger polygons.

@coderabbitai
Copy link

coderabbitai bot commented Jun 19, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

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.

Walkthrough

The codebase was refactored to replace the use of the JTS planar geometry library with the geodesy library for ellipsoid-aware computations. Polygon creation, point-in-polygon tests, and closest-point calculations now use geodesic calculations with GlobalCoordinates. Tests were updated for higher precision and additional cases, and dependencies were adjusted accordingly.

Changes

Files/Paths Change Summary
build.gradle Replaced JTS dependency with geodesy library.
src/main/java/org/javarosa/core/model/utils/PolygonUtils.java Refactored to use geodesic calculations; changed polygon representation and updated/added methods for new logic.
src/main/java/org/javarosa/xpath/expr/XPathClosestPointOnPolygonFunc.java,
.../XPathIsPointInsidePolygonFunc.java
Updated to use new polygon representation and geodesic methods; adjusted imports and validation accordingly.
src/test/java/org/javarosa/xpath/test/XPathEvalTest.java Updated expected outputs for higher precision; added new test cases for large polygons.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PolygonUtils
    participant GeodesyLib

    Caller->>PolygonUtils: createPolygon(latLngList)
    PolygonUtils->>GeodesyLib: Validate/convert coordinates
    PolygonUtils-->>Caller: List<GlobalCoordinates>

    Caller->>PolygonUtils: isPointInsideOrOnPolygon(point, polygon)
    PolygonUtils->>GeodesyLib: Ray casting/geodesic calculations
    PolygonUtils-->>Caller: Boolean

    Caller->>PolygonUtils: findClosestPoint(point, polygon)
    PolygonUtils->>GeodesyLib: Project point onto polygon edges geodesically
    PolygonUtils-->>Caller: Closest point as String
Loading

Possibly related PRs

  • Commcare 2.57 Backmerge #1482: Both PRs modify coordinate validation in PolygonUtils, but this PR transitions from JTS to geodesic calculations, whereas the related PR adds validation within the existing JTS-based logic.

Suggested labels

cross requested, Release Note

Suggested reviewers

  • shubham1g5

Poem

A bunny hopped across the globe,
Swapping JTS for geodesy’s robe.
Now polygons curve with the earth’s embrace,
Closest points found with elegant grace.
Test cases precise, the journey complete—
Hopping through code, making geodesy sweet!
🐇🌍

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch pm_ccc_1367

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 auto-generate unit tests to generate unit tests for 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: 0

🧹 Nitpick comments (1)
src/main/java/org/javarosa/core/model/utils/PolygonUtils.java (1)

144-173: Consider floating-point precision for vertex equality checks.

The ray casting algorithm is correctly implemented, but the vertex equality check on lines 161-162 uses exact floating-point comparison:

if ((testLat == lat1 && testLon == lon1) || (testLat == lat2 && testLon == lon2)) {

Consider using a small epsilon for floating-point comparison to handle potential precision issues.

+    private static final double VERTEX_EPSILON = 1e-12;
+    
     // Vertex check
-    if ((testLat == lat1 && testLon == lon1) || (testLat == lat2 && testLon == lon2)) {
+    if ((Math.abs(testLat - lat1) < VERTEX_EPSILON && Math.abs(testLon - lon1) < VERTEX_EPSILON) ||
+        (Math.abs(testLat - lat2) < VERTEX_EPSILON && Math.abs(testLon - lon2) < VERTEX_EPSILON)) {
         return true;
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dbfba9b and fd643bc.

📒 Files selected for processing (5)
  • build.gradle (1 hunks)
  • src/main/java/org/javarosa/core/model/utils/PolygonUtils.java (1 hunks)
  • src/main/java/org/javarosa/xpath/expr/XPathClosestPointOnPolygonFunc.java (3 hunks)
  • src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java (4 hunks)
  • src/test/java/org/javarosa/xpath/test/XPathEvalTest.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: task-list-completed
  • GitHub Check: task-list-completed
  • GitHub Check: build
🔇 Additional comments (13)
build.gradle (1)

86-86: Verify the geodesy library version is current and stable.

The addition of org.gavaghan:geodesy:1.1.3 looks correct for the migration from JTS to geodesic calculations. Please confirm this is the latest stable version and check for any known security vulnerabilities.

#!/bin/bash
# Check for the latest version of the geodesy library and any security advisories
echo "Checking latest version of org.gavaghan:geodesy on Maven Central..."
curl -s "https://search.maven.org/solrsearch/select?q=g:org.gavaghan+AND+a:geodesy&rows=1&wt=json" | jq -r '.response.docs[0].latestVersion // "Version not found"'

echo "Checking for security advisories..."
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: MAVEN, package: "org.gavaghan:geodesy") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'
src/test/java/org/javarosa/xpath/test/XPathEvalTest.java (2)

614-682: LGTM! Enhanced precision reflects geodesic calculations.

The updated expected coordinate values with higher floating-point precision correctly reflect the transition from planar JTS geometry to geodesic-aware computations. The more precise results are expected when accounting for Earth's curvature.


704-712: Excellent addition of large-scale polygon tests.

The new test cases for ~150km scale polygons are valuable for verifying the accuracy of geodesic calculations over larger geographic areas where the difference between planar and ellipsoidal calculations becomes more significant.

src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java (2)

3-3: Correct import for geodesic coordinates.

The import of GlobalCoordinates from the geodesy library appropriately replaces the JTS Polygon import, aligning with the migration to ellipsoid-aware calculations.


70-75: Good practice: added coordinate validation and geodesic-aware processing.

The explicit coordinate validation using PolygonUtils.isValidCoordinates() before creating GlobalCoordinates is excellent defensive programming. The transition to List<GlobalCoordinates> and isPointInsideOrOnPolygon() properly implements geodesic calculations.

src/main/java/org/javarosa/xpath/expr/XPathClosestPointOnPolygonFunc.java (2)

3-3: Consistent import changes for geodesic library.

The import of GlobalCoordinates maintains consistency with the other XPath polygon function and supports the migration to geodesic-aware calculations.


75-80: Proper implementation of geodesic closest point calculation.

The coordinate validation and use of PolygonUtils.findClosestPoint() with GlobalCoordinates correctly implements ellipsoid-aware closest point calculations. The pattern is consistent with the point-in-polygon function.

src/main/java/org/javarosa/core/model/utils/PolygonUtils.java (6)

2-8: Appropriate imports for geodesic calculations.

The imports from org.gavaghan.geodesy provide the necessary components for ellipsoid-aware geographic calculations, properly replacing the JTS dependency.


23-51: Robust polygon creation with proper validation.

The createPolygon method includes excellent validation:

  • Minimum vertex count (3 distinct vertices)
  • Even number of coordinates
  • Coordinate bounds checking
  • Automatic polygon closure

The implementation correctly handles the transition from flat coordinate lists to GlobalCoordinates.


60-64: Simple and effective coordinate validation.

The public isValidCoordinates method provides proper bounds checking for latitude (-90 to 90) and longitude (-180 to 180). Making it public allows the XPath functions to validate coordinates before processing.


73-97: Well-implemented geodesic closest point calculation.

The findClosestPoint method correctly:

  • Uses WGS84 ellipsoid for accurate Earth calculations
  • Projects the point onto each polygon segment geodesically
  • Finds the minimum distance using ellipsoidal calculations
  • Returns proper coordinate formatting

109-135: Mathematically sound geodesic projection.

The projectOntoSegment method implements proper geodesic projection:

  • Handles degenerate cases (identical endpoints)
  • Uses azimuth and distance calculations on the ellipsoid
  • Correctly clamps projection to segment endpoints
  • Uses trigonometry to project point onto geodesic line

166-169: Good practice: epsilon handling for numerical stability.

The addition of 1e-10 in the denominator of the ray casting calculation (line 167) is excellent for avoiding division by zero and maintaining numerical stability in edge cases.

shubham1g5
shubham1g5 previously approved these changes Jun 20, 2025
Copy link
Contributor

@shubham1g5 shubham1g5 left a comment

Choose a reason for hiding this comment

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

Looks great, left some naming suggestions as something to improve on.

Comment on lines 155 to 158
double lat1 = A.getLatitude();
double lon1 = A.getLongitude();
double lat2 = B.getLatitude();
double lon2 = B.getLongitude();
Copy link
Contributor

Choose a reason for hiding this comment

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

should use A and B in naming instead of 1 and 2 to be consitent.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

int n = polygon.size();

double testLat = point.getLatitude();
double testLon = point.getLongitude();
Copy link
Contributor

Choose a reason for hiding this comment

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

Use Long for all Longitude short forms in all vars in this class.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

* @param longitude Longitude in degrees
* @throws IllegalArgumentException if values are outside geographic bounds
*/
public static void isValidCoordinates(double latitude, double longitude) {
Copy link
Contributor

Choose a reason for hiding this comment

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

rename to validateCoordinates as it is not returning any boolean

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@pm-dimagi pm-dimagi merged commit ed5725c into master Jun 23, 2025
2 of 3 checks passed
@shubham1g5
Copy link
Contributor

@pm-dimagi This needs to be duplicated as per instructions in PR template.

@pm-dimagi
Copy link
Contributor Author

@shubham1g5 i don't understand this

@shubham1g5
Copy link
Contributor

look at Duplicate PR in the PR description.

@pm-dimagi
Copy link
Contributor Author

duplicate this PR fd643bc 2849498

@pm-dimagi
Copy link
Contributor Author

@shubham1g5 this comment is not working this is due to the branch is already merged I have checked the PR's in formplayer repo there is no duplicate branch as such

@shubham1g5
Copy link
Contributor

@pm-dimagi You will need to manually do what the duplicate PR script does in that case and create a duplicate PR for it.

@pm-dimagi pm-dimagi mentioned this pull request Jun 24, 2025
3 tasks
@pm-dimagi
Copy link
Contributor Author

done @shubham1g5 #1489

@shubham1g5
Copy link
Contributor

thanks!

@shubham1g5 shubham1g5 deleted the pm_ccc_1367 branch June 24, 2025 10:50
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.

3 participants