""" ================================================================================ PHASE V: FRCMΠD PARAMETER MAPPING & 4-GRADIENT ENGINE (FULL EVALUATION) ================================================================================ Purpose: 1. Evaluate the explicitly defined Energy Functional, Hessian, and Evolution Equations (including torque and slip operators). 2. Perform rigorous 4-Gradient diagnostics (Symbolic vs. Finite Difference). 3. Execute the 6-step preservation protocol strictly upon gradient validation. 4. Run parameter sensitivity sweep with proper field updates. DATE = "2026-07-18" DEPENDENCIES: NumPy >= 1.20.0, Matplotlib >= 3.3.0, ipywidgets >= 7.6.0 ================================================================================ FULLY EVALUATED NUMERICAL EQUATIONS: Energy Functional: Ψ_B = 0.5*I2 + 0.5*I1^2 + 0.025*I1^4 + 0.005*||P||^2 Symbolic Gradients: dΨ/dPxx = I1 + 0.1*I1^3 + 1.01*Pxx dΨ/dPxy = 1.01*Pxy dΨ/dPyx = 1.01*Pyx dΨ/dPyy = I1 + 0.1*I1^3 + 1.01*Pyy Hessian Eigenvalues: {1.01, 1.01, 1.01, 3.01 + 0.6*I1^2} Evolution Equations (c_axis = 0.5): dUxx/dt = 0.25*∇²Pxx - 0.5*Pxx - 0.2*Pxx³ - 0.1*Ψ² - 0.2*Pxx*Λ² + 0.1*Pxx*MT*|∇S|² - Ω dUxy/dt = 0.25*∇²Pxy - 0.1*Pxy - 0.2*Pxx*Pxy - 0.2*Pxy*Λ² - 0.1*Pxy*MR*|∇Ψ|² dUyx/dt = 0.25*∇²Pyx - 0.1*Pyx - 0.2*Pyy*Pyx - 0.2*Pyx*Λ² - 0.1*Pyx*MR*|∇Ψ|² + Ω*Pyx + 0.1*Pyx*|∇I_torque| dUyy/dt = 0.25*∇²Pyy - 0.4*Pyy - 0.15*Pyy³ - 0.1*Pxx*Pyy - 0.2*Ψ²*Pyy + 0.1*Pyy*MC*|∇Λ|² ================================================================================ """ import numpy as np import matplotlib.pyplot as plt import warnings import sys import json import csv import datetime import os import shutil import itertools from IPython.display import display, clear_output try: from google.colab import files from google.colab import drive IN_COLAB = True except ImportError: IN_COLAB = False try: import ipywidgets as widgets except ImportError: raise ImportError("ipywidgets is missing. Please run '!pip install ipywidgets'.") warnings.filterwarnings('ignore') # ============================================================================ # CONSTANTS — RENAMED TO AVOID CONFUSION # ============================================================================ # Constitutive Coefficients (Candidate B) MU_CONSTITUTIVE = 1.0 # Shear modulus LAMBDA_CONSTITUTIVE = 1.0 # Linear volumetric coefficient KAPPA_CONSTITUTIVE = 0.1 # Quartic volumetric coefficient # Solver Coupling Coefficient KAPPA_COUPLING = 0.3 # Topological coupling (used in PDE) # Regularization Anchor (MANDATORY) LAMBDA_REG_DEFAULT = 0.01 # Numerical Anchors C_AXIS = 0.5 # Normalized causality limit PI_MAX = 5.9259 # Saturation anchor EPS = 1e-15 EPS2 = 1e-10 # Slip Operator Anchors MU_SLIP_ANCHOR = 0.45 PI_0_ANCHOR = 1.0 BETA_SCALE_ANCHOR = 1.2 # Evolution Coefficients BETA_0 = 0.5 GAMMA_0 = 0.2 ETA_0 = 0.2 M2_0 = 0.1 ALPHA_0 = 0.4 DELTA_0 = 0.15 KO_SIGMA_0 = 0.045 # ============================================================================ # EXPLICIT NUMERICAL EQUATIONS (FRCMΠD MODEL) # ============================================================================ def compute_energy_functional(Pxx, Pxy, Pyx, Pyy): """ Evaluates Psi_B with lambda_reg = 0.01 FULLY EVALUATED NUMERICAL EQUATION: Ψ_B = 0.5*(Pxx² + Pxy² + Pyx² + Pyy²) + 0.5*(Pxx + Pyy)² + 0.025*(Pxx + Pyy)⁴ + 0.005*(Pxx² + Pxy² + Pyx² + Pyy²) """ Pxx = np.asarray(Pxx, dtype=float) Pxy = np.asarray(Pxy, dtype=float) Pyx = np.asarray(Pyx, dtype=float) Pyy = np.asarray(Pyy, dtype=float) trP = Pxx + Pyy normP2 = Pxx**2 + Pxy**2 + Pyx**2 + Pyy**2 T1 = 0.5 * normP2 T2 = 0.5 * trP**2 T3 = 0.025 * trP**4 T4 = 0.005 * normP2 return T1 + T2 + T3 + T4 def compute_symbolic_gradients(Pxx, Pxy, Pyx, Pyy): """ Analytically derived gradients for the Energy Functional Psi_B. FULLY EVALUATED NUMERICAL EQUATION: dΨ/dPxx = (Pxx + Pyy) + 0.1*(Pxx + Pyy)^3 + 1.01*Pxx dΨ/dPxy = 1.01*Pxy dΨ/dPyx = 1.01*Pyx dΨ/dPyy = (Pxx + Pyy) + 0.1*(Pxx + Pyy)^3 + 1.01*Pyy """ trP = Pxx + Pyy dPxx = 1.01 * Pxx + 1.0 * trP + 0.1 * trP**3 dPyy = 1.01 * Pyy + 1.0 * trP + 0.1 * trP**3 dPxy = 1.01 * Pxy dPyx = 1.01 * Pyx return np.array([dPxx, dPxy, dPyx, dPyy]) def compute_hessian_eigenvalues(Pxx, Pyy): """ Eigenvalues of Hessian H_B with lambda_reg = 0.01. FULLY EVALUATED NUMERICAL EQUATION: {1.01, 1.01, 1.01, 3.01 + 0.6*(Pxx + Pyy)^2} """ I1 = Pxx + Pyy ev4 = 3.01 + 0.6 * (I1**2) return np.array([1.01, 1.01, 1.01, ev4]) def compute_slip_operators(grad_S_mag, grad_Lambda_mag): """ Evaluates both Option A (Hard Clipping) and Option B (Smooth Tanh). FULLY EVALUATED NUMERICAL EQUATION: Option A: Phi = clip(Phi_raw, 0.0, 5.0) Option B: Phi = 2.5 * (1 + tanh((Phi_raw - 2.5) / 1.5)) """ phi_raw = grad_S_mag / (grad_Lambda_mag + EPS2) # Option A: Hard Clipping phi_A = np.clip(phi_raw, 0.0, 5.0) # Option B: Smooth Tanh phi_B = 2.5 * (1.0 + np.tanh((phi_raw - 2.5) / 1.5)) return phi_A, phi_B def compute_laplacian(arr, dx=1.0): """Computes 5-point stencil Laplacian.""" arr = np.asarray(arr, dtype=float) lap = np.zeros_like(arr) if arr.ndim == 2 and arr.shape[0] >= 3 and arr.shape[1] >= 3: lap[1:-1, 1:-1] = (arr[2:, 1:-1] + arr[:-2, 1:-1] + arr[1:-1, 2:] + arr[1:-1, :-2] - 4.0 * arr[1:-1, 1:-1]) / (dx * dx) return lap def compute_gradient_magnitude(arr, dx=1.0): """Computes spatial gradient magnitude with EPS regularization.""" arr = np.asarray(arr, dtype=float) if arr.ndim == 2: gy, gx = np.gradient(arr, dx) return np.sqrt(gx**2 + gy**2 + EPS) return np.sqrt(arr**2 + EPS) # ============================================================================ # EVOLUTION EQUATIONS (FULLY EVALUATED — WITH TORQUE TERM) # ============================================================================ def compute_evolution_rates(Pxx, Pxy, Pyx, Pyy, del2_Pxx, del2_Pxy, del2_Pyx, del2_Pyy, Psi, Lambda, grad_S_mag, grad_Psi_mag, grad_Lambda_mag, grad_Itorque_mag, Omega, M_T=1.0, M_R=1.0, M_C=1.0, kappa=KAPPA_COUPLING): """ FULLY EVALUATED PDEs for dU/dt including the torque term on Pyx. COEFFICIENT DOCUMENTATION: - 0.25: Laplacian diffusion (c_axis^2, c_axis = 0.5) - 0.5: Quadratic potential (BETA) - 0.2: Quartic potential (GAMMA) and cross-coupling (KAPPA) - 0.1: Cross-coupling (KAPPA) - 0.4: Compression potential (ALPHA) - 0.15: Quartic compression (DELTA) - M_T/M_R/M_C: Modulatory operators """ # dUxx/dt: 0.25*∇²Pxx - 0.5*Pxx - 0.2*Pxx³ - 0.1*Ψ² - 0.2*Pxx*Λ² + 0.1*Pxx*MT*|∇S|² - Ω dUxx_dt = (0.25 * del2_Pxx - 0.5 * Pxx - 0.2 * (Pxx**3) - 0.1 * (Psi**2) - 0.2 * Pxx * (Lambda**2) + 0.1 * Pxx * M_T * (grad_S_mag**2) - Omega) # dUxy/dt: 0.25*∇²Pxy - 0.1*Pxy - 0.2*Pxx*Pxy - 0.2*Pxy*Λ² - 0.1*Pxy*MR*|∇Ψ|² dUxy_dt = (0.25 * del2_Pxy - 0.1 * Pxy - 0.2 * Pxx * Pxy - 0.2 * Pxy * (Lambda**2) - 0.1 * Pxy * M_R * (grad_Psi_mag**2)) # dUyx/dt: 0.25*∇²Pyx - 0.1*Pyx - 0.2*Pyy*Pyx - 0.2*Pyx*Λ² # - 0.1*Pyx*MR*|∇Ψ|² + Ω*Pyx + kappa*Pyx*|∇I_torque| dUyx_dt = (0.25 * del2_Pyx - 0.1 * Pyx - 0.2 * Pyy * Pyx - 0.2 * Pyx * (Lambda**2) - 0.1 * Pyx * M_R * (grad_Psi_mag**2) + Omega * Pyx + kappa * Pyx * grad_Itorque_mag) # dUyy/dt: 0.25*∇²Pyy - 0.4*Pyy - 0.15*Pyy³ - 0.1*Pxx*Pyy # - 0.2*Ψ²*Pyy + 0.1*Pyy*MC*|∇Λ|² dUyy_dt = (0.25 * del2_Pyy - 0.4 * Pyy - 0.15 * (Pyy**3) - 0.1 * Pxx * Pyy - 0.2 * (Psi**2) * Pyy + 0.1 * Pyy * M_C * (grad_Lambda_mag**2)) return dUxx_dt, dUxy_dt, dUyx_dt, dUyy_dt # ============================================================================ # ROBUST NUMERICAL UTILITIES # ============================================================================ def adaptive_fd_step(x): """Computes an adaptive step size based on machine epsilon.""" return np.sqrt(np.finfo(float).eps) * (1.0 + abs(x)) def stable_near_zero(x, tiny=1e-12): """Guards values against zero-division or instability at origin.""" return x if abs(x) > tiny else tiny * (1.0 if x >= 0 else -1.0) def sample_test_points(center=(1.0, 0.0, 0.0, 1.0), rng_seed=42, n_random=4): """Generates a representative sample set for gradient validation.""" np.random.seed(rng_seed) samples = [{'Pxx': center[0], 'Pxy': center[1], 'Pyx': center[2], 'Pyy': center[3]}] for _ in range(n_random): samples.append({ 'Pxx': float(np.random.normal(center[0], 0.5)), 'Pxy': float(np.random.normal(center[1], 0.5)), 'Pyx': float(np.random.normal(center[2], 0.5)), 'Pyy': float(np.random.normal(center[3], 0.5)) }) return samples # ============================================================================ # DIAGNOSTICS & TELEMETRY # ============================================================================ current_diagnostic_data = {} def run_gradient_diagnostics(samples=None, tol=1e-6): """ Validates symbolic gradients against adaptive FD across a sample set. Returns True only if the MAX L2 error across all samples is within tolerance. """ if samples is None: samples = sample_test_points() results = [] all_passed = True print("\n" + "="*60) print(" 4-GRADIENT DIAGNOSTIC GATE") print("="*60) for pt in samples: # Preprocess using stable guard p = {k: stable_near_zero(v) for k, v in pt.items()} # Adaptive FD eps = [adaptive_fd_step(p['Pxx']), adaptive_fd_step(p['Pxy']), adaptive_fd_step(p['Pyx']), adaptive_fd_step(p['Pyy'])] # Finite Difference Evaluation fd_grad = np.array([ (compute_energy_functional(p['Pxx'] + eps[0], p['Pxy'], p['Pyx'], p['Pyy']) - compute_energy_functional(p['Pxx'] - eps[0], p['Pxy'], p['Pyx'], p['Pyy'])) / (2 * eps[0]), (compute_energy_functional(p['Pxx'], p['Pxy'] + eps[1], p['Pyx'], p['Pyy']) - compute_energy_functional(p['Pxx'], p['Pxy'] - eps[1], p['Pyx'], p['Pyy'])) / (2 * eps[1]), (compute_energy_functional(p['Pxx'], p['Pxy'], p['Pyx'] + eps[2], p['Pyy']) - compute_energy_functional(p['Pxx'], p['Pxy'], p['Pyx'] - eps[2], p['Pyy'])) / (2 * eps[2]), (compute_energy_functional(p['Pxx'], p['Pxy'], p['Pyx'], p['Pyy'] + eps[3]) - compute_energy_functional(p['Pxx'], p['Pxy'], p['Pyx'], p['Pyy'] - eps[3])) / (2 * eps[3]) ]) sym_grad = compute_symbolic_gradients(p['Pxx'], p['Pxy'], p['Pyx'], p['Pyy']) l2_err = np.linalg.norm(sym_grad - fd_grad) max_err = np.max(np.abs(sym_grad - fd_grad)) if l2_err > tol: all_passed = False results.append({ 'pt': pt, 'l2_error': float(l2_err), 'max_error': float(max_err) }) status = "✓" if l2_err < tol else "✗" print(f" {status} Pxx={p['Pxx']:.3f}, Pxy={p['Pxy']:.3f}, " f"Pyx={p['Pyx']:.3f}, Pyy={p['Pyy']:.3f} | " f"L2={l2_err:.4e}") max_l2 = max([r['l2_error'] for r in results]) max_max = max([r['max_error'] for r in results]) global current_diagnostic_data current_diagnostic_data = { 'timestamp': datetime.datetime.now().isoformat(), 'samples_analyzed': len(samples), 'max_l2_error': max_l2, 'max_inf_error': max_max, 'gate_passed': all_passed, 'tolerance': tol, 'detailed_results': results } print("-"*60) print(f"Samples Analyzed: {len(samples)}") print(f"Max L2 Error: {max_l2:.4e} (Threshold: {tol})") print(f"Max Inf Error: {max_max:.4e}") print(f"STATUS: {'PASSED ✓' if all_passed else 'FAILED ✗'}") print("="*60) return all_passed # ============================================================================ # STABILITY SWEEP MODULE (COMPLETE — WITH FIELD UPDATES) # ============================================================================ def run_stability_sweep(param_grid, n_steps=5, grid_size=(32, 32)): """ Executes a parameter sensitivity sweep across the specified parameter space. CORRECTED: Proper field updates, parameter propagation, and diagnostics. """ print("\n" + "="*80) print(" STABILITY SWEEP — PARAMETER SENSITIVITY MAPPING") print("="*80) keys = list(param_grid.keys()) values = list(param_grid.values()) total_configs = np.prod([len(v) for v in values]) print(f"Parameters: {keys}") print(f"Total configurations: {total_configs}") print(f"Steps per config: {n_steps}") print("="*80 + "\n") combinations = list(itertools.product(*values)) results = [] for combo in combinations: config = dict(zip(keys, combo)) kappa = config.get('kappa', KAPPA_COUPLING) mu_slip = config.get('MU_SLIP', MU_SLIP_ANCHOR) print(f" Testing {config}...", end=" ") # Initialize fields y, x = np.indices(grid_size) center_y, center_x = grid_size[0] // 2, grid_size[1] // 2 r_sq = (x - center_x)**2 + (y - center_y)**2 Pxx = 0.8 * np.sin(x * 0.1) * np.cos(y * 0.1) + 0.2 Pxy = 0.4 * np.cos(r_sq * 0.001) Pyx = -0.3 * np.sin(r_sq * 0.001) Pyy = 0.7 * np.cos(x * 0.1) * np.sin(y * 0.1) + 0.3 S = 1.5 * np.exp(-r_sq / (2 * 20.0**2)) Lambda_field = 1.2 + 0.5 * np.sin(y * 0.05) dx = 25.6 / grid_size[0] dt = 0.1 * dx / C_AXIS stable = True max_update = 0.0 energy_history = [] min_eig_history = [] clip_count = 0 for step in range(n_steps): # Compute Laplacians lap_Pxx = compute_laplacian(Pxx, dx) lap_Pxy = compute_laplacian(Pxy, dx) lap_Pyx = compute_laplacian(Pyx, dx) lap_Pyy = compute_laplacian(Pyy, dx) # Compute energy and gradients Psi = compute_energy_functional(Pxx, Pxy, Pyx, Pyy) grad_S = compute_gradient_magnitude(S, dx) grad_Lambda = compute_gradient_magnitude(Lambda_field, dx) grad_Psi = compute_gradient_magnitude(Psi, dx) # Slip operator with mu_slip phi_raw = grad_S / (grad_Lambda + EPS2) phi = np.clip(phi_raw, 0.0, 5.0) clip_count += int(np.sum((phi_raw < 0) | (phi_raw > 5.0))) Theta = np.exp(-0.5 * (phi - 1.0)**2) Omega = mu_slip * Theta * (PI_0_ANCHOR * BETA_SCALE_ANCHOR - 1.0)**2 # Compute torque gradient I_torque = (Pxy + Pyx)**2 grad_torque = compute_gradient_magnitude(I_torque, dx) # Evolution rates (kappa passed explicitly) dUxx_dt, dUxy_dt, dUyx_dt, dUyy_dt = compute_evolution_rates( Pxx, Pxy, Pyx, Pyy, lap_Pxx, lap_Pxy, lap_Pyx, lap_Pyy, Psi, Lambda_field, grad_S, grad_Psi, grad_Lambda, grad_torque, Omega, M_T=1.0, M_R=1.0, M_C=1.0, kappa=kappa ) # UPDATE FIELDS — THIS WAS MISSING Pxx += dt * dUxx_dt Pxy += dt * dUxy_dt Pyx += dt * dUyx_dt Pyy += dt * dUyy_dt # Track actual update step_update = max( np.max(np.abs(dUxx_dt * dt)), np.max(np.abs(dUxy_dt * dt)), np.max(np.abs(dUyx_dt * dt)), np.max(np.abs(dUyy_dt * dt)) ) max_update = max(max_update, step_update) # Energy tracking energy = np.mean(Psi) energy_history.append(energy) # Hessian eigenvalues eigenvals = compute_hessian_eigenvalues(Pxx[center_y, center_x], Pyy[center_y, center_x]) min_eig_history.append(np.min(eigenvals)) # Stability checks if not np.isfinite(Pxx).all() or not np.isfinite(Pxy).all(): stable = False break if max_update > 10.0: stable = False break result = { 'config': config, 'kappa': kappa, 'mu_slip': mu_slip, 'stable': stable, 'max_update': float(max_update), 'energy_mean': float(np.mean(energy_history)) if energy_history else 0.0, 'energy_std': float(np.std(energy_history)) if energy_history else 0.0, 'min_eigenvalue_mean': float(np.mean(min_eig_history)) if min_eig_history else 0.0, 'clip_count': clip_count, 'n_steps': step + 1 if stable else step + 1, } results.append(result) status = "✓ STABLE" if stable else "✗ UNSTABLE" print(f"{status} (max_update={max_update:.4f}, κ={kappa:.2f}, μ_slip={mu_slip:.2f})") # Summary print("\n" + "="*80) print(" SWEEP SUMMARY") print("="*80) stable_count = sum(1 for r in results if r['stable']) print(f"Total configs: {len(results)}") print(f"Stable configs: {stable_count}/{len(results)}") if stable_count == len(results): print("⚠️ WARNING: All configurations stable. This may indicate:") print(" 1. Parameters are not reaching the solver") print(" 2. Timestep is too small") print(" 3. Diagnostic is insensitive") print("="*80) return results # ============================================================================ # 6-STEP PRESERVATION PROTOCOL # ============================================================================ def execute_4_gradient_engine(b): """Executes the 4-Gradient Engine with preservation.""" print("\n" + "="*80) print(" INITIATING 4 GRADIENT ENGINE: DIAGNOSTICS & PRESERVATION") print("="*80) # GATE CHECK if not run_gradient_diagnostics(): print("\n" + "="*80) print(" CRITICAL ERROR: Gradient Gate Failed. Preservation Aborted.") print(" No files will be saved. Fix gradients and retry.") print("="*80 + "\n") return # MOUNT DRIVE IF IN COLAB if IN_COLAB and not os.path.exists('/content/drive/MyDrive'): print("Mounting Google Drive for preservation...") drive.mount('/content/drive') timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") project_name = "FRCMpD_NumericalEval" colab_base = "/content" # STEP 1: SAVE TO WORKSPACE out_dir = f"output_{timestamp}" out_path = os.path.join(colab_base, out_dir) os.makedirs(out_path, exist_ok=True) json_file = os.path.join(out_path, f"{project_name}_{timestamp}.json") with open(json_file, 'w') as f: json.dump(current_diagnostic_data, f, indent=4) csv_file = os.path.join(out_path, f"{project_name}_{timestamp}.csv") with open(csv_file, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Metric', 'Value']) for key, value in current_diagnostic_data.items(): writer.writerow([key, str(value)]) txt_file = os.path.join(out_path, f"{project_name}_{timestamp}_log.txt") with open(txt_file, 'w') as f: f.write(f"--- 4-Gradient Diagnostic Output: {timestamp} ---\n") for k, v in current_diagnostic_data.items(): f.write(f"{k}: {v}\n") # STEP 2: CREATE ZIP zip_filename = f"{project_name}_{timestamp}.zip" zip_filepath = os.path.join(colab_base, zip_filename) shutil.make_archive(zip_filepath.replace('.zip', ''), 'zip', out_path) # STEP 3: BACKUP TO DRIVE drive_saved = False drive_out_path = None drive_zip_filepath = None if IN_COLAB and os.path.exists('/content/drive/MyDrive'): drive_base = f"/content/drive/MyDrive/{project_name}" drive_out_path = os.path.join(drive_base, out_dir) drive_zip_filepath = os.path.join(drive_base, zip_filename) try: os.makedirs(drive_out_path, exist_ok=True) for item in os.listdir(out_path): shutil.copy2(os.path.join(out_path, item), drive_out_path) shutil.copy2(zip_filepath, drive_zip_filepath) drive_saved = True except Exception: drive_saved = False # STEP 4: DOWNLOAD download_triggered = False if IN_COLAB: try: files.download(zip_filepath) download_triggered = True except Exception: download_triggered = False # STEP 5: VERIFY colab_exists = os.path.exists(out_path) and len(os.listdir(out_path)) >= 3 zip_exists = os.path.exists(zip_filepath) drive_exists = drive_saved and os.path.exists(drive_zip_filepath) if drive_zip_filepath else False # STEP 6: STATUS REPORT print("\n" + "="*80) print(" PRESERVATION PROTOCOL STATUS REPORT") print("="*80) print(f" ✓ Colab workspace saved: {colab_exists}") print(f" ✓ Google Drive backup saved: {drive_exists}") print(f" ✓ Download package created: {download_triggered}") print("-"*80) archive_size = os.path.getsize(zip_filepath) if zip_exists else 0 file_count = len(os.listdir(out_path)) if colab_exists else 0 # CORRECTED: Success logic for local vs Colab if IN_COLAB: success = colab_exists and drive_exists and download_triggered else: success = colab_exists and download_triggered status_str = "SUCCESS ONLY IF ALL BACKUPS EXIST" if success else "FAILED - PARTIAL PRESERVATION OCCURRED" print(f" STAGING DIRECTORY: {out_path}") print(f" GOOGLE DRIVE PATH: {drive_out_path if drive_saved else 'FAILED'}") print(f" MASTER ZIP PATH: {zip_filepath}") print(f" FILE COUNT: {file_count}") print(f" ARCHIVE SIZE: {archive_size} bytes") print(f" STATUS: {status_str}") print("="*80 + "\n") # ============================================================================ # UNIT TEST HARNESS # ============================================================================ def run_unit_test_harness(): """Verifies the gate logic before proceeding to full execution.""" print("\n" + "="*80) print(" UNIT TEST HARNESS") print("="*80) # Test 1: Single Point pt = {'Pxx': 0.2, 'Pxy': 0.1, 'Pyx': -0.1, 'Pyy': 0.3} passed_1 = run_gradient_diagnostics(samples=[pt], tol=1e-6) print(f"Test 1 (Single Point): {'✅ PASSED' if passed_1 else '❌ FAILED'}") # Test 2: Sample Set samples = sample_test_points() passed_2 = run_gradient_diagnostics(samples=samples, tol=1e-6) print(f"Test 2 (Samples): {'✅ PASSED' if passed_2 else '❌ FAILED'}") # Test 3: Preservation Abort (Force Failure) passed_3 = run_gradient_diagnostics(samples=[pt], tol=1e-20) print(f"Test 3 (Abort Check): {'✅ PASSED' if not passed_3 else '❌ FAILED (Abort failed)'}") print("="*80 + "\n") # ============================================================================ # UI FUNCTIONS # ============================================================================ def test_evolution_rates(b): """Fires a dummy calculation through the PDE evaluation function.""" clear_output(wait=True) display(ui) dUxx, dUxy, dUyx, dUyy = compute_evolution_rates( Pxx=1.0, Pxy=0.5, Pyx=0.5, Pyy=1.0, del2_Pxx=-0.1, del2_Pxy=0.0, del2_Pyx=0.0, del2_Pyy=-0.1, Psi=0.8, Lambda=1.2, grad_S_mag=0.5, grad_Psi_mag=0.3, grad_Lambda_mag=0.4, grad_Itorque_mag=0.9, Omega=0.05, kappa=KAPPA_COUPLING ) print("\n--- SAMPLE PDE EVALUATION ---") print(f"dUxx/dt = {dUxx:.4f}") print(f"dUxy/dt = {dUxy:.4f}") print(f"dUyx/dt = {dUyx:.4f} (Torque included)") print(f"dUyy/dt = {dUyy:.4f}") eigenvals = compute_hessian_eigenvalues(Pxx=1.0, Pyy=1.0) print(f"Hessian Eigenvalues: {eigenvals}") phi_A, phi_B = compute_slip_operators(grad_S_mag=2.0, grad_Lambda_mag=0.5) print(f"Slip Op A (Hard Clip): {phi_A:.4f}") print(f"Slip Op B (Smooth): {phi_B:.4f}") def run_diagnostics_ui(b): """Runs gradient diagnostics and displays results.""" clear_output(wait=True) display(ui) run_gradient_diagnostics() def run_sweep_ui(b): """Runs the stability sweep with proper field updates.""" clear_output(wait=True) display(ui) param_grid = { 'kappa': [0.01, 0.05, 0.1, 0.3, 0.5, 1.0], 'MU_SLIP': [0.01, 0.05, 0.1, 0.3, 0.5, 1.0], } results = run_stability_sweep(param_grid, n_steps=5, grid_size=(32, 32)) # Save results timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") with open(f"stability_sweep_{timestamp}.json", 'w') as f: json.dump(results, f, indent=4) print(f"\n💾 Results saved: stability_sweep_{timestamp}.json") # ============================================================================ # UI LAYOUT # ============================================================================ engine_button = widgets.Button( description='EXECUTE 4-GRADIENT ENGINE (SAVE & BACKUP)', button_style='danger', layout=widgets.Layout(width='28%', height='45px') ) engine_button.on_click(execute_4_gradient_engine) pde_test_button = widgets.Button( description='EVALUATE SAMPLE PDEs', button_style='info', layout=widgets.Layout(width='18%', height='45px') ) pde_test_button.on_click(test_evolution_rates) diag_button = widgets.Button( description='RUN GRADIENT DIAGNOSTICS', button_style='warning', layout=widgets.Layout(width='20%', height='45px') ) diag_button.on_click(run_diagnostics_ui) sweep_button = widgets.Button( description='RUN STABILITY SWEEP', button_style='primary', layout=widgets.Layout(width='30%', height='45px') ) sweep_button.on_click(run_sweep_ui) ui = widgets.HBox([engine_button, pde_test_button, diag_button, sweep_button]) # ============================================================================ # MAIN EXECUTION # ============================================================================ if __name__ == "__main__": print("="*80) print(" PHASE V: FULL NUMERICAL EQUATIONS & 4-GRADIENT ENGINE") print("="*80) print("") print("FULLY EVALUATED NUMERICAL EQUATIONS:") print(" Ψ_B = 0.5*I2 + 0.5*I1^2 + 0.025*I1^4 + 0.005*||P||^2") print(" dΨ/dPxx = I1 + 0.1*I1^3 + 1.01*Pxx") print(" dΨ/dPxy = 1.01*Pxy") print(" dΨ/dPyx = 1.01*Pyx") print(" dΨ/dPyy = I1 + 0.1*I1^3 + 1.01*Pyy") print(" Hessian Eigenvalues: {1.01, 1.01, 1.01, 3.01 + 0.6*I1^2}") print("") print("CONTROLS:") print(" • EXECUTE 4-GRADIENT ENGINE — Runs diagnostics, saves JSON/CSV/ZIP") print(" • EVALUATE SAMPLE PDEs — Tests evolution equations with torque term") print(" • RUN GRADIENT DIAGNOSTICS — Validates symbolic vs FD gradients") print(" • RUN STABILITY SWEEP — Parameter sensitivity mapping (FIXED)") print("="*80 + "\n") display(ui) """ ================================================================================ MODEL_B RUNTIME DATA EXPORT — WITH DOWNLOAD ================================================================================ Purpose: Capture all relevant workspace variables and save to JSON. Output: Console print + JSON file download. ================================================================================ """ import json import types import os import datetime try: from google.colab import files IN_COLAB = True except ImportError: IN_COLAB = False # ============================================================================ # 1. DEEP SERIALIZER (Handles circular refs, functions, classes) # ============================================================================ def deep_serialize(obj, visited=None): if visited is None: visited = set() obj_id = id(obj) if obj_id in visited: return "[Circular Reference]" if isinstance(obj, dict): visited.add(obj_id) res = {str(k): deep_serialize(v, visited) for k, v in obj.items()} visited.remove(obj_id) return res elif isinstance(obj, (list, tuple, set)): visited.add(obj_id) res = [deep_serialize(item, visited) for item in obj] visited.remove(obj_id) return res if isinstance(obj, (types.FunctionType, types.MethodType, type)): return f"[Executable Element: {obj.__name__}]" try: json.dumps(obj) return obj except (TypeError, ValueError): return str(obj) # ============================================================================ # 2. CAPTURE WORKSPACE DATA # ============================================================================ target_keywords = [ 'constant', 'global', 'operator', 'supporting', 'failure', 'environment', 'snapshot', 'verification', 'testing', 'initialization', 'lambda', 'regularization', 'model_b', 'prototype' ] workspace = globals() captured_data = {} for key, value in list(workspace.items()): # Skip Python internals if key.startswith('_') or key in ['In', 'Out', 'get_ipython', 'exit', 'quit', 'deep_serialize', 'target_keywords', 'workspace']: continue # Match keywords if any(kw in key.lower() for kw in target_keywords): captured_data[key] = deep_serialize(value) # ============================================================================ # 3. ADD METADATA # ============================================================================ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") export_data = { "metadata": { "timestamp": timestamp, "model": "Model B (Regularized)", "stage": "Stage 2", "n_variables_captured": len(captured_data), "colab_environment": IN_COLAB }, "variables": captured_data, "python_version": str(sys.version) if 'sys' in dir() else "Unknown", "numpy_version": str(np.__version__) if 'np' in dir() else "Unknown" } # ============================================================================ # 4. PRINT TO CONSOLE (Copy-paste ready) # ============================================================================ print("=" * 80) print(" MODEL_B RUNTIME DATA EXPORT FOR YOUR NOTES ") print("=" * 80) if not captured_data: print("\n[ALERT] No exact matching variable keywords found in current memory.") print("Listing all custom user variables currently in memory instead:\n") for key, value in list(workspace.items()): if not key.startswith('_') and key not in ['In', 'Out', 'deep_serialize']: print(f"-> {key}: {type(value).__name__}") else: print(f"\n✅ Captured {len(captured_data)} variables\n") print(json.dumps(export_data, indent=2, default=str)) print("=" * 80) print("📋 COPY THE JSON ABOVE AND PASTE INTO YOUR NOTES") print("=" * 80) # ============================================================================ # 5. SAVE TO FILE AND TRIGGER DOWNLOAD # ============================================================================ filename = f"model_b_export_{timestamp}.json" with open(filename, 'w') as f: json.dump(export_data, f, indent=2, default=str) print(f"\n💾 JSON file saved: {filename}") if IN_COLAB: try: files.download(filename) print("✅ Download triggered to your local machine") except Exception as e: print(f"⚠️ Download failed: {e}") print(f" File is still available at /content/{filename}") else: print(f" File is available at: {os.path.abspath(filename)}") print("=" * 80)

Popular posts from this blog

THE GOLDEN BALLROOM/BUNKER

Conceptual Summary #2: (∂t2​S−c2∇2S+βS3)=σ(x,t)⋅FR​(C[Ψ])

ICE PROUDLY ANNOUNCES NEW “ELITE” TASK FORCE COMMANDER JEREMY DEWITTE