File size: 7,756 Bytes
3b80460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Reproduce independent checks of positional endpoint-distance formulas.

Run: python3 verify_positional.py
Quadrature checks the endpoint formula independently; it is not a proof.
Opaque examples have separate elementary convex-hull proofs stated below.
No sampled line-intersection count is promoted to a rigorous global bound.
"""
from pathlib import Path
import json
import math
import platform
import numpy as np
import scipy
from scipy.integrate import quad
from positional_overlap import pair_overlap,positional_certificate

ROOT=Path(__file__).resolve().parent


def projection_overlap(theta,first,second):
    n=np.array([math.cos(theta),math.sin(theta)])
    u=np.asarray(first,dtype=float)@n
    v=np.asarray(second,dtype=float)@n
    return max(0.,min(float(u.max()),float(v.max()))-
                  max(float(u.min()),float(v.min())))


def independent_quadrature(first,second):
    points=np.vstack([first,second]).astype(float)
    critical=[0.,math.pi]
    for i in range(4):
        for j in range(i+1,4):
            difference=points[j]-points[i]
            if np.linalg.norm(difference)>0:
                critical.append((math.atan2(difference[1],difference[0])+math.pi/2)%math.pi)
    critical=sorted(set(critical))
    values=[]
    errors=[]
    for a,b in zip(critical[:-1],critical[1:]):
        if b-a<=1e-15:
            continue
        v,e=quad(lambda theta:projection_overlap(theta,first,second),a,b,
                 epsabs=1e-12,epsrel=1e-12)
        values.append(v)
        errors.append(e)
    return math.fsum(values),math.fsum(errors)


def checks():
    analytic=[
        ("parallel unit segments, separation 1",[[0,0],[1,0]],[[0,1],[1,1]],2*(math.sqrt(2)-1)),
        ("crossing orthogonal diameters of length 2",[[-1,0],[1,0]],[[0,-1],[0,1]],8-4*math.sqrt(2)),
        ("right-triangle adjacent legs",[[0,0],[1,0]],[[0,0],[0,1]],2-math.sqrt(2)),
        ("collinear shared endpoint",[[0,0],[1,0]],[[1,0],[2,0]],0.),
        ("collinear disjoint segments",[[0,0],[1,0]],[[2,0],[3,0]],0.),
        ("degenerate isolated point",[[0,0],[0,0]],[[1,0],[2,1]],0.)]
    analytic_records=[]
    for label,first,second,expected in analytic:
        actual=pair_overlap(first,second)
        quadrature,error=independent_quadrature(first,second)
        assert abs(actual-expected)<1e-10
        assert abs(actual-quadrature)<1e-10
        analytic_records.append({"case":label,"expected":expected,"endpoint_formula":actual,
                                 "independent_quadrature":quadrature,
                                 "quadrature_reported_error":error})
    rejected=False
    try:
        pair_overlap([[0,0],[2,0]],[[1,0],[3,0]])
    except ValueError:
        rejected=True
    assert rejected

    rng=np.random.default_rng(20261029)
    random_records=[]
    for number in range(100):
        first=rng.uniform(-3,3,size=(2,2))
        second=rng.uniform(-3,3,size=(2,2))
        actual=pair_overlap(first,second)
        quadrature,error=independent_quadrature(first,second)
        symmetry=max(abs(actual-pair_overlap(second,first)),
                     abs(actual-pair_overlap(first[::-1],second)),
                     abs(actual-pair_overlap(first,second[::-1])))
        assert abs(actual-quadrature)<2e-9
        assert symmetry<2e-9
        random_records.append({"index":number,"first":first.tolist(),"second":second.tolist(),
                               "endpoint_formula":actual,"independent_quadrature":quadrature,
                               "absolute_discrepancy":abs(actual-quadrature),
                               "quadrature_reported_error":error,"symmetry_error":symmetry})

    square=[([-1,-1],[1,-1]),([1,-1],[1,1]),([1,1],[-1,1]),([-1,1],[-1,-1])]
    square_record=positional_certificate(square,certified_max_hits=2)
    square_record["independent_geometric_facts"]=(
        "The square boundary surrounds the unit disk, so every line meeting the disk meets the boundary. "
        "A line not containing an edge and not through a vertex meets a convex polygon boundary at most twice; the exceptional lines have zero line measure.")
    root2=math.sqrt(2)
    cross=[([-root2,0],[root2,0]),([0,-root2],[0,root2])]
    cross_record=positional_certificate(cross,certified_max_hits=2)
    cross_record["independent_geometric_facts"]=(
        "The cross is connected. Its convex hull is the diamond |x|+|y|<=sqrt(2), which contains the unit disk. "
        "Every linear projection of a connected set is an interval, so containment of the disk in its convex hull makes it opaque. Two segments give the automatic almost-everywhere hit bound 2.")
    triangle_vertices=np.array([[0.,2.],[-math.sqrt(3),-1.],[math.sqrt(3),-1.]])
    triangle=[(triangle_vertices[i],triangle_vertices[(i+1)%3]) for i in range(3)]
    triangle_record=positional_certificate(triangle,certified_max_hits=2)
    triangle_record["independent_geometric_facts"]=(
        "The equilateral triangle is circumscribed about the unit disk; its boundary is opaque and a generic line hits it at most twice.")
    for record in [square_record,cross_record,triangle_record]:
        assert record["forest_necessary_lower_bound"]<=record["total_segment_length"]+1e-10
        assert record["conditional_pair_necessary_lower_bound"]<=record["total_segment_length"]+1e-10
    assert abs(square_record["pair_energy"]-8)<1e-10
    assert abs(triangle_record["pair_energy"]-6*math.sqrt(3))<1e-10
    assert abs(cross_record["pair_energy"]-(8*math.sqrt(2)-8))<1e-10

    fractional=[]
    for n in [3,4,6,12,24,96,384]:
        half_perimeter=n*math.tan(math.pi/n)
        fractional.append({"circumscribed_regular_polygon_sides":n,
                           "half_density_cost":half_perimeter,
                           "excess_above_pi":half_perimeter-math.pi})
    assert all(fractional[i]["half_density_cost"]>fractional[i+1]["half_density_cost"]
               for i in range(len(fractional)-1))
    assert fractional[-1]["excess_above_pi"]<1e-4
    return {"scope":"Necessary positional certificates, not an opacity decision procedure and not a solution of the minimum opaque-barrier problem.",
            "arithmetic":"Exact formulas evaluated in float64; numerical tests do not replace the analytic proofs.",
            "runtime":{"python":platform.python_version(),"numpy":np.__version__,"scipy":scipy.__version__},
            "summary":{"all_assertions_passed":True,"analytic_cases":len(analytic_records),
                       "random_cases":len(random_records),"positive_collinear_overlap_rejected":rejected,
                       "max_random_quadrature_discrepancy":max(r["absolute_discrepancy"] for r in random_records),
                       "max_random_symmetry_discrepancy":max(r["symmetry_error"] for r in random_records),
                       "actual_opaque_examples":3},
            "analytic_cases":analytic_records,"random_cases":random_records,
            "actual_opaque_examples":{"square_boundary":square_record,"cross":cross_record,"triangle_boundary":triangle_record},
            "fractional_no_go":{"analytic_statement":
                "Half of the unit-circle boundary measure has cost pi and weighted intersection count 1 on every non-tangent line through the disk. Consequently line-count covering constraints allowing fractional density cannot imply a bound strictly greater than pi. For a regular circumscribed N-gon, half boundary density has cost N*tan(pi/N), tending to pi. This is a fractional relaxation, not a physical barrier.",
                "polygon_diagnostics":fractional}}


if __name__=="__main__":
    result=checks()
    (ROOT/"POSITIONAL_VERIFICATION.json").write_text(json.dumps(result,indent=2)+"\n")
    print(json.dumps(result["summary"],indent=2))