""" TBO Oracle - Hugging Face Space ================================ Temporal Bispectral Operator for blockchain-anchored predictions. "THE SHAPE IS THE ORACLE" - We reveal, not compute. """ import gradio as gr import numpy as np import hashlib import time from datetime import datetime, timezone from scipy import stats # ═══════════════════════════════════════════════════════════════════════════ # TBO CORE FUNCTIONS # ═══════════════════════════════════════════════════════════════════════════ def compute_cross_bispectrum_fast(signal, nfft=None): """Vectorized bispectrum computation.""" signal = np.asarray(signal, dtype=np.float64) N = len(signal) if nfft is None: nfft = N X = np.fft.fft(signal, n=nfft) idx = np.arange(nfft) i_grid, j_grid = np.meshgrid(idx, idx, indexing='ij') k_grid = (i_grid + j_grid) % nfft B = X[i_grid] * X[j_grid] * np.conj(X[k_grid]) return B def compute_tbo_scalar(signal, nfft=None): """Compute the TBO scalar Lambda.""" signal = np.asarray(signal, dtype=np.float64) N = len(signal) if nfft is None: nfft = N B = compute_cross_bispectrum_fast(signal, nfft=nfft) half = nfft // 2 mask = np.zeros((nfft, nfft), dtype=bool) for i in range(1, half): for j in range(1, half): if i + j < half: mask[i, j] = True magnitudes = np.abs(B[mask]) if len(magnitudes) == 0: return 0.0 return float(np.mean(magnitudes)) def compute_tbo_zscore(signal, n_null=100, seed=None): """Compute z-score relative to null distribution.""" rng = np.random.default_rng(seed) signal = np.asarray(signal, dtype=np.float64) lam_obs = compute_tbo_scalar(signal) null_lambdas = np.empty(n_null) for i in range(n_null): perm = rng.permutation(signal) null_lambdas[i] = compute_tbo_scalar(perm) mu = np.mean(null_lambdas) sigma = np.std(null_lambdas, ddof=1) if sigma < 1e-15: sigma = 1e-15 z = (lam_obs - mu) / sigma return float(z), float(lam_obs), float(mu), float(sigma), null_lambdas def classify_signal(z_score): """Classify based on z-score.""" if z_score < -1.96: return 'DEFICIT' elif z_score > 1.96: return 'EXCESS' return 'NORMAL' def _sieve_primes(limit): """Sieve of Eratosthenes.""" is_prime = [True] * (limit + 1) is_prime[0] = is_prime[1] = False for i in range(2, int(limit**0.5) + 1): if is_prime[i]: for j in range(i * i, limit + 1, i): is_prime[j] = False return [i for i in range(2, limit + 1) if is_prime[i]] def generate_cyclotomic(N, order=7, seed=None): """Generate cyclotomic signal with prime harmonics.""" rng = np.random.default_rng(seed) t = np.arange(N, dtype=np.float64) primes = _sieve_primes(N // 2)[:order] signal = np.zeros(N) for p in primes: amp = rng.uniform(0.5, 2.0) phase = rng.uniform(0, 2 * np.pi) signal += amp * np.sin(2 * np.pi * p * t / N + phase) signal += 0.1 * rng.standard_normal(N) return signal # ═══════════════════════════════════════════════════════════════════════════ # SIGNAL COLLECTORS # ═══════════════════════════════════════════════════════════════════════════ def collect_entropy(n=256, seed=None): """System entropy signal.""" rng = np.random.default_rng(seed) arr = rng.integers(0, 2**32, size=n, dtype=np.uint32).astype(np.float64) return (arr - arr.mean()) / (arr.std() + 1e-15) def collect_clock_jitter(n=256): """Clock timing jitter.""" timestamps = [] for _ in range(n * 4): timestamps.append(time.perf_counter_ns()) deltas = np.diff(timestamps).astype(np.float64) block = len(deltas) // n signal = np.array([deltas[i*block:(i+1)*block].mean() for i in range(n)]) return (signal - signal.mean()) / (signal.std() + 1e-15) def collect_hash_chain(n=256, seed=None): """SHA-256 hash chain.""" rng = np.random.default_rng(seed) h = rng.bytes(32) values = np.empty(n, dtype=np.float64) for i in range(n): h = hashlib.sha256(h + i.to_bytes(4, 'big')).digest() values[i] = float(int.from_bytes(h[:4], 'big')) return (values - values.mean()) / (values.std() + 1e-15) def collect_cyclotomic(n=256, seed=None): """Cyclotomic calibration signal.""" signal = generate_cyclotomic(n, order=7, seed=seed) return (signal - signal.mean()) / (signal.std() + 1e-15) # ═══════════════════════════════════════════════════════════════════════════ # ORACLE PREDICTION # ═══════════════════════════════════════════════════════════════════════════ def run_oracle_prediction(question: str, deadline: str, n_samples: int = 256, n_null: int = 100): """Run full TBO Oracle prediction.""" # Generate question-based seed q_hash = hashlib.sha256(question.encode()).hexdigest() base_seed = int(q_hash[:8], 16) # Collect signals from 4 sources sources = { "entropy": collect_entropy(n_samples, seed=base_seed), "clock": collect_clock_jitter(n_samples), "hash_chain": collect_hash_chain(n_samples, seed=base_seed + 1), "cyclotomic": collect_cyclotomic(n_samples, seed=base_seed + 2), } results = {} predictions = [] z_scores = [] for name, signal in sources.items(): z, lam, mu, sigma, null_dist = compute_tbo_zscore(signal, n_null=n_null, seed=base_seed) classification = classify_signal(z) prediction = 1 if z < -1.96 else 0 results[name] = { "z_score": round(z, 4), "lambda": round(lam, 6), "classification": classification, "prediction": "YES" if prediction else "NO", } predictions.append(prediction) z_scores.append(abs(z)) # Consensus vote_count = sum(predictions) consensus = "YES" if vote_count >= 2 else "NO" # Confidence mean_z = np.mean(z_scores) if mean_z >= 10: confidence = "VERY HIGH" elif mean_z >= 5: confidence = "HIGH" elif mean_z >= 3: confidence = "MEDIUM" elif mean_z >= 1.5: confidence = "LOW" else: confidence = "UNCERTAIN" # Probability estimate k = 0.25 prob = 1.0 / (1.0 + np.exp(-k * mean_z)) prob = max(0.5, min(prob, 0.95)) return results, consensus, confidence, prob, vote_count, mean_z def create_source_chart(results): """Create a visual bar chart of z-scores.""" import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt sources = list(results.keys()) z_scores = [results[s]["z_score"] for s in sources] colors = [] for z in z_scores: if z < -1.96: colors.append('#10b981') # green - deficit elif z > 1.96: colors.append('#8b5cf6') # purple - excess else: colors.append('#6b7280') # gray - normal fig, ax = plt.subplots(figsize=(8, 4), facecolor='#0f172a') ax.set_facecolor('#0f172a') bars = ax.barh(sources, z_scores, color=colors, height=0.6, edgecolor='#1e293b', linewidth=2) # Add threshold lines ax.axvline(x=-1.96, color='#10b981', linestyle='--', alpha=0.5, label='Deficit threshold') ax.axvline(x=1.96, color='#8b5cf6', linestyle='--', alpha=0.5, label='Excess threshold') ax.axvline(x=0, color='#475569', linestyle='-', alpha=0.3) # Style ax.set_xlabel('Z-Score', color='#e2e8f0', fontsize=12) ax.set_title('Source Analysis', color='#e2e8f0', fontsize=14, fontweight='bold') ax.tick_params(colors='#e2e8f0') ax.spines['bottom'].set_color('#334155') ax.spines['left'].set_color('#334155') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # Add value labels for bar, z in zip(bars, z_scores): width = bar.get_width() ax.text(width + 0.1 if width >= 0 else width - 0.5, bar.get_y() + bar.get_height()/2, f'{z:.2f}', ha='left' if width >= 0 else 'right', va='center', color='#e2e8f0', fontsize=10) plt.tight_layout() return fig def predict(question: str, deadline: str, n_samples: int, n_null: int): """Main prediction function for Gradio.""" if not question.strip(): return "❌ Please enter a question.", None, "", "" if not deadline: return "❌ Please select a deadline.", None, "", "" try: results, consensus, confidence, prob, votes, mean_z = run_oracle_prediction( question, deadline, int(n_samples), int(n_null) ) # Create chart chart = create_source_chart(results) # Big result display if consensus == "YES": result_emoji = "✅" result_color = "green" else: result_emoji = "❌" result_color = "red" big_result = f"""
Detects third-order phase coupling invisible to standard power spectrum analysis.
Manifold closure condition ensuring prediction convergence through topological constraints.
Two-State Vector Formalism from quantum mechanics enables retrocausal signal detection.
Entropy, clock jitter, hash chains, and cyclotomic signals vote independently.