Skip to content

Hotfix/union returning wrong empty result - #1522

Open
gastald88 wants to merge 4 commits into
boostorg:developfrom
gastald88:hotfix/union_returning_wrong_empty_result
Open

gastald88 wants to merge 4 commits into
boostorg:developfrom
gastald88:hotfix/union_returning_wrong_empty_result

Conversation

@gastald88

@gastald88 gastald88 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Fix crossing ratios of nearly parallel segments

This PR is ai-driven fix to a case where a union of non-emtpy polygons generated an empty result.

Remark: while testing, also intersection of the same polygons provided a wrong result, so this PR extends the intent of this fix to intersection too:


For two segments that cross at a very small angle, Cramer's rule loses most of its digits: the nominators are differences of nearly equal products. The crossing ratio can then contradict the other intersections on the same segment, the turns get the wrong order, and the overlay gives a wrong result.

For crossing segments that are nearly parallel (denominator below 1e-3 of the products' magnitude), this PR computes the ratios as s1 / (s1 - s2) instead. The side values are computed accurately (exact products from precise_math). Since s1 and s2 have opposite signs, there is no cancellation. The new ratios are used only if their signs agree with the side strategy. Other segments are unchanged.

Reproduction

#include <boost/geometry.hpp>
#include <iostream>

namespace bg = boost::geometry;
using point = bg::model::d2::point_xy<double>;
using polygon = bg::model::polygon<point>;

int main()
{
   polygon a, b;
   bg::read_wkt("POLYGON((547.0194 1164.9817,623.376 1088.6251,543.6382 1161.6005,547.0194 1164.9817))", a);
   bg::read_wkt("POLYGON((547.2261 1164.775,543.2119 1160.7608,543.2119 1168.7892,547.2261 1164.775))", b);
   bg::correct(a);
   bg::correct(b);

   std::string reason;
   std::cout << bg::is_valid(a, reason) << " " << reason << "\n";   // 1 Geometry is valid
   std::cout << bg::is_valid(b, reason) << " " << reason << "\n";   // 1 Geometry is valid

   bg::model::multi_polygon<polygon> result;
   bg::union_(a, b, result);
   std::cout << bg::area(result) << "\n";
}

The edge (547.2261 1164.775)-(543.2119 1160.7608) of B crosses the edge (543.6382 1161.6005)-(547.0194 1164.9817) of A at a very small angle.

  • Before: union 0 (empty), intersection 258.177: all of A, although B's area is only 16.11.
  • After: union 272.895, intersection 1.3959.

I added test cases in the test suite, let me know if something else is needed.

gastald88S and others added 2 commits November 20, 2026 12:34
Cramer's rule loses most digits for nearly parallel crossing segments:
the turns on a segment could get the wrong order, and the overlay
the wrong result (e.g. an empty union).

For such crossings, compute the ratios as s1 / (s1 - s2) with
accurate side values (exact products, see precise_math), which is
free of cancellation. Other segments are unchanged.
@barendgehrels

Copy link
Copy Markdown
Collaborator

Thanks for this other PR, same here: pls call correct and is_valid to see if the input is really valid

@gastald88

Copy link
Copy Markdown
Contributor Author

Thanks for this other PR, same here: pls call correct and is_valid to see if the input is really valid

sure, both inputs are valid, I added the calls in the repro example.

@tinko92 tinko92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR!

I commented on some issues I have with it as currently proposed. I may be wrong of course, so those comments could also be addressed with convincing arguments and test instead of changes.

Comment on lines +527 to +542
T const ax = util::numeric_cast<T>(get<0>(a));
T const ay = util::numeric_cast<T>(get<1>(a));
std::array<T, 2> const dx1 = pm::two_diff(util::numeric_cast<T>(get<0>(b)), ax);
std::array<T, 2> const dy1 = pm::two_diff(util::numeric_cast<T>(get<1>(b)), ay);
std::array<T, 2> const dx2 = pm::two_diff(util::numeric_cast<T>(get<0>(c)), ax);
std::array<T, 2> const dy2 = pm::two_diff(util::numeric_cast<T>(get<1>(c)), ay);

// Exact difference of the products, components in ascending magnitude
std::array<T, 4> const e = pm::two_two_expansion_diff(
pm::two_product(dx1[0], dy2[0]),
pm::two_product(dy1[0], dx2[0]));

T const tails = (dx1[0] * dy2[1] + dy2[0] * dx1[1])
- (dy1[0] * dx2[1] + dx2[0] * dy1[1]);

return ((e[0] + e[1]) + (e[2] + tails)) + e[3];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is essentially a duplication of Shewchuk's orient2d stage C (roughly the first half of orient2dadapt in https://www.cs.cmu.edu/afs/cs/project/quake/public/code/predicates.c ), which we have already implemented across orient2d and orient2dtail in precise_math.hpp. This duplication can be avoided by passing some argument like skip_to_c to orient2d and orient2dadapt, that is checked as !skip_to_c in the early returns of those methods.

Another consideration is that side_robust's side_value method is already adaptive, i.e. when it returns with just stage A or stage B (vast majority of degenerate cases), then those values have already survived an error bound check. It should be tested, whether that is sufficient for the relevant cases.

Comment on lines +583 to +590
// Use them only if they agree with the side strategy (they should)
if (math::sign(s1) != sides.get<0, 0>()
|| math::sign(s2) != sides.get<0, 1>()
|| math::sign(t1) != sides.get<1, 0>()
|| math::sign(t2) != sides.get<1, 1>())
{
return;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AFAIU, those will be the results of side_by_triangle under current default strategy choice, so this will apply this refinement only consistently when side_by_triangle happens to agree with side_robust's stage C (which is almost always correct and thereby the same as the result of full side_robust, see table 8 in https://www.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps). But the near-parallel cases are exactly the ones where side_by_triangle's outputs become near random. I think, a patch like this should at least be tested in combination with a change of default to be somewhat consistent here.

CoordinateType const magnitude
= geometry::math::abs(sinfo.dx_a * sinfo.dy_b)
+ geometry::math::abs(sinfo.dy_a * sinfo.dx_b);
if (geometry::math::abs(denominator) >= magnitude * CoordinateType(1.0e-3))

@tinko92 tinko92 Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is a fairly coarse error bound (~5*10^12 times the machine epsilon for double). It's also not CoordinateType dependent, should it be the same for float, double, and long double? The comment marks it as arbitrary but it guards a fairly expensive computation, it should probably be tuned (I suspect it could be lower).

A bigger concern is that this error bound here seems unrelated or at best heuristically related to whether the resulting ratios affect any comparison. But that is the point, where it would actually matter. Refining it when no uncertain comparison depends on it, is extra cost and failing to refine it when it does but is above this threshold would still fail to guarantee consistency.

@barendgehrels
barendgehrels self-requested a review November 29, 2026 12:07

@barendgehrels barendgehrels left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR and the analysis.

The diagnosis is right: the crossing ratio of the nearly collinear edges is inaccurate, and the turns on that edge get the wrong order.

A few remarks:

  • The case is platform dependent. With FMA contraction (e.g. clang on ARM64) develop already gives the right result. Without it (-ffp-contract=off, as on x86-64) the union is empty.
  • The nearly parallel edges are A's (547.0194 1164.9817, 623.376 1088.6251) and B's (543.2119 1168.7892, 547.2261 1164.775). In decimal both lie on x + y = 1712.0011, so they are collinear and overlap; only in double do they cross at a tiny angle. The edge named in the description is not the one involved.
  • With this PR, built without FMA, the existing test issue_1487 in set_ops_areal_areal fails: difference (b − a) and symmetric difference become invalid.
  • Besides @tinko92 's remarks: he is proposing a more systematic approach to these precision problems (#1520). A local refinement in the cartesian intersection strategy, with its own threshold, is probably not the future direction.

The test case is welcome, though. Could you add an issue for it, and reduce the PR to the test case? Then we keep it as a known failure for now, or it goes in together with a fix that passes all tests.

@gastald88

Copy link
Copy Markdown
Contributor Author

Thanks for the PR and the analysis.

The diagnosis is right: the crossing ratio of the nearly collinear edges is inaccurate, and the turns on that edge get the wrong order.

A few remarks:

  • The case is platform dependent. With FMA contraction (e.g. clang on ARM64) develop already gives the right result. Without it (-ffp-contract=off, as on x86-64) the union is empty.
  • The nearly parallel edges are A's (547.0194 1164.9817, 623.376 1088.6251) and B's (543.2119 1168.7892, 547.2261 1164.775). In decimal both lie on x + y = 1712.0011, so they are collinear and overlap; only in double do they cross at a tiny angle. The edge named in the description is not the one involved.
  • With this PR, built without FMA, the existing test issue_1487 in set_ops_areal_areal fails: difference (b − a) and symmetric difference become invalid.
  • Besides @tinko92 's remarks: he is proposing a more systematic approach to these precision problems (Experiment/exact and fast cartesian strategies #1520). A local refinement in the cartesian intersection strategy, with its own threshold, is probably not the future direction.

The test case is welcome, though. Could you add an issue for it, and reduce the PR to the test case? Then we keep it as a known failure for now, or it goes in together with a fix that passes all tests.

Yes sure, I'll do as you asked, thank you!

@gastald88

Copy link
Copy Markdown
Contributor Author

The issue related to this PR I just generated is #1530

@tinko92 tinko92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, same as #1521, I approve but let's wait with the merge (and the conflict resolution) until the fix is merged, which may take some time.

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.

4 participants