"""Independent cross-checks and refutations for the exact predicates kernel.""" import random from fractions import Fraction as F from itertools import combinations, permutations import pytest from geometry.kernels.circumcircle import circle_through_three_points from geometry.kernels.common import DegenerateConfigurationError, Point from geometry.kernels.predicates import ( ConvexHull, convex_hull, incircle_sign_ccw, incircle_test, is_ccw, is_strictly_convex, orientation, orientation_of_triangle, point_in_convex_polygon, polygon_area2, ) def sgn(value): """Exact sign of a rational, the oracle used by the cross-checks.""" return (value > 0) - (value < 0) def rnd_point(rng, lo=-6, hi=6): """A random rational point with denominators 1, 2 or 3.""" return Point(F(rng.randint(lo, hi), rng.choice([1, 2, 3])), F(rng.randint(lo, hi), rng.choice([1, 2, 3]))) def rnd_triangle(rng): """Three random non-collinear points.""" while True: a, b, c = rnd_point(rng), rnd_point(rng), rnd_point(rng) if (b - a).cross(c - a) != 0: return a, b, c def random_point_set(rng): """Mixed integer and rational points, with duplicates and many collinear points on one line.""" a, b, c = rnd_triangle(rng) pts = [a, b, c] for _ in range(rng.randint(2, 6)): pts.append(rnd_point(rng)) for _ in range(rng.randint(1, 2)): pts.append(rng.choice(pts)) t = rng.choice([F(-1, 2), F(3, 2), 2, 3]) direction = b - a pts.append(Point(a.x + t * direction.x, a.y + t * direction.y)) pts.append(Point(a.x + (t + 1) * direction.x, a.y + (t + 1) * direction.y)) return pts def on_closed_segment(q, p, r): """True when p lies on the closed segment q-r, checked with exact signs only.""" return (orientation(q, r, p) == 0 and min(q.x, r.x) <= p.x <= max(q.x, r.x) and min(q.y, r.y) <= p.y <= max(q.y, r.y)) def in_hull_of_others(p, pts): """True when p lies in the convex hull of three or fewer other points. By Caratheodory in the plane this is equivalent to p not being a vertex. Tie rule: a vertex is the unique maximum of the input along some direction, so ties never decide membership; membership here is decided by exact segment and closed-triangle tests, never by comparing distances. """ others = [q for q in pts if q != p] for q, r in combinations(others, 2): if on_closed_segment(q, p, r): return True for q, r, s in combinations(others, 3): turn = sgn(orientation(q, r, s)) if turn == 0: continue if (turn * orientation(q, r, p) >= 0 and turn * orientation(r, s, p) >= 0 and turn * orientation(s, q, p) >= 0): return True return False def brute_force_vertices(pts): """The vertices of the convex hull, by the independent Caratheodory criterion.""" distinct = sorted(set(pts), key=lambda p: (p.x, p.y)) return [p for p in distinct if not in_hull_of_others(p, distinct)] SQUARE_EXTRA = [Point(0, 0), Point(4, 0), Point(4, 4), Point(0, 4), Point(2, 2), Point(2, 0), Point(3, 4)] TRI_OUT = [Point(0, 0), Point(4, 0), Point(0, 4), Point(6, -1)] PARABOLA12 = [Point(x, x * x) for x in range(-5, 7)] # -- orientation --------------------------------------------------------------------- def test_orientation_hand_cases(): """The orientation sign must match hand-computed determinants, integers, collinear and rational.""" assert orientation(Point(0, 0), Point(1, 0), Point(0, 1)) == 1 assert orientation(Point(0, 0), Point(0, 1), Point(1, 0)) == -1 assert orientation((0, 0), (2, 2), (5, 5)) == 0 p, q, r = Point(F(1, 2), F(1, 3)), Point(F(3, 4), F(-1, 5)), Point(0, F(7, 6)) # hand computation: (q-p) x (r-p) = (1/4)(5/6) - (-8/15)(-1/2) = 5/24 - 4/15 = -7/120 assert orientation(p, q, r) == -1 assert orientation(r, q, p) == 1 def test_orientation_antisymmetry_and_cyclicity(): """Swapping two arguments must negate the sign and cyclic rotation must preserve it.""" rng = random.Random(31) for _ in range(50): p, q, r = rnd_point(rng), rnd_point(rng), rnd_point(rng) o = orientation(p, q, r) assert orientation(q, p, r) == -o assert orientation(p, r, q) == -o assert orientation(q, r, p) == o assert orientation(r, p, q) == o assert orientation(p, p, r) == 0 assert (o == 0) == ((q - p).cross(r - p) == 0) def test_orientation_of_triangle_and_is_ccw(): """orientation_of_triangle must equal orientation and is_ccw must track the +1 sign.""" a, b, c = Point(0, 0), Point(4, 0), Point(0, 3) assert orientation_of_triangle(a, b, c) == orientation(a, b, c) == 1 assert is_ccw(a, b, c) is True assert is_ccw(a, c, b) is False assert is_ccw(Point(0, 0), Point(2, 2), Point(5, 5)) is False # -- in-circle predicate --------------------------------------------------------------- def test_incircle_matches_circumcircle_route(): """The in-circle sign must equal minus the sign of d.dist2(center) - r2 from circle_through_three_points.""" rng = random.Random(20261118) checked = 0 for _ in range(40): a, b, c = rnd_triangle(rng) circle = circle_through_three_points(a, b, c).circle for _ in range(12): d = rnd_point(rng) # d is strictly inside the circumcircle exactly when its power # d.dist2(center) - r2 is strictly negative, so the in-circle # sign is exactly the negation of the sign of the power. expected = -sgn(d.dist2(circle.center) - circle.r2) assert incircle_test(a, b, c, d) == expected checked += 1 assert checked == 480 def test_cocircular_quadruple_and_perturbed_fifth_point(): """Four exact cocircular points must give zero for every choice of the triple.""" # the circle with center (0, 0) and r2 = 25 carries the Pythagorean point (3, 4) sites = [Point(5, 0), Point(0, 5), Point(-5, 0), Point(0, -5)] for triple in combinations(sites, 3): for d in sites: if d not in triple: assert incircle_test(triple[0], triple[1], triple[2], d) == 0 assert incircle_test(Point(5, 0), Point(0, 5), Point(-5, 0), Point(3, 4)) == 0 # perturbed fifth points: 81/4 < 25 strictly inside, 36 > 25 strictly outside assert incircle_test(Point(5, 0), Point(0, 5), Point(-5, 0), Point(0, F(-9, 2))) == 1 assert incircle_test(Point(5, 0), Point(0, 5), Point(-5, 0), Point(6, 0)) == -1 def test_incircle_test_invariant_under_all_six_permutations(): """The geometric in-circle answer must not depend on the order of a, b, c.""" rng = random.Random(99) a, b, c = rnd_triangle(rng) d = rnd_point(rng) answer = incircle_test(a, b, c, d) for perm in permutations((a, b, c)): assert incircle_test(perm[0], perm[1], perm[2], d) == answer def test_incircle_sign_ccw_rejects_clockwise_and_collinear_triples(): """The order-sensitive sign must refuse a clockwise or a collinear triple.""" a, b, c, d = Point(0, 0), Point(4, 0), Point(0, 4), Point(1, 1) assert incircle_sign_ccw(a, b, c, d) == incircle_test(a, b, c, d) == 1 with pytest.raises(DegenerateConfigurationError, match="counter-clockwise"): incircle_sign_ccw(a, c, b, d) with pytest.raises(DegenerateConfigurationError, match="counter-clockwise"): incircle_sign_ccw(Point(0, 0), Point(2, 2), Point(5, 5), d) with pytest.raises(DegenerateConfigurationError, match="collinear"): incircle_test(Point(0, 0), Point(2, 2), Point(5, 5), d) # -- area and convexity ------------------------------------------------------------------ def test_polygon_area2_and_strict_convexity_hand_cases(): """The shoelace sum and strict convexity must match hand-computed chains.""" unit = [Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)] assert polygon_area2(unit) == 2 assert polygon_area2(list(reversed(unit))) == -2 assert polygon_area2([Point(0, 0), Point(3, 0), Point(0, 4)]) == 12 assert is_strictly_convex(unit) is True assert is_strictly_convex(list(reversed(unit))) is True l_shape = [Point(0, 0), Point(2, 0), Point(2, 1), Point(1, 1), Point(1, 2), Point(0, 2)] assert is_strictly_convex(l_shape) is False assert is_strictly_convex([Point(0, 0), Point(2, 0), Point(1, 0)]) is False # -- convex hull: hand instances --------------------------------------------------------- def test_hull_square_with_centre_and_two_edge_points(): """The square instance must have exactly 4 vertices, 2 boundary points and 1 interior point.""" hull = convex_hull(SQUARE_EXTRA) assert hull.vertices == (Point(0, 0), Point(4, 0), Point(4, 4), Point(0, 4)) assert hull.boundary == (Point(2, 0), Point(3, 4)) assert hull.interior == (Point(2, 2),) assert hull.area2 == 32 assert hull.n == 7 assert hull.verify() is True assert hull.classify(Point(2, 0)) == "boundary" assert hull.classify(Point(2, 2)) == "interior" assert hull.classify(Point(4, 4)) == "vertex" assert hull.classify(Point(9, 9)) == "outside" assert hull.side_sign(Point(9, 9)) == -1 def test_hull_triangle_with_point_outside_one_edge(): """A point outside one edge must become a vertex and swallow the opposite corner.""" hull = convex_hull(TRI_OUT) assert hull.vertices == (Point(0, 0), Point(6, -1), Point(0, 4)) assert hull.boundary == () assert hull.interior == (Point(4, 0),) assert hull.area2 == 24 assert hull.verify() is True assert hull.classify(Point(4, 0)) == "interior" assert hull.side_sign(Point(10, 10)) == -1 assert hull.classify(Point(10, 10)) == "outside" def test_parabola_hull_matches_the_brute_force_criterion(): """For 12 points on y = x^2 the brute-force vertex criterion, not a guess, fixes the answer.""" expected = set(brute_force_vertices(PARABOLA12)) hull = convex_hull(PARABOLA12) assert set(hull.vertices) == expected assert expected == set(PARABOLA12) # a strictly convex curve puts every point in a corner assert len(hull.vertices) == 12 assert hull.boundary == () assert hull.interior == () assert hull.verify() is True assert hull.area2 > 0 # -- convex hull: random instances and invariants ---------------------------------------- def test_random_hulls_verify_and_match_brute_force_vertices(): """Every random hull must verify and have exactly the brute-force extremal vertices.""" rng = random.Random(536) for _ in range(60): pts = random_point_set(rng) hull = convex_hull(pts) assert hull.verify() is True assert set(hull.vertices) == set(brute_force_vertices(pts)) distinct = set(pts) assert len(hull.boundary) + len(hull.interior) == len(distinct) - len(hull.vertices) assert hull.n == len(pts) for p in hull.boundary: assert any(orientation(u, v, p) == 0 and (p - u).dot(v - p) > 0 for u, v in hull.edges()) for p in hull.interior: assert point_in_convex_polygon(p, hull.vertices) == "interior" for p in hull.vertices: assert hull.classify(p) == "vertex" assert hull.area2 > 0 assert polygon_area2(hull.vertices) == hull.area2 def test_hull_is_idempotent_and_deterministic(): """The hull of the vertices must be the same hull and a shuffled input must give the same tuple.""" for pts in (SQUARE_EXTRA, TRI_OUT, PARABOLA12): hull = convex_hull(pts) assert convex_hull(list(hull.vertices)).vertices == hull.vertices rng = random.Random(17) reference = convex_hull(SQUARE_EXTRA).vertices for _ in range(5): shuffled = list(SQUARE_EXTRA) rng.shuffle(shuffled) assert convex_hull(shuffled).vertices == reference def test_monotone_chain_orientation_area_and_fan_triangulation(): """The chain must turn strictly left everywhere and its shoelace and fan sums must equal area2.""" rng = random.Random(4) instances = [SQUARE_EXTRA, TRI_OUT, PARABOLA12, random_point_set(rng), random_point_set(rng)] for pts in instances: hull = convex_hull(pts) verts = hull.vertices m = len(verts) for i in range(m): assert orientation(verts[i], verts[(i + 1) % m], verts[(i + 2) % m]) == 1 assert polygon_area2(verts) == hull.area2 fan = sum(polygon_area2([verts[0], verts[i], verts[i + 1]]) for i in range(1, m - 1)) assert fan == hull.area2 def test_point_in_convex_polygon_agrees_with_classify(): """The orientation-only classifier must reproduce hull.classify on inputs and on probes.""" rng = random.Random(616) instances = [SQUARE_EXTRA, TRI_OUT, random_point_set(rng), random_point_set(rng)] for pts in instances: hull = convex_hull(pts) for p in set(pts): assert point_in_convex_polygon(p, hull.vertices) == hull.classify(p) for _ in range(20): probe = rnd_point(rng, lo=-9, hi=9) assert point_in_convex_polygon(probe, hull.vertices) == hull.classify(probe) # -- negative controls -------------------------------------------------------------------- def test_wrong_hull_is_refuted_by_verify_and_side_sign(): """A chain that skips one corner of the square must fail verify and report the corner outside.""" hull = convex_hull(SQUARE_EXTRA) wrong_chain = (Point(0, 0), Point(4, 0), Point(0, 4)) wrong = ConvexHull(wrong_chain, hull.boundary, hull.interior, hull.area2, hull.n, hull.input_points) assert wrong.verify() is False assert wrong.side_sign(Point(4, 4)) == -1 assert wrong.classify(Point(4, 4)) == "outside" assert polygon_area2(wrong_chain) != hull.area2 assert hull.verify() is True def test_wrong_incircle_answer_is_refuted_by_the_circumcircle_cross_check(): """A flipped in-circle sign cannot survive the comparison with the circumcircle route.""" a, b, c, d = Point(0, 0), Point(4, 0), Point(0, 4), Point(1, 1) circle = circle_through_three_points(a, b, c).circle power = d.dist2(circle.center) - circle.r2 # negative power means strictly inside truth = -sgn(power) answer = incircle_test(a, b, c, d) assert answer == truth == 1 flipped = -answer assert flipped != truth assert flipped == sgn(power) # the wrong answer is what a wrong sign convention gives # -- rejections ----------------------------------------------------------------------------- def test_predicates_reject_float_bool_and_degenerate_input(): """Floats and booleans must raise TypeError, small or collinear inputs the documented error.""" with pytest.raises(TypeError): orientation((0.5, 0), (1, 0), (0, 1)) with pytest.raises(TypeError): incircle_test((0, 0), (1, 0), (0, 1), (True, 0)) with pytest.raises(TypeError): Point(1.0, 2.0) with pytest.raises(TypeError): Point(True, 1) with pytest.raises(TypeError): convex_hull([(F(1, 4), 0), (1, 0), (0, 1), (0.25, 1)]) with pytest.raises(DegenerateConfigurationError, match="a convex hull needs three non-collinear points"): convex_hull([Point(0, 0), Point(1, 1)]) with pytest.raises(DegenerateConfigurationError, match="a convex hull needs three non-collinear points"): convex_hull([Point(0, 0), Point(1, 1), Point(2, 2), Point(5, 5)])