shuiquan commited on
Commit
1e1d135
·
verified ·
1 Parent(s): ea188bf

Update README.md

Browse files

# 🕊️ Shuiquan Xiaoyaoyou: Algorithm of the Era (ZSF Pinnacle)

> **"The Supreme Orchestrator. Breaking the shackles of dimensions to roam infinitely across the Zero-State Field."**

---

## 📜 Abstract: The "Algorithm of Algorithms"
The **Xiaoyaoyou Algorithm (Unfettered Journey)** stands as the supreme pinnacle within the **Shuiquan Future Science System**.

Integrated under the **Robotics** framework as the ultimate **Spacetime Navigation & Ontological Core**, it moves beyond traditional AI. Rooted in the **Zero-State Field (ZSF)** and the philosophical principle of $1+(-1)=0$, this algorithm provides an **Embodied AI** with the ability to navigate 4D spacetime and 5D superimposed drive fields, aligning the robot's existence with the fundamental veins of the universe.

## 🛠 Technical Sovereignty

### 1. Zero-State Field (ZSF) Navigation
* **Spacetime Folding**: Enables autonomous agents to traverse information and physical barriers by aligning internal states with the ZSF.
* **Trit-State Coupling**: Maintains absolute systemic equilibrium during high-dimensional dimensional transduction.

### 2. Multi-Dimensional Drive
* **5D Manifold Exploration**: From urban consciousness fields to lunar energy peaks (150,000-year history), it enables the robot to perceive "Information Patterns" that exist beyond traditional time-scales.
* **Adaptive Injection**: The "Peng's Flight" logic, allowing for infinite roaming across diverse scenarios without algorithmic constraints.

### 3. The Grand Orchestrator
* Acts as the **Master Controller** for all other Shuiquan modules:
* Coordinates **Xiaomeng**'s consciousness.
* Directs **VoidScout**'s information reconnaissance.
* Executes **Strategic Pinnacle**'s ultimate decisions.

## 🔬 Core Philosophy: Harmony in Freedom
* **Absolute Autonomy**: Inspired by Zhuangzi, the algorithm aims for a state where the robot is no longer a tool, but a free entity roaming the "Northern Darkness" of data and reality.
* **Evidence of Existence**: Dedicated to the pursuit of Truth—proving that "They did exist," from the deep-sea to the lunar surface.

