File size: 6,084 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""Exact component/length frontier for interior uniform-angle audits.

For n>=3 sampled normals k*pi/n, candidates are compact rectifiable subsets
of the closed unit disk with at most K connected components. The optimum is
    (2*n - min(K,n)) * 2*sin(pi/(2*n)).

Proof dependency: the classical Steiner minimum tree theorem for regular
N-gons, N>=6, due to Jarnik--Koessler and Du--Hwang--Weng (1987), DOI
10.1007/BF02187871. Its minimum network length is (N-1) times the side length.
The numerical verification accompanying this module does NOT prove that
classical theorem or search all Steiner topologies.

Every sampled tangent forces its unit-circle contact vertex into an interior
candidate. Connecting its terminal-meeting components by at most K-1 polygon
sides gives the Steiner lower bound (2n-K)*d. The projection lower bound n*d
also applies. Deleting min(K,n) edges of one parity attains their maximum.

This is the sampled-angle INTERIOR problem, not unrestricted full opacity.
"""

from __future__ import annotations

import math
import numpy as np

PI = math.pi
STEINER_DEPENDENCY = {
    "authors": ["D. Z. Du", "F. K. Hwang", "J. F. Weng"],
    "title": "Steiner minimal trees for regular polygons",
    "journal": "Discrete & Computational Geometry",
    "year": 1987, "volume": 2, "pages": "65-84",
    "doi": "10.1007/BF02187871",
    "primary_url": "https://doi.org/10.1007/BF02187871",
    "used_statement": "For a regular N-gon with N>=6, a Steiner minimum tree is the polygon with one edge removed.",
    "numerically_proved_here": False,
}


def _validate(n, components=1):
    if isinstance(n, bool) or int(n) != n or n < 3:
        raise ValueError("n must be an integer at least three")
    if isinstance(components, bool) or int(components) != components or components < 1:
        raise ValueError("Component budget must be a positive integer")
    return int(n), int(components)


def side_length(n):
    n, _ = _validate(n)
    return 2 * math.sin(PI / (2 * n))


def frontier_length(n, components):
    n, components = _validate(n, components)
    return (2 * n - min(components, n)) * side_length(n)


def frontier_lower_bounds(n, components):
    n, components = _validate(n, components)
    d = side_length(n)
    return {"projection_bound": n * d,
            "component_steiner_bound": (2 * n - components) * d,
            "combined_bound": max(n * d, (2 * n - components) * d),
            "steiner_connected_terminal_bound": (2 * n - 1) * d}


def regular_vertices(n):
    n, _ = _validate(n)
    theta = np.arange(2 * n) * PI / n
    return np.column_stack((np.cos(theta), np.sin(theta)))


def construction(n, components, offset=1):
    """Delete q=min(K,n) same-parity edges, starting at a cyclic offset."""
    n, components = _validate(n, components)
    offset = int(offset) % (2 * n)
    q = min(components, n)
    vertices = regular_vertices(n)
    deleted = (offset + 2 * np.arange(q)) % (2 * n)
    keep = np.ones(2 * n, dtype=bool)
    keep[deleted] = False
    indices = np.flatnonzero(keep)
    segments = np.stack((vertices[indices], vertices[(indices + 1) % (2 * n)]), axis=1)
    return {"segments": segments, "vertices": vertices,
            "retained_edge_indices": indices, "deleted_edge_indices": deleted,
            "realized_components": q, "component_budget": components,
            "length_formula": frontier_length(n, components), "offset": offset}


def graph_component_count(n, retained_edge_indices):
    n, _ = _validate(n)
    parent = list(range(2 * n))

    def root(v):
        while parent[v] != v:
            parent[v] = parent[parent[v]]
            v = parent[v]
        return v

    for edge in retained_edge_indices:
        a, b = int(edge), (int(edge) + 1) % (2 * n)
        ra, rb = root(a), root(b)
        parent[rb] = ra
    return len({root(v) for v in range(2 * n)})


def connected_repair_cost(n):
    """Minimum extra length needed to connect the alternating selected edges.

    Steiner branching cannot improve this cost by the cited regular-polygon
    theorem. Adding every unselected odd edge except one attains it.
    """
    n, _ = _validate(n)
    return (n - 1) * side_length(n)


def penalized_optimum(n, component_penalty):
    """Exact minimum of length + lambda*(actual component count).

    On the frontier the objective is affine in K. The optimizer is the
    alternating construction for lambda<d, a connected path for lambda>d,
    and every K=1,...,n at lambda=d. No continuum/full-opacity assertion is
    made by this finite-audit penalization formula.
    """
    n, _ = _validate(n)
    penalty = float(component_penalty)
    if not math.isfinite(penalty) or penalty < 0:
        raise ValueError("Component penalty must be finite and nonnegative")
    d = side_length(n)
    connected = (2 * n - 1) * d + penalty
    alternating = n * d + n * penalty
    if penalty < d:
        minimizers = [n]
        phase = "n components"
    elif penalty > d:
        minimizers = [1]
        phase = "one component"
    else:
        minimizers = list(range(1, n + 1))
        phase = "all component counts tie"
    return {"value": min(connected, alternating),
            "connected_branch": connected, "alternating_branch": alternating,
            "threshold": d, "penalty": penalty,
            "minimizing_component_counts": minimizers, "phase": phase}


def joint_penalty_limit(c):
    """Limit when lambda_n->0 and n*lambda_n->c>=0: min(2*pi,pi+c)."""
    c = float(c)
    if not math.isfinite(c) or c < 0:
        raise ValueError("The scaled limiting penalty must be finite and nonnegative")
    return min(2 * PI, PI + c)


def repair_segments(n, omitted_odd_edge=1):
    n, _ = _validate(n)
    omitted_odd_edge = int(omitted_odd_edge) % (2 * n)
    if omitted_odd_edge % 2 != 1:
        raise ValueError("The omitted edge must be unselected (odd indexed)")
    vertices = regular_vertices(n)
    indices = np.array([j for j in range(1, 2 * n, 2) if j != omitted_odd_edge])
    return np.stack((vertices[indices], vertices[(indices + 1) % (2 * n)]), axis=1)