-
Notifications
You must be signed in to change notification settings - Fork 18
PM-Xpath implementation to calculate the distance from the boundary #1455
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
Conversation
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughA new set of utility classes and methods have been added to the JavaRosa library to support advanced geospatial calculations. The changes introduce Changes
Sequence DiagramsequenceDiagram
participant XPath as XPath Expression
participant BoundaryFunc as XPathBoundaryDistanceFunc
participant PolygonUtils as PolygonUtils
XPath->>BoundaryFunc: Evaluate boundaryDistance()
BoundaryFunc->>BoundaryFunc: Parse coordinates
BoundaryFunc->>PolygonUtils: Calculate distance to boundary
PolygonUtils-->>BoundaryFunc: Return distance
BoundaryFunc-->>XPath: Return result
Poem
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (5)
src/main/java/org/javarosa/xpath/expr/XPathBoundaryDistanceFunc.java (2)
36-37: Throw an exception instead of returning-1.0for invalid inputsReturning
-1.0to indicate an error may lead to ambiguity in the calling code. Throwing an exception provides clearer error handling and prevents the propagation of invalid values.Apply this diff to improve error handling:
- if (unpackedFrom == null || "".equals(unpackedFrom) || unpackedTo == null || "".equals(unpackedTo)) { - return Double.valueOf(-1.0); - } + if (unpackedFrom == null || "".equals(unpackedFrom) || unpackedTo == null || "".equals(unpackedTo)) { + throw new XPathTypeMismatchException("boundaryDistance() function requires non-empty string arguments."); + }
52-53: Correct the function name in the exception messageThe exception message incorrectly refers to
"distance()"instead of"boundaryDistance()". Updating it helps avoid confusion.Apply this diff to correct the message:
- throw new XPathTypeMismatchException("distance() function requires arguments containing " + + throw new XPathTypeMismatchException("boundaryDistance() function requires arguments containing " +src/main/java/org/javarosa/core/model/utils/PolygonUtils.java (2)
14-33: OptimizeisPointInsidePolygonmethod for performanceConsider optimizing the
isPointInsidePolygonmethod by utilizing existing geometry libraries or algorithms optimized for computational efficiency, especially if this method will be called frequently or on large datasets.
73-91: Validate input data indistanceToClosestBoundaryAdding input validation can prevent potential errors due to malformed or empty inputs. Ensuring that
polygonPointscontains an even number of elements and thattestPointhas the correct length enhances robustness.Apply this diff to add input validation:
public static double distanceToClosestBoundary(List<Double> polygonPoints, double[] testPoint) { + if (polygonPoints == null || polygonPoints.size() < 6 || polygonPoints.size() % 2 != 0) { + throw new IllegalArgumentException("polygonPoints must contain pairs of latitude and longitude coordinates."); + } + if (testPoint == null || testPoint.length != 2) { + throw new IllegalArgumentException("testPoint must contain latitude and longitude."); + }src/main/java/org/javarosa/xpath/expr/FunctionUtils.java (1)
93-93: Maintain alphabetical order infuncListfor readabilityThe
funcListis primarily organized alphabetically. Consider insertingXPathBoundaryDistanceFuncin the appropriate alphabetical position to improve maintainability.Apply this diff to reorder the entry:
funcList.put(XPathChecksumFunc.NAME, XPathChecksumFunc.class); +funcList.put(XPathBoundaryDistanceFunc.NAME, XPathBoundaryDistanceFunc.class); funcList.put(XPathSortFunc.NAME, XPathSortFunc.class);(Note: Adjust the insertion point based on the correct alphabetical order.)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/main/java/org/javarosa/core/model/utils/PolygonUtils.java(1 hunks)src/main/java/org/javarosa/xpath/expr/FunctionUtils.java(1 hunks)src/main/java/org/javarosa/xpath/expr/XPathBoundaryDistanceFunc.java(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
- GitHub Check: task-list-completed
| public class XPathBoundaryDistanceFunc extends XPathFuncExpr{ | ||
| public static final String NAME = "boundaryDistance"; | ||
| private static final int EXPECTED_ARG_COUNT = 2; | ||
|
|
||
| public XPathBoundaryDistanceFunc() { | ||
| name = NAME; | ||
| expectedArgCount = EXPECTED_ARG_COUNT; | ||
| } | ||
|
|
||
| public XPathBoundaryDistanceFunc(XPathExpression[] args) throws XPathSyntaxException { | ||
| super(NAME, args, EXPECTED_ARG_COUNT, true); | ||
| } | ||
|
|
||
|
|
||
| @Override | ||
| protected Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) { | ||
| return boundaryDistance(evaluatedArgs[0], evaluatedArgs[1]); | ||
| } | ||
|
|
||
| public static Double boundaryDistance(Object from, Object to) { | ||
| String unpackedFrom = (String)FunctionUtils.unpack(from); | ||
| String unpackedTo = (String)FunctionUtils.unpack(to); | ||
| if (unpackedFrom == null || "".equals(unpackedFrom) || unpackedTo == null || "".equals(unpackedTo)) { | ||
| return Double.valueOf(-1.0); | ||
| } | ||
| try { | ||
| String[] coordinates=unpackedFrom.split(" "); | ||
| List<Double> polygonList = new ArrayList<Double>(); | ||
|
|
||
| for (String coordinate : coordinates) { | ||
| polygonList.add(Double.parseDouble(coordinate)); | ||
| } | ||
| // Casting and uncasting seems strange but is consistent with the codebase | ||
| GeoPointData castedTo = new GeoPointData().cast(new UncastData(unpackedTo)); | ||
| double distance=PolygonUtils.distanceToClosestBoundary(polygonList,new double[]{castedTo.getLatitude(), castedTo.getLongitude()}); | ||
|
|
||
| return distance; | ||
| } catch (NumberFormatException e) { | ||
| throw new XPathTypeMismatchException("distance() function requires arguments containing " + | ||
| "numeric values only, but received arguments: " + unpackedFrom + " and " + unpackedTo); | ||
| } | ||
| } | ||
| } No newline at end of file |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add unit tests for XPathBoundaryDistanceFunc
To ensure the correctness and robustness of the boundaryDistance function, it's crucial to add unit tests covering various scenarios, including valid inputs, invalid inputs, and edge cases.
Would you like assistance in generating unit tests for this function or opening a GitHub issue to track this task?
| String unpackedFrom = (String)FunctionUtils.unpack(from); | ||
| String unpackedTo = (String)FunctionUtils.unpack(to); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure safe casting from FunctionUtils.unpack(from/to)
Casting the result of FunctionUtils.unpack() directly to String may lead to a ClassCastException if the unpacked objects are not strings. It's advisable to check the instance type before casting to prevent potential runtime exceptions.
Apply this diff to safely handle the casting:
- String unpackedFrom = (String)FunctionUtils.unpack(from);
- String unpackedTo = (String)FunctionUtils.unpack(to);
+ Object unpackedFromObj = FunctionUtils.unpack(from);
+ Object unpackedToObj = FunctionUtils.unpack(to);
+ if (!(unpackedFromObj instanceof String) || !(unpackedToObj instanceof String)) {
+ throw new XPathTypeMismatchException("boundaryDistance() function requires string arguments.");
+ }
+ String unpackedFrom = (String) unpackedFromObj;
+ String unpackedTo = (String) unpackedToObj;📝 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.
| String unpackedFrom = (String)FunctionUtils.unpack(from); | |
| String unpackedTo = (String)FunctionUtils.unpack(to); | |
| Object unpackedFromObj = FunctionUtils.unpack(from); | |
| Object unpackedToObj = FunctionUtils.unpack(to); | |
| if (!(unpackedFromObj instanceof String) || !(unpackedToObj instanceof String)) { | |
| throw new XPathTypeMismatchException("boundaryDistance() function requires string arguments."); | |
| } | |
| String unpackedFrom = (String) unpackedFromObj; | |
| String unpackedTo = (String) unpackedToObj; |
| public static boolean isPointInsidePolygon(List<Double> polygonPoints, List<Double> testPoint) { | ||
| int intersectCount = 0; | ||
| int vertexCount = polygonPoints.size() / 2; | ||
|
|
||
| double testLat = testPoint.get(0); | ||
| double testLng = testPoint.get(1); | ||
|
|
||
| for (int i = 0; i < vertexCount; i++) { | ||
| double lat1 = polygonPoints.get(2 * i); | ||
| double lng1 = polygonPoints.get(2 * i + 1); | ||
| double lat2 = polygonPoints.get((2 * ((i + 1) % vertexCount))); | ||
| double lng2 = polygonPoints.get((2 * ((i + 1) % vertexCount)) + 1); | ||
|
|
||
| if (rayIntersectsEdge(testLat, testLng, lat1, lng1, lat2, lng2)) { | ||
| intersectCount++; | ||
| } | ||
| } | ||
|
|
||
| return (intersectCount % 2 == 1); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if a ray starting from the test point intersects the edge defined by two vertices. | ||
| */ | ||
| private static boolean rayIntersectsEdge(double testLat, double testLng, double lat1, double lng1, double lat2, double lng2) { | ||
| if (lat1 > lat2) { | ||
| double tempLat = lat1, tempLng = lng1; | ||
| lat1 = lat2; | ||
| lng1 = lng2; | ||
| lat2 = tempLat; | ||
| lng2 = tempLng; | ||
| } | ||
|
|
||
| if (testLat < lat1 || testLat > lat2) { | ||
| return false; | ||
| } | ||
|
|
||
| if (testLng > Math.max(lng1, lng2)) { | ||
| return false; | ||
| } | ||
|
|
||
| if (testLng < Math.min(lng1, lng2)) { | ||
| return true; | ||
| } | ||
|
|
||
| double slope = (lng2 - lng1) / (lat2 - lat1); | ||
| double intersectLng = lng1 + (testLat - lat1) * slope; | ||
|
|
||
| return testLng < intersectLng; | ||
| } | ||
|
|
||
| /** | ||
| * Calculates the distance from a point to the closest boundary of the polygon. | ||
| * | ||
| * @param polygonPoints A list of doubles representing the polygon vertices | ||
| * (latitude and longitude pairs). | ||
| * @param testPoint A list of doubles representing the latitude and longitude of the test point. | ||
| * @return The distance from the test point to the closest edge of the polygon. | ||
| */ | ||
| public static double distanceToClosestBoundary(List<Double> polygonPoints, double[] testPoint) { | ||
| double minDistance = Double.MAX_VALUE; | ||
|
|
||
| int vertexCount = polygonPoints.size() / 2; | ||
| double testLat = testPoint[0]; | ||
| double testLng = testPoint[1]; | ||
|
|
||
| for (int i = 0; i < vertexCount; i++) { | ||
| double lat1 = polygonPoints.get(2 * i); | ||
| double lng1 = polygonPoints.get(2 * i + 1); | ||
| double lat2 = polygonPoints.get((2 * ((i + 1) % vertexCount))); | ||
| double lng2 = polygonPoints.get((2 * ((i + 1) % vertexCount)) + 1); | ||
|
|
||
| double distance = pointToSegmentDistance(testLat, testLng, lat1, lng1, lat2, lng2); | ||
| minDistance = Math.min(minDistance, distance); | ||
| } | ||
|
|
||
| return minDistance; | ||
| } | ||
|
|
||
| /** | ||
| * Calculates the shortest distance from a point to a line segment. | ||
| */ | ||
| private static double pointToSegmentDistance(double px, double py, double x1, double y1, double x2, double y2) { | ||
| double dx = x2 - x1; | ||
| double dy = y2 - y1; | ||
|
|
||
| if (dx == 0 && dy == 0) { | ||
| // The segment is a point | ||
| return Math.sqrt(Math.pow(px - x1, 2) + Math.pow(py - y1, 2)); | ||
| } | ||
|
|
||
| // Calculate the projection of the point onto the line | ||
| double t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy); | ||
|
|
||
| if (t < 0) { | ||
| // Closest to the first endpoint | ||
| return Math.sqrt(Math.pow(px - x1, 2) + Math.pow(py - y1, 2)); | ||
| } else if (t > 1) { | ||
| // Closest to the second endpoint | ||
| return Math.sqrt(Math.pow(px - x2, 2) + Math.pow(py - y2, 2)); | ||
| } else { | ||
| // Closest to a point on the segment | ||
| double projX = x1 + t * dx; | ||
| double projY = y1 + t * dy; | ||
| return Math.sqrt(Math.pow(px - projX, 2) + Math.pow(py - projY, 2)); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add unit tests for PolygonUtils methods
Implementing unit tests for isPointInsidePolygon and distanceToClosestBoundary methods will help ensure their correctness and detect any regressions in future changes.
Would you like assistance in creating unit tests for these methods?
shubham1g5
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure I understand how this function is supposed to use. Do you mind writing some unit-tests to demonstrate the function usage in here
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| public class XPathBoundaryDistanceFunc extends XPathFuncExpr{ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we add a javadoc here explaining what this function does.
|
Note: This will also need to be added here: https://github.com/dimagi/commcare-android/blob/0a85740209c3436e2ad61faedc1dc506ca5e5c7b/app/unit-tests/src/org/commcare/android/tests/processing/FormStorageTest.java#L363 for longitudinal testing to work |
|
Now that this is in a limited test, I wanted to make sure to write down a list of the things that I think need to be addressed in the structure before this is ready for production, since I might not be around or remember the context in full.
|
|
Hi Clayton,
I have noted this work will be picking up this week .
Thanks & Regards
Parth Mittal
…On Thu, Jan 23, 2025 at 11:12 PM Clayton Sims ***@***.***> wrote:
Now that this is in a limited test, I wanted to make sure to write down a
list of the things that I think need to be addressed in the structure
before this is ready for production, since I might not be around or
remember the context in full.
- Implement appropriate sphere projection (great circle) math instead
of planar math, and document the source of the approach
- Address edge cases for inputs (like a malformed polygon) to make
sure they are communicated as effectively as possible, and add tests to
clarify how invalid inputs caught
- Review the interfaces for the new functions (method signatures and
names) - I don't think these are named super clearly right now, and I think
the arguments should be in the other order (single input first, polygon
second)
- Make a decision about the best set of data formats / models to be
used for portable Geospatial geometries
- Prepare the documentation for these functions, as well as any
supporting documentation to use them (both things like the data format for
the portable geometries and helpful usage documentation next to the
reference docs that explain the use cases and how someone would adopt them.
- Provide references from initial testing to confirm that these
methods are useful and complete enough from a Product perspective, and
worth adding to the generally available platform.
—
Reply to this email directly, view it on GitHub
<#1455 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BI42OB2KL3YTQGIKUANL3ML2MESYZAVCNFSM6AAAAABVJMAGTOVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMMJQGU2DMNJUG4>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
|
shubham1g5
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should update the wiki once we make the changes and have an approval here.
Since these are breaking changes with what was out earlier on Beta, we also need to co-ordinate with delivery on this to send comms before we release this.
| case "polygon-point": | ||
| return new XPathClosestPointToPolygonFunc(args); | ||
| case "inside-polygon": | ||
| return new XPathIsPointInsidePolygonFunc(args); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you can see that all other method classes follow a strict naming convention in relation to their actial names, we need to do the same for names of these 2 classes as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
src/main/java/org/javarosa/xpath/expr/XPathClosestPointToPolygonFunc.java
Outdated
Show resolved
Hide resolved
src/main/java/org/javarosa/xpath/expr/XPathClosestPointToPolygonFunc.java
Outdated
Show resolved
Hide resolved
| import java.util.Arrays; | ||
|
|
||
| public class XPathClosestPointToPolygonFunc extends XPathFuncExpr { | ||
| public static final String NAME = "polygon-point"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
probably call this method - "closest-point-on-polygon" to be more descriptive of what it does.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Class name needs to exactly reflect the method name here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
src/main/java/org/javarosa/xpath/expr/XPathClosestPointToPolygonFunc.java
Show resolved
Hide resolved
src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java
Outdated
Show resolved
Hide resolved
src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java
Outdated
Show resolved
Hide resolved
src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java
Outdated
Show resolved
Hide resolved
src/main/java/org/javarosa/xpath/expr/XPathIsPointInsidePolygonFunc.java
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to be merged. But holding the approval here until we can get sign off from delivery on this. Also can you update the wiki here to reflect these new additions for CC 2.57 ?
Product Description
Written down the functions that calculate the distance from the boundary of the polygon
Technical Summary
Followed this document for the implementation of the code logic(https://docs.google.com/document/d/1mEqXmtuLSBnPGzcvxyEg-3X7BBytAlEFb8epkbevO64/edit?usp=sharing)
Safety Assurance
Safety story
Automated test coverage
QA Plan
-Need proper testing to this function by creating the polygon and check the distance from that.
Special deploy instructions
Rollback instructions
Review
Duplicate PR
Automatically duplicate this PR as defined in contributing.md.
Summary by CodeRabbit
New Features
boundaryDistance()to calculate the distance to the closest polygon boundaryTechnical Improvements
Release Note: Adds two new Xpath methods closest-point-on-polygon and is-point-inside-polygon