File size: 9,805 Bytes
52fc221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""Gauge-aware passive fabrication; all quantities have declared finite scope.

The graph estimator is classical relative-measurement least squares. Its
effective-resistance covariance is prior art. The reserve feasibility,
robust construction, and manufacturing interpretation are derived in the report.
No electrical calibration algorithm certifies its own unmodeled bias.
"""
import itertools
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components, shortest_path


def incidence(nodes, edges):
    edges = np.asarray(edges, int).reshape(-1, 2)
    m = len(edges)
    return coo_matrix((np.tile([-1., 1.], m),
                      (np.repeat(np.arange(m), 2), edges.ravel())),
                     shape=(m, nodes)).tocsr()


def grid_edges(n, dim):
    shape = (n,) * dim
    coords = np.array(list(np.ndindex(shape)), dtype=int)
    index = {tuple(x): i for i, x in enumerate(coords)}
    edges = []
    for i, x in enumerate(coords):
        for axis in range(dim):
            if x[axis] + 1 < n:
                y = x.copy(); y[axis] += 1
                edges.append((i, index[tuple(y)]))
    return coords, np.asarray(edges, int)


def comparison_line_graph(functional_edges):
    """Module comparisons at shared junctions; one extra stable witness.

    The witness is uncalibrated in absolute units. Its numerical coordinate is
    fixed, and its physical response must stay stable throughout an epoch.
    """
    touches = {}
    for i, pair in enumerate(functional_edges):
        for node in pair:
            touches.setdefault(int(node), []).append(i)
    edges = set()
    for neighbours in touches.values():
        edges.update(itertools.combinations(sorted(neighbours), 2))
    count = len(functional_edges)
    edges.add((0, count))
    return count + 1, np.array(sorted(edges), dtype=int)


def edge_colors(nodes, edges):
    """Greedy matching schedule: no module is probed twice in one slot."""
    used = [set() for _ in range(nodes)]
    colors = []
    for a, b in edges:
        color = 0
        while color in used[a] or color in used[b]:
            color += 1
        used[a].add(color); used[b].add(color); colors.append(color)
    return np.asarray(colors, int)


class RelativeEstimator:
    def __init__(self, nodes, edges, reference=None):
        self.nodes = int(nodes)
        self.edges = np.asarray(edges, int)
        self.reference = nodes - 1 if reference is None else int(reference)
        self.B = incidence(nodes, edges)
        self.L = self.B.T @ self.B
        graph = self.L.copy()
        graph.setdiag(0); graph.eliminate_zeros()
        graph.data[:] = 1.
        if connected_components(graph, directed=False, return_labels=False) != 1:
            raise ValueError("The comparison graph is disconnected")
        self.free = np.delete(np.arange(nodes), self.reference)
        self.Bg = self.B[:, self.free]
        self.Lg = (self.Bg.T @ self.Bg).tocsr()
        self.factor = cho_factor(self.Lg.toarray())
        # This dense covariance is for finite numerical validation/compilation.
        self.covariance_unit = cho_solve(self.factor, np.eye(nodes-1))
        self.rho = np.diag(self.covariance_unit).copy()
        self.rho_max = float(self.rho.max())
        self.colors = edge_colors(nodes, edges)
        self.diameter = int(np.max(shortest_path(graph, directed=False,
                                                unweighted=True)))

    def estimate(self, y):
        y = np.asarray(y)
        z = np.zeros(self.nodes)
        rhs = np.asarray(self.Bg.T @ y)
        z[self.free] = cho_solve(self.factor, rhs)
        residual = rhs-self.Lg@z[self.free]
        # Unit-edge inverse entries are <= graph diameter by resistance and
        # Cauchy-Schwarz bounds, so the inverse infinity norm is <= R*diameter.
        # A conservative standard-roundoff allowance covers the sparse row sums
        # and residual evaluation (normal finite arithmetic, no under/overflow).
        degree = int(self.L.diagonal().max())
        machine = np.finfo(float).eps
        gamma = (2*degree+8)*machine/(1-(2*degree+8)*machine)
        arithmetic = gamma*(degree*np.max(np.abs(y)) +
                            2*degree*np.max(np.abs(z))+1.)
        self.last_numerical_bound = float((self.nodes-1)*self.diameter *
                                          (np.max(np.abs(residual))+arithmetic))
        return z

    def radius(self, sigma, samples, horizon, delta):
        return float(sigma * np.sqrt(
            2*self.rho_max*np.log(2*(self.nodes-1)*horizon/delta)/samples))

    def sample_budget(self, sigma, radius, horizon, delta):
        return max(1, int(np.ceil(
            2*sigma*sigma*self.rho_max *
            np.log(2*(self.nodes-1)*horizon/delta)/(radius*radius))))

    def local_estimate(self, y, tolerance=1e-5, max_rounds=200000):
        """Synchronous nearest-neighbour gradient messages, not pinned diffusion.

        Iterates have zero mean. A final reference-value broadcast fixes the
        numerical gauge. The conservative residual bound needs only graph size
        and diameter, not a centrally computed eigenvector.
        A global max of residual magnitudes is implementable by tree reduction.
        The returned round count excludes that reduction/broadcast latency.
        """
        rhs = np.asarray(self.B.T @ y)
        rhs -= rhs.mean()  # eliminate floating point sum residue
        z = np.zeros(self.nodes)
        step = 1/(float(self.L.diagonal().max())+1)
        lower_gap = 2/((self.nodes-1)*self.diameter)
        multiplier = np.sqrt(2*self.nodes)/lower_gap
        for turn in range(max_rounds+1):
            residual = rhs - self.L @ z
            bound = multiplier*np.max(np.abs(residual))
            if bound <= tolerance:
                return z-z[self.reference], {
                    'rounds': turn, 'certified_numerical_radius': float(bound),
                    'residual_max': float(np.max(np.abs(residual)))}
            z += step*residual
            # The sum is invariant mathematically; no global recentering
            # operation is used inside the local iteration.
        raise RuntimeError("Local estimator did not converge within its budget")


def ratio_observation(x, target, edges, common_gain, noise, physical_scale=1.,
                      node_bias=None):
    """Paired log measurements through the SAME gain, after offset removal.

    Independent log-noise of each completed ratio is supplied explicitly.
    Differential node_bias is NOT canceled and is an assumption-violation test.
    """
    u, v = np.asarray(edges).T
    g = physical_scale*np.asarray(target)*np.asarray(x)
    gain = np.broadcast_to(np.asarray(common_gain), len(edges))
    measured_u = gain*g[u]
    measured_v = gain*g[v]
    y = np.log(measured_v/measured_u) - np.log(target[v]/target[u])
    if node_bias is not None:
        bias = np.asarray(node_bias)
        y += bias[v]-bias[u]
    return y + noise


def exact_feasibility(x, capacity, tau):
    x = np.asarray(x, float); c = np.broadcast_to(capacity, x.shape)
    if np.any(x <= 0) or np.any(c < 0) or tau < 0:
        raise ValueError("Positive conductances and nonnegative reserves required")
    lower = float(np.exp(-tau)*x.max())
    upper = float(np.exp(tau)*np.min(x+c))
    feasible = lower <= upper + 1e-14
    final = np.maximum(x, np.exp(-tau)*lower) if feasible else None
    return lower, upper, final


def robust_feasibility(lower_x, upper_x, capacity, tau, seal_log, error_log,
                       increment_max):
    """Sufficient finite-noise/finite-increment certificate, G3."""
    half_band = tau-seal_log-2*error_log
    if half_band <= 0:
        return {'feasible': False, 'reason': 'no_guard_band'}
    a, b = np.exp(-half_band), np.exp(half_band)
    lo = max(float(np.max(upper_x)/b), increment_max/(b-a))
    hi = float(np.min(np.asarray(lower_x)+capacity-increment_max)/a)
    return {'feasible': bool(lo <= hi), 'scale_lower': lo,
            'scale_upper': hi, 'a': float(a), 'b': float(b),
            'reason': 'feasible' if lo <= hi else 'reserve_interval_empty'}


def uniform_reserve_yield(modules, low, high, capacity, tau):
    """Exact G4 iid Uniform[low, high] feasibility probability.

    Stable evaluation of the closed form; no simulation/fitting used here.
    """
    if modules < 1 or high <= low or low <= 0 or capacity < 0 or tau < 0:
        raise ValueError("Invalid finite reserve problem")
    width = high-low
    q = float(np.exp(2*tau))
    critical = max(0., high/q-low)
    if capacity >= critical:
        return 1.
    if modules == 1:
        return 1.
    if abs(q-1) < 1e-12:
        r = capacity/width
        return float(modules*r**(modules-1)-(modules-1)*r**modules)
    s = ((1-1/q)*high+capacity)/width
    t = ((q-1)*low+q*capacity)/width
    log_first = np.log(q)+modules*np.log(s)
    # q*s^R - t^R is positive on the branch in use.
    correction = -np.expm1(modules*np.log(t)-log_first) if t > 0 else 1.
    return float(np.clip(np.exp(log_first)*correction/(q-1), 0, 1))


def projective_response_error(actual, target):
    from contracts import relative_spectrum
    eigenvalues = relative_spectrum(actual, target)
    if np.min(eigenvalues) <= 0:
        return float('inf')
    return float(.5*np.log(eigenvalues.max()/eigenvalues.min()))


def closure_bridge_is_needed(nodes, edges, reference_edge):
    """An unfinished calibration dependency cannot lose its only connection."""
    keep = np.ones(len(edges), bool); keep[reference_edge] = False
    B = incidence(nodes, np.asarray(edges)[keep])
    L = B.T @ B; L.setdiag(0); L.eliminate_zeros()
    return connected_components(L, directed=False, return_labels=False) > 1