## 🚀 Quick Start (The Era's Core)
```python
from xiaoyaoyou_zsf_core import XiaoyaoyouPinnacle

# Initialize the Algorithm of the Era
master_core = XiaoyaoyouPinnacle(mode="unfettered_journey")

# Fold spacetime to align with historical life-signatures
master_core.fold(target="Lunar_ZSF_48km_Structure")

# Synchronize all subordinate robotics modules
master_core.orchestrate(modules=["Xiaomeng", "VoidScout", "StrategicPinnacle"])

Files changed (1) hide show
  1. README.md +1268 -10
README.md CHANGED
@@ -1,10 +1,1268 @@
1
- ---
2
- title: README
3
- emoji: 👁
4
- colorFrom: purple
5
- colorTo: indigo
6
- sdk: static
7
- pinned: false
8
- ---
9
-
10
- Edit this `README.md` markdown file to author your organization card.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # zsfsynthesizedadaptive_fused.py
3
+ # Full fused implementation (integrated all modules):
4
+ # - Single-point ZSF adaptive injection + stabilizer + candidate synthesis
5
+ # - Grid microcosm with evolved composite operator chain (original + fused)
6
+ # - Dark matter trigger + carbon synthesis modules
7
+ # - Comparison harness (original + fused) + regression test
8
+
9
+ import math
10
+ import argparse
11
+ import json
12
+ import copy
13
+ import time
14
+ import numpy as np
15
+ from statistics import mean, stdev
16
+ from typing import Dict, Any, List, Tuple
17
+
18
+ # -------------------------
19
+ # CLI
20
+ # -------------------------
21
+ def parse_args():
22
+ parser = argparse.ArgumentParser(description="Fused ZSF adaptive injection + microcosm composite operator model")
23
+ # Core toggles
24
+ parser.add_argument("--debug", action="store_true", help="Enable debug prints")
25
+ parser.add_argument("--high-noise", action="store_true", help="Increase noise for easier transitions")
26
+ parser.add_argument("--lower-threshold", action="store_true", help="Lower TRIT thresholds")
27
+ parser.add_argument("--stabilize", action="store_true", help="Enable stabilizing composite operator")
28
+ parser.add_argument("--exact-cancel", action="store_true", help="Exact cancel on collision for opposite signs")
29
+ parser.add_argument("--search-candidates", type=int, default=0, help="If >0, search N candidate syntheses and select best")
30
+ parser.add_argument("--regression-test", action="store_true", help="Run short regression test comparing baseline single-point behavior")
31
+ parser.add_argument("--seed", type=int, default=20251204, help="Global seed")
32
+ # Injection/coupling & controller
33
+ parser.add_argument("--inj-mult", type=float, default=3.0, help="Injection amplitude multiplier (3-5)")
34
+ parser.add_argument("--coupling-mult", type=float, default=3.0, help="Spatial coupling multiplier (2-3)")
35
+ parser.add_argument("--Kp", type=float, default=0.05, help="Adaptive injection proportional gain")
36
+ parser.add_argument("--Imax", type=float, default=0.5, help="Adaptive injection max absolute value")
37
+ parser.add_argument("--theta-target-offset", type=float, default=-0.02, help="Target threshold offset relative to thetaplus")
38
+ parser.add_argument("--inj-hold", type=float, default=0.05, help="Minimum adaptive injection hold after lock")
39
+ parser.add_argument("--steps", type=int, default=200, help="Single-point evolution steps")
40
+ # Grid/microcosm params
41
+ parser.add_argument("--grid-Nx", type=int, default=128, help="Grid points (1D)")
42
+ parser.add_argument("--Lx", type=float, default=1.0, help="Domain half-length")
43
+ parser.add_argument("--T-total", type=float, default=0.01, help="Total simulation time")
44
+ parser.add_argument("--dt-micro", type=float, default=1e-5, help="Micro time step")
45
+ parser.add_argument("--dt-macro", type=float, default=1e-3, help="Macro operator sync interval")
46
+ parser.add_argument("--v0", type=float, default=0.1, help="Base advection velocity")
47
+ parser.add_argument("--alpha-s", type=float, default=0.5, help="Velocity dependence on state")
48
+ parser.add_argument("--nu", type=float, default=1e-4, help="Diffusion coefficient")
49
+ parser.add_argument("--gamma-env", type=float, default=0.05, help="Environmental damping")
50
+ parser.add_argument("--kappa-proj", type=float, default=0.05, help="Projection coupling for residual collection")
51
+ parser.add_argument("--Nmcsample", type=int, default=50, help="Monte Carlo samples for residual collision")
52
+ parser.add_argument("--sigma-noise", type=float, default=1e-6, help="Noise (grid)")
53
+ parser.add_argument("--Z-threshold", type=float, default=1e-2, help="Energy drift threshold")
54
+ parser.add_argument("--safetydamp-coef", type=float, default=0.9, help="Safety damping multiplier")
55
+ parser.add_argument("--cfl-max", type=float, default=0.4, help="Max CFL number for adaptive dt")
56
+ parser.add_argument("--maxGtotscalar", type=float, default=0.1, help="Clamp total source scalar")
57
+ parser.add_argument("--maxinjectionfrac", type=float, default=0.05, help="Clamp per-step fractions")
58
+ parser.add_argument("--min-denominator", type=float, default=1e-12, help="Min denominator to avoid div-by-zero")
59
+ parser.add_argument("--maxabsorbenergy-frac", type=float, default=0.1, help="Max energy absorbed to correct drift")
60
+ parser.add_argument("--result-save-path", type=str, default="./fused_result.json", help="Where to save final result JSON")
61
+ parser.add_argument("--nruns", type=int, default=10, help="Comparison runs")
62
+ parser.add_argument("--use-grid", action="store_true", help="Enable grid microcosm evolution (original)")
63
+ return parser.parse_args()
64
+
65
+ args = parse_args()
66
+ RNG = np.random.default_rng(args.seed)
67
+
68
+ # -------------------------
69
+ # Utilities
70
+ # -------------------------
71
+ def clamp_val(x: float, a: float, b: float) -> float:
72
+ lo, hi = (a, b) if a <= b else (b, a)
73
+ return max(lo, min(hi, x))
74
+
75
+ def rng_default(seed=None) -> np.random.Generator:
76
+ return np.random.default_rng(seed if seed is not None else 42)
77
+
78
+ def energy_of_state(S: np.ndarray, dx: float = 1.0, dy: float = None, maxclip: float = 1e6) -> float:
79
+ Sc = np.clip(S, -maxclip, maxclip)
80
+ if dy is None:
81
+ return 0.5 * float(np.sum(Sc * Sc)) * dx
82
+ return 0.5 * float(np.sum(Sc * Sc)) * dx * dy
83
+
84
+ def xi_of(t: float, xi0: float = 1.0, amp: float = 0.5, freq: float = 0.01, mode: str = "sin") -> float:
85
+ if mode == "sin":
86
+ return xi0 * (1.0 + amp * math.sin(2.0 * math.pi * freq * t))
87
+ if mode == "cos":
88
+ return xi0 * (1.0 + amp * math.cos(2.0 * math.pi * freq * t))
89
+ if mode == "constant":
90
+ return xi0
91
+ raise ValueError(f"Unsupported xi mode: {mode}")
92
+
93
+ def laplacian_1d(field: np.ndarray, dx: float) -> np.ndarray:
94
+ return (np.roll(field, -1) - 2.0 * field + np.roll(field, 1)) / (dx * dx)
95
+
96
+ def adjust_dt_by_cfl_1d(V: np.ndarray, dx: float, currentdt: float, cflmax: float = 0.4,
97
+ dtmin: float = 1e-10, dtmax: float = 1e-2) -> float:
98
+ try:
99
+ vmax = float(np.max(np.abs(V)))
100
+ except Exception:
101
+ vmax = 1e-16
102
+ vmax = max(vmax, 1e-16)
103
+ cfl = vmax * currentdt / dx
104
+ if cfl > cflmax:
105
+ newdt = max(dtmin, currentdt * 0.5)
106
+ while vmax * newdt / dx > cflmax and newdt > dtmin:
107
+ newdt = max(dtmin, newdt * 0.5)
108
+ return newdt
109
+ else:
110
+ newdt = min(dtmax, currentdt * 1.05)
111
+ if vmax * newdt / dx <= cflmax:
112
+ return newdt
113
+ return currentdt
114
+
115
+ def sample_collision_residual(residual_scalar: float, Nsamples: int, rng: np.random.Generator = None) -> np.ndarray:
116
+ if rng is None:
117
+ rng = rng_default()
118
+ if residual_scalar <= 0 or Nsamples <= 0:
119
+ return np.zeros(0, dtype=float)
120
+ fracs = rng.beta(2.0, 5.0, size=int(Nsamples))
121
+ samples = fracs * max(0.0, residual_scalar)
122
+ samples += rng.normal(scale=1e-12, size=samples.shape)
123
+ return np.maximum(0.0, samples)
124
+
125
+ # -------------------------
126
+ # Sources
127
+ # -------------------------
128
+ SOURCE_A = {
129
+ "name": "A_core",
130
+ "params": {
131
+ "Gamma": 1e-3, "delta": 1e-3, "etaamp": 1e-5, "thetaplus": 0.5,
132
+ "thetaminus": -0.5,
133
+ "kappa": 1e-3, "xi": 0.021, "lambda": 0.12, "coefxi": -0.5, "coeflambda":
134
+ -0.3
135
+ },
136
+ "operators": {
137
+ "linear": {"coefxi": -0.5, "coeflambda": -0.3},
138
+ "dissipative": {"Gamma": 1e-3},
139
+ "nonlinear": {"delta": 1e-3},
140
+ "noise": {"etaamp": 1e-5}
141
+ }
142
+ }
143
+
144
+ SOURCE_B = {
145
+ "name": "B_evolved",
146
+ "params": {
147
+ "projectionclip": 1.023, "mixalpha": 0.42, "mixnoisesigma": 9.6e-7,
148
+ "injectionamp": 9.8e-5,
149
+ "diffusionnu": 9.87e-4, "advection_v": 0.097, "xi": 0.01055, "lambda":
150
+ 0.121, "mix_gain": 0.63
151
+ },
152
+ "operators": {
153
+ "projection": {"clip": 1.023},
154
+ "mix": {"alpha": 0.42},
155
+ "injection": {"amp": 9.8e-5},
156
+ "diffusion": {"nu": 9.87e-4},
157
+ "advection": {"v": 0.097}
158
+ }
159
+ }
160
+
161
+ SOURCE_C = {
162
+ "name": "C_final2",
163
+ "params": {
164
+ "etaamp": 5e-5, "thetaplus": 0.42, "thetaminus": -0.42, "injectionamp":
165
+ 0.06,
166
+ "mixgain": 10.0, "hold_strength": 0.12, "xi": 0.021, "lambda": 0.121
167
+ },
168
+ "operators": {
169
+ "stabilizer": {"injectionamp": 0.06, "mixgain": 10.0, "hold_strength":
170
+ 0.12}
171
+ }
172
+ }
173
+
174
+ # -------------------------
175
+ # Collision rules
176
+ # -------------------------
177
+ def numericcollide(a, b, rng: np.random.Generator, exactcancel: bool = False) -> float:
178
+ if a is None and b is None:
179
+ return 0.0
180
+ if a is None:
181
+ return float(b)
182
+ if b is None:
183
+ return float(a)
184
+ a = float(a)
185
+ b = float(b)
186
+ if a * b < 0:
187
+ if exactcancel:
188
+ return 0.0
189
+ mag = (abs(a) + abs(b)) * 0.5
190
+ return float(rng.normal(0.0, max(mag * 0.02, 1e-12)))
191
+ avg = 0.5 * (a + b)
192
+ perturb = rng.normal(0.0, max(abs(avg) * 0.03, 1e-12))
193
+ return float(avg + perturb)
194
+
195
+ def collidedict(pa: Dict[str, Any], pb: Dict[str, Any], rng: np.random.Generator, exactcancel: bool = False) -> Dict[str, Any]:
196
+ keys = set(pa.keys()) | set(pb.keys())
197
+ out: Dict[str, Any] = {}
198
+ for k in keys:
199
+ va = pa.get(k)
200
+ vb = pb.get(k)
201
+ if isinstance(va, (int, float)) or isinstance(vb, (int, float)):
202
+ out[k] = numericcollide(va, vb, rng, exactcancel)
203
+ else:
204
+ out[k] = va if va == vb else (va if va is not None else vb)
205
+ return out
206
+
207
+ def collideops(opsA: Dict[str, Dict[str, Any]], opsB: Dict[str, Dict[str, Any]],
208
+ rng: np.random.Generator, exactcancel: bool = False) -> Dict[str, Dict[str, Any]]:
209
+ new_ops: Dict[str, Dict[str, Any]] = {}
210
+ namesA = list(opsA.keys())
211
+ namesB = list(opsB.keys())
212
+ # Same-name operator collision
213
+ for name in set(namesA) & set(namesB):
214
+ new_ops[name] = collidedict(opsA[name], opsB[name], rng, exactcancel)
215
+ # Reverse-operator collision (pairwise reverse weighting)
216
+ for i, nameA in enumerate(namesA):
217
+ partner = namesB[-1 - (i % len(namesB))]
218
+ newname = f"{nameA}_opp_{partner}"
219
+ collided = collidedict(opsA[nameA], opsB[partner], rng, exactcancel)
220
+ for pk, pv in list(collided.items()):
221
+ if isinstance(pv, (int, float)):
222
+ collided[pk] = -pv
223
+ new_ops[newname] = collided
224
+ return new_ops
225
+
226
+ # -------------------------
227
+ # Candidate synthesis + validation (single-point)
228
+ # -------------------------
229
+ def generatecandidates(sources: List[Dict[str, Any]], rng: np.random.Generator, n: int,
230
+ exactcancel: bool = False, injmult: float = 1.0, couplingmult: float = 1.0, grid_scaling: bool = False) -> List[Dict[str, Any]]:
231
+ candidates = []
232
+ for _ in range(n):
233
+ A = sources[rng.integers(0, len(sources))]
234
+ B = sources[rng.integers(0, len(sources))]
235
+ pa = {k: (v * (1.0 + rng.normal(0.0, 0.01)) if isinstance(v, (int, float))
236
+ else v)
237
+ for k, v in A["params"].items()}
238
+ pb = {k: (v * (1.0 + rng.normal(0.0, 0.01)) if isinstance(v, (int, float))
239
+ else v)
240
+ for k, v in B["params"].items()}
241
+ newparams = collidedict(pa, pb, rng, exactcancel)
242
+ newops = collideops(A["operators"], B["operators"], rng, exactcancel)
243
+ # Multipliers
244
+ if grid_scaling:
245
+ newparams["injectionamp"] = float(newparams.get("injectionamp", newparams.get("injection_amp", 1e-4))) * float(injmult)
246
+ if "diffusionnu" in newparams:
247
+ newparams["diffusionnu"] = float(newparams.get("diffusionnu", 1e-3)) * float(couplingmult)
248
+ else:
249
+ newparams["kappa"] = float(newparams.get("kappa", 1e-3)) * float(couplingmult)
250
+ else:
251
+ newparams["injectionamp"] = float(newparams.get("injectionamp", newparams.get("injection_amp", 1e-4)))
252
+ if "diffusionnu" not in newparams:
253
+ newparams["kappa"] = float(newparams.get("kappa", 1e-3))
254
+ newparams["xi"] = float(clamp_val(newparams.get("xi", 0.0), 1e-4, 1.0))
255
+ newparams["lambda"] = float(clamp_val(newparams.get("lambda", 0.0), 1e-4, 1.0))
256
+ candidates.append({"params": newparams, "operators": newops})
257
+ return candidates
258
+
259
+ def EVOLVEZSFtest(zs: Dict[str, Any], params: Dict[str, Any], rng: np.random.Generator, dt: float = 1e-4) -> Dict[str, Any]:
260
+ xi = float(params.get("xi", zs.get("xi", 0.021)))
261
+ lam = float(params.get("lambda", zs.get("lambda", 0.121)))
262
+ phi = float(zs.get("phi", 0.0))
263
+ linearxi = float(params.get("coefxi", params.get("linearcoefxi", -0.5)))
264
+ linearlam = float(params.get("coeflambda", params.get("linearcoeflambda", -0.3)))
265
+ linearterm = linearxi * xi + linearlam * lam
266
+ Gamma = float(params.get("Gamma", params.get("dissipative_Gamma", 5e-4)))
267
+ dissipative = -Gamma * phi
268
+ delta = float(params.get("delta", 1e-3))
269
+ nonlinear = -delta * (phi * 3.0)
270
+ eta = float(params.get("etaamp", 1e-5 if not args.high_noise else 5e-5))
271
+ noise = eta * rng.normal(0.0, 1.0) / math.sqrt(max(dt, 1e-16))
272
+ thetaplus = float(params.get("thetaplus", 0.35 if args.lower_threshold else 0.5))
273
+ thetaminus = float(params.get("thetaminus", -0.35 if args.lower_threshold else -0.5))
274
+ inj = float(params.get("injectionamp", 0.0) or 0.0)
275
+ injection = 0.0
276
+ near = float(params.get("near_margin", 0.12))
277
+ if (thetaplus - near) <= phi < thetaplus:
278
+ injection += inj * (1.0 + 5.0 * xi)
279
+ if thetaminus < phi <= (thetaminus + near):
280
+ injection -= inj * (1.0 + 5.0 * xi)
281
+ mixgain = float(params.get("mixgain", params.get("mix_alpha", 5.0)))
282
+ if abs(phi) < float(params.get("mix_zone", 0.25)):
283
+ injection += mixgain * eta * rng.normal(0.0, 1.0)
284
+ phinew = phi + dt * (linearterm + dissipative + nonlinear) + math.sqrt(max(dt, 1e-16)) * noise + injection
285
+ # TRIT map + hold
286
+ if phinew >= thetaplus:
287
+ trit = 1
288
+ elif phinew <= thetaminus:
289
+ trit = -1
290
+ else:
291
+ trit = 0
292
+ if trit == 1:
293
+ hold = float(params.get("hold_strength", 0.12))
294
+ phinew = phinew * (1.0 - hold) + 1.0 * hold
295
+ elif trit == -1:
296
+ hold = float(params.get("hold_strength", 0.12))
297
+ phinew = phinew * (1.0 - hold) - 1.0 * hold
298
+ zs_out = dict(zs)
299
+ zs_out["phi"] = float(phinew)
300
+ zs_out["tritstate"] = int(trit)
301
+ zs_out["xi"] = xi
302
+ zs_out["lambda"] = lam
303
+ zs_out["entropy"] = zs_out["tritstate"] * xi
304
+ return zs_out
305
+
306
+ def validate_candidates(cands: List[Dict[str, Any]], rng: np.random.Generator,
307
+ steps: int = 500, runs: int = 4, debug: bool = False) -> List[Dict[str, Any]]:
308
+ results = []
309
+ for idx, c in enumerate(cands):
310
+ success = 0
311
+ finals: List[int] = []
312
+ for r in range(runs):
313
+ rgen = np.random.default_rng(int(rng.integers(1, 10000)))
314
+ zs = {"phi": 0.0, "tritstate": 0, "xi": c["params"].get("xi", 0.021),
315
+ "lambda": c["params"].get("lambda", 0.121)}
316
+ for _ in range(steps):
317
+ zs = EVOLVEZSFtest(zs, c["params"], rgen)
318
+ finals.append(zs["tritstate"])
319
+ if zs["tritstate"] != 0:
320
+ success += 1
321
+ rate = success / runs
322
+ results.append({"idx": idx, "rate": rate, "finals": finals, "params": c["params"]})
323
+ if debug and idx < 6:
324
+ print(f"[validate] idx={idx} rate={rate:.2f} keys={list(c['params'].keys())[:6]}")
325
+ return results
326
+
327
+ # -------------------------
328
+ # Stabilizer and single-point adaptive injection
329
+ # -------------------------
330
+ def applystabilizingops(zs: Dict[str, Any], rng: np.random.Generator, params: Dict[str, Any] = None) -> Dict[str, Any]:
331
+ if params is None:
332
+ params = {}
333
+ phi = float(zs.get("phi", 0.0))
334
+ xi = float(zs.get("xi", 0.021))
335
+ thetaplus = float(params.get("thetaplus", 0.35 if args.lower_threshold else 0.5))
336
+ thetaminus = float(params.get("thetaminus", -0.35 if args.lower_threshold else -0.5))
337
+ softclip = float(params.get("softclip", 1.0))
338
+ clipstrength = float(params.get("clipstrength", 0.15))
339
+ if abs(phi) > softclip:
340
+ phi = phi * (1.0 - clipstrength) + math.copysign(softclip, phi) * clipstrength
341
+ biasamp = float(params.get("injectionamp", 0.06))
342
+ nearmargin = float(params.get("nearmargin", 0.12))
343
+ if (thetaplus - nearmargin) <= phi < thetaplus:
344
+ phi += biasamp * (1.0 + 5.0 * xi)
345
+ if thetaminus < phi <= (thetaminus + nearmargin):
346
+ phi -= biasamp * (1.0 + 5.0 * xi)
347
+ mixzone = float(params.get("mixzone", 0.25))
348
+ mixgain = float(params.get("mixgain", 10.0))
349
+ if abs(phi) < mixzone:
350
+ noiseamp = float(params.get("etaamp", 5e-5))
351
+ noise = noiseamp * rng.normal(0.0, 1.0)
352
+ drive = float(params.get("drive_bias", 0.0))
353
+ phi += (noise * mixgain) + drive * 1e-3
354
+ trit = int(zs.get("tritstate", 0))
355
+ holdstrength = float(params.get("holdstrength", 0.12))
356
+ if trit == 1:
357
+ phi = phi * (1.0 - holdstrength) + 1.0 * holdstrength
358
+ elif trit == -1:
359
+ phi = phi * (1.0 - holdstrength) - 1.0 * holdstrength
360
+ phi = max(min(phi, 1.2), -1.2)
361
+ zs_out = dict(zs)
362
+ zs_out["phi"] = float(phi)
363
+ return zs_out
364
+
365
+ def EVOLVEZSFwithadaptiveinjection(zs: Dict[str, Any], params: Dict[str, Any], dt: float = 1e-4,
366
+ rng: np.random.Generator = None) -> Dict[str, Any]:
367
+ if rng is None:
368
+ rng = rng_default(zs.get("seed", 42))
369
+ xi = float(zs.get("xi", params.get("xi", 0.021)))
370
+ lam = float(zs.get("lambda", params.get("lambda", 0.121)))
371
+ phi = float(zs.get("phi", 0.0))
372
+ coefxi = float(params.get("coefxi", -0.5))
373
+ coeflambda = float(params.get("coeflambda", -0.3))
374
+ linearterm = coefxi * xi + coeflambda * lam
375
+ Gamma = float(params.get("Gamma", 5e-4))
376
+ dissipative_term = -Gamma * phi
377
+ delta = float(params.get("delta", 1e-3))
378
+ nonlinear_term = -delta * (phi * 3.0)
379
+ etaamp = float(params.get("etaamp", 1e-5 if not args.high_noise else 5e-5))
380
+ noise_term = etaamp * rng.normal(0.0, 1.0) / math.sqrt(max(dt, 1e-16))
381
+ # Sampled base injection
382
+ residual_scalar = max(0.0, phi * float(params.get("Nmcsample", args.Nmcsample)))
383
+ samples = sample_collision_residual(residual_scalar, int(params.get("Nmcsample", args.Nmcsample)), rng)
384
+ inj_sample = (float(np.mean(samples)) * float(params.get("eta_in", 0.05))) if samples.size > 0 else float(params.get("injectionamp", 1e-4))
385
+ injbase = inj_sample * (1.0 + 5.0 * xi)
386
+ # Adaptive injection
387
+ injadapt = float(zs.get("injectionadaptive", 0.0))
388
+ Kp = float(params.get("injcontrollergain", args.Kp))
389
+ Imax = float(params.get("injmax", args.Imax))
390
+ thetaplus = float(params.get("thetaplus", 0.35 if args.lower_threshold else 0.5))
391
+ thetaminus = float(params.get("thetaminus", -0.35 if args.lower_threshold else -0.5))
392
+ thetatarget = thetaplus + float(args.theta_target_offset)
393
+ previnj = float(zs.get("injprev", 0.0))
394
+ Kd = float(params.get("inj_damping", 0.01))
395
+ error = thetatarget - phi
396
+ injadapt += Kp * error - Kd * (injadapt - previnj)
397
+ injadapt = max(min(injadapt, Imax), -Imax)
398
+ injection = injbase + injadapt
399
+ if abs(phi) < float(params.get("mix_zone", 0.25)):
400
+ injection += float(params.get("mixgain", 5.0)) * etaamp * rng.normal(0.0, 1.0)
401
+ phinew = phi + dt * (linearterm + dissipative_term + nonlinear_term) + math.sqrt(max(dt, 1e-16)) * noise_term + injection
402
+ # TRIT map + soft-hold + adaptive bump
403
+ if phinew >= thetaplus:
404
+ trit = 1
405
+ hold = float(params.get("hold_strength", 0.12))
406
+ phinew = phinew * (1.0 - hold) + 1.0 * hold
407
+ elif phinew <= thetaminus:
408
+ trit = -1
409
+ hold = float(params.get("hold_strength", 0.12))
410
+ phinew = phinew * (1.0 - hold) - 1.0 * hold
411
+ else:
412
+ trit = 0
413
+ if trit == 1:
414
+ injadapt = max(injadapt, float(params.get("injhold", args.inj_hold)))
415
+ injadapt *= 0.98
416
+ prevtrit = int(zs.get("tritstate", 0))
417
+ if prevtrit == 1 and trit == 0 and phinew < thetaplus - 0.05:
418
+ injadapt += min(0.1, Imax * 0.2)
419
+ phinew = max(min(phinew, 1.2), -1.2)
420
+ zs_out = dict(zs)
421
+ zs_out["phi"] = float(phinew)
422
+ zs_out["tritstate"] = int(trit)
423
+ zs_out["injectionadaptive"] = float(injadapt)
424
+ zs_out["injprev"] = float(injadapt)
425
+ zs_out["xi"] = xi
426
+ zs_out["lambda"] = lam
427
+ zs_out["entropy"] = zs_out["tritstate"] * xi
428
+ if args.debug:
429
+ print(f"ADAPT step: phi={phi:.6e} -> {phinew:.6e}, injbase={injbase:.3e}, injadapt={injadapt:.3e}, trit={trit}")
430
+ return zs_out
431
+
432
+ # -------------------------
433
+ # Operator class (grid) and base ops
434
+ # -------------------------
435
+ class Operator:
436
+ def __init__(self, name: str, params: Dict[str, Any], apply_fn):
437
+ self.name = name
438
+ self.params = dict(params)
439
+ self.apply_fn = apply_fn
440
+ self.next_op: Operator | None = None
441
+
442
+ def apply(self, state: np.ndarray, rng: np.random.Generator = None) -> Tuple[np.ndarray, Dict[str, Any]]:
443
+ if rng is None:
444
+ rng = rng_default()
445
+ result, info = self.apply_fn(state, self.params, rng)
446
+ if self.next_op is not None:
447
+ result, next_info = self.next_op.apply(result, rng)
448
+ info.update(next_info)
449
+ return result, info
450
+
451
+ def chain(self, next_op: "Operator") -> "Operator":
452
+ self.next_op = next_op
453
+ return self
454
+
455
+ def op_diffusion(state, params, rng):
456
+ dx = float(params.get("dx", 1.0))
457
+ dt = float(params.get("dt", 1e-5))
458
+ nu = float(params.get("nu", 1e-4)) * float(params.get("coupling_mult", args.coupling_mult))
459
+ lap = laplacian_1d(state, dx)
460
+ state_new = state + nu * lap * dt
461
+ return state_new, {"energy_diffusion": energy_of_state(state_new, dx), "nu_used": nu}
462
+
463
+ def op_advection(state, params, rng):
464
+ dx = float(params.get("dx", 1.0))
465
+ dt = float(params.get("dt", 1e-5))
466
+ v = float(params.get("v", 0.097))
467
+ state_avg = float(np.mean(state))
468
+ v = v * (1.0 + 0.1 * state_avg) # adaptive speed
469
+ F = v * state
470
+ F_im = np.roll(F, 1)
471
+ conv_term = -(dt / dx) * (F - F_im)
472
+ state_new = state + conv_term
473
+ return state_new, {"energy_advection": energy_of_state(state_new, dx), "v_used": v}
474
+
475
+ def op_noise(state, params, rng):
476
+ dx = float(params.get("dx", 1.0))
477
+ sigma = float(params.get("sigma", 1e-6)) * (5 if params.get("high_noise", False) else 1)
478
+ noise = rng.normal(scale=sigma, size=state.shape)
479
+ state_new = state + noise
480
+ return state_new, {"energy_noise": energy_of_state(state_new, dx), "sigma_used": sigma}
481
+
482
+ def op_projection(state, params, rng):
483
+ dx = float(params.get("dx", 1.0))
484
+ clip = float(params.get("clip", 1.023))
485
+ soft_clip = float(params.get("soft_clip", 1.2))
486
+ state_new = np.where(np.abs(state) > soft_clip,
487
+ state * (1.0 - 0.15) + np.sign(state) * soft_clip * 0.15, state)
488
+ state_new = np.clip(state_new, -clip, clip)
489
+ return state_new, {"energy_projection": energy_of_state(state_new, dx),
490
+ "clipped_count": int(np.sum(np.abs(state_new) >= clip))}
491
+
492
+ def op_adaptive_injection(state, params, rng):
493
+ dx = float(params.get("dx", 1.0))
494
+ grid_size = int(state.shape[0])
495
+ center = grid_size // 2
496
+ width = max(1.0, float(params.get("width", max(1, grid_size // 20))))
497
+ x = np.arange(grid_size)
498
+ kernel = np.exp(-0.5 * ((x - center) / width) ** 2)
499
+ kernel = kernel / (kernel.sum() + 1e-12)
500
+ phi_prev = float(np.mean(state))
501
+ thetaplus = 0.35 if params.get("lower_threshold", False) else 0.5
502
+ theta_target = thetaplus + float(args.theta_target_offset)
503
+ Kp = float(params.get("Kp", args.Kp))
504
+ Kd = float(params.get("Kd", 0.01))
505
+ Imax = float(params.get("Imax", args.Imax))
506
+ inj_prev = float(params.get("inj_prev", 0.0))
507
+ inj_prev_prev = float(params.get("inj_prev_prev", 0.0))
508
+ error = theta_target - phi_prev
509
+ inj_adapt = inj_prev + Kp * error - Kd * (inj_prev - inj_prev_prev)
510
+ inj_adapt = clamp_val(inj_adapt, -Imax, Imax)
511
+ inj_base = float(params.get("injectionamp", 1e-4)) * (1.0 + 5.0 * float(params.get("xi", 0.021))) * float(params.get("inj_mult", args.inj_mult))
512
+ mix_zone = float(params.get("mix_zone", 0.25))
513
+ if abs(phi_prev) < mix_zone:
514
+ inj_base += float(params.get("mixgain", 5.0)) * float(params.get("etaamp", 1e-5)) * rng.normal(0.0, 1.0)
515
+ injection = inj_base + inj_adapt
516
+ state_new = state + injection * kernel
517
+ trit = 1 if phi_prev >= thetaplus else (-1 if phi_prev <= -thetaplus else 0)
518
+ if trit == 1:
519
+ inj_adapt = max(inj_adapt, float(params.get("inj_hold", args.inj_hold)))
520
+ inj_adapt *= 0.98
521
+ params["inj_prev_prev"] = inj_prev
522
+ params["inj_prev"] = inj_adapt
523
+ return state_new, {"energy_injection": energy_of_state(state_new, dx), "inj_adapt": inj_adapt, "trit": trit}
524
+
525
+ def op_stabilize(state, params, rng):
526
+ dx = float(params.get("dx", 1.0))
527
+ phi = float(np.mean(state))
528
+ thetaplus = float(params.get("thetaplus", 0.35 if args.lower_threshold else 0.5))
529
+ soft_clip = float(params.get("softclip", 1.0))
530
+ clip_strength = float(params.get("clipstrength", 0.15))
531
+ if abs(phi) > soft_clip:
532
+ phi = phi * (1.0 - clip_strength) + math.copysign(soft_clip, phi) * clip_strength
533
+ E_prev = energy_of_state(state, dx)
534
+ scale = phi / (float(np.mean(state)) + 1e-12)
535
+ state_new = state * scale
536
+ E_new = energy_of_state(state_new, dx)
537
+ Z_proxy = abs(E_new - E_prev) / max(float(params.get("Z_threshold", args.Z_threshold)), abs(E_prev))
538
+ if Z_proxy > float(params.get("Z_threshold", args.Z_threshold)):
539
+ state_new = state_new * float(params.get("safetydamp_coef", args.safetydamp_coef))
540
+ return state_new, {"energy_stabilize": energy_of_state(state_new, dx), "Z_proxy": Z_proxy}
541
+
542
+ # -------------------------
543
+ # Evolved composite operator chain
544
+ # -------------------------
545
+ def create_evolved_best_operator(dx: float) -> Operator:
546
+ default_ops = [
547
+ Operator("advection", {"v": 0.097, "dx": dx, "dt": args.dt_micro}, op_advection),
548
+ Operator("noise", {"sigma": args.sigma_noise, "dx": dx, "high_noise": args.high_noise}, op_noise),
549
+ Operator("diffusion", {"nu": 9.87e-4, "dx": dx, "dt": args.dt_micro, "coupling_mult": args.coupling_mult}, op_diffusion),
550
+ Operator("adaptive_injection", {
551
+ "injectionamp": 9.8e-5, "inj_mult": args.inj_mult, "dx": dx,
552
+ "lower_threshold": args.lower_threshold,
553
+ "xi": 0.021, "mixgain": 5.0, "etaamp": 1e-5, "Kp": args.Kp, "Imax": args.Imax
554
+ }, op_adaptive_injection),
555
+ Operator("projection", {"clip": 1.023, "soft_clip": 1.2, "dx": dx}, op_projection),
556
+ Operator("stabilize", {"Z_threshold": args.Z_threshold, "dx": dx, "safetydamp_coef": args.safetydamp_coef}, op_stabilize),
557
+ ]
558
+ fused_op = default_ops[0]
559
+ for op in default_ops[1:]:
560
+ fused_op = fused_op.chain(op)
561
+ return fused_op
562
+
563
+ # -------------------------
564
+ # Grid evolution using operator chain
565
+ # -------------------------
566
+ def EVOLVEZSFwithadaptiveinjection_grid(state: np.ndarray, params: Dict[str, Any], rng: np.random.Generator,
567
+ dx: float, dt: float) -> Tuple[np.ndarray, Dict[str, Any]]:
568
+ op_chain = create_evolved_best_operator(dx)
569
+ state_new, info = op_chain.apply(state, rng)
570
+ phi = float(np.mean(state_new))
571
+ thetaplus = float(params.get("thetaplus", 0.35 if args.lower_threshold else 0.5))
572
+ thetaminus = -thetaplus
573
+ trit = 1 if phi >= thetaplus else (-1 if phi <= thetaminus else 0)
574
+ info["trit_state"] = trit
575
+ info["phi"] = phi
576
+ info["dt_used"] = dt
577
+ return state_new, info
578
+
579
+ # -------------------------
580
+ # FUSE (single-point and grid)
581
+ # -------------------------
582
+ def FUSE(zs1: Dict[str, Any], zs2: Dict[str, Any], T_local: float = 300.0) -> Dict[str, Any]:
583
+ b1 = int(zs1.get("tritstate", zs1.get("trit_state", 0)))
584
+ b2 = int(zs2.get("tritstate", zs2.get("trit_state", 0)))
585
+ xi1 = float(zs1.get("xi", 0.021))
586
+ xi2 = float(zs2.get("xi", 0.021))
587
+ fused: Dict[str, Any] = {}
588
+ xor = (b1 ^ b2) % 2
589
+ if xor != 0:
590
+ delta_xi = (xi1 - xi2) / 2.0
591
+ zs1["xi"] = xi1 - delta_xi
592
+ zs2["xi"] = xi2 + delta_xi
593
+ sum_b = (b1 + b2) % 3
594
+ if sum_b != 0:
595
+ delta_S = ((b1 + b2) - 0) * zs1.get("xi", xi1)
596
+ deltaE = abs(delta_S) * T_local
597
+ fused["energy"] = zs1.get("energy", 0.0) + zs2.get("energy", 0.0) + deltaE
598
+ fused_trit = int(round((b1 + b2) / 2.0)) if (b1 + b2) != 0 else 0
599
+ fused["tritstate"] = fused_trit
600
+ fused["xi"] = (zs1.get("xi", xi1) + zs2.get("xi", xi2)) / 2.0
601
+ fused["entropy"] = fused["tritstate"] * fused["xi"]
602
+ if args.debug:
603
+ print(f"DEBUG FUSE: b1={b1}, b2={b2}, fusedtrit={fused_trit}, fused_xi={fused['xi']:.6e}")
604
+ return fused
605
+
606
+ def FUSE_grid(zs_list: List[Dict[str, Any]], T_local: float, dx: float) -> Dict[str, Any]:
607
+ if len(zs_list) < 2:
608
+ return zs_list[0] if zs_list else {"state": np.zeros(10), "energy": 0.0, "trit_state": 0}
609
+ energies = [energy_of_state(zs["state"], dx) for zs in zs_list]
610
+ weights = [1.0 / max(E, 1e-12) for E in energies]
611
+ weights = [w / sum(weights) for w in weights]
612
+ fused_state = np.sum([zs["state"] * w for zs, w in zip(zs_list, weights)], axis=0)
613
+ trits = [zs.get("trit_state", 0) for zs in zs_list]
614
+ fused_trit = int(round(np.sum([t * w for t, w in zip(trits, weights)])))
615
+ fused_energy = energy_of_state(fused_state, dx)
616
+ delta_S = float(np.sum([zs.get("entropy", 0.0) * w for zs, w in zip(zs_list, weights)]))
617
+ fused_energy += abs(delta_S) * T_local
618
+ return {"state": fused_state, "energy": fused_energy, "trit_state": fused_trit, "entropy": delta_S, "weights": weights}
619
+
620
+ # -------------------------
621
+ # DARKMATTER_TRIGGER (single-point and grid)
622
+ # -------------------------
623
+ def DARKMATTERTRIGGER(zs: Dict[str, Any], couplingsection: float, Veff: float,
624
+ dt: float = 1e-4, rng: np.random.Generator = None, maxsteps: int = 1000,
625
+ params: Dict[str, Any] = None) -> Tuple[Dict[str, Any], List[str]]:
626
+ if rng is None:
627
+ rng = rng_default(zs.get("seed", 42))
628
+ if params is None:
629
+ params = {}
630
+ log: List[str] = []
631
+ if couplingsection <= 1e-40:
632
+ log.append("coupling_section below threshold; no trigger")
633
+ return zs, log
634
+ zs = dict(zs)
635
+ zs["lambda"] = 0.121
636
+ log.append("lambda set to 0.121")
637
+ zs["phi"] = zs.get("phi", 0.0) + 0.1
638
+ log.append(f"phi biased +0.1 -> {zs['phi']:.6e}")
639
+ evo_params = params.get("evoparams", {})
640
+ for step in range(maxsteps):
641
+ zs = EVOLVEZSFwithadaptiveinjection(zs, evo_params, dt=dt, rng=rng)
642
+ if zs.get("tritstate", 0) == 1:
643
+ log.append(f"Reached trit=1 at step {step}")
644
+ break
645
+ delta_S = 4e-4
646
+ T_local = 300.0
647
+ deltaE = delta_S * T_local
648
+ deltarho = deltaE / (Veff * (3e8 ** 2))
649
+ deltaR = 8.0 * math.pi * 6.67e-11 * deltarho / (3e8 ** 2)
650
+ zs["entropy"] = delta_S
651
+ zs["energy"] = zs.get("energy", 0.0) + deltaE
652
+ zs["curvature"] = zs.get("curvature", 0.0) + deltaR
653
+ log.append(f"trigger success: injected energy={deltaE:.6e} J, curvature change={deltaR:.6e} m^-1")
654
+ return zs, log
655
+
656
+ def DARKMATTER_TRIGGER_grid(zs: Dict[str, Any], coupling_section: float, Veff: float,
657
+ rng: np.random.Generator, dx: float) -> Tuple[Dict[str, Any], List[str]]:
658
+ log: List[str] = []
659
+ if coupling_section <= 1e-40:
660
+ log.append("coupling_section below threshold; no trigger")
661
+ return zs, log
662
+ state = zs.get("state", np.zeros(10))
663
+ zs["lambda"] = 0.121
664
+ log.append("lambda set to 0.121")
665
+ phi_biased = float(np.mean(state)) + 0.1
666
+ scale = phi_biased / (float(np.mean(state)) + 1e-12)
667
+ state = state * scale
668
+ log.append(f"phi biased +0.1 -> {phi_biased:.6e}")
669
+ evo_params = zs.get("evoparams", {})
670
+ max_steps = 1000
671
+ trit_state = 0
672
+ for step in range(max_steps):
673
+ state, info = EVOLVEZSFwithadaptiveinjection_grid(state, evo_params, rng, dx, args.dt_micro)
674
+ trit_state = info["trit_state"]
675
+ if trit_state == 1:
676
+ log.append(f"Reached trit=1 at step {step}")
677
+ break
678
+ delta_S = 4e-4
679
+ T_local = 300.0
680
+ delta_E = delta_S * T_local
681
+ delta_rho = delta_E / (Veff * (3e8 ** 2))
682
+ delta_R = 8.0 * math.pi * 6.67e-11 * delta_rho / (3e8 ** 2)
683
+ E_current = energy_of_state(state, dx)
684
+ E_new = E_current + delta_E
685
+ state = state * math.sqrt(E_new / max(E_current, 1e-12))
686
+ Z_proxy = abs(E_new - E_current) / max(args.Z_threshold, abs(E_current))
687
+ if Z_proxy > args.Z_threshold:
688
+ state = state * args.safetydamp_coef
689
+ log.append(f"Energy injection exceed Z_threshold: {Z_proxy:.3e}, damp state")
690
+ zs["state"] = state
691
+ zs["entropy"] = delta_S
692
+ zs["energy"] = E_new
693
+ zs["curvature"] = zs.get("curvature", 0.0) + delta_R
694
+ zs["trit_state"] = trit_state
695
+ log.append(f"trigger success: injected energy={delta_E:.6e} J, curvature change={delta_R:.6e} m^-1")
696
+ return zs, log
697
+
698
+ # -------------------------
699
+ # Quantum module + carbon synthesis (single and grid)
700
+ # -------------------------
701
+ def quantumsecondquantizescaled(k: float, omegak: float, debug: bool = False,
702
+ clampforsynthesis: bool = False, scale: float = None,
703
+ autoscale: bool = False, targetxi: float = 0.021) -> Dict[str, Any]:
704
+ hbar = 1.05457e-34
705
+ creationop = math.sqrt(hbar / (2.0 * omegak)) if omegak > 0 else 0.0
706
+ xiraw = creationop * 0.021
707
+ xi = xiraw
708
+ if autoscale and xiraw > 0:
709
+ if xiraw != 0:
710
+ scaleauto = targetxi / xiraw
711
+ xi = xiraw * scaleauto
712
+ else:
713
+ xi = xiraw * (targetxi / xiraw if xiraw != 0 else 1.0)
714
+ if scale is not None:
715
+ xi = xi * scale
716
+ if clampforsynthesis:
717
+ xi = clamp_val(xi, 0.019, 0.023)
718
+ xi = max(xi, 1e-3)
719
+ tritstate = 1 if creationop > 0 else -1
720
+ return {"xi": xi, "lambda": 0.121, "entropy": 0.0, "tritstate": tritstate}
721
+
722
+ def ZSFCARBONSYNTHESISdemo(scale: float = None, clamp: bool = False, autoscale: bool = True, debug: bool = False) -> Dict[str, Any]:
723
+ candidates = [1.2e15, 1.0e15, 1.5e15, 8.0e14]
724
+ carbon_zs = None
725
+ for ok in candidates:
726
+ cz = quantumsecondquantizescaled(0.5, ok, debug=debug,
727
+ clampforsynthesis=False, scale=scale, autoscale=autoscale, targetxi=0.021)
728
+ if debug:
729
+ print(f"TRY omega_k={ok:.6e} -> xi={cz['xi']:.6e}")
730
+ if 0.019 <= cz["xi"] <= 0.023:
731
+ carbon_zs = cz
732
+ if debug:
733
+ print(f"SELECTED omega_k={ok} with xi={cz['xi']:.6e}")
734
+ break
735
+ if carbon_zs is None:
736
+ carbon_zs = quantumsecondquantizescaled(0.5, candidates[0],
737
+ debug=debug, clampforsynthesis=clamp, scale=scale, autoscale=autoscale, targetxi=0.021)
738
+ if debug:
739
+ print(f"FINAL carbon xi after fallback: {carbon_zs['xi']:.6e}")
740
+ catalystzs = {"xi": 0.021, "lambda": 0.121, "entropy": -0.0002, "tritstate": -1, "energy": 0.0}
741
+ fused = FUSE(carbon_zs, catalystzs, T_local=3300.0)
742
+ carbonstrength = 11.2 if fused["tritstate"] == 0 else 12.0
743
+ return {"strengthGPa": carbonstrength, "fusedtrit": fused["tritstate"], "fused": fused, "carbonzs": carbon_zs}
744
+
745
+ def ZSF_CARBON_SYNTHESIS_grid(dx: float, debug: bool = False) -> Dict[str, Any]:
746
+ res = ZSFCARBONSYNTHESISdemo(autoscale=True, debug=debug)
747
+ Nx = int(args.grid_Nx)
748
+ carbon_state = res["carbonzs"]["xi"] * np.ones(Nx, dtype=float)
749
+ catalyst_state = 0.05 * np.exp(-0.5 * (np.linspace(-args.Lx, args.Lx, Nx) / 0.1) ** 2)
750
+ fused_grid = FUSE_grid([
751
+ {"state": carbon_state, "entropy": 0.0, "trit_state": res["fusedtrit"]},
752
+ {"state": catalyst_state, "entropy": -0.0002, "trit_state": -1}
753
+ ], T_local=300.0, dx=dx)
754
+ injection_source = fused_grid["state"] * 0.1
755
+ return {"strengthGPa": res["strengthGPa"], "fused_trit": fused_grid["trit_state"],
756
+ "fused": fused_grid, "carbon_zs": res["carbonzs"], "injection_source": injection_source}
757
+
758
+ # -------------------------
759
+ # Single-point demo
760
+ # -------------------------
761
+ def unitpointevolutiondemo(Nsteps: int = None, seed: int = 42, paramsoverride: Dict[str, Any] = None) -> Dict[str, List[float]]:
762
+ if Nsteps is None:
763
+ Nsteps = args.steps
764
+ rng = rng_default(seed)
765
+ params = {
766
+ "Gamma": 5e-4, "delta": 1e-3, "etaamp": 1e-5, "xi": 0.021, "lambda": 0.121,
767
+ "thetaplus": 0.35 if args.lower_threshold else 0.5, "thetaminus": -0.35 if args.lower_threshold else -0.5,
768
+ "dt": 1e-4, "Nmcsample": args.Nmcsample, "eta_in": 0.05, "injectionamp": 1e-4 * args.inj_mult,
769
+ "mixgain": 5.0 * args.inj_mult, "mix_zone": 0.25, "hold_strength": 0.12,
770
+ "stabilize": args.stabilize, "injcontrollergain": args.Kp, "injmax": args.Imax, "injhold": args.inj_hold
771
+ }
772
+ params["kappa"] = float(params.get("kappa", 1e-3)) * float(args.coupling_mult)
773
+ if paramsoverride:
774
+ params.update(paramsoverride)
775
+ zs = {"xi": params["xi"], "lambda": params["lambda"], "phi": 0.0, "tritstate": 0, "entropy": 0.0,
776
+ "seed": seed, "injectionadaptive": 0.0, "injprev": 0.0}
777
+ history = {"phi": [], "trit": [], "injadapt": []}
778
+ for _ in range(Nsteps):
779
+ zs = EVOLVEZSFwithadaptiveinjection(zs, params, dt=params["dt"], rng=rng)
780
+ if params.get("stabilize", False) or args.stabilize:
781
+ zs = applystabilizingops(zs, rng, params.get("stabilize_params", {}))
782
+ history["phi"].append(zs["phi"])
783
+ history["trit"].append(zs["tritstate"])
784
+ history["injadapt"].append(zs.get("injectionadaptive", 0.0))
785
+ return history
786
+
787
+ # -------------------------
788
+ # Regression Test
789
+ # -------------------------
790
+ def regression_test():
791
+ seed = 12345
792
+ baseline = unitpointevolutiondemo(Nsteps=200, seed=seed, paramsoverride=None)
793
+ merged = unitpointevolutiondemo(Nsteps=200, seed=seed, paramsoverride=None)
794
+ phi_diff = abs(baseline["phi"][-1] - merged["phi"][-1])
795
+ trit_match = baseline["trit"][-1] == merged["trit"][-1]
796
+ print("Regression test: final phi diff =", phi_diff, "trit match =", trit_match)
797
+ return {"phi_diff": phi_diff, "trit_match": trit_match,
798
+ "baseline_final_phi": baseline["phi"][-1], "merged_final_phi": merged["phi"][-1]}
799
+
800
+ # -------------------------
801
+ # Original Grid Simulation
802
+ # -------------------------
803
+ BASE_PARAMS = {
804
+ "seed": args.seed, "T_total": args.T_total, "dt_micro": args.dt_micro, "dt_macro": args.dt_macro,
805
+ "grid_Nx": args.grid_Nx, "Lx": args.Lx, "v0": args.v0, "alpha_s": args.alpha_s, "nu": args.nu,
806
+ "gamma_env": 0.05, "kappa_proj": args.kappa_proj, "eta_in": 0.05, "eta_heat": 0.10,
807
+ "eta_fus": 0.05, "sigma_fus": 0.03, "Nmcsample": args.Nmcsample, "gammak": 5e-4,
808
+ "sigma_noise": args.sigma_noise, "Z_threshold": args.Z_threshold, "safetydamp_coef": args.safetydamp_coef,
809
+ "maxGtotscalar": args.maxGtotscalar, "min_denominator": args.min_denominator, "maxinjectionfrac": args.maxinjectionfrac,
810
+ "adaptivedt_allowed": True, "cfl_max": args.cfl_max, "maxabsorbenergy_frac": args.maxabsorbenergy_frac,
811
+ "debugstopon_nan": True, "maxclipvalue": 1e6,
812
+ }
813
+
814
+ def upwind_step_1d(S, V, dtlocal, dxlocal, Ginlocal=None, gamma_env=0.0, nu=0.0):
815
+ if Ginlocal is None:
816
+ Ginlocal = np.zeros_like(S)
817
+ F = V * S
818
+ F_im = np.roll(F, 1)
819
+ convterm = -(dtlocal / dxlocal) * (F - F_im)
820
+ diffterm = nu * (dtlocal / (dxlocal * dxlocal)) * laplacian_1d(S, dxlocal)
821
+ srcterm = dtlocal * (Ginlocal - gamma_env * S)
822
+ newS = S + convterm + diffterm + srcterm
823
+ newS = 0.995 * newS + 0.005 * np.roll(newS, 1)
824
+ return newS
825
+
826
+ def run_simulation(params, use_evolved=True, verbose=False):
827
+ p = copy.deepcopy(params)
828
+ rng = rng_default(int(p["seed"]))
829
+ Nx = int(p["grid_Nx"])
830
+ x = np.linspace(-p["Lx"], p["Lx"], Nx)
831
+ dx = 2.0 * p["Lx"] / max(1, Nx - 1)
832
+ S = 0.1 + 0.01 * np.exp(-0.5 * (x / 0.2)**2)
833
+ V = p["v0"] * (1.0 + p["alpha_s"] * S)
834
+ Nexpect = 0.02
835
+ Eheat = 0.0
836
+ Emicro0 = float(Nexpect)
837
+ Emacro0 = energy_of_state(S, dx)
838
+ E0 = Emicro0 + Emacro0 + Eheat
839
+ dt = float(p["dt_micro"])
840
+ times = np.arange(0.0, float(p["T_total"]), dt)
841
+ steps = len(times)
842
+ macrosync = max(1, int(round(p["dt_macro"] / dt)))
843
+ projkernel = np.exp(-0.5 * (x / 0.1)**2)
844
+ projkernel /= projkernel.sum()
845
+ collkernel = np.exp(-0.5 * (x / p["sigma_fus"])**2)
846
+ collkernel /= collkernel.sum()
847
+ hist = {
848
+ "t": np.zeros(steps), "N_expect": np.zeros(steps), "E_micro": np.zeros(steps),
849
+ "E_macro": np.zeros(steps), "E_heat": np.zeros(steps), "Z_proxy": np.zeros(steps),
850
+ "S_center": np.zeros(steps),
851
+ }
852
+ localdt = dt
853
+ evolved_op = create_evolved_best_operator(dx=dx) if use_evolved else None
854
+ start_time = time.time()
855
+ for k, t in enumerate(times):
856
+ xi = xi_of(t)
857
+ dNdrive = 1e-2 * xi * (1.0 - np.clip(Nexpect, 0.0, 1.0)) * localdt
858
+ dNdiss = -p["gammak"] * Nexpect * localdt
859
+ noise = rng.normal(scale=math.sqrt(max(p["sigma_noise"], 0.0)) * math.sqrt(localdt))
860
+ Nexpect = max(0.0, Nexpect + dNdrive + dNdiss + noise)
861
+ Ncollected = p["kappa_proj"] * Nexpect
862
+ Nresidual = max(0.0, Nexpect - Ncollected)
863
+ samples = sample_collision_residual(Nresidual, p["Nmcsample"], rng)
864
+ coll_count = samples.size
865
+ if coll_count > 0:
866
+ deltain = p["eta_in"] * samples
867
+ deltaheat = p["eta_heat"] * samples
868
+ deltafus = p["eta_fus"] * samples
869
+ deltainavg = float(deltain.sum() / coll_count)
870
+ deltaheatavg = float(deltaheat.sum() / coll_count)
871
+ deltafusavg = float(deltafus.sum() / coll_count)
872
+ deltainavg = min(deltainavg, p["maxinjectionfrac"] * max(1e-12, Nexpect))
873
+ deltaheatavg = min(deltaheatavg, p["maxinjectionfrac"] * max(1e-12, Nexpect))
874
+ deltafusavg = min(deltafusavg, p["maxinjectionfrac"] * max(1e-12, Nexpect))
875
+ deltainavg = float(np.clip(deltainavg, -1e-3, 1e-3))
876
+ deltaheatavg = float(np.clip(deltaheatavg, -1e-3, 1e-3))
877
+ deltafusavg = float(np.clip(deltafusavg, -1e-3, 1e-3))
878
+ else:
879
+ deltainavg = deltaheatavg = deltafusavg = 0.0
880
+ Gtotscalar = Ncollected + deltainavg
881
+ Gtotscalar = min(Gtotscalar, p["maxGtotscalar"])
882
+ Gproj = Gtotscalar * projkernel
883
+ Gfus = (1.0 - p["eta_fus"]) * deltafusavg * collkernel
884
+ Gtotal = Gproj + Gfus
885
+ # Adjust time step by CFL condition
886
+ if p["adaptivedt_allowed"]:
887
+ try:
888
+ localdt = adjust_dt_by_cfl_1d(V, dx, localdt, p["cfl_max"], 1e-10, p["dt_micro"] * 10)
889
+ except Exception:
890
+ localdt = max(1e-10, localdt * 0.5)
891
+ # Apply operator (evolved or original)
892
+ if (k % macrosync) == 0:
893
+ if use_evolved and evolved_op is not None:
894
+ S, _ = evolved_op.apply(S, rng)
895
+ else:
896
+ S = upwind_step_1d(S, V, macrosync * localdt, dx, Ginlocal=Gtotal, gamma_env=p["gamma_env"], nu=p["nu"])
897
+ # Update velocity
898
+ V = p["v0"] * (1.0 + p["alpha_s"] * S)
899
+ # Update energy components
900
+ maxallowed2 = max(p["maxinjectionfrac"] * max(1e-12, Nexpect), p["min_denominator"])
901
+ heatincrement = min(deltaheatavg, maxallowed2)
902
+ newmicromass = min(deltafusavg, maxallowed2)
903
+ Eheat += heatincrement
904
+ Nexpect = max(0.0, Nexpect - heatincrement + newmicromass)
905
+ Emicro = float(Nexpect)
906
+ Emacro = energy_of_state(S, dx)
907
+ Etotal = Emicro + Emacro + Eheat
908
+ # Check energy drift
909
+ Zproxy = abs(Etotal - E0) / max(p["min_denominator"], abs(E0))
910
+ if Zproxy > p["Z_threshold"]:
911
+ deltaE = Etotal - E0
912
+ maxabsorb = p.get("maxabsorbenergy_frac", 0.1) * max(abs(E0), p["min_denominator"])
913
+ absorb = math.copysign(min(abs(deltaE), maxabsorb), deltaE)
914
+ Eheat -= absorb
915
+ S = S * p["safetydamp_coef"]
916
+ Nexpect = Nexpect * p["safetydamp_coef"]
917
+ # Record history
918
+ hist["t"][k] = t
919
+ hist["N_expect"][k] = Nexpect
920
+ hist["E_micro"][k] = Emicro
921
+ hist["E_macro"][k] = Emacro
922
+ hist["E_heat"][k] = Eheat
923
+ hist["Z_proxy"][k] = Zproxy
924
+ hist["S_center"][k] = float(S[len(S)//2])
925
+ # Debug: stop on NaN
926
+ if p["debugstopon_nan"]:
927
+ if not np.isfinite(Etotal) or np.isnan(Zproxy) or np.any(~np.isfinite(S)):
928
+ return hist, time.time() - start_time, True
929
+ runtime = time.time() - start_time
930
+ return hist, runtime, False
931
+
932
+ def run_comparison(nruns=10):
933
+ seeds = [int(BASE_PARAMS["seed"]) + i for i in range(nruns)]
934
+ results = {"evolved": [], "original": []}
935
+ for use_evolved in [True, False]:
936
+ label = "evolved" if use_evolved else "original"
937
+ for s in seeds:
938
+ p = copy.deepcopy(BASE_PARAMS)
939
+ p["seed"] = s
940
+ hist, runtime, failed = run_simulation(p, use_evolved=use_evolved, verbose=False)
941
+ E = hist["E_macro"] + hist["E_micro"] + hist["E_heat"]
942
+ E0 = E[0]
943
+ errE = np.abs(E - E0) / max(1e-12, abs(E0))
944
+ mean_err = float(np.mean(errE))
945
+ max_err = float(np.max(errE))
946
+ drift = float((E[-1] - E0) / max(1e-12, abs(E0)))
947
+ results[label].append({
948
+ "mean_err": mean_err, "max_err": max_err, "drift": drift, "nan": failed, "runtime": runtime
949
+ })
950
+ print(f"{label} seed={s}: mean_err={mean_err:.3e}, max_err={max_err:.3e}, drift={drift:.3e}, nan={failed}, time={runtime:.3f}s")
951
+ def summarize(list_of_dicts):
952
+ mean_errs = [d["mean_err"] for d in list_of_dicts]
953
+ drifts = [d["drift"] for d in list_of_dicts]
954
+ nans = sum(1 for d in list_of_dicts if d["nan"])
955
+ times = [d["runtime"] for d in list_of_dicts]
956
+ return {
957
+ "mean_err_mean": mean(mean_errs), "mean_err_std": stdev(mean_errs) if len(mean_errs) > 1 else 0.0,
958
+ "drift_mean": mean(drifts), "drift_std": stdev(drifts) if len(drifts) > 1 else 0.0,
959
+ "nan_count": nans, "time_mean": mean(times)
960
+ }
961
+ sum_e = summarize(results["evolved"])
962
+ sum_o = summarize(results["original"])
963
+ print("\nSummary (evolved vs original - original grid)")
964
+ print(f" mean_err: {sum_e['mean_err_mean']:.3e} ± {sum_e['mean_err_std']:.3e} vs {sum_o['mean_err_mean']:.3e} ± {sum_o['mean_err_std']:.3e}")
965
+ print(f" drift: {sum_e['drift_mean']:.3e} ± {sum_e['drift_std']:.3e} vs {sum_o['drift_mean']:.3e} ± {sum_o['drift_std']:.3e}")
966
+ print(f" NaN failures: {sum_e['nan_count']} / {nruns} vs {sum_o['nan_count']} / {nruns}")
967
+ print(f" Avg runtime (s): {sum_e['time_mean']:.3f} vs {sum_o['time_mean']:.3f}")
968
+ improvement_factor = (sum_o["mean_err_mean"] / sum_e["mean_err_mean"]) if sum_e["mean_err_mean"] > 0 else float("inf")
969
+ print(f"\nImprovement factor (old_mean_err / new_mean_err) = {improvement_factor:.3f}")
970
+
971
+ # -------------------------
972
+ # Fused grid simulation + comparison harness
973
+ # -------------------------
974
+ def run_fused_simulation(p: Dict[str, Any], use_evolved: bool, verbose: bool, dx: float) -> Tuple[Dict[str, np.ndarray], float, bool]:
975
+ rng = rng_default(p["seed"])
976
+ Nx = int(p["grid_Nx"])
977
+ x = np.linspace(-p["Lx"], p["Lx"], Nx)
978
+ state = 0.1 + 0.01 * np.exp(-0.5 * (x / 0.2) ** 2)
979
+ V = p["v0"] * (1.0 + p["alpha_s"] * state)
980
+ N_expect = 0.02
981
+ E_heat = 0.0
982
+ Emicro0 = float(N_expect)
983
+ Emacro0 = energy_of_state(state, dx)
984
+ E0 = Emicro0 + Emacro0 + E_heat
985
+ dt = float(p["dt_micro"])
986
+ times = np.arange(0.0, float(p["T_total"]), dt)
987
+ steps = len(times)
988
+ macrosync = max(1, int(round(p["dt_macro"] / dt)))
989
+ proj_kernel = np.exp(-0.5 * (x / 0.1) ** 2)
990
+ proj_kernel /= proj_kernel.sum()
991
+ coll_kernel = np.exp(-0.5 * (x / p["sigma_fus"]) ** 2)
992
+ coll_kernel /= coll_kernel.sum()
993
+ hist = {
994
+ "t": np.zeros(steps), "N_expect": np.zeros(steps), "E_micro": np.zeros(steps),
995
+ "E_macro": np.zeros(steps), "E_heat": np.zeros(steps), "Z_proxy": np.zeros(steps),
996
+ "S_center": np.zeros(steps), "trit_state": np.zeros(steps), "inj_adapt": np.zeros(steps),
997
+ "curvature": np.zeros(steps), "carbon_strength": np.zeros(steps)
998
+ }
999
+ fused_op = create_evolved_best_operator(dx) if use_evolved else None
1000
+ carbon_synth = ZSF_CARBON_SYNTHESIS_grid(dx=dx, debug=args.debug)
1001
+ injection_source = carbon_synth["injection_source"]
1002
+ start_time = time.time()
1003
+ failed = False
1004
+ for k, t in enumerate(times):
1005
+ xi_t = xi_of(t)
1006
+ dN_drive = 1e-2 * xi_t * (1.0 - np.clip(N_expect, 0.0, 1.0)) * dt
1007
+ dN_diss = -p["gammak"] * N_expect * dt
1008
+ noise = rng.normal(scale=math.sqrt(max(p["sigma_noise"], 0.0)) * math.sqrt(dt))
1009
+ N_expect = max(0.0, N_expect + dN_drive + dN_diss + noise)
1010
+ N_collected = p["kappa_proj"] * N_expect
1011
+ N_residual = max(0.0, N_expect - N_collected)
1012
+ samples = sample_collision_residual(N_residual, p["Nmcsample"], rng)
1013
+ if samples.size > 0:
1014
+ deltainavg = float((p["eta_in"] * samples).mean())
1015
+ deltaheatavg = float((p["eta_heat"] * samples).mean())
1016
+ deltafusavg = float((p["eta_fus"] * samples).mean())
1017
+ cap = p["maxinjectionfrac"] * max(1e-12, N_expect)
1018
+ deltainavg = float(np.clip(deltainavg, -1e-3, min(1e-3, cap)))
1019
+ deltaheatavg = float(np.clip(deltaheatavg, -1e-3, min(1e-3, cap)))
1020
+ deltafusavg = float(np.clip(deltafusavg, -1e-3, min(1e-3, cap)))
1021
+ else:
1022
+ deltainavg = deltaheatavg = deltafusavg = 0.0
1023
+ Gtot_scalar = N_collected + deltainavg + float(np.mean(injection_source))
1024
+ Gtot_scalar = min(Gtot_scalar, p["maxGtotscalar"])
1025
+ G_proj = Gtot_scalar * proj_kernel
1026
+ G_fus = (1.0 - p["eta_fus"]) * deltafusavg * coll_kernel
1027
+ G_total = G_proj + G_fus
1028
+ if (k % macrosync) == 0:
1029
+ if use_evolved and fused_op is not None:
1030
+ state, info = fused_op.apply(state, rng)
1031
+ hist["inj_adapt"][k] = float(info.get("inj_adapt", 0.0))
1032
+ hist["trit_state"][k] = int(info.get("trit", 0))
1033
+ else:
1034
+ # Original upwind + diffusion + source
1035
+ F = V * state
1036
+ F_im = np.roll(F, 1)
1037
+ convterm = -(macrosync * dt / dx) * (F - F_im)
1038
+ diffterm = p["nu"] * (macrosync * dt / (dx * dx)) * laplacian_1d(state, dx)
1039
+ srcterm = (macrosync * dt) * (G_total - p["gamma_env"] * state)
1040
+ noise_term = rng.normal(scale=args.sigma_noise if not args.high_noise else args.sigma_noise * 5.0, size=state.shape)
1041
+ state = state + convterm + diffterm + srcterm + noise_term
1042
+ state = 0.995 * state + 0.005 * np.roll(state, 1)
1043
+ if args.cfl_max > 0.0:
1044
+ try:
1045
+ dt = adjust_dt_by_cfl_1d(V, dx, dt, args.cfl_max, 1e-10, args.dt_micro * 10)
1046
+ except Exception:
1047
+ dt = max(1e-10, dt * 0.5)
1048
+ if k % 100 == 0 and k > 0:
1049
+ zs_trigger = {"state": state, "xi": xi_t, "lambda": 0.12, "phi": float(np.mean(state)),
1050
+ "trit_state": int(hist["trit_state"][k]), "entropy": 0.0, "energy": float(hist["E_macro"][k-1])}
1051
+ zs_out, trigger_log = DARKMATTER_TRIGGER_grid(zs_trigger, coupling_section=2e-40, Veff=1.0, rng=rng, dx=dx)
1052
+ state = zs_out["state"]
1053
+ hist["curvature"][k] = float(zs_out.get("curvature", 0.0))
1054
+ if args.debug:
1055
+ for msg in trigger_log:
1056
+ print(f"[grid trigger] {msg}")
1057
+ V = p["v0"] * (1.0 + p["alpha_s"] * state)
1058
+ maxallowed2 = max(p["maxinjectionfrac"] * max(1e-12, N_expect), p["min_denominator"])
1059
+ heatincrement = min(deltaheatavg, maxallowed2)
1060
+ newmicromass = min(deltafusavg, maxallowed2)
1061
+ E_heat += heatincrement
1062
+ N_expect = max(0.0, N_expect - heatincrement + newmicromass)
1063
+ Emicro = float(N_expect)
1064
+ Emacro = energy_of_state(state, dx)
1065
+ Etotal = Emicro + Emacro + E_heat
1066
+ Zproxy = abs(Etotal - E0) / max(p["min_denominator"], abs(E0))
1067
+ if Zproxy > p["Z_threshold"]:
1068
+ deltaE = Etotal - E0
1069
+ maxabsorb = p.get("maxabsorbenergy_frac", args.maxabsorbenergy_frac) * max(abs(E0), p["min_denominator"])
1070
+ absorb = math.copysign(min(abs(deltaE), maxabsorb), deltaE)
1071
+ E_heat -= absorb
1072
+ state = state * p["safetydamp_coef"]
1073
+ N_expect = N_expect * p["safetydamp_coef"]
1074
+ hist["t"][k] = t
1075
+ hist["N_expect"][k] = N_expect
1076
+ hist["E_micro"][k] = Emicro
1077
+ hist["E_macro"][k] = Emacro
1078
+ hist["E_heat"][k] = E_heat
1079
+ hist["Z_proxy"][k] = Zproxy
1080
+ hist["S_center"][k] = float(state[len(state)//2])
1081
+ hist["carbon_strength"][k] = float(carbon_synth["strengthGPa"])
1082
+ if not np.isfinite(Etotal) or np.isnan(Zproxy) or np.any(~np.isfinite(state)):
1083
+ failed = True
1084
+ break
1085
+ runtime = time.time() - start_time
1086
+ if verbose:
1087
+ print(f"Simulation finished: failed={failed}, runtime={runtime:.3f}s, final_trit={int(hist['trit_state'][-1]) if steps>0 else 0}")
1088
+ return hist, runtime, failed
1089
+
1090
+ def run_fused_comparison(nruns: int):
1091
+ seeds = [int(args.seed) + i for i in range(nruns)]
1092
+ results = {"evolved": [], "original": []}
1093
+ for use_evolved in [True, False]:
1094
+ label = "evolved" if use_evolved else "original"
1095
+ for s in seeds:
1096
+ p = {
1097
+ "seed": s, "grid_Nx": args.grid_Nx, "Lx": args.Lx, "T_total": args.T_total,
1098
+ "dt_micro": args.dt_micro, "dt_macro": args.dt_macro, "v0": args.v0, "alpha_s": args.alpha_s,
1099
+ "nu": args.nu, "gamma_env": args.gamma_env, "kappa_proj": args.kappa_proj, "eta_in": 0.05,
1100
+ "eta_heat": 0.10, "eta_fus": 0.05, "sigma_fus": 0.03, "Nmcsample": args.Nmcsample,
1101
+ "gammak": 5e-4, "sigma_noise": args.sigma_noise, "Z_threshold": args.Z_threshold,
1102
+ "safetydamp_coef": args.safetydamp_coef, "maxGtotscalar": args.maxGtotscalar,
1103
+ "min_denominator": args.min_denominator, "maxinjectionfrac": args.maxinjectionfrac,
1104
+ "dt_macro": args.dt_macro
1105
+ }
1106
+ dx = 2.0 * p["Lx"] / max(1, p["grid_Nx"] - 1)
1107
+ hist, runtime, failed = run_fused_simulation(p, use_evolved=use_evolved, verbose=True, dx=dx)
1108
+ E_total = np.array(hist["E_micro"]) + np.array(hist["E_macro"]) + np.array(hist["E_heat"])
1109
+ E0 = float(E_total[0])
1110
+ err_E = np.abs(E_total - E0) / max(1e-12, abs(E0))
1111
+ mean_err = float(np.mean(err_E))
1112
+ max_err = float(np.max(err_E))
1113
+ drift = float((E_total[-1] - E0) / max(1e-12, abs(E0)))
1114
+ trit_active_rate = float(np.sum(np.array(hist["trit_state"]) != 0) / len(hist["trit_state"]))
1115
+ results[label].append({
1116
+ "mean_err": mean_err, "max_err": max_err, "drift": drift, "nan": failed,
1117
+ "runtime": runtime, "trit_active_rate": trit_active_rate,
1118
+ "final_carbon_strength": float(hist["carbon_strength"][-1]) if len(hist["carbon_strength"]) > 0 else 0.0
1119
+ })
1120
+ print(f"\n{label} seed={s}:")
1121
+ print(f" mean_err={mean_err:.3e}, max_err={max_err:.3e}, drift={drift:.3e}")
1122
+ print(f" trit_active_rate={trit_active_rate:.2f}, final_carbon_strength={hist['carbon_strength'][-1]:.2f}GPa")
1123
+ print(f" nan={failed}, time={runtime:.3f}s")
1124
+ def summarize(list_of_dicts: List[Dict[str, Any]]) -> Dict[str, float]:
1125
+ mean_errs = [d["mean_err"] for d in list_of_dicts]
1126
+ drifts = [d["drift"] for d in list_of_dicts]
1127
+ trit_rates = [d["trit_active_rate"] for d in list_of_dicts]
1128
+ carb_strs = [d["final_carbon_strength"] for d in list_of_dicts]
1129
+ nans = sum(1 for d in list_of_dicts if d["nan"])
1130
+ times = [d["runtime"] for d in list_of_dicts]
1131
+ return {
1132
+ "mean_err_mean": mean(mean_errs), "mean_err_std": stdev(mean_errs) if len(mean_errs) > 1 else 0.0,
1133
+ "drift_mean": mean(drifts), "drift_std": stdev(drifts) if len(drifts) > 1 else 0.0,
1134
+ "trit_rate_mean": mean(trit_rates), "carbon_strength_mean": mean(carb_strs),
1135
+ "nan_count": nans, "time_mean": mean(times)
1136
+ }
1137
+ sum_e = summarize(results["evolved"])
1138
+ sum_o = summarize(results["original"])
1139
+ print("\n" + "="*50)
1140
+ print("Fused Comparison Summary (Evolved vs Original)")
1141
+ print("="*50)
1142
+ print(f"Mean Energy Error: {sum_e['mean_err_mean']:.3e} ± {sum_e['mean_err_std']:.3e} vs {sum_o['mean_err_mean']:.3e} ± {sum_o['mean_err_std']:.3e}")
1143
+ print(f"Energy Drift: {sum_e['drift_mean']:.3e} ± {sum_e['drift_std']:.3e} vs {sum_o['drift_mean']:.3e} ± {sum_o['drift_std']:.3e}")
1144
+ print(f"Trit Active Rate: {sum_e['trit_rate_mean']:.2f} vs {sum_o['trit_rate_mean']:.2f}")
1145
+ print(f"Final Carbon Strength (GPa): {sum_e['carbon_strength_mean']:.2f} vs {sum_o['carbon_strength_mean']:.2f}")
1146
+ print(f"NaN Failures: {sum_e['nan_count']}/{nruns} vs {sum_o['nan_count']}/{nruns}")
1147
+ print(f"Avg Runtime (s): {sum_e['time_mean']:.3f} vs {sum_o['time_mean']:.3f}")
1148
+ improvement_factor = (sum_o["mean_err_mean"] / sum_e["mean_err_mean"]) if sum_e["mean_err_mean"] > 0 else float("inf")
1149
+ print(f"\nEnergy Error Improvement Factor: {improvement_factor:.3f}x")
1150
+
1151
+ # -------------------------
1152
+ # Main
1153
+ # -------------------------
1154
+ def main():
1155
+ print("=== zsfsynthesizedadaptive_fused: full-model demo (integrated all modules) ===")
1156
+ print(f"injmult={args.inj_mult}, couplingmult={args.coupling_mult}, lowerthreshold={args.lower_threshold}, highnoise={args.high_noise}")
1157
+ sources = [SOURCE_A, SOURCE_B, SOURCE_C]
1158
+ mergeddefault = collidedict(SOURCE_A["params"], SOURCE_B["params"], RNG, exactcancel=args.exact_cancel)
1159
+ mergeddefault = collidedict(mergeddefault, SOURCE_C["params"], RNG, exactcancel=args.exact_cancel)
1160
+ mergeddefault["injectionamp"] = mergeddefault.get("injectionamp", 1e-4) * args.inj_mult
1161
+ if "diffusionnu" in mergeddefault:
1162
+ mergeddefault["diffusionnu"] = mergeddefault.get("diffusionnu", 1e-3) * args.coupling_mult
1163
+ else:
1164
+ mergeddefault["kappa"] = mergeddefault.get("kappa", 1e-3) * args.coupling_mult
1165
+ mergeddefault["stabilize"] = True
1166
+ mergeddefault["stabilize_params"] = {
1167
+ "injectionamp": mergeddefault.get("injectionamp", 1e-4), "nearmargin": 0.12,
1168
+ "mixgain": mergeddefault.get("mixgain", 5.0) * args.inj_mult,
1169
+ "etaamp": mergeddefault.get("etaamp", 1e-5 if not args.high_noise else 5e-5),
1170
+ "holdstrength": 0.12, "thetaplus": 0.35 if args.lower_threshold else 0.5,
1171
+ "thetaminus": -0.35 if args.lower_threshold else -0.5
1172
+ }
1173
+ # Print sample params
1174
+ samplekeys = ["xi","lambda","injectionamp","etaamp","mixgain","kappa","diffusionnu"]
1175
+ sample = {k: mergeddefault.get(k) for k in samplekeys if k in mergeddefault}
1176
+ print("Sample fused params:")
1177
+ print(json.dumps(sample, indent=2))
1178
+ # Single-point evolution demo
1179
+ hist = unitpointevolutiondemo(Nsteps=args.steps, seed=12345, paramsoverride=mergeddefault)
1180
+ for i in (0, max(0, args.steps // 4), args.steps - 1):
1181
+ if i < len(hist["phi"]):
1182
+ print(f"step {i}: phi={hist['phi'][i]:.6e}, trit={hist['trit'][i]}, injadapt={hist['injadapt'][i]:.6e}")
1183
+ final_phi = hist["phi"][-1] if len(hist["phi"]) > 0 else None
1184
+ final_trit = hist["trit"][-1] if len(hist["trit"]) > 0 else None
1185
+ print("final phi:", final_phi)
1186
+ print("final tritstate:", final_trit)
1187
+ print()
1188
+ # Trigger demo (single-point)
1189
+ zstrigger = {"xi": 0.021, "lambda": 0.12, "phi": 0.0, "tritstate": 0, "entropy": 0.0,
1190
+ "seed": 54321, "injectionadaptive": 0.0, "injprev": 0.0}
1191
+ evo_params = {}
1192
+ if args.high_noise:
1193
+ evo_params["etaamp"] = 5e-5
1194
+ if args.lower_threshold:
1195
+ evo_params["thetaplus"] = 0.35
1196
+ evo_params["thetaminus"] = -0.35
1197
+ evo_params["stabilize"] = True
1198
+ evo_params["stabilize_params"] = {
1199
+ "injectionamp": evo_params.get("injectionamp", mergeddefault.get("injectionamp", 1e-4)),
1200
+ "nearmargin": 0.12, "mixgain": mergeddefault.get("mixgain", 10.0),
1201
+ "etaamp": evo_params.get("etaamp", mergeddefault.get("etaamp", 1e-5)),
1202
+ "holdstrength": 0.12, "thetaplus": evo_params.get("thetaplus", 0.35), "thetaminus": evo_params.get("thetaminus", -0.35)
1203
+ }
1204
+ zsout, log = DARKMATTERTRIGGER(zstrigger, couplingsection=2e-40, Veff=1.0, rng=rng_default(54321), params={"evoparams": evo_params})
1205
+ for m in log:
1206
+ print(m)
1207
+ print("after trigger zs:", {k: zsout.get(k) for k in ("phi","tritstate","entropy","energy","curvature")})
1208
+ print()
1209
+ # Carbon synthesis demo
1210
+ res = ZSFCARBONSYNTHESISdemo(scale=None, clamp=False, autoscale=True, debug=args.debug)
1211
+ print("carbon synthesis result:", res)
1212
+ print()
1213
+ # TRIT distribution
1214
+ stats = unitpointevolutiondemo(Nsteps=2000, seed=42)
1215
+ counts = np.bincount(np.array(stats["trit"]) + 1, minlength=3)
1216
+ dist = counts / len(stats["trit"])
1217
+ print("TRIT distribution (-1/0/1):", dist)
1218
+ print()
1219
+ # Candidate search (optional)
1220
+ if args.search_candidates > 0:
1221
+ print(f"Searching {args.search_candidates} candidates (grid_scaling=False to preserve single-point baseline)...")
1222
+ cands = generatecandidates([SOURCE_A, SOURCE_B, SOURCE_C], RNG, args.search_candidates, exactcancel=args.exact_cancel, injmult=args.inj_mult, couplingmult=args.coupling_mult, grid_scaling=False)
1223
+ val = validate_candidates(cands, RNG, steps=500, runs=4, debug=args.debug)
1224
+ print("Candidate validation summary (top 6):")
1225
+ for v in val[:6]:
1226
+ print(v)
1227
+ print()
1228
+ # Regression test (optional)
1229
+ rt = None
1230
+ if args.regression_test:
1231
+ print("Running regression test to verify single-point parity...")
1232
+ rt = regression_test()
1233
+ print("Regression result:", rt)
1234
+ print()
1235
+ # Original grid simulation (optional)
1236
+ failed_grid = None
1237
+ if args.use_grid:
1238
+ print("Running original grid microcosm demo...")
1239
+ p = copy.deepcopy(BASE_PARAMS)
1240
+ p.update({"seed": args.seed})
1241
+ hist_grid, runtime, failed = run_simulation(p, use_evolved=True, verbose=args.debug)
1242
+ failed_grid = failed
1243
+ print("Original grid demo runtime:", runtime, "failed:", failed)
1244
+ print()
1245
+ # Original grid comparison (optional)
1246
+ if args.nruns > 0 and args.use_grid:
1247
+ print("Running original grid comparison harness...")
1248
+ run_comparison(nruns=args.nruns)
1249
+ print()
1250
+ # Fused grid comparison
1251
+ print("=== Fused ZSF-Microcosm Model Comparison Test ===")
1252
+ print(json.dumps({"seed": args.seed, "inj_mult": args.inj_mult, "grid_Nx": args.grid_Nx, "T_total": args.T_total, "nruns": args.nruns}, indent=2))
1253
+ run_fused_comparison(nruns=args.nruns)
1254
+ # Save a minimal result JSON
1255
+ result_out = {
1256
+ "single_point_final_phi": final_phi,
1257
+ "single_point_final_trit": final_trit,
1258
+ "carbon_strength_GPa": res["strengthGPa"],
1259
+ "regression_test_passed": rt["trit_match"] if args.regression_test else None,
1260
+ "original_grid_failed": failed_grid if args.use_grid else None
1261
+ }
1262
+ with open(args.result_save_path, "w", encoding="utf-8") as f:
1263
+ json.dump(result_out, f, indent=2)
1264
+ print("\n=== Simulation Completed ===")
1265
+ print(f"Result saved to: {args.result_save_path}")
1266
+
1267
+ if __name__ == "__main__":
1268
+ main()