| from __future__ import annotations |
|
|
| |
| """ |
| Bi‑Coupled Recursive Coherence Renewal (CR²BC) — clean Python skeleton |
| --------------------------------------------------------------------- |
| A faithful, runnable reconstruction of your mirrored/palette‑swapped |
| spec, organized into modular classes with clear type hints. |
| |
| Major pieces |
| ============ |
| - FrequencyBand, StreamType: enums |
| - SpatialPosition: geometry helpers |
| - ChainComponent: per‑band chain observation |
| - AuditResult: integrity/audit metrics |
| - RenewalState: scratchpad for invariants & counters |
| - UniverseCoherenceConfig: global thresholds & constants |
| - FrequencyField: spatial grid and wave synthesis |
| - QuantumPostProcessor: feature extraction & Hamiltonian terms |
| - CoherenceIntegrityAuditor: produces AuditResult |
| - CognitiveRenewalEngine: renew/mix priors Π and step κ |
| - UniverseCoherenceSystem: orchestration, simulation, save/load, viz |
| |
| This module is intentionally self‑contained: numpy, matplotlib only. |
| The maths follows your notes: per‑band envelopes κ_d, phases φ_d, |
| spatial propagation with k = 2π f / c, cross‑band & temporal coupling, |
| and an audit that decides whether to accept the reconstruction. |
| |
| You can import this file and call `demo_complete_workflow()` to see the |
| end‑to‑end process. |
| """ |
|
|
| from dataclasses import dataclass, field |
| from enum import Enum |
| from typing import Dict, List, Tuple, Optional, Any |
| from datetime import datetime |
| import logging |
| import math |
| import json |
| import numpy as np |
| import matplotlib.pyplot as plt |
|
|
| |
| logging.basicConfig(level=logging.INFO, |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
| |
| class FrequencyBand(Enum): |
| DELTA = 'delta' |
| THETA = 'theta' |
| ALPHA = 'alpha' |
| BETA = 'beta' |
| GAMMA = 'gamma' |
|
|
| class StreamType(Enum): |
| TYPE_I = "Type I: Return Without Loss" |
| TYPE_II = "Type II: Return With Loss" |
| TYPE_III = "Type III: Unverifiable" |
|
|
| |
| @dataclass |
| class SpatialPosition: |
| x: float |
| y: float |
| m: int |
| n: int |
|
|
| def distance_to(self, other: 'SpatialPosition') -> float: |
| return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) |
|
|
| def radius(self) -> float: |
| return math.sqrt(self.x ** 2 + self.y ** 2) |
|
|
| def angle(self) -> float: |
| return math.atan2(self.y, self.x) |
|
|
| @dataclass |
| class ChainComponent: |
| band: FrequencyBand |
| positions: List[SpatialPosition] |
| coherence: float |
| phase_std: float |
|
|
| @dataclass |
| class AuditResult: |
| d_kappa: float |
| tau_R: float |
| D_C: float |
| D_w: float |
| R: float |
| s: float |
| I: float |
| stream_type: StreamType |
| audit_pass: bool |
| details: Dict[str, Any] = field(default_factory=dict) |
|
|
| @dataclass |
| class RenewalState: |
| kappa_sequential: Dict[FrequencyBand, float] |
| Pi_invariant: Dict[FrequencyBand, float] |
| alpha: float |
| timestamp: float |
| release_count: int = 0 |
|
|
| |
| class UniverseCoherenceConfig: |
| SPATIAL_GRID_M = 8 |
| SPATIAL_GRID_N = 8 |
| SPATIAL_UNIT = 0.1 |
| PROPAGATION_SPEED = 1.0 |
|
|
| COHERENCE_THRESH = 0.3 |
| PHASE_COHERENCE_THRESH = 0.6 |
| MAX_RECON_ITERS = 200 |
| CONVERGENCE_TOL = 0.01 |
|
|
| AUDIT_TOLERANCE = 0.005 |
| TYPE_I_THRESHOLD = 1e-9 |
|
|
| RELEASE_THRESH = 0.3 |
| RENEWAL_TIME_CONSTANT = 3.0 |
| ALPHA_DEFAULT = 0.6 |
|
|
| EMERGENCY_ESCAPE_THRESH = 0.05 |
| MAX_OUTPUT_DURATION = 500 |
|
|
| BAND_FREQUENCIES = { |
| FrequencyBand.DELTA: 3.0, |
| FrequencyBand.THETA: 7.0, |
| FrequencyBand.ALPHA: 10.0, |
| FrequencyBand.BETA: 30.0, |
| FrequencyBand.GAMMA: 75.0, |
| } |
|
|
| |
| class FrequencyField: |
| def __init__(self, M: int = UniverseCoherenceConfig.SPATIAL_GRID_M, |
| N: int = UniverseCoherenceConfig.SPATIAL_GRID_N): |
| self.M = M |
| self.N = N |
| self.positions = self._init_positions() |
| self._spatial_cache: Dict[Tuple[int, int, int, int, str, str], float] = {} |
|
|
| def _init_positions(self) -> List[SpatialPosition]: |
| pos: List[SpatialPosition] = [] |
| for m in range(-self.M, self.M + 1): |
| for n in range(-self.N, self.N + 1): |
| x = m * UniverseCoherenceConfig.SPATIAL_UNIT |
| y = n * UniverseCoherenceConfig.SPATIAL_UNIT |
| pos.append(SpatialPosition(x, y, m, n)) |
| return pos |
|
|
| def encode(self, |
| kappa_bands: Dict[FrequencyBand, float], |
| phi_bands: Dict[FrequencyBand, float], |
| timestamp: float) -> np.ndarray: |
| bands = list(FrequencyBand) |
| num_bands = len(bands) |
| cube = np.zeros((2 * self.M + 1, 2 * self.N + 1, num_bands), dtype=complex) |
|
|
| for pos in self.positions: |
| r = pos.radius() |
| atten = np.exp(-r / (self.M * UniverseCoherenceConfig.SPATIAL_UNIT)) |
|
|
| for idx, band in enumerate(bands): |
| omega = UniverseCoherenceConfig.BAND_FREQUENCIES[band] |
| k = 2 * math.pi * omega / UniverseCoherenceConfig.PROPAGATION_SPEED |
| phase_shift = k * r |
| total_phase = phi_bands[band] - phase_shift |
| amp = atten * kappa_bands[band] |
| cube[pos.m + self.M, pos.n + self.N, idx] = amp * np.exp(1j * total_phase) |
|
|
| logger.info("Encoded cube: shape=%s, mean_magnitude=%.3f", |
| cube.shape, np.mean(np.abs(cube))) |
| return cube |
|
|
| def spatial_coupling(self, |
| p1: SpatialPosition, p2: SpatialPosition, |
| b1: FrequencyBand, b2: FrequencyBand) -> float: |
| key = (p1.m, p1.n, p2.m, p2.n, b1.value, b2.value) |
| if key in self._spatial_cache: |
| return self._spatial_cache[key] |
|
|
| dist = p1.distance_to(p2) |
| spatial_factor = np.exp(-dist / UniverseCoherenceConfig.SPATIAL_UNIT) |
|
|
| freq_diff = abs(UniverseCoherenceConfig.BAND_FREQUENCIES[b1] - |
| UniverseCoherenceConfig.BAND_FREQUENCIES[b2]) |
| freq_factor = np.exp(-freq_diff / 10.0) |
|
|
| coupling = float(spatial_factor * freq_factor) |
| self._spatial_cache[key] = coupling |
| return coupling |
|
|
| |
| class QuantumPostProcessor: |
| def __init__(self, field: FrequencyField): |
| self.field = field |
| self.embeddings: Dict[FrequencyBand, List[SpatialPosition]] = {} |
| self.H_s: Dict[FrequencyBand, complex] = {} |
| self.F_s: Dict[Tuple[FrequencyBand, FrequencyBand], float] = {} |
|
|
| def create_embeddings(self, cube: np.ndarray, threshold: float = 1e-6 |
| ) -> Dict[FrequencyBand, List[SpatialPosition]]: |
| emb: Dict[FrequencyBand, List[SpatialPosition]] = {} |
| bands = list(FrequencyBand) |
| for b_idx, band in enumerate(bands): |
| significant: List[SpatialPosition] = [] |
| for pos in self.field.positions: |
| amp = np.abs(cube[pos.m + self.field.M, pos.n + self.field.N, b_idx]) |
| if amp > threshold: |
| significant.append(pos) |
| emb[band] = significant |
| logger.debug("Band %s: %d significant positions", band.value, len(significant)) |
| self.embeddings = emb |
| return emb |
|
|
| def identify_broken_chains(self, |
| kappa_now: Dict[FrequencyBand, float], |
| cube: np.ndarray |
| ) -> Tuple[List[ChainComponent], Dict[FrequencyBand, float]]: |
| broken: List[ChainComponent] = [] |
| intact: Dict[FrequencyBand, float] = {} |
|
|
| for band in FrequencyBand: |
| k = kappa_now[band] |
| if k > UniverseCoherenceConfig.COHERENCE_THRESH: |
| phases: List[float] = [] |
| b_idx = list(FrequencyBand).index(band) |
| for pos in self.embeddings.get(band, []): |
| ph = np.angle(cube[pos.m + self.field.M, pos.n + self.field.N, b_idx]) |
| phases.append(ph) |
| phase_std = float(np.std(phases)) if phases else math.pi |
| if phase_std < UniverseCoherenceConfig.PHASE_COHERENCE_THRESH: |
| comp = ChainComponent(band, self.embeddings.get(band, []), k, phase_std) |
| broken.append(comp) |
| logger.info("Broken chain: %s (k=%.3f, phase_std=%.3f)", band.value, k, phase_std) |
| else: |
| intact[band] = k |
| else: |
| intact[band] = k |
| return broken, intact |
|
|
| def compute_postprocess_hamiltonian(self, |
| broken: List[ChainComponent], |
| intact_k: Dict[FrequencyBand, float], |
| cube: np.ndarray) -> None: |
| self.H_s.clear(); self.F_s.clear() |
| for comp in broken: |
| band = comp.band |
| b_idx = list(FrequencyBand).index(band) |
| H_val = 0+0j |
| for pos in comp.positions: |
| H_val += cube[pos.m + self.field.M, pos.n + self.field.N, b_idx] |
| self.H_s[band] = H_val |
|
|
| for in_band, in_val in intact_k.items(): |
| coupling_strength = 0.0 |
| for p1 in comp.positions: |
| for p2 in self.embeddings.get(in_band, []): |
| coupling_strength += self.field.spatial_coupling(p1, p2, band, in_band) |
| self.F_s[(band, in_band)] = coupling_strength |
| logger.info("Postprocess Hamiltonian: %d diag terms, %d off‑diag", |
| len(self.H_s), len(self.F_s)) |
|
|
| def reconstruct_broken_chains(self, |
| broken: List[ChainComponent], |
| intact_k: Dict[FrequencyBand, float]) -> Dict[FrequencyBand, float]: |
| recon = intact_k.copy() |
| for comp in broken: |
| |
| H_mag = abs(self.H_s.get(comp.band, 0.0)) |
| cross = 0.0 |
| for (b_from, b_to), v in self.F_s.items(): |
| if b_from == comp.band: |
| cross += v * intact_k.get(b_to, 0.0) |
| field_val = H_mag + cross |
| new_val = 1.0 / (1.0 + math.exp(-field_val)) |
| recon[comp.band] = new_val |
| return recon |
|
|
| class CoherenceIntegrityAuditor: |
| def audit(self, |
| original_k: Dict[FrequencyBand, float], |
| recon_k: Dict[FrequencyBand, float], |
| t_original: float, t_recon: float, |
| cube: np.ndarray) -> AuditResult: |
| d_kappa_per_band = {b: recon_k[b] - original_k[b] for b in FrequencyBand} |
| d_kappa_avg = float(np.mean(list(d_kappa_per_band.values()))) |
|
|
| tau_R = abs(t_recon - t_original) |
| D_C = float(np.std(list(d_kappa_per_band.values()))) |
| D_w = float(np.linalg.norm(np.abs(cube))) |
| R = self._return_stability(original_k, recon_k) |
|
|
| budget_check = R * tau_R - (D_w + D_C) |
| s = R * tau_R - (d_kappa_avg + D_w + D_C) |
| I = float(np.exp(d_kappa_avg)) |
|
|
| if abs(s) > UniverseCoherenceConfig.AUDIT_TOLERANCE: |
| stream_type = StreamType.TYPE_I if abs(d_kappa_avg) > UniverseCoherenceConfig.TYPE_I_THRESHOLD else StreamType.TYPE_II |
| passed = True |
| else: |
| stream_type = StreamType.TYPE_III |
| passed = False |
|
|
| details = { |
| 'd_kappa_per_band': {b.value: v for b, v in d_kappa_per_band.items()}, |
| 'budget_check': budget_check, |
| 't_original': t_original, |
| 't_recon': t_recon, |
| } |
| logger.info("Audit: %s, Δκ=%.3e, s=%.6f, pass=%s", stream_type.value, d_kappa_avg, s, passed) |
| return AuditResult(d_kappa_avg, tau_R, D_C, D_w, R, s, I, stream_type, passed, details) |
|
|
| @staticmethod |
| def _return_stability(original_k: Dict[FrequencyBand, float], |
| recon_k: Dict[FrequencyBand, float]) -> float: |
| ratios: List[float] = [] |
| for b in FrequencyBand: |
| o = original_k[b] |
| if o > 0: |
| r = recon_k[b] / o |
| ratios.append(max(0.0, min(3.0, r))) |
| return float(np.mean(ratios)) if ratios else 0.0 |
|
|
| |
| class CognitiveRenewalEngine: |
| def __init__(self, alpha: float = UniverseCoherenceConfig.ALPHA_DEFAULT): |
| self.alpha = alpha |
| self.Pi: Optional[Dict[FrequencyBand, float]] = None |
| self.release_history: List[Dict[str, Any]] = [] |
| self.renewal_history: List[Dict[str, Any]] = [] |
|
|
| def init_invariant_field(self, kappa_init: Dict[FrequencyBand, float]) -> None: |
| self.Pi = kappa_init.copy() |
| logger.info("Invariant Π initialized: mean κ=%.3f", float(np.mean(list(self.Pi.values())))) |
|
|
| def update_sequential_state(self, kappa_now: Dict[FrequencyBand, float], dt: float) -> Dict[FrequencyBand, float]: |
| k_next: Dict[FrequencyBand, float] = {} |
| for b in FrequencyBand: |
| d_k = self.alpha * (1.0 - kappa_now[b]) |
| k_val = max(0.0, min(1.0, kappa_now[b] + d_k * dt)) |
| k_next[b] = k_val |
| return k_next |
|
|
| def update_invariant_field(self, kappa_now: Dict[FrequencyBand, float], beta: float = 0.1) -> None: |
| if self.Pi is None: |
| self.init_invariant_field(kappa_now) |
| return |
| for b in FrequencyBand: |
| self.Pi[b] = (1.0 - beta) * self.Pi[b] + beta * kappa_now[b] |
| logger.info("Π updated β=%.3f, mean Π=%.3f", beta, float(np.mean(list(self.Pi.values())))) |
|
|
| def check_release_event(self, kappa_now: Dict[FrequencyBand, float], thresh: float = UniverseCoherenceConfig.RELEASE_THRESH) -> bool: |
| m = min(kappa_now.values()) |
| if m > thresh: |
| self.release_history.append({ |
| 'timestamp': datetime.now().isoformat(), |
| 'min_kappa': m, |
| 'kappa_state': {b.value: k for b, k in kappa_now.items()}, |
| }) |
| logger.warning("Release event: min κ=%.3f > %.3f", m, thresh) |
| return True |
| return False |
|
|
| def perform_renewal(self, kappa_observed: Dict[FrequencyBand, float], rho: float = 0.5, novelty: float = 0.1) -> Dict[FrequencyBand, float]: |
| if self.Pi is None: |
| logger.warning("Cannot renew: Π not initialized") |
| return kappa_observed |
| renewed: Dict[FrequencyBand, float] = {} |
| rng = np.random.default_rng() |
| for b in FrequencyBand: |
| baseline = 0.6 |
| xi = rng.normal(0.0, novelty) |
| val = rho * self.Pi[b] + (1.0 - rho) * baseline + xi |
| renewed[b] = max(0.0, min(1.0, val)) |
| self.renewal_history.append({ |
| 'timestamp': datetime.now().isoformat(), |
| 'kappa_before': {b.value: kappa_observed[b] for b in FrequencyBand}, |
| 'kappa_after': {b.value: renewed[b] for b in FrequencyBand}, |
| 'Pi_state': {b.value: self.Pi[b] for b in FrequencyBand}, |
| }) |
| logger.info("Renewal: mean κ before=%.3f, after=%.3f", |
| float(np.mean(list(kappa_observed.values()))), |
| float(np.mean(list(renewed.values())))) |
| return renewed |
|
|
| |
| class UniverseCoherenceSystem: |
| def __init__(self, M: int = UniverseCoherenceConfig.SPATIAL_GRID_M, |
| N: int = UniverseCoherenceConfig.SPATIAL_GRID_N, |
| alpha: float = UniverseCoherenceConfig.ALPHA_DEFAULT): |
| self.field = FrequencyField(M, N) |
| self.post = QuantumPostProcessor(self.field) |
| self.auditor = CoherenceIntegrityAuditor() |
| self.renewal = CognitiveRenewalEngine(alpha) |
|
|
| self.current_cube: Optional[np.ndarray] = None |
| self.meta: Dict[str, Any] = {} |
| self.system_history: List[Dict[str, Any]] = [] |
| logger.info("Universe Coherence System initialized") |
|
|
| def encode_state(self, |
| kappa_bands: Dict[FrequencyBand, float], |
| phi_bands: Dict[FrequencyBand, float], |
| t: float) -> np.ndarray: |
| cube = self.field.encode(kappa_bands, phi_bands, t) |
| self.current_cube = cube |
| self.meta = { |
| 'timestamp': t, |
| 'original_kappa': kappa_bands.copy(), |
| 'original_phi': phi_bands.copy(), |
| 'created_at': datetime.now().isoformat(), |
| } |
| logger.info("State encoded into cube at t=%.1f", t) |
| return cube |
|
|
| def handle_bicoherence(self, |
| kappa_now: Dict[FrequencyBand, float], |
| t: float, |
| emergency_mode: bool = False) -> Optional[Dict[FrequencyBand, float]]: |
| if min(kappa_now.values()) > UniverseCoherenceConfig.EMERGENCY_ESCAPE_THRESH or emergency_mode: |
| logger.critical("EMERGENCY ESCAPE: min κ=%.3f", min(kappa_now.values())) |
| return None |
|
|
| if not self.renewal.check_release_event(kappa_now): |
| logger.debug("No release event – steady state") |
| return kappa_now |
|
|
| logger.info("=" * 80) |
| logger.info("DECOHERENCE HANDLING INITIATED") |
| logger.info("=" * 80) |
|
|
| if self.current_cube is None: |
| logger.error("No cube available for reconstruction") |
| return None |
|
|
| self.post.create_embeddings(self.current_cube) |
| broken, intact = self.post.identify_broken_chains(kappa_now, self.current_cube) |
|
|
| if len(broken) == 0: |
| logger.info("No broken chains — applying renewal only") |
| recon = self.renewal.perform_renewal(kappa_now) |
| return recon |
|
|
| logger.info("Broken chains: %s", [c.band.value for c in broken]) |
| logger.info("Intact bands: %s", list(b.value for b in intact.keys())) |
|
|
| self.post.compute_postprocess_hamiltonian(broken, intact, self.current_cube) |
| recon = self.post.reconstruct_broken_chains(broken, intact) |
| logger.info("Reconstruction complete: mean κ=%.3f", float(np.mean(list(recon.values())))) |
|
|
| audit = self.auditor.audit(self.meta['original_kappa'], recon, self.meta['timestamp'], t, self.current_cube) |
| logger.info("Audit stream type: %s", audit.stream_type.value) |
|
|
| if audit.audit_pass: |
| self.renewal.update_invariant_field(recon) |
| logger.info("✓ Renewal complete — Π updated") |
| self.system_history.append({ |
| 'timestamp': t, |
| 'event': 'successful_renewal', |
| 'kappa_before': {b.value: kappa_now[b] for b in FrequencyBand}, |
| 'kappa_after': {b.value: recon[b] for b in FrequencyBand}, |
| 'audit': audit.__dict__, |
| 'broken_bands': [c.band.value for c in broken], |
| }) |
| return recon |
| else: |
| logger.error("✗ Audit FAILED — emergency fallback activated") |
| self.system_history.append({ |
| 'timestamp': t, |
| 'event': 'audit_failure_fallback', |
| 'kappa_before': {b.value: kappa_now[b] for b in FrequencyBand}, |
| 'audit': audit.__dict__, |
| 'broken_bands': [c.band.value for c in broken], |
| }) |
| return None |
|
|
| |
| def simulate_coherence_dynamics(self, duration: float = 20.0, dt: float = 0.1, noise_level: float = 0.05) -> List[Dict[str, Any]]: |
| time_steps = int(duration / dt) |
| history: List[Dict[str, Any]] = [] |
|
|
| kappa_base = { |
| FrequencyBand.DELTA: 0.65, |
| FrequencyBand.THETA: 0.68, |
| FrequencyBand.ALPHA: 0.85, |
| FrequencyBand.BETA: 0.66, |
| FrequencyBand.GAMMA: 0.90, |
| } |
| phi_base = { |
| FrequencyBand.DELTA: 0.0, |
| FrequencyBand.THETA: 0.3, |
| FrequencyBand.ALPHA: 0.6, |
| FrequencyBand.BETA: 1.0, |
| FrequencyBand.GAMMA: 0.6, |
| } |
|
|
| k_now = kappa_base.copy() |
| phi_now = phi_base.copy() |
|
|
| for i in range(time_steps): |
| t = i * dt |
| if i == 0: |
| self.encode_state(k_now, phi_now, t) |
| self.renewal.init_invariant_field(k_now) |
|
|
| if 8.0 <= t <= 9.0: |
| |
| rng = np.random.default_rng() |
| k_now = { |
| FrequencyBand.DELTA: 0.55 + noise_level * rng.random(), |
| FrequencyBand.THETA: 0.58 + noise_level * rng.random(), |
| FrequencyBand.ALPHA: 0.83 + noise_level * rng.random(), |
| FrequencyBand.BETA: 0.55 + noise_level * rng.random(), |
| FrequencyBand.GAMMA: 0.70 + noise_level * rng.random(), |
| } |
| else: |
| k_now = self.renewal.update_sequential_state(k_now, dt) |
| rng = np.random.default_rng() |
| for b in FrequencyBand: |
| k_now[b] = max(0.0, min(1.0, k_now[b] + noise_level * (rng.random() - 0.5))) |
|
|
| recon = self.handle_bicoherence(k_now, t) |
| if recon is not None: |
| k_now = recon |
|
|
| history.append({ |
| 'timestamp': t, |
| 'kappa_state': {b.value: k_now[b] for b in FrequencyBand}, |
| 'reconstructed': recon is not None, |
| }) |
| return history |
|
|
| def visualize_coherence_dynamics(self, history: List[Dict[str, Any]]) -> None: |
| times = [e['timestamp'] for e in history] |
| series: Dict[FrequencyBand, List[float]] = {b: [] for b in FrequencyBand} |
| recon_flags = [e['reconstructed'] for e in history] |
| for e in history: |
| for b in FrequencyBand: |
| series[b].append(e['kappa_state'][b.value]) |
|
|
| fig, ax1 = plt.subplots(1, 1, figsize=(14, 6)) |
| colors = { |
| 'delta': 'blue', 'theta': 'green', 'alpha': 'red', |
| 'beta': 'orange', 'gamma': 'purple' |
| } |
| for b in FrequencyBand: |
| ax1.plot(times, series[b], label=b.value, color=colors[b.value], linewidth=2) |
| ax1.axhline(y=UniverseCoherenceConfig.RELEASE_THRESH, color='red', linestyle='--', alpha=0.5, label='Release Threshold') |
| ax1.axvspan(8.0, 9.0, alpha=0.15, color='gray', label='Decoherence Event') |
| ax1.set_ylabel('Coherence κ') |
| ax1.set_title('Neural Coherence Dynamics with Bi‑Coupled Recovery') |
| ax1.legend(); ax1.grid(True, alpha=0.3) |
|
|
| |
| ax2 = ax1.twinx() |
| recon_times = [t for t, f in zip(times, recon_flags) if f] |
| if recon_times: |
| ax2.plot(recon_times, np.ones_like(recon_times), 'ko', markersize=6, label='Recovery Events') |
| ax2.set_ylabel('Recovery Events') |
| ax2.set_ylim(0.6, 1.4) |
| plt.tight_layout() |
| plt.show() |
|
|
| |
| def save_system_state(self, filepath: str) -> None: |
| state = { |
| 'current_cube': self.current_cube.tolist() if self.current_cube is not None else None, |
| 'meta': self.meta, |
| 'system_history': self.system_history, |
| 'release_history': self.renewal.release_history, |
| 'renewal_history': self.renewal.renewal_history, |
| 'Pi': {b.value: float(self.renewal.Pi[b]) for b in FrequencyBand} if self.renewal.Pi else None, |
| } |
| with open(filepath, 'w') as f: |
| json.dump(state, f, indent=2) |
| logger.info("System state saved to %s", filepath) |
|
|
| def load_system_state(self, filepath: str) -> None: |
| with open(filepath, 'r') as f: |
| state = json.load(f) |
| self.current_cube = np.array(state['current_cube'], dtype=complex) if state['current_cube'] is not None else None |
| self.meta = state['meta'] |
| self.system_history = state['system_history'] |
| self.renewal.release_history = state['release_history'] |
| self.renewal.renewal_history = state['renewal_history'] |
| if state['Pi'] is not None: |
| self.renewal.Pi = {FrequencyBand(k): float(v) for k, v in state['Pi'].items()} |
| logger.info("System state loaded from %s", filepath) |
|
|
| |
| def demo_complete_workflow() -> None: |
| print("=" * 60) |
| print("QUANTUM‑INSPIRED NEURAL COHERENCE RECOVERY — COMPLETE WORKFLOW") |
| print("=" * 60) |
|
|
| sys = UniverseCoherenceSystem(M=8, N=8, alpha=0.6) |
| hist = sys.simulate_coherence_dynamics(duration=20.0, dt=0.1, noise_level=0.04) |
|
|
| successful = sum(1 for e in sys.system_history if e['event'] == 'successful_renewal') |
| total = len(sys.system_history) |
|
|
| print("\nWorkflow Results:") |
| print(f"Coherence events processed: {len(hist)}") |
| print(f"Recovery attempts: {total}") |
| print(f"Successful recoveries: {successful}") |
| print(f"Success rate: {100.0 * successful / total:.1f}%" if total > 0 else "N/A") |
|
|
| |
| sys.visualize_coherence_dynamics(hist) |
| sys.save_system_state('coherence_system_state.json') |
|
|
| print("\nSystem state saved to 'coherence_system_state.json'") |
| print("Visualization rendered.") |
| print("=" * 60) |
|
|
|
|
| if __name__ == "__main__": |
| demo_complete_workflow() |
|
|