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

ratio for calculation of bbox area should always be > 1 (#708) #710

Merged
merged 4 commits into from
Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/apps/testapps/testBBox.c
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,26 @@ SUITE(BBox) {
"bboxHexEstimate of invalid resolution fails");
}

TEST(bboxHexEstimate_ratio) {
BBox bbox1 = {0.82294, 0.82273, 0.131671, 0.131668};
BBox bbox2 = {0.131671, 0.131668, 0.82294, 0.82273};
int64_t numHexagons1;
int64_t numHexagons2;

t_assertSuccess(bboxHexEstimate(&bbox1, 15, &numHexagons1));
t_assertSuccess(bboxHexEstimate(&bbox2, 15, &numHexagons2));

double diffPercentage = fabs(1.0 - numHexagons1 / (double)numHexagons2);

// numHexagons1 and numHexagons2 cannot be exactly equal because the
// diameter of the two bboxes is not exactly the same (it's calculated
// using greatCircleDistanceKm)
t_assert(
diffPercentage < 0.03,
"Should be true for bounding boxes with (almost) the same diameter "
"and side ratio");
}

TEST(lineHexEstimate_invalidRes) {
int64_t numHexagons;
LatLng origin = {0.0, 0.0};
Expand Down
13 changes: 8 additions & 5 deletions src/h3lib/lib/bbox.c
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,17 @@ H3Error bboxHexEstimate(const BBox *bbox, int res, int64_t *out) {
p2.lat = bbox->south;
p2.lng = bbox->west;
double d = H3_EXPORT(greatCircleDistanceKm)(&p1, &p2);
// Derived constant based on: https://math.stackexchange.com/a/1921940
// Clamped to 3 as higher values tend to rapidly drag the estimate to zero.
double lngDiff = p1.lng - p2.lng;
double latDiff = p1.lat - p2.lat;
double lngDiff = fabs(p1.lng - p2.lng);
double latDiff = fabs(p1.lat - p2.lat);
if (lngDiff == 0 || latDiff == 0) {
return E_FAILED;
}
double a = d * d / fmin(3.0, fabs(lngDiff / latDiff));
double length = fmax(lngDiff, latDiff);
double width = fmin(lngDiff, latDiff);
double ratio = length / width;
// Derived constant based on: https://math.stackexchange.com/a/1921940
// Clamped to 3 as higher values tend to rapidly drag the estimate to zero.
double a = d * d / fmin(3.0, ratio);

// Divide the two to get an estimate of the number of hexagons needed
double estimateDouble = ceil(a / pentagonAreaKm2);
Expand Down