PureOne's picture
Publish ELYSIAEN complete research dataset release
973efa6 verified
Raw History Blame Contribute Delete
24.2 kB
#!/usr/bin/env python3
"""ELYSIAEN final: endpoint-safe local attenuation from one frozen Green capsule.
Standalone: no earlier ELYSIAEN files are imported. Requires Python 3.10+,
numpy, scipy and matplotlib. Run `python v4_engine.py`; `--quick` reduces the
randomized suite. This is a CPU finite-model correctness experiment, not an
optical-device, commercial-game-engine, energy or frame-rate benchmark.
Models: T_D = D_full T0 D_full, 0 <= D_full <= I diagonal; and the more
general fixed-interface local block [[B, Lin*T_ZR], [T_RZ*Rout, T_RR]].
These update a declared finite state basis. Scene-to-transport compilation,
new reflective surfaces and new scattering directions are not demonstrated.
"""
from __future__ import annotations
import os
# Keep this small reproducible experiment from oversubscribing BLAS threads.
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
import argparse
import json
import platform
from pathlib import Path
import numpy as np
import scipy
from scipy.linalg import solve
SEED = 20261025
def frozen_capsule(green, indices):
"""Compile a return matrix and harmonic lift using k coordinate columns.
All acquisition/storage below is explicit numerical array access here.
An optical device would have to acquire and validate these responses.
"""
z = np.asarray(indices, dtype=int)
columns = green[:, z]
principal = columns[z]
inverse = solve(principal, np.eye(len(z)))
lift = columns @ inverse
return {"indices": z, "inverse": inverse, "return": np.eye(len(z))-inverse,
"lift": lift, "principal": principal}
def capsule_response(capsule, source, reference_response, attenuation):
"""Exact T_D response; finite at all-transparent and all-opaque endpoints.
S=I-K^-1, L=G[:,Z]K^-1; u is the actual state on the edited coordinates.
(I-D S D)u=(I-D)b_Z + D K^-1 q_Z.
x=q + L(Du-q_Z) + E(I-D)u.
No inverse attenuation or infinite penalty is formed.
"""
z = capsule["indices"]
d = np.asarray(attenuation, dtype=float)
if d.shape != (len(z),) or np.any(d < 0) or np.any(d > 1):
raise ValueError("attenuation must have k entries in [0,1]")
small = np.eye(len(z)) - d[:, None]*capsule["return"]*d[None, :]
rhs = (1-d[:, None])*source[z] + d[:, None]*(capsule["inverse"]@reference_response[z])
boundary = solve(small, rhs)
answer = reference_response + capsule["lift"]@(d[:, None]*boundary-reference_response[z])
answer[z] += (1-d[:, None])*boundary
return answer, boundary, small
def material_response(capsule, t0, source, reference_response, local, incoming, outgoing):
"""Compile arbitrary admitted local nonnegative mixing behind the same Z.
Reordered as Z,R, the edited transport is
[[local, incoming*T_ZR], [T_RZ*outgoing, T_RR]].
The entire nonlocal return is cached: J=T_ZR*(I-T_RR)^-1*T_RZ.
Stability must be checked for C=local+incoming*J*outgoing.
"""
z = capsule["indices"]
external_return = capsule["return"]-t0[np.ix_(z, z)]
lift = capsule["lift"].copy()
lift[z] -= np.eye(len(z))
forcing = capsule["inverse"]@reference_response[z]-source[z]
reduced_return = local+incoming@external_return@outgoing
small = np.eye(len(z))-reduced_return
boundary = solve(small, source[z]+incoming@forcing)
answer = reference_response+lift@(outgoing@boundary-reference_response[z])
answer[z] = boundary
return answer, reduced_return, small
def weighted_infinity(matrix, row_weight, column_weight=None):
if column_weight is None:
column_weight = row_weight
return float(np.max(np.sum(np.abs(matrix)*column_weight[None, :], axis=1)/row_weight))
def world_index(x, y):
return (x//10)*100 + y*10 + x%10
def tile_world():
adjacency = np.zeros((200, 200))
for y in range(10):
for x in range(20):
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
xx, yy = x+dx, y+dy
if not (0 <= xx < 20 and 0 <= yy < 10):
continue
if (x < 10) != (xx < 10) and y not in (3, 4, 5, 6):
continue
adjacency[world_index(x, y), world_index(xx, yy)] = 1
return .72*adjacency/4
def obstacle(pose):
x, y = pose
return np.asarray([world_index(xx, yy) for yy in range(y, y+3)
for xx in range(x, x+2)], dtype=int)
def sources_for_pose(indices):
base = np.full((200, 3), .004)
for x, y, rgb in [(2, 2, [1.6, .25, .04]), (3, 2, [1.6, .25, .04]),
(16, 7, [.04, .85, 1.7]), (16, 8, [.04, .85, 1.7])]:
base[world_index(x, y)] += rgb
warm = base*np.asarray([.37, 1.2, .65])
local = base.copy()
local[world_index(8, 1)] += [.18, .4, .23]
energized = base.copy()
energized[indices] += (1+np.arange(len(indices))[:, None]/10)*np.asarray([.29, .31, .37])
return np.concatenate([base, warm, local, energized], axis=1)
def scene_suite():
t0 = tile_world()
green = solve(np.eye(200)-t0, np.eye(200))
rng = np.random.default_rng(SEED)
patterns = [("opaque", np.zeros(6)), ("transparent", np.ones(6)),
("uniform_020", np.full(6, .2)), ("uniform_060", np.full(6, .6)),
("mixed_endpoints", np.asarray([0, .25, .5, .75, 1., 0.])),
("random_interior", rng.uniform(.05, .95, 6))]
cache = set()
records = []
selected = None
max_error = 0.
max_condition = 0.
for pose in [(x, 4) for x in range(5, 17)]:
z = obstacle(pose)
misses = [int(j) for j in z if int(j) not in cache]
cache.update(map(int, z))
capsule = frozen_capsule(green, z)
source = sources_for_pose(z)
reference = green@source
min_lift = float(np.min(capsule["lift"]))
lift_norm = weighted_infinity(capsule["lift"], np.ones(200), np.ones(6))
return_norm = weighted_infinity(capsule["return"], np.ones(6))
assert min_lift >= -1e-12 and lift_norm <= 1+1e-12 and return_norm <= .72+1e-12
for name, d in patterns:
full_d = np.ones(200)
full_d[z] = d
actual_t = full_d[:, None]*t0*full_d[None, :]
truth = solve(np.eye(200)-actual_t, source)
answer, boundary, small = capsule_response(capsule, source, reference, d)
error = float(np.max(np.abs(answer-truth)))
condition = float(np.linalg.cond(small, np.inf))
assert error < 2e-11
assert condition <= (1+.72)/(1-.72)+1e-11
assert np.max(np.abs(answer[z]-boundary)) < 1e-12
max_error = max(max_error, error)
max_condition = max(max_condition, condition)
record = {"pose": list(pose), "attenuation_pattern": name,
"attenuation": d.tolist(), "coordinate_ports": 6,
"RGB_source_families": 4, "scalar_source_RHS": 12,
"max_abs_RGB_coefficient_error": error,
"small_system_condition_infinity": condition,
"lift_weighted_infinity_norm": lift_norm,
"return_weighted_infinity_norm": return_norm,
"new_coordinate_columns_at_pose": len(misses) if name == "opaque" else 0,
"new_value_dependent_columns": 0,
"local_output_coordinates": 6}
records.append(record)
if pose == (9, 4) and name == "mixed_endpoints":
selected = {"pose": pose, "attenuation": d, "reference": reference[:, 9:12],
"truth": truth[:, 9:12], "answer": answer[:, 9:12]}
return {"transport_states": 200, "reference_rho": .72, "poses": 12,
"attenuation_patterns_per_pose": 6, "RGB_source_families": 4,
"RGB_world_states_checked": len(records)*4,
"scalar_RHS_checked": len(records)*12,
"maximum_absolute_RGB_error": max_error,
"maximum_small_system_condition_infinity": max_condition,
"uniform_small_system_condition_bound": (1+.72)/(1-.72),
"response_work": {"unique_coordinate_columns": len(cache),
"coordinate_columns_in_current_capsule": 6,
"warm_attenuation_changes_requiring_new_coordinate_columns": 0,
"value_dependent_columns": 0,
"source_queries_per_pose_scalar_RHS": 12,
"source_queries_total_scalar_RHS": 12*12,
"source_queries_reused_across_attenuation_patterns": True,
"full_RGB_coefficients_reconstructed_per_world_state": 200*3,
"prototype_reference_storage_coefficients": 200*200,
"prototype_computes_full_reference_inverse": True,
"prototype_reassembles_capsule_from_dense_reference_each_pose": True,
"scope": "Logical cache/acquisition counters, not optical measurements. Columns, source projection, small solves, calibration, and full output have costs."},
"records": records}, selected
def material_suite():
"""Changing local scatter/routing matrices with a fixed six-port capsule."""
t0 = tile_world()
green = solve(np.eye(200)-t0, np.eye(200))
rng = np.random.default_rng(SEED+3)
records = []
selected = None
for pose in [(x, 4) for x in range(5, 17)]:
z = obstacle(pose)
r = np.asarray([j for j in range(200) if j not in set(z)], dtype=int)
capsule = frozen_capsule(green, z)
source = sources_for_pose(z)
q = green@source
p = np.roll(np.eye(6), 1, axis=0)
h = np.eye(6)[::-1]
random_mix = []
for _ in range(3):
m = rng.uniform(.1, 1, (6, 6))
random_mix.append(m/m.sum(axis=1)[:, None])
configs = [("reference", t0[np.ix_(z, z)], np.eye(6), np.eye(6)),
("noncommuting_routes", .04*np.eye(6)+.08*p, .7*p+.1*np.eye(6), .6*h+.2*np.eye(6)),
("dense_local_mixing", .15*random_mix[0], .8*random_mix[1], .9*random_mix[2])]
for name, local, incoming, outgoing in configs:
edited = t0.copy()
edited[np.ix_(z, z)] = local
edited[np.ix_(z, r)] = incoming@t0[np.ix_(z, r)]
edited[np.ix_(r, z)] = t0[np.ix_(r, z)]@outgoing
truth = solve(np.eye(200)-edited, source)
answer, reduced, small = material_response(capsule, t0, source, q, local, incoming, outgoing)
actual_rho = float(np.max(np.abs(np.linalg.eigvals(edited))))
reduced_rho = float(np.max(np.abs(np.linalg.eigvals(reduced))))
error = float(np.max(np.abs(answer-truth)))
assert error < 2e-11 and actual_rho < 1 and reduced_rho < 1
assert np.all(edited >= 0) and np.min(reduced) >= -1e-12
records.append({"pose": list(pose), "configuration": name,
"coordinate_ports": 6, "RGB_source_families": 4,
"local_matrix_commutator_norm": float(np.linalg.norm(local@incoming-incoming@local, ord=np.inf)),
"incoming_outgoing_commutator_norm": float(np.linalg.norm(incoming@outgoing-outgoing@incoming, ord=np.inf)),
"full_transport_spectral_radius": actual_rho,
"small_return_spectral_radius": reduced_rho,
"small_system_condition_infinity": float(np.linalg.cond(small, np.inf)),
"maximum_RGB_coefficient_error": error,
"new_coordinate_columns_after_capsule_acquisition": 0,
"new_value_dependent_columns": 0})
if pose == (9, 4) and name == "dense_local_mixing":
selected = {"pose": pose, "attenuation": None, "reference": q[:, 9:12],
"truth": truth[:, 9:12], "answer": answer[:, 9:12]}
return {"poses": 12, "local_configurations_per_pose": 3,
"RGB_source_families": 4, "RGB_world_states_checked": len(records)*4,
"maximum_absolute_RGB_error": max(a["maximum_RGB_coefficient_error"] for a in records),
"scope": "Local internal B and incoming/outgoing mixing L,R vary behind a fixed six-coordinate interface; existing exterior transport remains fixed. Physical scene-to-matrix compilation is not demonstrated.",
"records": records}, selected
def randomized_suite(count):
rng = np.random.default_rng(SEED+1)
rows = []
for trial in range(count):
n = (16, 32, 64)[trial % 3]
rho = (.2, .7, .95, .999)[trial % 4]
weight = np.exp(rng.uniform(-1.3, 1.3, n))
base = rng.uniform(0, 1, (n, n))
base *= rng.uniform(size=(n, n)) < .3
base += np.eye(n)*.2
base *= rho/base.sum(axis=1)[:, None]
t0 = weight[:, None]*base/weight[None, :]
green = solve(np.eye(n)-t0, np.eye(n))
k = int(rng.integers(1, min(12, n)+1))
z = rng.choice(n, k, replace=False)
capsule = frozen_capsule(green, z)
d = rng.uniform(0, 1, k)
d[::3] = 0.
d[1::4] = 1.
source = rng.uniform(0, 1, (n, 3))*weight[:, None]
reference = green@source
full_d = np.ones(n)
full_d[z] = d
truth = solve(np.eye(n)-full_d[:, None]*t0*full_d[None, :], source)
answer, boundary, small = capsule_response(capsule, source, reference, d)
error = float(np.max(np.abs(answer-truth)/weight[:, None]))
relative_error = error/float(np.max(np.abs(truth)/weight[:, None]))
lift_norm = weighted_infinity(capsule["lift"], weight, weight[z])
return_norm = weighted_infinity(capsule["return"], weight[z])
condition = weighted_infinity(small, weight[z])*weighted_infinity(solve(small, np.eye(k)), weight[z])
min_lift = float(np.min(capsule["lift"]))
min_return = float(np.min(capsule["return"]))
assert min_lift >= -2e-10 and min_return >= -2e-10
assert error < 2e-9 and lift_norm <= 1+2e-10 and return_norm <= rho+2e-10
assert condition <= (1+rho)/(1-rho)+2e-8
# Opaque occupancy: a residual at the coordinates has a harmonic lift
# with gain <=1. Check this independently of source response accuracy.
qz = reference[z]
theta = solve(capsule["principal"], qz)
perturbation = rng.normal(size=(k, 3))*weight[z, None]*1e-5
candidate = theta+perturbation
residual = capsule["principal"]@candidate-qz
exact_opaque = reference-capsule["lift"]@qz
exact_opaque[z] += source[z]
approximate = reference-green[:, z]@candidate
approximate[z] += source[z]
actual = float(np.max(np.abs(approximate-exact_opaque)/weight[:, None]))
bound = float(np.max(np.abs(residual)/weight[z, None]))
assert actual <= bound+2e-10
rows.append({"n": n, "k": k, "rho": rho,
"weighted_absolute_response_error": error,
"relative_weighted_response_error": relative_error,
"minimum_lift_entry": min_lift, "minimum_return_entry": min_return,
"lift_weighted_infinity_norm": lift_norm,
"return_weighted_infinity_norm": return_norm,
"small_system_weighted_condition": condition,
"small_system_condition_bound": (1+rho)/(1-rho),
"occupancy_residual_error": actual, "occupancy_residual_certificate": bound})
return {"cases": count, "response_failures": 0, "passivity_failures": 0,
"occupancy_residual_certificate_violations": 0,
"occupancy_residual_check_absolute_tolerance": 2e-10,
"maximum_positive_floating_point_certificate_excess": max(0., max(r["occupancy_residual_error"]-r["occupancy_residual_certificate"] for r in rows)),
"certificate_check_scope": "Double-precision checks within the declared tolerance; the theorem is exact but these numerical evaluations are not outward-rounded certificates.",
"maximum_weighted_response_error": max(r["weighted_absolute_response_error"] for r in rows),
"maximum_relative_weighted_response_error": max(r["relative_weighted_response_error"] for r in rows),
"maximum_lift_weighted_norm": max(r["lift_weighted_infinity_norm"] for r in rows),
"maximum_residual_error_to_bound": max(r["occupancy_residual_error"]/r["occupancy_residual_certificate"] for r in rows),
"records": rows}
def endpoint_controls():
# A one-state near-conservative world disproves a rho-independent bound
# for residuals of the partial-attenuation boundary equation itself.
values = []
for rho in (.9, .99, .999, .9999):
gain = 1/(1-rho)
values.append({"rho": rho, "transparent_boundary_residual_gain": gain,
"occupancy_harmonic_lift_residual_gain": 1.})
# Incorrectly treating a partial mask as a binary opaque obstacle fails.
t0 = np.asarray([[0, .6], [.6, 0]])
b = np.asarray([[1.], [.2]])
green = solve(np.eye(2)-t0, np.eye(2))
capsule = frozen_capsule(green, [0])
q = green@b
good, _, _ = capsule_response(capsule, b, q, [.5])
binary, _, _ = capsule_response(capsule, b, q, [0.])
return {"near_conservative_boundary_residual_control": values,
"partial_mask_misclassified_as_opaque_maximum_error": float(np.max(np.abs(good-binary))),
"source_convention": "An opaque isolated coordinate retains its local numerical source x_Z=b_Z. Mask b_Z to zero when the physical renderer requires a dark occupied coordinate."}
def stability_suite(count):
rng = np.random.default_rng(SEED+4)
cases = []
for trial in range(count):
n, k = 24, 5
t0 = rng.uniform(.1, 1, (n, n))
t0 *= .6/t0.sum(axis=1)[:, None]
green = solve(np.eye(n)-t0, np.eye(n))
z = rng.choice(n, k, replace=False)
r = np.asarray([i for i in range(n) if i not in set(z)])
capsule = frozen_capsule(green, z)
m = rng.uniform(0, 1, (k, k)); m /= m.sum(axis=1)[:, None]
h = rng.uniform(0, 1, (k, k)); h /= h.sum(axis=1)[:, None]
incoming = .8*m
outgoing = .8*h
if trial % 2:
local = 1.05*np.eye(k)+.01*m
else:
local = .1*m
edited = t0.copy()
edited[np.ix_(z, z)] = local
edited[np.ix_(z, r)] = incoming@t0[np.ix_(z, r)]
edited[np.ix_(r, z)] = t0[np.ix_(r, z)]@outgoing
reduced = local+incoming@(capsule["return"]-t0[np.ix_(z, z)])@outgoing
full_rho = float(np.max(np.abs(np.linalg.eigvals(edited))))
small_rho = float(np.max(np.abs(np.linalg.eigvals(reduced))))
assert (full_rho < 1) == (small_rho < 1)
cases.append({"full_transport_spectral_radius": full_rho,
"reduced_return_spectral_radius": small_rho,
"stable": bool(full_rho < 1)})
return {"cases": count, "stable_cases": sum(r["stable"] for r in cases),
"unstable_cases": sum(not r["stable"] for r in cases),
"classification_discrepancies": 0,
"scope": "Only the threshold relation rho(T')<1 iff rho(C)<1 is asserted. Spectral radii need not be numerically equal.",
"records": cases}
def image(values):
return np.concatenate([values[:100].reshape(10, 10, -1), values[100:].reshape(10, 10, -1)], axis=1)
def render(selected, scenes, materials, randoms, path):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.patches import Rectangle
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9})
fig, axes = plt.subplots(2, 2, figsize=(11.4, 7.2), layout="constrained")
fig.patch.set_facecolor("#f4f7fc")
for ax, key, title in zip(axes.flat[:3], ("reference", "truth", "answer"),
("Frozen reference | energized source in edited region", "Dense local scatter/routing | direct 200-state oracle", "Six-column capsule | local material and route update")):
display = (1-np.exp(-3*np.maximum(image(selected[key]), 0)))**(1/2.2)
ax.imshow(display, interpolation="nearest")
ax.set_title(title, loc="left", color="#1b2846", fontsize=10, pad=10)
x, y = selected["pose"]
ax.add_patch(Rectangle((x-.5, y-.5), 2, 3, fc="none", ec="#d7bdff", lw=1.5))
ax.axvline(9.5, color="#cac0ee", ls="--", lw=.7)
ax.set_xticks([]); ax.set_yticks([])
ax = axes.flat[3]
error = np.max(np.abs(selected["truth"]-selected["answer"]), axis=1)
im = ax.imshow(image(np.maximum(error, 1e-18)[:, None])[:, :, 0], cmap="magma",
norm=LogNorm(1e-18, 1e-12), interpolation="nearest")
ax.set_title(f"Absolute RGB coefficient error | max {error.max():.2e}", loc="left", color="#1b2846", fontsize=10, pad=10)
ax.set_xticks([]); ax.set_yticks([])
fig.colorbar(im, ax=ax, fraction=.035, pad=.025, label="Maximum RGB coefficient error")
for ax in axes.flat:
for spine in ax.spines.values(): spine.set_visible(False)
fig.suptitle("ELYSIAEN final | one frozen capsule, changing local worlds", x=.01, ha="left", fontsize=15, weight="bold", color="#182441")
fig.supxlabel(f"{scenes['RGB_world_states_checked']} attenuation + {materials['RGB_world_states_checked']} material RGB states; {randoms['cases']} weighted tests. CPU correctness only; acquisition and output have costs.", fontsize=9, color="#596680")
fig.savefig(path, dpi=190)
plt.close(fig)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--quick", action="store_true", help="Run 24 rather than 180 randomized cases")
parser.add_argument("--output-prefix", default="v4_engine")
args = parser.parse_args()
prefix = Path(args.output_prefix)
prefix.parent.mkdir(parents=True, exist_ok=True)
scenes, selected = scene_suite()
materials, selected_material = material_suite()
randoms = randomized_suite(24 if args.quick else 180)
stability = stability_suite(20 if args.quick else 120)
result = {"title": "Lh//?∞ — ELYSIÆN — The Noctilucent Algebra of Self-Evolving Worlds",
"edition": "Final standalone research experiment", "seed": SEED,
"model": "T_D=D_full*T0*D_full with diagonal D in [0,1]; and fixed-interface local block [[B,Lin*T_ZR],[T_RZ*Rout,T_RR]]; unchanged finite state basis",
"software": {"Python": platform.python_version(), "NumPy": np.__version__, "SciPy": scipy.__version__},
"scene_suite": scenes, "material_suite": materials,
"randomized_suite": randoms, "stability_suite": stability,
"negative_and_endpoint_controls": endpoint_controls(),
"scope": "Exact finite transport identities and CPU checks. No optical hardware, game-engine deployment, timing, energy, historical-priority or T9 validation."}
render(selected_material, scenes, materials, randoms, prefix.with_suffix(".png"))
result_path = Path(str(prefix)+"_results.json")
result_path.write_text(json.dumps(result, indent=2)+"\n", encoding="utf-8")
print(json.dumps({"results": str(result_path), "figure": str(prefix.with_suffix('.png')),
"RGB_world_states_checked": scenes["RGB_world_states_checked"],
"maximum_absolute_RGB_error": scenes["maximum_absolute_RGB_error"],
"material_RGB_states_checked": materials["RGB_world_states_checked"],
"maximum_material_RGB_error": materials["maximum_absolute_RGB_error"],
"stability_classifications": stability["cases"],
"randomized_cases": randoms["cases"],
"maximum_weighted_response_error": randoms["maximum_weighted_response_error"],
"unique_coordinate_columns": scenes["response_work"]["unique_coordinate_columns"]}, indent=2))
if __name__ == "__main__":
main()