import os import sys import html import subprocess from pathlib import Path import numpy as np import gradio as gr try: import spaces gpu_task = spaces.GPU except Exception: def gpu_task(fn): return fn BASE_DIR = Path(__file__).resolve().parent if str(BASE_DIR) not in sys.path: sys.path.insert(0, str(BASE_DIR)) from quantum_co_processor.q_navigation_engine import ( ObstaclePolygon, QUAVTrajectoryPlanner, PQCQuantumRLAttitudeController, RelativisticSpacetimeQFIEstimator, ) UI_DIR = BASE_DIR / "ui" BUILD_DIR = Path("/tmp/qsnasb_build") BUILD_DIR.mkdir(parents=True, exist_ok=True) L1_BIN = BUILD_DIR / "quantum_core_driver" L2_BIN = BUILD_DIR / "swarm_wci_dtn_node" def compile_cpp_layers() -> str: """Compiles C++20 Layer 1 Firmware and Layer 2 Swarm Middleware on startup.""" logs = [] targets = [ (BASE_DIR / "firmware" / "quantum_core_driver.cpp", L1_BIN, "Layer 1 Firmware"), (BASE_DIR / "middleware" / "swarm_wci_dtn_node.cpp", L2_BIN, "Layer 2 Middleware"), ] for src, out_bin, label in targets: if not src.exists(): logs.append(f"[WARN] {label} source not found at {src}") continue res = subprocess.run( ["g++", "-std=c++20", "-O3", str(src), "-o", str(out_bin)], capture_output=True, text=True, ) if res.returncode == 0: logs.append(f"[OK] Compiled {label} -> {out_bin}") else: logs.append(f"[ERR] {label} build failed:\n{res.stderr}") return "\n".join(logs) BUILD_STATUS = compile_cpp_layers() def render_embedded_html(filename: str, height_px: int) -> str: """Embeds a standalone HTML5 simulation module inside a sandboxed srcdoc iframe.""" html_path = UI_DIR / filename if not html_path.exists(): return ( f'
Missing UI file: {html_path}
' ) raw_html = html_path.read_text(encoding="utf-8") escaped_html = html.escape(raw_html, quote=True) return ( f'' ) def run_stack_computation(buffer_scale: float, pqc_layers: int, radial_km: float): """Executes Layer 1 C++20, Layer 2 C++20, and Layer 3 Python Quantum Co-Processor.""" l1_out = ( subprocess.run([str(L1_BIN)], capture_output=True, text=True, timeout=5).stdout.strip() if L1_BIN.exists() else f"Layer 1 binary unavailable.\n{BUILD_STATUS}" ) l2_out = ( subprocess.run([str(L2_BIN)], capture_output=True, text=True, timeout=5).stdout.strip() if L2_BIN.exists() else f"Layer 2 binary unavailable.\n{BUILD_STATUS}" ) obstacles = [ ObstaclePolygon( center_xy=(500.0, 200.0), radius_m=120.0, buffer_scale_sx_sy=(buffer_scale, buffer_scale), ) ] planner = QUAVTrajectoryPlanner(start_xy=(0.0, 0.0), end_xy=(1000.0, 400.0), obstacles=obstacles) candidates = [ [(0.0, 0.0), (500.0, 210.0), (1000.0, 400.0)], [(0.0, 0.0), (480.0, 460.0), (1000.0, 400.0)], [(0.0, 0.0), (200.0, -350.0), (750.0, 680.0), (1000.0, 400.0)], ] quav_res = planner.evaluate_candidate_paths(candidates) qrl = PQCQuantumRLAttitudeController(n_qubits=4, n_layers=int(pqc_layers)) obs_state = np.array([0.12, -0.08, 0.04, -0.15]) q_actions = qrl.forward_expectation_z(obs_state) q_grad = qrl.symmetric_difference_gradient(obs_state, action_idx=int(np.argmax(q_actions))) qfim_res = RelativisticSpacetimeQFIEstimator.compute_qfim_and_qcrb( r_meters=radial_km * 1000.0, photon_freq_hz=3.84e14, ) l3_out = ( "=== Q-SNASB LAYER 3 QUANTUM CO-PROCESSOR TELEMETRY ===\n" f"QUAV-QAOA Selected Path : Path #{quav_res['selected_path_index']} " f"(Length: {quav_res['selected_path_length_m']:.2f} m)\n" f"Mean-Field Lyapunov Max : {quav_res['lyapunov_hardness']:.5f}\n" f"PQC-QRL Pauli-Z Expects : {np.round(q_actions, 4).tolist()}\n" f"Sym-Diff Gradient Norm : {np.linalg.norm(q_grad):.4f} ({4 * int(pqc_layers) * 2} params)\n" f"Relativistic QFIM F_rr : {qfim_res['qfim_rr']:.3e} m^-2\n" f"QCRB Radial Std Dev : {qfim_res['qcrb_radial_std_m']:.3e} m" ) return l1_out, l2_out, l3_out @gpu_task def execute_full_stack_gpu(buffer_scale: float, pqc_layers: int, radial_km: float): """ZeroGPU-registered execution hook for interactive button runs.""" return run_stack_computation(buffer_scale, pqc_layers, radial_km) with gr.Blocks(title="Q-SNASB & Q-MCT v4.2 Flight Deck") as demo: gr.Markdown( "## 🛰️ Q-SNASB & Q-MCT v4.2: Quantum Space Navigation & Adaptive Surveillance Bot System\n" "Switch between the **6-Mode Interactive Flight Deck**, **Quantum Metrology Benchmarks**, " "**Quantum Algorithmic Benchmarks**, and the **Live C++20 + Python Telemetry Console**." ) with gr.Tabs(): with gr.Tab("🛰️ Q-MCT v4.2 Flight Deck (6-Mode Simulator)"): gr.HTML(render_embedded_html("q_mct_flight_deck.html", 880)) with gr.Tab("📊 Quantum Metrology Benchmarks (CAI & DSAC)"): gr.HTML(render_embedded_html("metrology_benchmarks.html", 760)) with gr.Tab("⚛️ Quantum Algorithmic Benchmarks (QUAV & Mean-Field AOA)"): gr.HTML(render_embedded_html("algorithmic_benchmarks.html", 720)) with gr.Tab("⚙️ Layer 1–3 Live Execution Console (C++20 & Python)"): gr.Markdown( "Execute the compiled **C++20 Layer 1 Quantum Firmware**, **C++20 Layer 2 Swarm WCI/DTN Middleware**, " "and **Python Layer 3 Quantum Co-Processor** with custom orbital and obstacle parameters." ) with gr.Row(): buf_slider = gr.Slider(1.0, 2.5, value=1.5, step=0.1, label="Obstacle Safety Buffer (sx, sy)") pqc_slider = gr.Slider(2, 8, value=3, step=1, label="PQC-QRL Entanglement Layers (L)") rad_slider = gr.Slider(6600.0, 42164.0, value=7000.0, step=100.0, label="Orbital Radius r (km)") run_btn = gr.Button("🚀 Execute Full 4-Layer Quantum Stack", variant="primary") with gr.Row(): l1_box = gr.Textbox(label="Layer 1: C++20 Quantum Core Firmware (CAI / GGT / DSAC)", lines=9) l2_box = gr.Textbox(label="Layer 2: C++20 Swarm WCI, GCC-AKF & QKD-DTN Middleware", lines=9) l3_box = gr.Textbox(label="Layer 3: Python Hybrid Quantum-Classical Co-Processor", lines=8) run_btn.click( fn=execute_full_stack_gpu, inputs=[buf_slider, pqc_slider, rad_slider], outputs=[l1_box, l2_box, l3_box], ) demo.load( fn=run_stack_computation, inputs=[buf_slider, pqc_slider, rad_slider], outputs=[l1_box, l2_box, l3_box], ) if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)), )