File size: 14,388 Bytes
973efa6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
"""ELYSIAEN: a standalone headless local-scattering capsule API.

Only NumPy and SciPy are required.  No earlier ELYSIAEN file is imported.
Compilation may inspect the full reference world; evaluate() has only six
small retained arrays and performs no global query.  A separately assembled
full sparse solve is used solely as the verification oracle in main().
This script makes no photonic timing, hardware, or energy claim.
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Mapping
import argparse
import json
import platform
import numpy as np
import scipy
from scipy import sparse
from scipy.sparse.linalg import splu, spsolve


@dataclass(frozen=True)
class Capsule:
    """The complete retained model: six owning arrays and scalar metadata.

    No full-world state, source, observation, coordinate set, inverse, sparse
    factorization, callback, or external reference is retained.
    """
    Cext: np.ndarray  # k by k: T_ZR (I-T_RR)^-1 T_RZ
    g: np.ndarray     # k by s: T_ZR (I-T_RR)^-1 W_R
    Y: np.ndarray     # m by s: O_R (I-T_RR)^-1 W_R
    M: np.ndarray     # m by k: O_R (I-T_RR)^-1 T_RZ
    WZ: np.ndarray    # k by s: W_Z
    OZ: np.ndarray    # m by k: O_Z
    metadata: Mapping[str, object]


def _own(a):
    result = np.array(a, dtype=float, order="C", copy=True)
    result.setflags(write=False)
    assert result.base is None and result.flags.owndata
    return result


def compile_capsule(T0, Z, sourcebasis, obs):
    """Compile a fixed source family b=W xi and fixed output map y=O x.

    T0 must be nonnegative with a stable exterior principal block.  For the
    declared nonnegative transport family, checking a strict full reference
    contraction is a simple sufficient compilation admission condition.  A
    production uncertainty contract must conservatively enclose these data.
    No positivity clipping or approximation is performed here.
    """
    t = sparse.csc_matrix(T0, dtype=float)
    n = t.shape[0]
    zz = np.asarray(Z, dtype=int)
    if t.shape != (n, n) or len(zz) == 0 or len(np.unique(zz)) != len(zz):
        raise ValueError("Expected a square reference and nonempty unique Z")
    if min(zz) < 0 or max(zz) >= n:
        raise ValueError("Z is outside the reference coordinates")
    if np.min(t.data, initial=0.) < 0:
        raise ValueError("The reference must be nonnegative")
    W = np.asarray(sourcebasis, dtype=float)
    O = np.asarray(obs, dtype=float)
    if W.ndim != 2 or W.shape[0] != n or O.ndim != 2 or O.shape[1] != n:
        raise ValueError("Source and output families have incompatible shapes")
    rr = np.setdiff1d(np.arange(n), zz)
    tzr = t[zz, :][:, rr]
    trz = t[rr, :][:, zz]
    trr = t[rr, :][:, rr]
    if len(rr):
        factor = splu(sparse.eye(len(rr), format="csc")-trr)
        # Solve all compilation right hand sides together, once.  factor,
        # exterior arrays and the full input matrices die when this returns.
        response_with_witness = factor.solve(np.column_stack((trz.toarray(), W[rr, :], np.ones(len(rr)))))
        vext = response_with_witness[:, -1]
        if not np.all(np.isfinite(vext)) or np.any(vext <= 0):
            raise ValueError("The nonnegative exterior failed its positive stability witness")
        # For a nonnegative exterior, a positive v with (I-T_RR)v=1
        # is an exact mathematical stability witness.  Here its residual is
        # checked numerically, with the ordinary-float scope stated above.
        witness_residual = (sparse.eye(len(rr), format="csc")-trr) @ vext-np.ones(len(rr))
        if np.max(abs(witness_residual)) > 1e-8:
            raise ValueError("The exterior stability witness residual is too large")
        response = response_with_witness[:, :-1]
        lift = response[:, :len(zz)]
        background = response[:, len(zz):]
        cext = tzr @ lift
        incoming = tzr @ background
        ybg = O[:, rr] @ background
        outlift = O[:, rr] @ lift
    else:
        cext = np.zeros((len(zz), len(zz)))
        incoming = np.zeros((len(zz), W.shape[1]))
        ybg = np.zeros((O.shape[0], W.shape[1]))
        outlift = np.zeros((O.shape[0], len(zz)))
    arrays = [_own(a) for a in (cext, incoming, ybg, outlift, W[zz, :], O[:, zz])]
    metadata = {"reference_dimension": n, "ports": len(zz),
                "source_basis_dimension": W.shape[1], "outputs": O.shape[0],
                "retained_array_bytes": sum(a.nbytes for a in arrays),
                "retained_global_arrays": 0, "fresh_global_queries_per_evaluation": 0,
                "exterior_stability_diagnostic": "positive resolvent witness",
                "contract": "b=sourcebasis@xi; fixed source and observation families"}
    return Capsule(*arrays, metadata)


def evaluate(capsule, B, L, R, xi, *, witness=None, eta=None):
    """Return (protected output, local state) using only retained arrays.

    The nonnegative closure C=B+L Cext R must satisfy rho(C)<1.  Passing a
    positive witness and eta validates C v<=eta v in ordinary floating point;
    without one the spectral-radius check is a diagnostic admission test.
    This is a finite numerical API, not an outward-rounded hard certificate.
    """
    k = capsule.Cext.shape[0]
    B, L, R, xi = (np.asarray(a, dtype=float) for a in (B, L, R, xi))
    if any(a.shape != (k, k) for a in (B, L, R)):
        raise ValueError("B, L, R must be k by k")
    if xi.shape != (capsule.WZ.shape[1],):
        raise ValueError("xi is outside the declared source coordinate dimension")
    if any(np.min(a, initial=0.) < 0 for a in (B, L, R)):
        raise ValueError("Local scattering maps must be nonnegative")
    C = B+L @ capsule.Cext @ R
    if witness is not None:
        v = np.asarray(witness, dtype=float)
        if v.shape != (k,) or min(v) <= 0 or eta is None or not (0 <= eta < 1):
            raise ValueError("Expected a positive local witness and 0<=eta<1")
        if np.any(C @ v > eta*v+1e-12*np.maximum(1., abs(v))):
            raise ValueError("Local positive stability witness failed")
    elif float(np.max(abs(np.linalg.eigvals(C)))) >= 1:
        raise ValueError("Local closure is unstable")
    f = capsule.WZ @ xi+L @ (capsule.g @ xi)
    z = np.linalg.solve(np.eye(k)-C, f)
    y = capsule.Y @ xi+capsule.OZ @ z+capsule.M @ (R @ z)
    return y, z


def _world(n, k, s, m, rng):
    """A sparse positive reference with a fixed six-state editable patch."""
    rows, cols, vals = [], [], []
    for i in range(n):
        for offset, value in ((-1,.30),(1,.30),(-3,.08),(3,.08)):
            rows.append(i); cols.append((i+offset) % n); vals.append(value)
    t0 = sparse.csc_matrix((vals, (rows, cols)), shape=(n, n))
    zz = np.arange(2, 2+k)
    # The fixed source family is deliberately small and positive.  The API
    # is exact only for this span, however many configurations are evaluated.
    W = np.zeros((n, s))
    for j in range(s):
        for i in ((j*11+1) % n, (j*17+13) % n):
            W[i, j] += rng.uniform(.2, 1.)
    O = np.zeros((m, n))
    for j in range(m):
        O[j, (j*19+4) % n] = 1.
        O[j, (j*23+12) % n] += .2
    return t0, zz, W, O


def _local_maps(k, cext, rng, frame):
    # Includes positive noncommuting mixers and arbitrary local B additions.
    L = rng.uniform(.0, 1., (k, k))
    R = rng.uniform(.0, 1., (k, k))
    L *= rng.uniform(.3, 1., (k, 1))/L.sum(axis=1, keepdims=True)
    R *= rng.uniform(.3, 1., (k, 1))/R.sum(axis=1, keepdims=True)
    B = rng.uniform(.0, 1., (k, k))
    B *= rng.uniform(.1, .4, (k, 1))/B.sum(axis=1, keepdims=True)
    C = B+L @ cext @ R
    scale = np.minimum(1., .82/C.sum(axis=1))
    B *= scale[:, None]; L *= scale[:, None]
    if frame % 25 == 0:
        B[:] = L[:] = R[:] = 0.  # Fully opaque endpoint with local emitters.
    return B, L, R


def _oracle(t0, zz, W, O, B, L, R, xi):
    """Independent global assembly and solve; never called by evaluate()."""
    n = t0.shape[0]
    rr = np.setdiff1d(np.arange(n), zz)
    # Permute to [Z, exterior] so sparse block assembly is simple and explicit.
    edited = sparse.bmat([[sparse.csc_matrix(B), L @ t0[zz, :][:, rr]],
                           [t0[rr, :][:, zz] @ R, t0[rr, :][:, rr]]], format="csc")
    order = np.concatenate((zz, rr))
    xperm = spsolve(sparse.eye(n, format="csc")-edited, (W @ xi)[order])
    return O[:, order] @ xperm, xperm[:len(zz)]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--quick", action="store_true", help="Run 12 frames per size instead of 100")
    parser.add_argument("--output", default="v4_compiled_results.json")
    args = parser.parse_args()
    rng = np.random.default_rng(2026102541)
    frames = 12 if args.quick else 100
    k, m, s = 6, 4, 5
    records = []
    max_y, max_z, max_noncommute = 0., 0., 0.
    bytes_values = []
    for n in (64, 128, 256, 512):
        t0, zz, W, O = _world(n, k, s, m, rng)
        capsule = compile_capsule(t0, zz, W, O)
        assert set(capsule.__dict__) == {"Cext","g","Y","M","WZ","OZ","metadata"}
        arrays = [capsule.Cext,capsule.g,capsule.Y,capsule.M,capsule.WZ,capsule.OZ]
        assert [a.shape for a in arrays] == [(k,k),(k,s),(m,s),(m,k),(k,s),(m,k)]
        assert all(a.base is None and a.flags.owndata and not a.flags.writeable for a in arrays)
        assert all(not isinstance(v, np.ndarray) for v in capsule.metadata.values())
        array_bytes = sum(a.nbytes for a in arrays)
        bytes_values.append(array_bytes)
        this_y, this_z = 0., 0.
        for frame in range(frames):
            B, L, R = _local_maps(k, capsule.Cext, rng, frame)
            xi = rng.uniform(.0, 1., s)
            y, z = evaluate(capsule, B, L, R, xi, witness=np.ones(k), eta=.82)
            yo, zo = _oracle(t0, zz, W, O, B, L, R, xi)
            ey, ez = float(max(abs(y-yo))), float(max(abs(z-zo)))
            assert ey < 1e-11 and ez < 1e-11
            this_y, this_z = max(this_y, ey), max(this_z, ez)
            max_noncommute = max(max_noncommute, float(max(abs((L @ R-R @ L).ravel()))))
        max_y, max_z = max(max_y, this_y), max(max_z, this_z)
        records.append({"reference_dimension":n,"frames":frames,"ports":k,
                        "source_basis_dimension":s,"protected_outputs":m,
                        "retained_six_array_bytes":array_bytes,
                        "retained_full_world_arrays":0,"fresh_global_queries_in_evaluate":0,
                        "max_output_error":this_y,"max_local_state_error":this_z})
    assert len(set(bytes_values)) == 1 and bytes_values[0] == 1312

    # Source-span negative control: a missing independent emitter cannot be
    # represented by changing xi.  This is outside evaluate()'s contract.
    n = 64
    t0, zz, W, O = _world(n, k, s, m, rng)
    capsule = compile_capsule(t0, zz, W, O)
    B, L, R = _local_maps(k, capsule.Cext, rng, 1)
    xi = rng.uniform(.2, 1., s)
    y, _ = evaluate(capsule, B, L, R, xi)
    # Choose a protected observed exterior coordinate absent from source span.
    source_index = 35
    extra = np.zeros(n); extra[source_index] = 1.
    span_residual = float(np.linalg.norm(extra-W @ np.linalg.lstsq(W,extra,rcond=None)[0]))
    assert span_residual > .9
    W_aug = np.column_stack((W,extra))
    outside_source_y, _ = _oracle(t0,zz,W_aug,O,B,L,R,np.r_[xi,1.])
    stale_source_error = float(max(abs(outside_source_y-y)))
    assert stale_source_error > .01
    recomp_source = compile_capsule(t0,zz,W_aug,O)
    repaired_source_y, _ = evaluate(recomp_source,B,L,R,np.r_[xi,1.])
    source_recompile_error = float(max(abs(repaired_source_y-outside_source_y)))
    assert source_recompile_error < 1e-11

    # A new observation also requires its compiled projections.  Reusing y
    # from the old protected map produces a visible negative control.
    O_new = O.copy()
    O_new[0,:] = 0.; O_new[0,13] = 1.
    new_view_y, _ = _oracle(t0,zz,W,O_new,B,L,R,xi)
    stale_view_error = float(max(abs(new_view_y-y)))
    assert stale_view_error > 1e-3
    new_view_cap = compile_capsule(t0,zz,W,O_new)
    repaired_view_y, _ = evaluate(new_view_cap,B,L,R,xi)
    view_recompile_error = float(max(abs(repaired_view_y-new_view_y)))
    assert view_recompile_error < 1e-11

    # Nonnegative but unstable local closure must be rejected before solving.
    rejection = False
    try:
        evaluate(capsule,1.1*np.eye(k),np.zeros((k,k)),np.zeros((k,k)),xi)
    except ValueError:
        rejection = True
    assert rejection
    exterior_rejected = False
    try:
        compile_capsule(1.1*sparse.eye(n, format="csc"),zz,W,O)
    except ValueError:
        exterior_rejected = True
    assert exterior_rejected
    summary = {"project":"ELYSIAEN standalone compiled local capsule",
               "date":"2026-10-25","status":"All assertions passed","seed":2026102541,
               "python":platform.python_version(),"numpy":np.__version__,"scipy":scipy.__version__,
               "sizes":[64,128,256,512],"total_frames":4*frames,
               "maximum_output_error":max_y,"maximum_local_state_error":max_z,
               "retained_array_bytes_at_every_size":bytes_values[0],
               "retained_array_shapes":[[k,k],[k,s],[m,s],[m,k],[k,s],[m,k]],
               "retained_global_state_arrays":0,"fresh_global_queries_in_evaluate":0,
               "maximum_noncommutation_LR":max_noncommute,
               "outside_source_span_residual":span_residual,
               "stale_source_family_error":stale_source_error,
               "source_recompilation_error":source_recompile_error,
               "stale_observation_error":stale_view_error,
               "observation_recompilation_error":view_recompile_error,
               "unstable_local_closure_rejected":rejection,
               "unstable_exterior_reference_rejected":exterior_rejected,
               "scope":"Exact finite source/view families; compilation includes full-world work. Zero evaluation queries is a code property, not a measured optical advantage.",
               "records":records}
    Path(args.output).write_text(json.dumps(summary,indent=2)+"\n")
    print(json.dumps(summary,indent=2))


if __name__ == "__main__":
    try:
        from threadpoolctl import threadpool_limits
    except ImportError:
        main()
    else:
        with threadpool_limits(limits=1):
            main()