|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +NRC Interactive Gradio Space |
| 4 | +============================ |
| 5 | +Three-tab interactive app demonstrating the full Nexus Resonance Codex |
| 6 | +mathematical and AI framework. Runs on HuggingFace Spaces (CPU tier). |
| 7 | +
|
| 8 | +Deploy to HF Spaces: |
| 9 | + huggingface-cli repo create Nexus-Resonance-Codex/nrc-interactive --type space --space-sdk gradio |
| 10 | + git push hub main |
| 11 | +""" |
| 12 | + |
| 13 | +import math |
| 14 | +import numpy as np |
| 15 | +import gradio as gr |
| 16 | + |
| 17 | +# ─────────────────────────── NRC Math (inline, no pip install needed) ────────── |
| 18 | +PHI = (1.0 + math.sqrt(5.0)) / 2.0 |
| 19 | +PHI_INV = 1.0 / PHI |
| 20 | +SQRT5 = math.sqrt(5.0) |
| 21 | +SQRT2 = math.sqrt(2.0) |
| 22 | +PI = math.pi |
| 23 | +GIZA_DEG = 51.853 |
| 24 | +GIZA_RAD = GIZA_DEG * (PI / 180.0) |
| 25 | + |
| 26 | +def binet(n: int) -> float: |
| 27 | + return (PHI**n - (-PHI)**(-n)) / SQRT5 |
| 28 | + |
| 29 | +def qrt(x: float) -> float: |
| 30 | + return math.sin(PHI * SQRT2 * GIZA_DEG * x) * math.exp(-(x**2) / PHI) + math.cos(PI / PHI * x) |
| 31 | + |
| 32 | +def mst(x: float) -> float: |
| 33 | + xp = abs(x) + 1e-9 |
| 34 | + return abs(math.floor(1000.0 * math.sinh(min(xp, 20.0))) + math.log(xp**2 + 1.0) + PHI**min(xp, 20.0)) % 24389 |
| 35 | + |
| 36 | +def tupt_gate(x: float) -> float: |
| 37 | + mod_val = x % 2187 |
| 38 | + if any(mod_val % p == 0 for p in [3, 6, 7, 9] if p != 0): |
| 39 | + return 0.0 |
| 40 | + return x |
| 41 | + |
| 42 | +def phi_fold(x: float, iterations: int = 5) -> float: |
| 43 | + for n in range(1, iterations + 1): |
| 44 | + x = (PHI**n) * x + (1.0 / SQRT5) |
| 45 | + return x |
| 46 | + |
| 47 | +def lattice_norm(x: float) -> float: |
| 48 | + dims = np.arange(2048, dtype=np.float64) |
| 49 | + vec = x * np.power(PHI, -dims / 2048) * np.cos(dims * GIZA_RAD) |
| 50 | + return float(np.linalg.norm(vec)) |
| 51 | + |
| 52 | +# Amino acid masses |
| 53 | +AA_MASS = { |
| 54 | + 'A':71.04,'R':156.19,'N':114.10,'D':115.09,'C':103.14,'E':129.12,'Q':128.13, |
| 55 | + 'G':57.05,'H':137.14,'I':113.16,'L':113.16,'K':128.17,'M':131.19,'F':147.18, |
| 56 | + 'P':97.12,'S':87.08,'T':101.11,'W':186.21,'Y':163.18,'V':99.13 |
| 57 | +} |
| 58 | + |
| 59 | +# ─────────────────────────── Tab 1: NRC Math Explorer ────────────────────────── |
| 60 | +def explore_nrc_math(x_val: float, fib_n: int) -> tuple: |
| 61 | + qrt_v = qrt(x_val) |
| 62 | + mst_v = mst(x_val) |
| 63 | + tupt_v = tupt_gate(x_val) |
| 64 | + fold_v = phi_fold(x_val) |
| 65 | + bn = binet(int(fib_n)) |
| 66 | + l_norm = lattice_norm(x_val) |
| 67 | + |
| 68 | + stability = "🔴 EXCLUDED" if tupt_v == 0 else ("🟡 RESONANT" if abs(qrt_v) < 0.5 else "🟢 STABLE") |
| 69 | + |
| 70 | + table_md = f""" |
| 71 | +| Operation | Result | |
| 72 | +|:----------|-------:| |
| 73 | +| **φ (Golden Ratio)** | `{PHI:.15f}` | |
| 74 | +| **QRT Wave** `QRT({x_val})` | `{qrt_v:.8f}` | |
| 75 | +| **MST Step** `MST({x_val})` | `{mst_v:.4f}` | |
| 76 | +| **TUPT Gate** | `{tupt_v:.4f}` | |
| 77 | +| **φ^∞ Fold** (5 iter) | `{fold_v:.6f}` | |
| 78 | +| **Binet F({int(fib_n)})** | `{bn:.4f}` | |
| 79 | +| **2048D Lattice ‖L‖** | `{l_norm:.6f}` | |
| 80 | +| **NRC Stability** | {stability} | |
| 81 | +""" |
| 82 | + |
| 83 | + # Generate QRT curve data |
| 84 | + xs = np.linspace(-5, 5, 500) |
| 85 | + ys = np.array([qrt(float(xi)) for xi in xs]) |
| 86 | + |
| 87 | + plot = gr.LinePlot( |
| 88 | + value={"x": xs.tolist(), "QRT(x)": ys.tolist()}, |
| 89 | + x="x", y="QRT(x)", |
| 90 | + title=f"QRT Wave Function (marked: x={x_val:.3f})" |
| 91 | + ) |
| 92 | + |
| 93 | + return table_md, (xs.tolist(), ys.tolist()) |
| 94 | + |
| 95 | + |
| 96 | +# ─────────────────────────── Tab 2: Protein Sequence → Lattice ───────────────── |
| 97 | +def analyze_sequence(sequence: str) -> str: |
| 98 | + sequence = sequence.upper().strip() |
| 99 | + if not sequence: |
| 100 | + return "_Please enter a valid amino acid sequence._" |
| 101 | + |
| 102 | + masses = [AA_MASS.get(aa, 0.0) for aa in sequence] |
| 103 | + valid = [(aa, m) for aa, m in zip(sequence, masses) if m > 0] |
| 104 | + unknown = [aa for aa in sequence if aa not in AA_MASS] |
| 105 | + |
| 106 | + if not valid: |
| 107 | + return "⚠️ No recognized amino acids found." |
| 108 | + |
| 109 | + # Project using phi-lattice |
| 110 | + mass_arr = np.array([m for _, m in valid]) * PHI |
| 111 | + dims = np.arange(2048, dtype=np.float64) |
| 112 | + scale = np.power(PHI, -dims / 2048) * np.cos(dims * GIZA_RAD) |
| 113 | + |
| 114 | + # Per-residue lattice norms |
| 115 | + coord_norms = [float(np.linalg.norm(m_val * scale)) for m_val in mass_arr] |
| 116 | + |
| 117 | + out = f"### Sequence Analysis: `{sequence}`\n\n" |
| 118 | + out += f"**Length:** {len(sequence)} residues | **Valid:** {len(valid)} | **Unknown:** {len(unknown) if unknown else 0}\n\n" |
| 119 | + |
| 120 | + out += "| # | Residue | Mass (Da) | 2048D Lattice ‖L‖ | TUPT Gate |\n" |
| 121 | + out += "|:--|:--------|----------:|------------------:|:---------:|\n" |
| 122 | + for i, ((aa, mass), cnorm) in enumerate(zip(valid[:25], coord_norms[:25])): |
| 123 | + gated = tupt_gate(mass) |
| 124 | + gate_sym = "🔴 EXC" if gated == 0 else "🟢 OK" |
| 125 | + out += f"| {i+1} | **{aa}** | `{mass:.2f}` | `{cnorm:.4f}` | {gate_sym} |\n" |
| 126 | + |
| 127 | + if len(valid) > 25: |
| 128 | + out += f"\n_...{len(valid)-25} more residues not shown._\n" |
| 129 | + |
| 130 | + total_norm = float(np.linalg.norm(coord_norms)) |
| 131 | + excluded_count = sum(1 for _, m in valid if tupt_gate(m) == 0) |
| 132 | + out += f"\n**Total Lattice Energy (‖L‖):** `{total_norm:.6f}` \n" |
| 133 | + out += f"**TUPT-Excluded Residues:** `{excluded_count}` / {len(valid)} " |
| 134 | + out += f"(`{excluded_count/len(valid)*100:.1f}%`)\n" |
| 135 | + |
| 136 | + return out |
| 137 | + |
| 138 | + |
| 139 | +# ─────────────────────────── Tab 3: AI Enhancement Browser ───────────────────── |
| 140 | +ENHANCEMENTS = [ |
| 141 | + ("PhiInfinityShardFolding", "Attention", "φ^∞ fractal shard folding — replaces standard attention weights with φ-scaled topology"), |
| 142 | + ("NRCProteinFoldingEngine", "Scaffold", "2048D lattice + TUPT exclusion — embeds protein physics directly into model layers"), |
| 143 | + ("GoldenAttractorFlowNorm", "LayerNorm", "φ-attractor normalization — replaces mean/variance with Golden Ratio normalization"), |
| 144 | + ("TripleThetaInitializer", "Weight Init", "3θ resonance seed — initializes weights at positions of maximum φ-harmonic stability"), |
| 145 | + ("ResonanceShardKVCache", "KV-Cache", "φ^n memory sharding — organizes KV cache in Golden Ratio proportions"), |
| 146 | + ("BiologicalExclusionGradientRouter", "Grad Routing", "TUPT mod-9 gate — routes gradients through biologically stable branches only"), |
| 147 | + ("HodgePhiTTorsionAttention", "Self-Attention", "Hodge torsion biasing — warps attention scores with differential geometry"), |
| 148 | + ("E8GoldenBasisEmbedding", "Embedding", "E8 root basis + φ — embeds tokens on the E8 exceptional Lie group lattice"), |
| 149 | + ("PhiInfinityLosslessLoRA", "LoRA", "φ^∞ lossless adapter — deterministic rank compression without information loss"), |
| 150 | + ("NavierStokesDampingRegularizer", "Regularizer", "NS fractional damping — penalizes turbulent weight gradients using fluid equations"), |
| 151 | + ("PrimeDensityConditionedGeneration", "Sampling", "Prime density seeds — conditions token generation on prime number distributions"), |
| 152 | + ("GTTEntropyCollapseRegularizer", "Entropy Loss", "GTT threshold collapse — penalizes entropy exceeding the Golden Transfer Threshold"), |
| 153 | + ("PhiInverseMomentumAccelerator", "Momentum", "φ⁻¹ velocity scaling — accelerates convergence via inverse-Golden momentum"), |
| 154 | + ("TUPTAttractorSyncSeed", "RNG Seed", "TUPT cycle sync — synchronizes all random seeds to the TUPT attractor cycle"), |
| 155 | + ("QRTKernelConvolution", "Conv1D/2D", "QRT wave kernel — replaces Gaussian/uniform conv kernels with fractal QRT pattern"), |
| 156 | + ("LucasWeightedSparseAttention", "Sparse Attn", "Lucas number masking — only attends from positions in Lucas number pattern"), |
| 157 | + ("PhiPoweredResonantWeighting", "Weight Init", "φ^n spectral decay — initializes weight spectra with Golden Ratio power decay"), |
| 158 | + ("GizaLatticeIsomorphism", "Projection", "51.85° slope map — transforms feature maps through Giza pyramid geometry"), |
| 159 | + ("MSTLyapunovGradientClipping", "Grad Clipping", "MST λ≈0.381 bound — clips gradients to the MST Lyapunov stability limit"), |
| 160 | + ("PisanoModulatedLRSchedule", "LR Schedule", "Pisano period cycle — modulates learning rate on the Fibonacci Pisano period"), |
| 161 | + ("LucasPellHybridWeightDecay", "Weight Decay", "Lucas-Pell recursion — decays weights along the Lucas-Pell hybrid sequence"), |
| 162 | + ("TUPTExclusionTokenPruning", "Token Pruning", "Mod-9 pruning gate — prunes tokens at positions excluded by TUPT rule"), |
| 163 | + ("PhiVoidResonancePositionalEncoding","Positional Enc.", "φ-void sinusoidal PE — a new positional encoding based on φ-void gaps"), |
| 164 | + ("InfiniteEInfinityContextUnfolder", "Context Window", "E∞ recursive unfolding — expands effective context beyond hardware limits"), |
| 165 | + ("TUPTModularDropout", "Dropout", "TUPT-gated structural drop — drops connections at TUPT-excluded positions"), |
| 166 | + ("QRTTurbulenceOptimizer", "Optimizer", "QRT turbulence gradient — replaces Adam noise with oscillating QRT corrections"), |
| 167 | + ("GizaSlopeAttentionBias", "Attention Bias", "51.85° Giza weighting — biases attention scores with pyramid slope geometry"), |
| 168 | + ("FloorSinhActivation", "Activation", "floor(1000·sinh(x)) + φ·x — a new activation replacing ReLU/GELU"), |
| 169 | + ("GoldenSpiralRotaryEmbedding", "RoPE", "φ-spiral rotation matrix — embeds rotary positions on the Golden Spiral"), |
| 170 | + ("NRCEntropyAttractorEarlyStopping", "Early Stopping", "NRC entropy convergence — stops training when entropy collapses to NRC attractor"), |
| 171 | +] |
| 172 | + |
| 173 | +def browse_enhancement(name: str) -> str: |
| 174 | + match = next((e for e in ENHANCEMENTS if e[0] == name), None) |
| 175 | + if not match: |
| 176 | + return "_Enhancement not found._" |
| 177 | + |
| 178 | + cls, replaces, desc = match |
| 179 | + code = f"""```python |
| 180 | +import torch, torch.nn as nn |
| 181 | +from nrc_ai import {cls} |
| 182 | +
|
| 183 | +# Example: wrapping a standard layer |
| 184 | +layer = nn.Linear(512, 512) |
| 185 | +enhancement = {cls}() |
| 186 | +
|
| 187 | +# Forward pass with NRC physics |
| 188 | +x = torch.randn(8, 64, 512) # (batch, seq_len, d_model) |
| 189 | +out = enhancement(x) |
| 190 | +print(f"Output shape: {{out.shape}}") # torch.Size([8, 64, 512]) |
| 191 | +```""" |
| 192 | + |
| 193 | + return f"""### `{cls}` |
| 194 | +
|
| 195 | +**Replaces:** `{replaces}` |
| 196 | +**Description:** {desc} |
| 197 | +
|
| 198 | +**Formula:** Derived from the NRC QRT / MST / TUPT / φ-lattice foundations. |
| 199 | +
|
| 200 | +{code} |
| 201 | +
|
| 202 | +**Install & use:** |
| 203 | +```bash |
| 204 | +pip install "nrc @ git+https://github.com/Nexus-Resonance-Codex/NRC.git" |
| 205 | +pip install "nrc_ai @ git+https://github.com/Nexus-Resonance-Codex/ai-enhancements.git" |
| 206 | +``` |
| 207 | +""" |
| 208 | + |
| 209 | + |
| 210 | +# ─────────────────────────── Build Gradio App ────────────────────────────────── |
| 211 | +THEME = gr.themes.Soft( |
| 212 | + primary_hue="violet", |
| 213 | + secondary_hue="indigo", |
| 214 | + neutral_hue="slate", |
| 215 | + font=[gr.themes.GoogleFont("Inter"), "sans-serif"], |
| 216 | +) |
| 217 | + |
| 218 | +with gr.Blocks(title="NRC Interactive — Nexus Resonance Codex") as demo: |
| 219 | + gr.Markdown(""" |
| 220 | +# 🌀 Nexus Resonance Codex — Interactive Explorer |
| 221 | +*Real-time computation of NRC mathematics, protein lattice projections, and AI enhancement browsing.* |
| 222 | +
|
| 223 | +[](https://github.com/Nexus-Resonance-Codex) |
| 224 | +""") |
| 225 | + |
| 226 | + with gr.Tabs(): |
| 227 | + # ── Tab 1 ────────────────────────────────────────────────────────────── |
| 228 | + with gr.Tab("🔢 NRC Math Explorer"): |
| 229 | + gr.Markdown("Enter any real number to see all NRC mathematical operations applied in real time.") |
| 230 | + with gr.Row(): |
| 231 | + with gr.Column(scale=1): |
| 232 | + x_input = gr.Slider(-10, 10, value=1.618, step=0.001, label="Input x") |
| 233 | + n_input = gr.Slider(1, 30, value=10, step=1, label="Fibonacci index n") |
| 234 | + math_btn = gr.Button("⚡ Compute", variant="primary") |
| 235 | + with gr.Column(scale=2): |
| 236 | + math_out = gr.Markdown() |
| 237 | + plot_out = gr.LinePlot(x="x", y="QRT(x)", title="QRT Wave Function") |
| 238 | + math_btn.click(explore_nrc_math, inputs=[x_input, n_input], outputs=[math_out, plot_out]) |
| 239 | + demo.load(explore_nrc_math, inputs=[x_input, n_input], outputs=[math_out, plot_out]) |
| 240 | + |
| 241 | + # ── Tab 2 ────────────────────────────────────────────────────────────── |
| 242 | + with gr.Tab("🧬 Protein Sequence → Lattice"): |
| 243 | + gr.Markdown("Enter an amino acid sequence (1-letter FASTA codes) to project it into the 2048D φ-lattice.") |
| 244 | + with gr.Row(): |
| 245 | + with gr.Column(scale=1): |
| 246 | + seq_input = gr.Textbox( |
| 247 | + label="Amino Acid Sequence", |
| 248 | + placeholder="e.g. MKTIIALSYIFCLVFAQC", |
| 249 | + value="MKTIIALSYIFCLVFAQC", |
| 250 | + lines=3 |
| 251 | + ) |
| 252 | + seq_btn = gr.Button("🔬 Analyze", variant="primary") |
| 253 | + with gr.Column(scale=2): |
| 254 | + seq_out = gr.Markdown() |
| 255 | + seq_btn.click(analyze_sequence, inputs=seq_input, outputs=seq_out) |
| 256 | + demo.load(analyze_sequence, inputs=seq_input, outputs=seq_out) |
| 257 | + |
| 258 | + # ── Tab 3 ────────────────────────────────────────────────────────────── |
| 259 | + with gr.Tab("🤖 AI Enhancement Browser"): |
| 260 | + gr.Markdown("Browse all 30 NRC AI Enhancement modules with descriptions, formulas, and ready-to-run PyTorch examples.") |
| 261 | + with gr.Row(): |
| 262 | + with gr.Column(scale=1): |
| 263 | + enh_dropdown = gr.Dropdown( |
| 264 | + choices=[e[0] for e in ENHANCEMENTS], |
| 265 | + value=ENHANCEMENTS[0][0], |
| 266 | + label="Select Enhancement" |
| 267 | + ) |
| 268 | + with gr.Column(scale=2): |
| 269 | + enh_out = gr.Markdown() |
| 270 | + enh_dropdown.change(browse_enhancement, inputs=enh_dropdown, outputs=enh_out) |
| 271 | + demo.load(browse_enhancement, inputs=enh_dropdown, outputs=enh_out) |
| 272 | + |
| 273 | + gr.Markdown(""" |
| 274 | +--- |
| 275 | +*Built with the [NRC Python Libraries](https://github.com/Nexus-Resonance-Codex) — open source, mathematically rigorous, φ-grounded.* |
| 276 | +""") |
| 277 | + |
| 278 | +if __name__ == "__main__": |
| 279 | + demo.launch(share=False, theme=THEME) |
0 commit comments