"""Exact cross-checks for the classical triangle kernels. Every expectation below is computed again in this file, by code that shares nothing with the kernels beyond the input coordinates: the metric, the doubled area, the line coefficients, the distance from a point to a line as cross squared over the squared side, the projection formula for an altitude foot, a two by two Cramer solve for circumcenters and line intersections, the law of cosines for the angles, and the conjugate rationalization used to divide inside the radical tower. No floating point literal appears anywhere, and no expectation is ever compared up to a tolerance. """ import json import random from fractions import Fraction as F import pytest from geometry.algebra.fields import Ext, ExtError, MAX_INDEPENDENT_PRIMES from geometry.kernels.classical import ( ClassicalError, EulerData, ExtPoint, NinePointCircle, altitude_foot, angle_signed_cosines, angle_squares, angle_sum_is_pi, bisector_foot, contact_points, euler_inequality_data, excenters, exradii2, ext_point_from_json, incenter, inradius2, lemoine_point, nine_point_circle, side_squares, usable_triangle, verify_angle_identity, verify_excenter, verify_incenter, verify_lemoine, ) from geometry.kernels.circumcircle import circle_through_three_points from geometry.kernels.common import ( DegenerateConfigurationError, Point, ) from geometry.kernels.triangle_centers import centroid, orthocenter CORPUS_SIZE = 64 # --------------------------------------------------------------------------- # test-side recomputation: none of it calls a kernel # --------------------------------------------------------------------------- def _own_metric(p, q): """Squared distance between two rational points, from the coordinates.""" return (q.x - p.x) * (q.x - p.x) + (q.y - p.y) * (q.y - p.y) def _own_doubled_area(a, b, c): """Doubled signed area of the triangle, as a rational determinant.""" return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) def _own_sides(a, b, c): """The three side lengths |BC|, |CA|, |AB| as test-side tower elements.""" return (Ext.sqrt(_own_metric(b, c)), Ext.sqrt(_own_metric(c, a)), Ext.sqrt(_own_metric(a, b))) def _own_line(p, q): """Coefficients (u, v, w) of the line through p and q: ux + vy + w = 0.""" u, v = q.y - p.y, p.x - q.x return u, v, -(u * p.x + v * p.y) def _own_line_distance_squared(p, q, x, y): """Squared distance from a tower point to a rational line, cross squared over the squared side, so without ever extracting a root.""" u, v = q.y - p.y, p.x - q.x shifted = Ext.of(u) * x + Ext.of(v) * y + Ext.of(-(u * p.x + v * p.y)) side_square = Ext.of(u * u + v * v) return shifted * shifted * Ext.of(F(1) / side_square.to_fraction()) def _own_tower_quotient(numerator, denominator): """Divide two tower elements by the test-side conjugate product.""" product = Ext.one() for conjugate in denominator.conjugate_flips()[1:]: product = product * conjugate norm = denominator * product return numerator * product * Ext.of(F(1) / norm.to_fraction()) def _own_barycentric(a, b, c, weights): """Barycentric combination of the vertices, with a tower weight system.""" total = weights[0] + weights[1] + weights[2] x = _own_tower_quotient(weights[0] * Ext.of(a.x) + weights[1] * Ext.of(b.x) + weights[2] * Ext.of(c.x), total) y = _own_tower_quotient(weights[0] * Ext.of(a.y) + weights[1] * Ext.of(b.y) + weights[2] * Ext.of(c.y), total) return ExtPoint(x, y) def _own_barycentric_on(first, second, weight_first, weight_second): """Affine combination of two vertices with tower weights, divided by their sum.""" total = weight_first + weight_second x = _own_tower_quotient(weight_first * Ext.of(first.x) + weight_second * Ext.of(second.x), total) y = _own_tower_quotient(weight_first * Ext.of(first.y) + weight_second * Ext.of(second.y), total) return ExtPoint(x, y) def _is_zero_ext(value): """Structural zero test on a tower element, done by equality with zero.""" return value == Ext.zero() def _own_is_interior(p, a, b, c): """Strict interior test by the three edge orientations, decided exactly.""" wanted = 1 if _own_doubled_area(a, b, c) > 0 else -1 for first, second in ((a, b), (b, c), (c, a)): cross = Ext.of(second.x - first.x) * (p.y - Ext.of(first.y)) - Ext.of( second.y - first.y) * (p.x - Ext.of(first.x)) if cross.sign() != wanted: return False return True def _own_cramer(two_rows, right): """Solve a 2x2 rational linear system by Cramer's rule.""" # rows are ((alpha, beta), (gamma, delta)) and right is (r0, r1) (p0, p1), (q0, q1) = two_rows det = p0 * q1 - p1 * q0 if det == 0: raise AssertionError("the test-side linear system is singular") x = (right[0] * q1 - p1 * right[1]) / det y = (p0 * right[1] - right[0] * q0) / det return x, y def _own_norm2(p): """Squared distance of a point from the origin, used by the bisector solve.""" return p.x * p.x + p.y * p.y def _own_circumcenter(a, b, c): """Circumcenter from the equality of the three squared distances.""" first = (2 * (b.x - a.x), 2 * (b.y - a.y)) second = (2 * (c.x - a.x), 2 * (c.y - a.y)) right = (_own_norm2(b) - _own_norm2(a), _own_norm2(c) - _own_norm2(a)) x, y = _own_cramer((first, second), right) return Point(x, y) def _own_line_intersection(p, q, r, s): """Intersection of the lines pq and rs, solved from their coefficients.""" u0, v0, w0 = _own_line(p, q) u1, v1, w1 = _own_line(r, s) x, y = _own_cramer(((u0, v0), (u1, v1)), (-w0, -w1)) return Point(x, y) def _own_projection(vertex, first, second): """Foot of the perpendicular from a vertex to the line through two points.""" ux, uy = second.x - first.x, second.y - first.y parameter = ((vertex.x - first.x) * ux + (vertex.y - first.y) * uy) / (ux * ux + uy * uy) return Point(first.x + parameter * ux, first.y + parameter * uy) def _own_foot_triple(a, b, c): """The three altitude feet, one per vertex, by the projection formula.""" return (_own_projection(a, b, c), _own_projection(b, c, a), _own_projection(c, a, b)) def _own_tower_point(point): """Lift a rational point into the tower without touching a kernel.""" return ExtPoint(Ext.of(point.x), Ext.of(point.y)) def _own_prime_factors(value): """Distinct prime factors of a positive integer, by trial division.""" n, found, divisor = int(value), set(), 2 while divisor * divisor <= n: if n % divisor == 0: found.add(divisor) while n % divisor == 0: n //= divisor divisor += 1 if n > 1: found.add(n) return found def _own_odd_primes(value): """Primes with an odd exponent in a positive rational, so of its root.""" q = value return {p for p in _own_prime_factors(q.numerator * q.denominator)} def _random_point(rng): """A rational point with small integer numerator and a small denominator.""" return Point(F(rng.randint(-9, 9), rng.choice((1, 1, 2, 3))), F(rng.randint(-9, 9), rng.choice((1, 1, 2, 3)))) def _build_corpus(count): """Seeded, nondegenerate rational triangles used by the cross-checks.""" rng = random.Random(2024) triangles = [] while len(triangles) < count: candidate = (_random_point(rng), _random_point(rng), _random_point(rng)) if _own_doubled_area(*candidate) != 0: triangles.append(candidate) return triangles CORPUS = _build_corpus(CORPUS_SIZE) SEVEN_PRIME_TRIANGLE = (Point(0, 0), Point(7, 19), Point(22, 3)) RIGHT_TRIANGLE = (Point(0, 0), Point(4, 0), Point(0, 3)) SKEW_TRIANGLE = (Point(-2, 1), Point(5, 3), Point(1, -4)) # --------------------------------------------------------------------------- # sides, incenter, inradius # --------------------------------------------------------------------------- def test_side_squares_are_the_independent_metric(): """side_squares returns |BC|^2, |CA|^2 and |AB|^2 in that exact order.""" for a, b, c in CORPUS: got = side_squares(a, b, c) assert got == (_own_metric(b, c), _own_metric(c, a), _own_metric(a, b)) assert all(min(side, 1) != 0 for side in got) def test_incenter_satisfies_the_barycentric_identity_and_is_interior(): """The incenter is the mass center of the side lengths and lies strictly inside.""" for a, b, c in CORPUS: side_a, side_b, side_c = _own_sides(a, b, c) point = incenter(a, b, c) total = side_a + side_b + side_c left_x = total * point.x right_x = side_a * Ext.of(a.x) + side_b * Ext.of(b.x) + side_c * Ext.of(c.x) left_y = total * point.y right_y = side_a * Ext.of(a.y) + side_b * Ext.of(b.y) + side_c * Ext.of(c.y) assert left_x == right_x and left_y == right_y assert _own_is_interior(point, a, b, c) assert verify_incenter(a, b, c, point) for a, b, c in CORPUS[:12]: side_a, side_b, side_c = _own_sides(a, b, c) assert incenter(a, b, c) == _own_barycentric(a, b, c, (side_a, side_b, side_c)) def test_incenter_is_equidistant_from_the_three_side_lines(): """The three squared distances from the incenter to the sides are equal.""" for a, b, c in CORPUS: point = incenter(a, b, c) first = _own_line_distance_squared(b, c, point.x, point.y) second = _own_line_distance_squared(c, a, point.x, point.y) third = _own_line_distance_squared(a, b, point.x, point.y) assert first == second == third and first.sign() > 0 def test_inradius2_matches_area_over_perimeter_squared(): """The squared inradius equals the squared doubled area over the squared perimeter.""" for a, b, c in CORPUS: radius2 = inradius2(a, b, c) side_a, side_b, side_c = _own_sides(a, b, c) perimeter = side_a + side_b + side_c doubled = _own_doubled_area(a, b, c) assert Ext.of(doubled * doubled) == radius2 * perimeter * perimeter assert radius2.sign() > 0 point = incenter(a, b, c) assert _own_line_distance_squared(b, c, point.x, point.y) == radius2 def test_excenters_satisfy_signed_barycentrics_and_verify(): """Each excenter carries a signed mass system and passes its own predicate.""" for a, b, c in CORPUS: side_a, side_b, side_c = _own_sides(a, b, c) triples = excenters(a, b, c) systems = ((-side_a, side_b, side_c), (side_a, -side_b, side_c), (side_a, side_b, -side_c)) for index, (point, weights) in enumerate(zip(triples, systems)): total = weights[0] + weights[1] + weights[2] assert total.sign() != 0 left_x = total * point.x right_x = (weights[0] * Ext.of(a.x) + weights[1] * Ext.of(b.x) + weights[2] * Ext.of(c.x)) assert left_x == right_x assert verify_excenter(a, b, c, point, index) assert triples[0] != triples[1] != triples[2] def test_exradii2_match_signed_area_over_signed_sum_squared(): """Each squared exradius times the squared signed side sum gives the area square.""" for a, b, c in CORPUS: side_a, side_b, side_c = _own_sides(a, b, c) doubled = _own_doubled_area(a, b, c) sums = (-side_a + side_b + side_c, side_a - side_b + side_c, side_a + side_b - side_c) values = exradii2(a, b, c) for radius2, total in zip(values, sums): assert radius2.sign() > 0 assert Ext.of(doubled * doubled) == radius2 * total * total # --------------------------------------------------------------------------- # contact points and angle bisectors # --------------------------------------------------------------------------- def test_contact_points_lie_on_sides_and_at_inradius_distance(): """Every contact point sits on its side and one inradius away from the incenter.""" for a, b, c in CORPUS: radius2 = inradius2(a, b, c) point = incenter(a, b, c) assert _own_line_distance_squared(b, c, point.x, point.y) == radius2 ends = ((b, c), (c, a), (a, b)) for contact, (first, second) in zip(contact_points(a, b, c), ends): cross = (Ext.of(second.x - first.x) * (contact.y - Ext.of(first.y)) - Ext.of(second.y - first.y) * (contact.x - Ext.of(first.x))) assert cross == Ext.zero() assert contact.dist2(point) == radius2 def test_contact_point_tangent_lengths_match_semiperimeter(): """The tangent lengths of the contact points are the semiperimeter differences.""" for a, b, c in CORPUS: side_a, side_b, side_c = _own_sides(a, b, c) semiperimeter = (side_a + side_b + side_c) * Ext.of(F(1, 2)) first, second, third = contact_points(a, b, c) assert first.dist2(_own_tower_point(b)) == (semiperimeter - side_b) ** 2 assert first.dist2(_own_tower_point(c)) == (semiperimeter - side_c) ** 2 assert second.dist2(_own_tower_point(c)) == (semiperimeter - side_c) ** 2 assert third.dist2(_own_tower_point(a)) == (semiperimeter - side_a) ** 2 def test_bisector_feet_satisfy_ratio_and_equidistance(): """Each bisector foot divides its side in the ratio of the adjacent sides.""" for a, b, c in CORPUS: side_a, side_b, side_c = _own_sides(a, b, c) ends = ((b, c, side_c, side_b), (c, a, side_a, side_c), (a, b, side_b, side_a)) for label, (first, second, near, away) in zip("ABC", ends): foot = bisector_foot(a, b, c, label) cross = (Ext.of(second.x - first.x) * (foot.y - Ext.of(first.y)) - Ext.of(second.y - first.y) * (foot.x - Ext.of(first.x))) assert cross == Ext.zero() left = away * away * foot.dist2(_own_tower_point(first)) right = near * near * foot.dist2(_own_tower_point(second)) assert left == right for label, (first, second) in zip("ABC", ((b, c), (c, a), (a, b))): foot = bisector_foot(a, b, c, label) vertex = {"A": a, "B": b, "C": c}[label] one = _own_line_distance_squared(vertex, first, foot.x, foot.y) other = _own_line_distance_squared(vertex, second, foot.x, foot.y) assert one == other near, away = {"A": (side_c, side_b), "B": (side_a, side_c), "C": (side_b, side_a)}[label] total = near + away expected = _own_barycentric_on(first, second, away, near) assert expected == foot assert not _is_zero_ext(total) def test_lemoine_point_matches_independent_barycentrics_and_is_interior(): """The Lemoine point is rational and is the mass center of the squared sides.""" for a, b, c in CORPUS: squares = (_own_metric(b, c), _own_metric(c, a), _own_metric(a, b)) total = sum(squares) expected = Point((squares[0] * a.x + squares[1] * b.x + squares[2] * c.x) / total, (squares[0] * a.y + squares[1] * b.y + squares[2] * c.y) / total) got = lemoine_point(a, b, c) assert got == expected assert isinstance(got, Point) assert _own_is_interior(_own_tower_point(got), a, b, c) def test_lemoine_distance_ratios_match_side_squares_and_verify(): """Squared distances from the Lemoine point to the sides follow the side squares.""" for a, b, c in CORPUS: squares = (_own_metric(b, c), _own_metric(c, a), _own_metric(a, b)) point = _own_tower_point(lemoine_point(a, b, c)) distances = (_own_line_distance_squared(b, c, point.x, point.y), _own_line_distance_squared(c, a, point.x, point.y), _own_line_distance_squared(a, b, point.x, point.y)) assert distances[0] * Ext.of(squares[1] * squares[2]) == distances[1] * Ext.of( squares[0] * squares[2]) assert distances[1] * Ext.of(squares[0] * squares[2]) == distances[2] * Ext.of( squares[0] * squares[1]) assert verify_lemoine(a, b, c, lemoine_point(a, b, c)) # --------------------------------------------------------------------------- # altitudes and the nine-point circle # --------------------------------------------------------------------------- def test_altitude_feet_match_independent_projection(): """The altitude feet are the projections and sit on the opposite side lines.""" for a, b, c in CORPUS: expected = _own_foot_triple(a, b, c) for label, foot, want in zip("ABC", (altitude_foot(a, b, c, "A"), altitude_foot(a, b, c, "B"), altitude_foot(a, b, c, "C")), expected): assert foot == want vertex = {"A": a, "B": b, "C": c}[label] opposite = {"A": (b, c), "B": (c, a), "C": (a, b)}[label] u, v, w = _own_line(*opposite) assert u * foot.x + v * foot.y + w == 0 direction = (opposite[1].x - opposite[0].x, opposite[1].y - opposite[0].y) assert (foot.x - vertex.x) * direction[0] + (foot.y - vertex.y) * direction[1] == 0 def test_nine_point_circle_agrees_with_existing_kernels_and_relations(): """The circle matches the circumcircle and orthocenter kernels and the Euler line.""" for a, b, c in CORPUS: circle = nine_point_circle(a, b, c) circum = circle_through_three_points(a, b, c) height = orthocenter(a, b, c) assert circle.circumcenter == circum.center assert circle.circumradius2 == circum.circle.r2 assert circle.orthocenter == height assert circle.center == circum.center.midpoint(height) assert 4 * circle.radius2 == circum.circle.r2 assert circle.center == _own_circumcenter(a, b, c).midpoint(height) assert circle.centroid() == centroid(a, b, c) assert circle.euler_collinearity_holds() assert circle.verify() def test_nine_point_circle_holds_nine_independently_recomputed_points(): """All nine points, recomputed here, lie on the circle at exactly radius2.""" for a, b, c in CORPUS: circle = nine_point_circle(a, b, c) height = _own_line_intersection(a, _own_projection(a, b, c), b, _own_projection(b, c, a)) sides = (b.midpoint(c), c.midpoint(a), a.midpoint(b)) feet = _own_foot_triple(a, b, c) tops = (a.midpoint(height), b.midpoint(height), c.midpoint(height)) expected = sides + feet + tops assert sorted(circle.points(), key=lambda p: (p.x, p.y)) == sorted( expected, key=lambda p: (p.x, p.y)) for point in expected: assert point.dist2(circle.center) == circle.radius2 assert circle.membership_failures() == () assert len(circle.points()) == 9 def test_nine_point_center_is_the_euler_midpoint_of_the_orthocenter(): """The independent altitude intersection reproduces the stored orthocenter.""" for a, b, c in CORPUS: circle = nine_point_circle(a, b, c) first = _own_projection(a, b, c) second = _own_projection(b, c, a) assert _own_line_intersection(a, first, b, second) == circle.orthocenter # The nine point center is the midpoint of the orthocenter and the # circumcenter, so it halves the Euler segment: |N O|^2 = |H O|^2 / 4. assert _own_metric(circle.center, circle.circumcenter) * 4 == _own_metric( circle.orthocenter, circle.circumcenter) # --------------------------------------------------------------------------- # angles and the Euler relation # --------------------------------------------------------------------------- def test_angle_squares_match_independent_law_of_cosines(): """Each squared cosine is the square of the law-of-cosines quotient.""" for a, b, c in CORPUS: squares = (_own_metric(b, c), _own_metric(c, a), _own_metric(a, b)) numerator_a = squares[1] + squares[2] - squares[0] numerator_b = squares[0] + squares[2] - squares[1] numerator_c = squares[0] + squares[1] - squares[2] expected = (numerator_a * numerator_a / (4 * squares[1] * squares[2]), numerator_b * numerator_b / (4 * squares[0] * squares[2]), numerator_c * numerator_c / (4 * squares[0] * squares[1])) assert angle_squares(a, b, c) == expected assert all(0 <= value <= 1 for value in expected) def test_angle_signed_cosines_match_independent_law_of_cosines(): """Each signed cosine squares to its rational value and keeps the law sign.""" for a, b, c in CORPUS: squares = (_own_metric(b, c), _own_metric(c, a), _own_metric(a, b)) numerators = (squares[1] + squares[2] - squares[0], squares[0] + squares[2] - squares[1], squares[0] + squares[1] - squares[2]) denominators = (4 * squares[1] * squares[2], 4 * squares[0] * squares[2], 4 * squares[0] * squares[1]) for cos, numerator, denominator, square in zip(angle_signed_cosines(a, b, c), numerators, denominators, angle_squares(a, b, c)): assert cos * cos == Ext.of(square) assert cos.sign() == (1 if numerator > 0 else (-1 if numerator < 0 else 0)) rebuilt = _own_tower_quotient(Ext.of(abs(numerator)), Ext.sqrt(denominator)) if numerator > 0: assert cos == rebuilt elif numerator < 0: assert cos == -rebuilt else: assert cos == Ext.zero() def test_angle_identity_and_angle_sum_hold_on_every_triangle(): """The cosine identity and the angle-sum addition hold on the whole corpus.""" for a, b, c in CORPUS: assert verify_angle_identity(a, b, c) is True assert angle_sum_is_pi(a, b, c) is True def test_euler_identity_holds_and_oi2_matches_independent_distance(): """Euler's relation holds and OI squared matches the independently built centers.""" for a, b, c in CORPUS: data = euler_inequality_data(a, b, c) assert data.identity_holds() is True assert data.oi2.sign() >= 0 and data.OI2 == data.oi2 assert data.inradius * data.inradius == data.inradius2 assert data.circumcenter == _own_circumcenter(a, b, c) assert Ext.of(data.circumradius2) == Ext.of( _own_metric(_own_circumcenter(a, b, c), a)) side_a, side_b, side_c = _own_sides(a, b, c) own_center = _own_barycentric(a, b, c, (side_a, side_b, side_c)) assert data.oi2 == own_center.dist2(_own_tower_point(_own_circumcenter(a, b, c))) squared = Ext.of(data.circumradius2) - data.oi2 assert squared * squared == Ext.of(4 * data.circumradius2) * data.inradius2 def test_hand_built_equilateral_data_and_rational_corpus(): """No rational triangle is equilateral, while hand-built data of an equilateral is.""" for a, b, c in CORPUS[:24]: data = euler_inequality_data(a, b, c) assert data.is_equilateral() is False hand_built = EulerData(oi2=Ext.zero(), circumradius2=F(4), inradius2=Ext.of(1), inradius=Ext.of(1)) assert hand_built.is_equilateral() is True assert hand_built.identity_holds() is True assert not hasattr(hand_built, "gap2") # --------------------------------------------------------------------------- # usability and the tower budget # --------------------------------------------------------------------------- def test_usable_triangle_accepts_the_corpus(): """Every seeded instance stays inside the declared prime budget of the tower.""" assert MAX_INDEPENDENT_PRIMES == 6 for a, b, c in CORPUS: assert usable_triangle(a, b, c) is True def test_usable_triangle_rejects_the_seven_prime_example(): """The searched example needs seven primes and is reported as unusable.""" a, b, c = SEVEN_PRIME_TRIANGLE squares = side_squares(a, b, c) assert squares == (F(481), F(493), F(410)) needed = set() for square in squares: needed |= _own_odd_primes(square) assert len(needed) == 7 assert usable_triangle(a, b, c) is False assert usable_triangle(Point(0, 0), Point(1, 1), Point(2, 2)) is False def test_tower_refuses_seven_independent_primes(): """The tower itself refuses an element built on seven independent primes.""" element = Ext.one() for prime in (2, 3, 5, 7, 11, 13, 17): element = element * Ext.sqrt(prime) assert element == Ext.monomial(510510) with pytest.raises(ExtError, match="limit of 6 primes"): element.norm() # --------------------------------------------------------------------------- # negative controls # --------------------------------------------------------------------------- def test_wrong_incenter_is_rejected_by_verification(): """A center built from swapped barycentrics fails the predicate and the distances.""" for a, b, c in (RIGHT_TRIANGLE, SKEW_TRIANGLE): assert _own_metric(b, c) != _own_metric(c, a) side_a, side_b, side_c = _own_sides(a, b, c) imposter = _own_barycentric(a, b, c, (side_a, side_c, side_b)) assert imposter != incenter(a, b, c) assert verify_incenter(a, b, c, imposter) is False distances = (_own_line_distance_squared(b, c, imposter.x, imposter.y), _own_line_distance_squared(c, a, imposter.x, imposter.y), _own_line_distance_squared(a, b, imposter.x, imposter.y)) assert not distances[0] == distances[1] == distances[2] assert verify_excenter(a, b, c, incenter(a, b, c), 0) is False def test_shifted_nine_point_center_fails_verification(): """A hand-built circle with a shifted center is refused by the verifier.""" for a, b, c in (RIGHT_TRIANGLE, SKEW_TRIANGLE): circle = nine_point_circle(a, b, c) shifted = NinePointCircle( center=Point(circle.center.x + F(1, 7), circle.center.y), radius2=circle.radius2, side_midpoints=circle.side_midpoints, altitude_feet=circle.altitude_feet, vertex_midpoints=circle.vertex_midpoints, circumcenter=circle.circumcenter, circumradius2=circle.circumradius2, orthocenter=circle.orthocenter, ) assert shifted.verify() is False assert len(shifted.membership_failures()) == 9 assert shifted.center != _own_circumcenter(a, b, c).midpoint(orthocenter(a, b, c)) assert circle.verify() is True def test_centroid_is_not_the_lemoine_point(): """The centroid of a non-equilateral triangle fails the Lemoine predicate.""" for a, b, c in (RIGHT_TRIANGLE, SKEW_TRIANGLE): middle = centroid(a, b, c) assert lemoine_point(a, b, c) != middle assert verify_lemoine(a, b, c, middle) is False assert verify_lemoine(a, b, c, "not a point") is False def test_degenerate_triangles_report_the_doubled_area(): """Every construction refuses a zero-area triangle and quotes the doubled area.""" for triple in ((Point(0, 0), Point(2, 1), Point(4, 2)), (Point(1, 1), Point(1, 1), Point(5, 0))): builders = (side_squares, incenter, excenters, inradius2, exradii2, lemoine_point, contact_points, angle_squares, angle_signed_cosines, angle_sum_is_pi) for builder in builders: with pytest.raises(DegenerateConfigurationError, match="doubled signed area is 0"): builder(*triple) with pytest.raises(DegenerateConfigurationError, match="doubled signed area is 0"): verify_incenter(*triple, ExtPoint(Ext.of(0), Ext.of(0))) with pytest.raises(ClassicalError, match="vertex label must be one of A, B or C"): bisector_foot(*triple[:3], at="D") assert usable_triangle(*triple) is False def test_float_coordinates_are_rejected(): """A float coordinate is refused by the coercion of the rational point type.""" assert isinstance(SKEW_TRIANGLE[0].x, F) with pytest.raises(TypeError, match="exact arithmetic only"): side_squares(Point(0, 0), Point(3, 0), Point(1 / 2, F(9, 5))) with pytest.raises(TypeError, match="exact arithmetic only"): incenter(Point(0, 0), Point(7 / 2, 0), Point(0, 1)) with pytest.raises(TypeError, match="exact arithmetic only"): Point(F(1, 2), 1 / 3) def test_label_and_index_guards_raise(): """The vertex label and the excenter index are checked on every entry point.""" a, b, c = RIGHT_TRIANGLE with pytest.raises(ClassicalError, match="vertex label must be one of A, B or C"): bisector_foot(a, b, c, "D") with pytest.raises(ClassicalError, match="vertex label must be one of A, B or C"): altitude_foot(a, b, c, "d") with pytest.raises(ClassicalError, match="excenter index must be 0, 1 or 2"): verify_excenter(a, b, c, excenters(a, b, c)[0], 3) # --------------------------------------------------------------------------- # exact encodings # --------------------------------------------------------------------------- def test_json_round_trip_survives_text_and_rebuild(): """Every tower point the kernels emit comes back from its JSON text intact.""" seen = 0 for a, b, c in CORPUS[:20]: values = [incenter(a, b, c)] values.extend(excenters(a, b, c)) values.extend(contact_points(a, b, c)) values.append(bisector_foot(a, b, c, "A")) for point in values: text = json.dumps(point.to_json()) assert ext_point_from_json(json.loads(text)) == point seen += 1 data = euler_inequality_data(a, b, c) assert json.loads(json.dumps(data.to_json()))["circumradius2"] == str(data.circumradius2) assert seen == 20 * 8 def test_json_text_of_classical_points_has_no_float(): """The JSON text of a tower point carries rationals as strings, never decimals.""" for a, b, c in CORPUS[:8] + [RIGHT_TRIANGLE, SKEW_TRIANGLE]: for point in (incenter(a, b, c), bisector_foot(a, b, c, "B")): text = json.dumps(point.to_json()) assert "e" not in text and "." not in text stack = [json.loads(text)] while stack: current = stack.pop() assert not isinstance(current, float) if isinstance(current, dict): stack.extend(current.values()) elif isinstance(current, list): stack.extend(current) elif isinstance(current, str): F(current) def test_public_surface_matches_the_frozen_api(): """The exported names of the module are exactly the ones the domain package uses.""" from geometry.kernels import classical expected = {"ExtPoint", "ext_point_from_json", "side_squares", "ClassicalError", "incenter", "excenters", "inradius2", "exradii2", "verify_incenter", "verify_excenter", "bisector_foot", "contact_points", "lemoine_point", "verify_lemoine", "NinePointCircle", "nine_point_circle", "altitude_foot", "angle_squares", "angle_signed_cosines", "verify_angle_identity", "angle_sum_is_pi", "EulerData", "usable_triangle"} assert set(classical.__all__) == expected for name in expected: assert hasattr(classical, name) assert callable(classical.euler_inequality_data) assert "euler_inequality_data" not in classical.__all__ assert ExtPoint(Ext.of(1), Ext.of(2)).plus(ExtPoint(Ext.of(1), Ext.of(1))) == ExtPoint( Ext.of(2), Ext.of(3)) assert ExtPoint(Ext.of(1), Ext.of(2)).minus(ExtPoint(Ext.of(1), Ext.of(1))).dist2( ExtPoint(Ext.zero(), Ext.zero())) == Ext.of(1)