#!/usr/bin/env python3 """ Exact Mathematical Verification Suite for The Neon Mirror Room Verifies: 1. Penrose Double-Elliptical Unilluminable Room (zero-leakage theorem across all 5 zones) 2. Coffee-Cup Caustics (Nephroid & Cardioid exact tangent envelopes) + Water Droplet Rainbow Angles 3. Integrable Ellipse Invariant I = d1*d2 & Poncelet Periodic Closure (3-, 4-, 5-, 6-gons) 4. Bunimovich Mushroom Billiard (whispering gallery invariant r_min > w vs chaotic stem entry) """ import math EPS = 1e-11 def dot(a, b): return a[0] * b[0] + a[1] * b[1] def sub(a, b): return (a[0] - b[0], a[1] - b[1]) def add(a, b): return (a[0] + b[0], a[1] + b[1]) def mul(a, s): return (a[0] * s, a[1] * s) def norm(a): return math.hypot(a[0], a[1]) def normalize(a): n = norm(a) return (a[0] / n, a[1] / n) def reflect(d, n): """Reflect unit ray direction d across unit normal n.""" dn = dot(d, n) return normalize((d[0] - 2.0 * dn * n[0], d[1] - 2.0 * dn * n[1])) def intersect_segment(p, d, a, b): """Ray p + t*d (t > EPS) with segment a..b. Returns (t, hit_pt, normal) or None.""" r = d s = sub(b, a) rxs = r[0] * s[1] - r[1] * s[0] if abs(rxs) < 1e-14: return None qmp = sub(a, p) t = (qmp[0] * s[1] - qmp[1] * s[0]) / rxs u = (qmp[0] * r[1] - qmp[1] * r[0]) / rxs if t > 1e-9 and -1e-12 <= u <= 1.0 + 1e-12: hit = (p[0] + t * d[0], p[1] + t * d[1]) # Unit normal pointing against d n = normalize((-s[1], s[0])) if dot(n, d) > 0: n = (-n[0], -n[1]) return (t, hit, n) return None def intersect_half_ellipse(p, d, cx, cy, a, b, upper=True): """Ray p + t*d with upper (y>=cy) or lower (y<=cy) half of ellipse ((x-cx)/a)^2 + ((y-cy)/b)^2 = 1.""" ox, oy = p[0] - cx, p[1] - cy A = (d[0] * d[0]) / (a * a) + (d[1] * d[1]) / (b * b) B = 2.0 * ((ox * d[0]) / (a * a) + (oy * d[1]) / (b * b)) C = (ox * ox) / (a * a) + (oy * oy) / (b * b) - 1.0 disc = B * B - 4.0 * A * C if disc < 0: return None sq = math.sqrt(max(0.0, disc)) best = None for t in ((-B - sq) / (2.0 * A), (-B + sq) / (2.0 * A)): if t > 1e-9: hx = p[0] + t * d[0] hy = p[1] + t * d[1] if (upper and hy >= cy - 1e-9) or ((not upper) and hy <= cy + 1e-9): # Inward normal for interior reflection nx = -(hx - cx) / (a * a) ny = -(hy - cy) / (b * b) n = normalize((nx, ny)) if dot(n, d) > 0: n = (-n[0], -n[1]) if best is None or t < best[0]: best = (t, (hx, hy), n) return best def verify_penrose_room(): print("=" * 72) print("1. PENROSE DOUBLE-ELLIPTICAL UNILLUMINABLE ROOM") print("=" * 72) a = 1.0 b = 0.68 c = math.sqrt(a * a - b * b) h = 0.55 # half-height of central neck (ellipses centered at y = +h and y = -h) gap = 0.08 # gap separating upper and lower pockets around y = 0 # Upper pockets: x in (-a, -c) and (c, a), y in (gap, h) # Lower pockets: x in (-a, -c) and (c, a), y in (-h, -gap) # Central neck: x in (-c, c), y in (-h, h) # Notice: simply connected! Boundary traces one continuous closed loop! segments = [ # Left upper pocket U_L ((-a, h), (-a, gap)), ((-a, gap), (-c, gap)), ((-c, gap), (-c, h)), # vertical divider up to focus (-c, h) # Left wall of central neck (Wait: to be simply connected, the wall goes # from (-c, h) down to (-c, -h)! Wait—if (-c, gap) connects to (-c, h) AND # (-c, h) connects down to (-c, -h), that's a zero-thickness fin! Let's give # the central neck width (-c, c) and put a tiny fin thickness 0 or let's # check: a zero-thickness two-sided mirror fin from (-c, gap) to (-c, h) # makes it a strict slit-polygon! Even better: give the divider wall a small # positive thickness or keep the slit tip EXACTLY at (-c, h) so NO ray leaks!) # Actually, let's place the inner vertical wall of the central neck at x = -c, # and the pocket inner wall at x = -c - eps? NO! If pocket wall is at -c - w, # then the tip at y=h is from -c-w to -c (horizontal cap), which is STILL # strictly outside (-c, c)! Let's check with w = 0.03! ] w = 0.03 # solid mirror peninsula thickness (strictly outside foci x = +-c!) # Trace the exact 16-segment + 2-arc simple closed curve: # Start at (-a, h) -> (-a, gap) -> (-c-w, gap) -> (-c-w, h) -> (-c, h) -> # (-c, -h) -> (-c-w, -h) -> (-c-w, -gap) -> (-a, -gap) -> (-a, -h) # -> lower half-ellipse from (-a, -h) to (a, -h) -> # (a, -h) -> (a, -gap) -> (c+w, -gap) -> (c+w, -h) -> (c, -h) -> # (c, h) -> (c+w, h) -> (c+w, gap) -> (a, gap) -> (a, h) # -> upper half-ellipse from (a, h) to (-a, h)! # WAIT A SECOND! Look at the horizontal step (-c-w, h) -> (-c, h): # It sits at y = h, strictly between -a and -c! # So U_L opening is (-a, -c-w) (strictly OUTSIDE foci!), # Central Neck opening is (-c, c) (EXACTLY BETWEEN foci!)! # No zero-thickness slit, 100% genuine simply-connected room with finite-thickness walls! segments = [ # Left side (top to bottom) ((-a, h), (-a, gap)), ((-a, gap), (-c - w, gap)), ((-c - w, gap), (-c - w, h)), ((-c - w, h), (-c, h)), ((-c, h), (-c, -h)), ((-c, -h), (-c - w, -h)), ((-c - w, -h), (-c - w, -gap)), ((-c - w, -gap), (-a, -gap)), ((-a, -gap), (-a, -h)), # Right side (bottom to top) ((a, -h), (a, -gap)), ((a, -gap), (c + w, -gap)), ((c + w, -gap), (c + w, -h)), ((c + w, -h), (c, -h)), ((c, -h), (c, h)), ((c, h), (c + w, h)), ((c + w, h), (c + w, gap)), ((c + w, gap), (a, gap)), ((a, gap), (a, h)), ] def classify_point(pt): x, y = pt if y > h + 1e-6: return "E_top" if y < -h - 1e-6: return "E_bot" if -c + 1e-6 < x < c - 1e-6 and -h < y < h: return "Neck" if x < -c - w - 1e-6 and y > gap + 1e-6: return "U_L" if x > c + w + 1e-6 and y > gap + 1e-6: return "U_R" if x < -c - w - 1e-6 and y < -gap - 1e-6: return "D_L" if x > c + w + 1e-6 and y < -gap - 1e-6: return "D_R" return "Edge" def trace_ray(start, angle, max_bounces=80): p = start d = (math.cos(angle), math.sin(angle)) visited = {classify_point(p)} for _ in range(max_bounces): best = None for seg in segments: res = intersect_segment(p, d, seg[0], seg[1]) if res is not None and (best is None or res[0] < best[0]): best = res for cy, upper in ((h, True), (-h, False)): res = intersect_half_ellipse(p, d, 0.0, cy, a, b, upper=upper) if res is not None and (best is None or res[0] < best[0]): best = res if best is None: break t, hit, n = best mid = (p[0] + 0.5 * t * d[0], p[1] + 0.5 * t * d[1]) visited.add(classify_point(mid)) visited.add(classify_point(hit)) p = hit d = reflect(d, n) return visited tests = [ ("Upper-Left Pocket U_L", (-0.88, 0.30), {"Neck", "E_bot", "D_L", "D_R"}), ("Upper Dome E_top", (0.15, h + 0.35), {"D_L", "D_R"}), ("Central Neck", (0.12, 0.05), {"U_L", "U_R", "D_L", "D_R"}), ("Lower Dome E_bot", (-0.20, -h - 0.30), {"U_L", "U_R"}), ("Lower-Right Pocket D_R",(0.88, -0.30), {"Neck", "E_top", "U_L", "U_R"}), ] n_rays = 720 n_bounces = 80 all_ok = True for name, src, forbidden in tests: leaked = set() reached = set() for k in range(n_rays): ang = (k + 0.37123) * (2.0 * math.pi / n_rays) vis = trace_ray(src, ang, max_bounces=n_bounces) reached |= vis leaked |= (vis & forbidden) status = "PASS" if not leaked else f"FAIL (leaked into {leaked})" if leaked: all_ok = False print(f" Source {name:24s} ({n_rays} rays x {n_bounces} bounces): " f"reached={sorted(reached - {'Edge'})} | dark={sorted(forbidden)} -> {status}") assert all_ok, "Penrose dark-pocket test failed!" print(f" => Simply-connected 18-segment + 2-ellipse Penrose room (a={a}, b={b}, c={c:.6f}, w={w}) VERIFIED!\n") def verify_coffee_cup_and_rainbow(): print("=" * 72) print("2. COFFEE-CUP CAUSTICS (NEPHROID & CARDIOID) + RAINBOW ANGLES") print("=" * 72) # 2A. Nephroid caustic: parallel horizontal rays coming from x = -inf, hitting right semicircle x^2+y^2=1 # Ray at height y0 = sin(phi), phi in (-pi/2, pi/2), hits P = (cos phi, sin phi). # Inward normal N = (-cos phi, -sin phi), incident d = (1, 0). # Reflected d' = d - 2(d.N)N = (1 - 2 cos^2 phi, -2 cos phi sin phi) = (-cos(2 phi), -sin(2 phi)). # Envelope (Nephroid): x(phi) = 0.75 cos phi - 0.25 cos(3 phi), y(phi) = 0.75 sin phi - 0.25 sin(3 phi) max_neph_err = 0.0 for k in range(1, 180): phi = -math.pi / 2 + k * (math.pi / 180) px, py = math.cos(phi), math.sin(phi) dx, dy = -math.cos(2 * phi), -math.sin(2 * phi) # Exact tangent point on nephroid: nx = 0.75 * math.cos(phi) - 0.25 * math.cos(3 * phi) ny = 0.75 * math.sin(phi) - 0.25 * math.sin(3 * phi) # Distance from (nx, ny) to ray P + t*d: dist = abs((nx - px) * dy - (ny - py) * dx) # Also verify tangency (derivative of nephroid parallel to d): tx = -0.75 * math.sin(phi) + 0.75 * math.sin(3 * phi) ty = 0.75 * math.cos(phi) - 0.75 * math.cos(3 * phi) cross = abs(tx * dy - ty * dx) / max(1e-12, math.hypot(tx, ty)) max_neph_err = max(max_neph_err, dist, cross) print(f" Nephroid caustic envelope max tangency residual (179 rays): {max_neph_err:.3e} -> PASS") assert max_neph_err < 1e-12 # 2B. Cardioid caustic: point light at (-1, 0) on the unit circle rim # Ray leaves (-1, 0) at angle alpha in (-pi/2, pi/2), hits circle at theta = 2*alpha: P = (cos 2a, sin 2a). # Incident d = (cos a, sin a). Inward normal N = (-cos 2a, -sin 2a). # d.N = -cos(a). Reflected d' = (cos a - 2(-cos a)(-cos 2a), sin a - 2(-cos a)(-sin 2a)) # = (-cos(3a), -sin(3a)). # Cardioid envelope: x(a) = (1/3)(2 cos(2a) - cos(4a))? Let's check! # Wait: for P(2a) + t*(-cos 3a, -sin 3a), differentiate wrt a: # (-2 sin 2a, 2 cos 2a) + t*(3 sin 3a, -3 cos 3a) parallel to (-cos 3a, -sin 3a): # Cross with (-cos 3a, -sin 3a) = 0 => 2 sin 2a sin 3a + 2 cos 2a cos 3a - 3t = 0 => 2 cos(a) - 3t = 0 => t = (2/3) cos(a)! # So envelope is: P(2a) + (2/3) cos(a) * (-cos 3a, -sin 3a) # = (cos 2a - (1/3)(cos 4a + cos 2a), sin 2a - (1/3)(sin 4a + sin 2a)) # = ((2 cos 2a - cos 4a)/3, (2 sin 2a - sin 4a)/3) !! max_card_err = 0.0 for k in range(1, 180): a = -math.pi / 2 + k * (math.pi / 180) px, py = math.cos(2 * a), math.sin(2 * a) dx, dy = -math.cos(3 * a), -math.sin(3 * a) cx = (2.0 * math.cos(2 * a) - math.cos(4 * a)) / 3.0 cy = (2.0 * math.sin(2 * a) - math.sin(4 * a)) / 3.0 dist = abs((cx - px) * dy - (cy - py) * dx) tx = (-4.0 * math.sin(2 * a) + 4.0 * math.sin(4 * a)) / 3.0 ty = (4.0 * math.cos(2 * a) - 4.0 * math.cos(4 * a)) / 3.0 cross = abs(tx * dy - ty * dx) / max(1e-12, math.hypot(tx, ty)) max_card_err = max(max_card_err, dist, cross) print(f" Cardioid caustic envelope max tangency residual (179 rays): {max_card_err:.3e} -> PASS") assert max_card_err < 1e-12 # 2C. Descartes Rainbow Angles for Water Droplet (red n=1.331, violet n=1.344) # Primary rainbow (1 internal reflection): D1(i) = 4r - 2i (deviation from antisolar), maximized at cos^2 i = (n^2 - 1)/3 # Secondary rainbow (2 internal reflections): D2(i) = pi - (6r - 2i), minimized at cos^2 i = (n^2 - 1)/8 for label, n in [("Red (656 nm)", 1.3311), ("Yellow (589 nm)", 1.3330), ("Violet (405 nm)", 1.3435)]: cos_i1 = math.sqrt((n * n - 1.0) / 3.0) i1 = math.acos(cos_i1) r1 = math.asin(math.sin(i1) / n) theta1 = math.degrees(4.0 * r1 - 2.0 * i1) cos_i2 = math.sqrt((n * n - 1.0) / 8.0) i2 = math.acos(cos_i2) r2 = math.asin(math.sin(i2) / n) theta2 = math.degrees(math.pi - (6.0 * r2 - 2.0 * i2)) print(f" Water droplet {label:16s} (n={n:.4f}): Primary={theta1:.2f} deg, Secondary={theta2:.2f} deg, Alexander's Dark Band={theta2 - theta1:.2f} deg") print() def verify_ellipse_and_poncelet(): print("=" * 72) print("3. INTEGRABLE ELLIPSE INVARIANT I = d1*d2 & PONCELET PORISM") print("=" * 72) a, b = 1.0, 0.72 c = math.sqrt(a * a - b * b) def focal_invariant(p, d): # I = (x*dy - y*dx)^2 - c^2 * dy^2 return (p[0] * d[1] - p[1] * d[0]) ** 2 - (c * c) * (d[1] * d[1]) def step_ellipse(p, d): ox, oy = p A = (d[0] * d[0]) / (a * a) + (d[1] * d[1]) / (b * b) B = 2.0 * ((ox * d[0]) / (a * a) + (oy * d[1]) / (b * b)) t = -B / A hit = (ox + t * d[0], oy + t * d[1]) n = normalize((-hit[0] / (a * a), -hit[1] / (b * b))) return hit, reflect(d, n) # Check conservation of I over 200 bounces for both elliptic (I>0) and hyperbolic (I<0) orbits max_drift = 0.0 for theta0, launch_ang in [(0.3, 2.3), (1.1, -1.6), (0.0, 1.15)]: p = (a * math.cos(theta0), b * math.sin(theta0)) d = (math.cos(launch_ang), math.sin(launch_ang)) # Ensure pointing inward n_in = normalize((-p[0] / (a * a), -p[1] / (b * b))) if dot(d, n_in) < 0: d = (-d[0], -d[1]) I0 = focal_invariant(p, d) for _ in range(200): p, d = step_ellipse(p, d) max_drift = max(max_drift, abs(focal_invariant(p, d) - I0)) print(f" Focal invariant I = d1*d2 max drift over 200 bounces: {max_drift:.3e} -> PASS") assert max_drift < 1e-11 # Verify exact Poncelet 3-bounce (triangle), 4-bounce (parallelogram), and 5-bounce (pentagon) closure! # For a given confocal ellipse caustic parameter I = b'^2 (0 < b' < b), launch from ANY boundary point # tangent to the inner confocal ellipse (a'^2 = c^2 + I, b'^2 = I). # Find I_n by bisection on winding after n bounces! def tangent_dir_from_boundary(phi, b_caustic): p = (a * math.cos(phi), b * math.sin(phi)) a_c = math.sqrt(c * c + b_caustic * b_caustic) b_c = b_caustic # Polar line of p wrt inner ellipse: (px*x)/a_c^2 + (py*y)/b_c^2 = 1 # Solve intersection of polar line with inner ellipse for tangent point T (CCW choice) ux, uy = p[0] / a_c, p[1] / b_c r2 = ux * ux + uy * uy sq = math.sqrt(max(0.0, r2 - 1.0)) # Tangent point in scaled coords: (u + (-uy, ux)*sq) / r2 tx = a_c * (ux - uy * sq) / r2 ty = b_c * (uy + ux * sq) / r2 return p, normalize((tx - p[0], ty - p[1])) def winding_after_n(b_c, n, phi0=0.0): p, d = tangent_dir_from_boundary(phi0, b_c) total_angle = 0.0 cur_ang = math.atan2(p[1] / b, p[0] / a) for _ in range(n): p, d = step_ellipse(p, d) nxt_ang = math.atan2(p[1] / b, p[0] / a) delta = (nxt_ang - cur_ang) % (2.0 * math.pi) total_angle += delta cur_ang = nxt_ang return total_angle print(" Poncelet Porism exact caustic semi-minor axes b' (for a=1.0, b=0.72):") for n, wind, label in [(3, 1, "Triangle (3,1)"), (4, 1, "Quadrilateral (4,1)"), (5, 1, "Pentagon (5,1)"), (5, 2, "Pentagram Star (5,2)"), (6, 1, "Hexagon (6,1)")]: lo, hi = 1e-4, b - 1e-4 target = 2.0 * math.pi * wind # winding decreases monotonically as b_c increases (bigger caustic => shorter steps) for _ in range(80): mid = 0.5 * (lo + hi) if winding_after_n(mid, n) > target: lo = mid else: hi = mid b_star = 0.5 * (lo + hi) # NOW TEST PONCELET'S PORISM: Does it close from 12 DIFFERENT starting angles phi0?! max_close_err = 0.0 for j in range(12): phi0 = j * 0.517 p0, d0 = tangent_dir_from_boundary(phi0, b_star) p, d = p0, d0 for _ in range(n): p, d = step_ellipse(p, d) max_close_err = max(max_close_err, norm(sub(p, p0))) print(f" {label:20s}: b' = {b_star:.10f}, max closure error across 12 starts = {max_close_err:.3e} -> PASS") assert max_close_err < 1e-10 print() def verify_bunimovich_mushroom(): print("=" * 72) print("4. BUNIMOVICH MUSHROOM BILLIARD (INTEGRABLE CAP + CHAOTIC STEM)") print("=" * 72) R = 1.0 # semicircular cap radius w = 0.45 # half-width of stem (stem x in [-w, w], y in [-h, 0]) h = 0.85 # stem height # Boundary segments: # Left shelf: (-R, 0) -> (-w, 0) # Stem left: (-w, 0) -> (-w, -h) # Stem floor: (-w, -h) -> (w, -h) # Stem right: (w, -h) -> (w, 0) # Right shelf:(w, 0) -> (R, 0) # Plus upper semicircle x^2 + y^2 = R^2, y >= 0 segs = [ ((-R, 0.0), (-w, 0.0)), ((-w, 0.0), (-w, -h)), ((-w, -h), (w, -h)), ((w, -h), (w, 0.0)), ((w, 0.0), (R, 0.0)), ] def trace_mushroom(p0, d0, bounces=500): p, d = p0, normalize(d0) entered_stem = False min_r = 1e9 for _ in range(bounces): best = None for s in segs: res = intersect_segment(p, d, s[0], s[1]) if res is not None and (best is None or res[0] < best[0]): best = res res = intersect_half_ellipse(p, d, 0.0, 0.0, R, R, upper=True) if res is not None and (best is None or res[0] < best[0]): best = res if best is None: break t, hit, n = best # Distance from origin to segment p..hit # Closest point parameter along d: s_closest = max(0.0, min(t, -dot(p, d))) cp = (p[0] + s_closest * d[0], p[1] + s_closest * d[1]) min_r = min(min_r, norm(cp)) if hit[1] < -1e-6 or (p[1] + 0.5 * t * d[1]) < -1e-6: entered_stem = True p, d = hit, reflect(d, n) return entered_stem, min_r # Whispering gallery rays: angular momentum |x*dy - y*dx| > w => NEVER enter stem! for r_target in (0.55, 0.72, 0.88): p0 = (0.0, r_target) d0 = (1.0, 0.0) entered, min_r = trace_mushroom(p0, d0, bounces=500) print(f" Whispering-gallery ray (r_0={r_target:.2f} > w={w:.2f}): entered_stem={entered}, min_r={min_r:.6f} -> {'PASS' if not entered else 'FAIL'}") assert not entered and abs(min_r - r_target) < 1e-9 # Chaotic stem rays: |x*dy - y*dx| < w => enters stem and mixes! for r_target in (0.15, 0.30, 0.40): p0 = (0.0, r_target) d0 = (0.93, 0.3675595) entered, min_r = trace_mushroom(p0, d0, bounces=500) print(f" Chaotic-sea ray (r_0={r_target:.2f} < w={w:.2f}): entered_stem={entered}, min_r={min_r:.6f} -> {'PASS' if entered else 'FAIL'}") assert entered # ============================================================================= # 5. TOKARSKY-CASTRO 24-SIDED POLYGONAL UNILLUMINABLE ROOM (EXACT RATIONAL) # ============================================================================= TOKARSKY_24 = [ (2, -2), (2, -1), (3, -1), (4, 0), (3, 0), (3, 1), (2, 1), (2, 2), (1, 1), (0, 2), (0, 1), (-1, 1), (-2, 2), (-2, 1), (-3, 1), (-3, 0), (-4, 0), (-3, -1), (-2, -1), (-2, -2), (-1, -1), (-1, 0), (1, 0), (1, -1), ] def _vtype(x, y): px, py = x % 2, y % 2 if px == 0 and py == 0: return "A" if px == 1 and py == 1: return "C" return "B" def _point_in_poly_exact(pt, poly): px, py = pt n = len(poly) for i in range(n): ax, ay = poly[i] bx, by = poly[(i + 1) % n] if (bx - ax) * (py - ay) - (by - ay) * (px - ax) == 0: if min(ax, bx) <= px <= max(ax, bx) and min(ay, by) <= py <= max(ay, by): return "boundary" inside = False for i in range(n): ax, ay = poly[i] bx, by = poly[(i + 1) % n] if (ay > py) != (by > py): x_int = ax + (py - ay) * (bx - ax) / (by - ay) if px < x_int: inside = not inside return "interior" if inside else "outside" def _trace_tokarsky_exact(start, direction, target=(2, 0), max_bounces=60): from fractions import Fraction poly_f = [(Fraction(vx), Fraction(vy)) for vx, vy in TOKARSKY_24] n = len(poly_f) x, y = Fraction(start[0]), Fraction(start[1]) dx, dy = Fraction(direction[0]), Fraction(direction[1]) tx, ty = Fraction(target[0]), Fraction(target[1]) t_total = Fraction(0) for b in range(max_bounces + 1): best_t = None best_hits = [] t_target = None if dx != 0: tt = (tx - x) / dx if tt > 0 and y + tt * dy == ty: t_target = tt elif dy != 0: tt = (ty - y) / dy if tt > 0 and x + tt * dx == tx: t_target = tt for i in range(n): ax, ay = poly_f[i] bx, by = poly_f[(i + 1) % n] ex, ey = bx - ax, by - ay denom = dx * ey - dy * ex if denom == 0: for vc in ((ax, ay), (bx, by)): vx, vy = vc t = (vx - x) / dx if dx != 0 else (vy - y) / dy if t > 0 and x + t * dx == vx and y + t * dy == vy: if best_t is None or t < best_t: best_t = t best_hits = [(i, True, vc)] elif t == best_t: best_hits.append((i, True, vc)) continue rx, ry = ax - x, ay - y t = (rx * ey - ry * ex) / denom u = (rx * dy - ry * dx) / denom if t > 0 and 0 <= u <= 1: is_v = u == 0 or u == 1 vc = (ax, ay) if u == 0 else ((bx, by) if u == 1 else None) if best_t is None or t < best_t: best_t = t best_hits = [(i, is_v, vc)] elif t == best_t: best_hits.append((i, is_v, vc)) if t_target is not None and (best_t is None or t_target < best_t): return ("HIT_TARGET", b, (tx, ty), t_total + t_target) if best_t is None: return ("ESCAPED", b, None, t_total) t_total += best_t nx, ny = x + best_t * dx, y + best_t * dy if any(h[1] for h in best_hits): return ("HIT_CORNER", b, (nx, ny), t_total) edge_idx = best_hits[0][0] ax, ay = poly_f[edge_idx] bx, by = poly_f[(edge_idx + 1) % n] nx_v, ny_v = -(by - ay), (bx - ax) dot = dx * nx_v + dy * ny_v nn = nx_v * nx_v + ny_v * ny_v dx = dx - 2 * dot * nx_v / nn dy = dy - 2 * dot * ny_v / nn x, y = nx, ny return ("MAX_BOUNCES", max_bounces, None, t_total) def verify_tokarsky_room(): from collections import defaultdict from fractions import Fraction print("\n" + "=" * 72) print("5. TOKARSKY-CASTRO 24-SIDED POLYGONAL UNILLUMINABLE ROOM (EXACT)") print("=" * 72) poly_f = [(Fraction(x), Fraction(y)) for x, y in TOKARSKY_24] n = len(TOKARSKY_24) assert n == 24, f"Expected 24 sides, got {n}" # Verify CCW signed area = 13.5 (27 right-isosceles triangles of area 0.5) area2 = sum( TOKARSKY_24[i][0] * TOKARSKY_24[(i + 1) % n][1] - TOKARSKY_24[(i + 1) % n][0] * TOKARSKY_24[i][1] for i in range(n) ) assert area2 == 27, f"Expected 2*area = 27, got {area2}" # Collect all (45,45,90) triangles whose centroid lies strictly inside TOKARSKY_24 vert_angle = defaultdict(int) tris = [] for i in range(-4, 4): for j in range(-2, 2): corners = [(i, j), (i + 1, j), (i + 1, j + 1), (i, j + 1)] A = [c for c in corners if _vtype(*c) == "A"][0] C = [c for c in corners if _vtype(*c) == "C"][0] Bs = [c for c in corners if _vtype(*c) == "B"] for B in Bs: cx = Fraction(A[0] + B[0] + C[0], 3) cy = Fraction(A[1] + B[1] + C[1], 3) if _point_in_poly_exact((cx, cy), poly_f) == "interior": tris.append((A, B, C)) for v in (A, B, C): vert_angle[v] += 90 if _vtype(*v) == "B" else 45 assert len(tris) == 27, f"Expected 27 triangles, got {len(tris)}" assert vert_angle[(-2, 0)] == 360 and vert_angle[(2, 0)] == 360, "L and D must be strictly interior" # Tokarsky parity obstruction theorem: zero Type B or C vertices at 180 or 360 deg violations = [ (v, _vtype(*v), ang) for v, ang in vert_angle.items() if _vtype(*v) in ("B", "C") and ang in (180, 360) ] assert not violations, f"Tokarsky parity violations found: {violations}" print(f" Topology & Coxeter Mesh : 24 sides, 27 right-isosceles tris, area=13.5, 0 parity violations -> PASS") # Exact rational raytracing from L=(-2, 0) toward all 168 Type-A unfolded targets (2m, 2n) L = (Fraction(-2), Fraction(0)) tested = 0 absorbed = 0 hits = 0 for m in range(-6, 7): for k in range(-6, 7): tx, ty = 2 * m, 2 * k if (tx, ty) == (-2, 0): continue tested += 1 st, b, corner, t_tot = _trace_tokarsky_exact(L, (tx - (-2), ty - 0), target=(2, 0), max_bounces=60) if st == "HIT_TARGET": hits += 1 elif st == "HIT_CORNER" and t_tot < 1: absorbed += 1 else: raise AssertionError(f"Unexpected ray result toward {(tx, ty)}: {st}, b={b}, t={t_tot}") assert hits == 0 and absorbed == tested == 168 print(f" Exact Rational Sweep L->D* ({tested} Type-A targets): {hits} hits, {absorbed}/{tested} corner-absorbed (t < 1) -> PASS") # Verify razor-edge contrast: slight nudge off L DOES illuminate D=(2, 0) L_nudge = (Fraction(-23, 10), Fraction(-2, 10)) st1, b1, _, _ = _trace_tokarsky_exact(L_nudge, (Fraction(4) - L_nudge[0], Fraction(2) - L_nudge[1]), target=(2, 0)) assert st1 == "HIT_TARGET" and b1 == 2, f"Expected 2-bounce hit from (-2.3,-0.2), got {st1}, {b1}" L_nudge2 = (Fraction(-5, 2), Fraction(-1, 5)) st2, b2, _, _ = _trace_tokarsky_exact(L_nudge2, (Fraction(2) - L_nudge2[0], Fraction(2) - L_nudge2[1]), target=(2, 0)) assert st2 == "HIT_TARGET" and b2 == 1, f"Expected 1-bounce hit, got {st2}, {b2}" print(f" Nudge Contrast (-2.3, -0.2)->D*(4,2): HIT D in {b1} bounces | (-2.5, -0.2)->D*(2, 2): HIT D in {b2} bounce -> PASS") # ============================================================================= # 6. HYPERBOLIC COXETER KALEIDOSCOPE (POINCARE DISK <-> BELTRAMI-KLEIN DISK) # ============================================================================= def _hyp_dist(z1, z2): dx = z1[0] - z2[0] dy = z1[1] - z2[1] d2 = dx * dx + dy * dy n1 = z1[0] * z1[0] + z1[1] * z1[1] n2 = z2[0] * z2[0] + z2[1] * z2[1] val = 1.0 + 2.0 * d2 / ((1.0 - n1) * (1.0 - n2)) return math.acosh(max(1.0, val)) def _poincare_to_klein(z): s = 1.0 + z[0] * z[0] + z[1] * z[1] return (2.0 * z[0] / s, 2.0 * z[1] / s) def _klein_to_poincare(w): w2 = w[0] * w[0] + w[1] * w[1] fac = 1.0 / (1.0 + math.sqrt(max(0.0, 1.0 - w2))) return (w[0] * fac, w[1] * fac) def _build_coxeter_triangle(p, q, r): alpha, beta, gamma = math.pi / p, math.pi / q, math.pi / r assert 1.0 / p + 1.0 / q + 1.0 / r < 1.0 cosh_c = (math.cos(gamma) + math.cos(alpha) * math.cos(beta)) / (math.sin(alpha) * math.sin(beta)) cosh_b = (math.cos(beta) + math.cos(alpha) * math.cos(gamma)) / (math.sin(alpha) * math.sin(gamma)) cosh_a = (math.cos(alpha) + math.cos(beta) * math.cos(gamma)) / (math.sin(beta) * math.sin(gamma)) c_H, b_H, a_H = math.acosh(cosh_c), math.acosh(cosh_b), math.acosh(cosh_a) rB = math.tanh(c_H / 2.0) rC = math.tanh(b_H / 2.0) A = (0.0, 0.0) B = (rB, 0.0) C = (rC * math.cos(alpha), rC * math.sin(alpha)) cx = (rB * rB + 1.0) / (2.0 * rB) cy = ((rC * rC + 1.0) / (2.0 * rC) - cx * math.cos(alpha)) / math.sin(alpha) R = math.sqrt(cx * cx + cy * cy - 1.0) return { "p": p, "q": q, "r": r, "alpha": alpha, "beta": beta, "gamma": gamma, "a_H": a_H, "b_H": b_H, "c_H": c_H, "area": math.pi * (1.0 - 1.0 / p - 1.0 / q - 1.0 / r), "A": A, "B": B, "C": C, "cx": cx, "cy": cy, "R": R, } def _hyp_reflect_wall(z, wall, tri): x, y = z if wall == 0: return (x, -y) elif wall == 1: a = tri["alpha"] ca, sa = math.cos(2.0 * a), math.sin(2.0 * a) return (ca * x + sa * y, sa * x - ca * y) else: dx, dy = x - tri["cx"], y - tri["cy"] k = (tri["R"] * tri["R"]) / (dx * dx + dy * dy) return (tri["cx"] + k * dx, tri["cy"] + k * dy) def _hyp_geodesic_from_dir(S, u): x0, y0 = S ux, uy = u det = x0 * uy - y0 * ux if abs(det) < 1e-11: return ("line", S, u) rhs1 = 0.5 * (x0 * x0 + y0 * y0 + 1.0) rhs2 = x0 * ux + y0 * uy gx = (rhs1 * uy - y0 * rhs2) / det gy = (x0 * rhs2 - rhs1 * ux) / det Rg = math.sqrt(gx * gx + gy * gy - 1.0) orient = 1.0 if ((x0 - gx) * uy - (y0 - gy) * ux) > 0.0 else -1.0 return ("circle", (gx, gy), Rg, orient) def _hyp_next_hit(S, u, tri, ignore_wall=-1): wS = _poincare_to_klein(S) x, y = S denom = 1.0 + x * x + y * y dot_xu = x * u[0] + y * u[1] dw = ( 2.0 * (u[0] * denom - 2.0 * x * dot_xu) / (denom * denom), 2.0 * (u[1] * denom - 2.0 * y * dot_xu) / (denom * denom), ) nrm = math.hypot(dw[0], dw[1]) wu = (dw[0] / nrm, dw[1] / nrm) wA, wB, wC = _poincare_to_klein(tri["A"]), _poincare_to_klein(tri["B"]), _poincare_to_klein(tri["C"]) best_t, best_wall, best_w = 1e18, -1, None for wall_id, P, Q in [(0, wA, wB), (1, wA, wC), (2, wB, wC)]: if wall_id == ignore_wall: continue dx, dy = Q[0] - P[0], Q[1] - P[1] det = wu[0] * dy - wu[1] * dx if abs(det) < 1e-14: continue rx, ry = P[0] - wS[0], P[1] - wS[1] t = (rx * dy - ry * dx) / det s = (rx * wu[1] - ry * wu[0]) / det if t > 1e-11 and -1e-9 <= s <= 1.0 + 1e-9 and t < best_t: best_t, best_wall, best_w = t, wall_id, (wS[0] + t * wu[0], wS[1] + t * wu[1]) P_D = _klein_to_poincare(best_w) geo = _hyp_geodesic_from_dir(S, u) if geo[0] == "line": u_in = u else: _, (gx, gy), Rg, orient = geo u_in = (-orient * (P_D[1] - gy) / Rg, orient * (P_D[0] - gx) / Rg) if best_wall == 0: nM = (0.0, 1.0) elif best_wall == 1: nM = (-math.sin(tri["alpha"]), math.cos(tri["alpha"])) else: nM = ((P_D[0] - tri["cx"]) / tri["R"], (P_D[1] - tri["cy"]) / tri["R"]) dot_un = u_in[0] * nM[0] + u_in[1] * nM[1] u_out = (u_in[0] - 2.0 * dot_un * nM[0], u_in[1] - 2.0 * dot_un * nM[1]) un = math.hypot(u_out[0], u_out[1]) u_out = (u_out[0] / un, u_out[1] / un) return best_wall, P_D, u_in, u_out, nM def verify_hyperbolic_coxeter(): print("\n" + "=" * 72) print("6. HYPERBOLIC COXETER KALEIDOSCOPE (POINCARE <-> BELTRAMI-KLEIN)") print("=" * 72) families = [ ("(2,3,7) Hurwitz", (7, 3, 2), math.pi / 42.0), ("(2,3,8) Bolza", (8, 3, 2), math.pi / 24.0), ("(2,4,5) Pentag", (5, 4, 2), math.pi / 20.0), ("(3,3,4) Octag", (4, 3, 3), math.pi / 12.0), ("(2,5,5) Kite", (5, 5, 2), math.pi / 10.0), ("(4,4,4) Equil", (4, 4, 4), math.pi / 4.0), ] for name, (p, q, r), exact_area in families: tri = _build_coxeter_triangle(p, q, r) assert abs(tri["area"] - exact_area) < 1e-15 side_err = max( abs(_hyp_dist(tri["A"], tri["B"]) - tri["c_H"]), abs(_hyp_dist(tri["A"], tri["C"]) - tri["b_H"]), abs(_hyp_dist(tri["B"], tri["C"]) - tri["a_H"]), ) orth_err = abs(tri["cx"] ** 2 + tri["cy"] ** 2 - tri["R"] ** 2 - 1.0) assert side_err < 1e-12 and orth_err < 1e-12 # Verify exact interior vertex angles at B and C nxB, nyB = (tri["B"][0] - tri["cx"]) / tri["R"], (tri["B"][1] - tri["cy"]) / tri["R"] txB, tyB = -nyB, nxB if tyB < 0: txB, tyB = -txB, -tyB angB = math.acos(max(-1.0, min(1.0, -txB))) nxC, nyC = (tri["C"][0] - tri["cx"]) / tri["R"], (tri["C"][1] - tri["cy"]) / tri["R"] txC, tyC = nyC, -nxC if txC * (tri["B"][0] - tri["C"][0]) + tyC * (tri["B"][1] - tri["C"][1]) < 0: txC, tyC = -txC, -tyC angC = math.acos(max(-1.0, min(1.0, txC * (-math.cos(tri["alpha"])) + tyC * (-math.sin(tri["alpha"]))))) ang_err = max(abs(angB - tri["beta"]), abs(angC - tri["gamma"])) assert ang_err < 1e-12 # Trace 20 bounces & verify conformal reflection, unfolding length conservation, and Klein chord collinearity wA, wB, wC = _poincare_to_klein(tri["A"]), _poincare_to_klein(tri["B"]), _poincare_to_klein(tri["C"]) wS = (0.42 * wA[0] + 0.31 * wB[0] + 0.27 * wC[0], 0.42 * wA[1] + 0.31 * wB[1] + 0.27 * wC[1]) S = _klein_to_poincare(wS) ang0 = 0.61803398875 u0 = (math.cos(ang0), math.sin(ang0)) geo0 = _hyp_geodesic_from_dir(S, u0) cur_P, cur_u, ignore = S, u0, -1 wall_seq = [] total_hyp_len = 0.0 max_len_err = 0.0 max_klein_err = 0.0 max_refl_err = 0.0 for _ in range(20): w_id, P_next, u_in, u_out, nM = _hyp_next_hit(cur_P, cur_u, tri, ignore) inc = abs(u_in[0] * nM[0] + u_in[1] * nM[1]) ref = abs(u_out[0] * nM[0] + u_out[1] * nM[1]) max_refl_err = max(max_refl_err, abs(inc - ref)) total_hyp_len += _hyp_dist(cur_P, P_next) P_unf = P_next for prev_w in reversed(wall_seq): P_unf = _hyp_reflect_wall(P_unf, prev_w, tri) max_len_err = max(max_len_err, abs(_hyp_dist(S, P_unf) - total_hyp_len)) w_unf = _poincare_to_klein(P_unf) if geo0[0] == "circle": _, (gx, gy), _, _ = geo0 k_err = abs(gx * w_unf[0] + gy * w_unf[1] - 1.0) / math.hypot(gx, gy) else: k_err = abs((w_unf[0] - wS[0]) * u0[1] - (w_unf[1] - wS[1]) * u0[0]) max_klein_err = max(max_klein_err, k_err) wall_seq.append(w_id) cur_P, cur_u, ignore = P_next, u_out, w_id assert max_refl_err < 1e-12 assert max_len_err < 1e-11 assert max_klein_err < 1e-12 print( f" {name:16s} area={tri['area']:.6f} | ang_err={ang_err:.2e} | " f"20b_len_drift={max_len_err:.2e} | klein_chord={max_klein_err:.2e} -> PASS" ) if __name__ == "__main__": verify_penrose_room() verify_coffee_cup_and_rainbow() verify_ellipse_and_poncelet() verify_bunimovich_mushroom() verify_tokarsky_room() verify_hyperbolic_coxeter() print("\nALL MATHEMATICAL VERIFICATIONS PASSED TO MACHINE PRECISION!")