DataScience / Pi_Hex_DataScience_V1.0.py
MartialTerran's picture
Create Pi_Hex_DataScience_V1.0.py
35575ba verified
Raw History Blame Contribute Delete
15.8 kB
"""
PiDataScience_V1.0.py
Standalone Data Science Suite for Substring Collision & Repetition Analysis in Pi (Base 16).
Features:
- Fast Chudnovsky Binary-Splitting Hex Generator (CPU-optimized, zero external libraries).
- Exhaustive Substring Collision Engine for lengths L in [4, 64].
- Exponential Search Expansion: Doubles search horizon N whenever repeats are absent.
- Full Telemetry: Counts, first-incident coordinates, and 0-F digit histograms.
- Safety & Persistence: 30-min checkpoints, auto-download in Colab, resume capability,
and a hardcoded 3-hour maximum runtime budget.
"""
import os
import sys
import time
import json
import math
from typing import Dict, List, Tuple, Any, Optional
# =====================================================================
# 1. RUNTIME BUDGET & PERSISTENCE CONFIGURATION
# =====================================================================
CONFIG = {
"min_length": 4,
"max_length": 64,
"initial_n": 2000, # Starting search horizon
"max_n_limit": 2000000, # Safety ceiling (2 million hex places)
"checkpoint_interval_sec": 1800, # 1800 = 30 minutes
"max_runtime_sec": 10800, # 10800 = 3 hours hard ceiling
"checkpoint_file": "pi_datascience_checkpoint.json",
"report_txt": "pi_repetition_report.txt",
"report_md": "pi_repetition_report.md",
"report_html": "pi_repetition_report.html",
}
HEX_CHARS = "0123456789ABCDEF"
# =====================================================================
# 2. HIGH-SPEED PI HEXADECIMAL ENGINE (CHUDNOVSKY BINARY SPLIT)
# =====================================================================
def chudnovsky_hex_pi(num_hex_digits: int) -> str:
"""
Computes num_hex_digits of Pi after decimal in Base 16 using binary splitting.
Pure Python arbitrary-precision integers (extremely fast on standard CPU).
"""
# Number of decimal digits needed ~ num_hex_digits * 1.204
digits_dec = int(num_hex_digits * 1.21) + 50
C = 640320
C3_OVER_24 = C**3 // 24
def bs(a, b):
if b - a == 1:
if a == 0:
Pab = 1
Qab = 1
else:
Pab = (6*a - 5) * (2*a - 1) * (6*a - 1)
Qab = a**3 * C3_OVER_24
Tab = Pab * (13591409 + 545140134 * a)
if a & 1:
Tab = -Tab
return Pab, Qab, Tab
else:
m = (a + b) // 2
Pam, Qam, Tam = bs(a, m)
Pmb, Qmb, Tmb = bs(m, b)
Pab = Pam * Pmb
Qab = Qam * Qmb
Tab = Qmb * Tam + Pam * Tmb
return Pab, Qab, Tab
# Digits per term ~ 14.18 decimal digits
terms = int(digits_dec / 14.181647462725477) + 2
P, Q, T = bs(0, terms)
one_shift = 1 << (num_hex_digits * 4 + 64)
# sqrt(10005) via integer Newton-Raphson
target = 10005 * (1 << (num_hex_digits * 8 + 128))
x = int(math.isqrt(target))
sqrt_10005 = x
pi_val = (Q * 426880 * sqrt_10005) // T
# Shift right 64 bits of guard precision
hex_str = f"{pi_val >> 64:x}"
# 3 is the integer part; fractional part follows
return hex_str[1:num_hex_digits + 1].upper()
# =====================================================================
# 3. REPETITION & DATA SCIENCE ENGINE
# =====================================================================
class PiDataScienceAnalyzer:
def __init__(self, cfg: Dict[str, Any]):
self.cfg = cfg
self.start_time = time.time()
self.last_checkpoint_time = self.start_time
self.current_n = cfg["initial_n"]
self.results: Dict[int, Dict[str, Any]] = {}
# Load existing checkpoint if available
self.load_checkpoint()
def load_checkpoint(self):
ckpt_file = self.cfg["checkpoint_file"]
if os.path.exists(ckpt_file):
try:
with open(ckpt_file, "r") as f:
data = json.load(f)
self.current_n = data.get("current_n", self.cfg["initial_n"])
self.results = {int(k): v for k, v in data.get("results", {}).items()}
print(f"[RECOVERY] Loaded checkpoint from {ckpt_file}. Resuming at N={self.current_n}")
except Exception as e:
print(f"[WARNING] Could not load checkpoint: {e}. Starting fresh.")
def save_checkpoint(self, force_download: bool = False):
ckpt_file = self.cfg["checkpoint_file"]
data = {
"current_n": self.current_n,
"elapsed_sec": time.time() - self.start_time,
"results": self.results,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
}
with open(ckpt_file, "w") as f:
json.dump(data, f, indent=2)
print(f"[CHECKPOINT] Saved state at N={self.current_n} to {ckpt_file}")
# Generate all reports
self.generate_reports()
# Auto-download in Colab
if force_download or "google.colab" in sys.modules:
self.trigger_colab_downloads()
def trigger_colab_downloads(self):
try:
from google.colab import files
print("[COLAB] Auto-initiating file download...")
files.download(self.cfg["checkpoint_file"])
files.download(self.cfg["report_txt"])
files.download(self.cfg["report_md"])
files.download(self.cfg["report_html"])
except Exception:
pass # Non-colab environments simply retain files on disk
def analyze_length(self, pi_stream: str, length: int) -> Dict[str, Any]:
"""Examines substring repetitions for a given length L."""
seen: Dict[str, int] = {}
repeats: Dict[str, List[int]] = {}
first_rep_seq = None
first_rep_idx1 = None
first_rep_idx2 = None
total_substrings = len(pi_stream) - length + 1
for i in range(total_substrings):
sub = pi_stream[i:i + length]
if sub in seen:
if sub not in repeats:
repeats[sub] = [seen[sub], i]
if first_rep_seq is None:
first_rep_seq = sub
first_rep_idx1 = seen[sub]
first_rep_idx2 = i
else:
repeats[sub].append(i)
else:
seen[sub] = i
has_repeat = len(repeats) > 0
# Compute histogram of hex numerals across repeating sequences
hist = {c: 0 for c in HEX_CHARS}
for seq, occurrences in repeats.items():
mult = len(occurrences)
for ch in seq:
hist[ch] += mult
return {
"length": length,
"has_repeat": has_repeat,
"repeat_sequence_count": len(repeats),
"total_repeat_events": sum(len(indices) for indices in repeats.values()),
"first_repeated_sequence": first_rep_seq,
"first_index": first_rep_idx1,
"repeat_index": first_rep_idx2,
"distance": (first_rep_idx2 - first_rep_idx1) if first_rep_idx1 is not None else None,
"numeral_histogram": hist,
"evaluated_at_n": len(pi_stream)
}
def execute_search(self):
print("=" * 84)
print(f"PiDataScience_V1.0 Search Engine Started [Base 16]")
print(f"Lengths: {self.cfg['min_length']} to {self.cfg['max_length']} | Initial N: {self.current_n}")
print("=" * 84)
while True:
elapsed = time.time() - self.start_time
if elapsed >= self.cfg["max_runtime_sec"]:
print(f"[TIMEOUT] Reached hard maximum runtime budget of {self.cfg['max_runtime_sec']}s. Finalizing.")
self.save_checkpoint(force_download=True)
break
if self.current_n > self.cfg["max_n_limit"]:
print(f"[LIMIT] Reached safety limit N={self.cfg['max_n_limit']}. Stopping search expansion.")
self.save_checkpoint(force_download=True)
break
print(f"\n>>> Generating {self.current_n} hex digits of Pi via Chudnovsky...")
t0 = time.time()
pi_stream = chudnovsky_hex_pi(self.current_n)
print(f">>> Generated {len(pi_stream)} digits in {time.time() - t0:.2f}s. Scanning lengths {self.cfg['min_length']}..{self.cfg['max_length']}...")
all_lengths_have_repeats = True
for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
# If length was already solved and repeated in an earlier smaller N, keep that record
if L in self.results and self.results[L]["has_repeat"]:
continue
res = self.analyze_length(pi_stream, L)
self.results[L] = res
status = "YES" if res["has_repeat"] else "NO"
info = ""
if res["has_repeat"]:
info = f"Count: {res['repeat_sequence_count']:4d} | First: '{res['first_repeated_sequence']}' @ [{res['first_index']} -> {res['repeat_index']}]"
else:
all_lengths_have_repeats = False
info = "No collision detected in current window."
print(f" Length {L:02d}: [{status:<3}] {info}")
# Check 30-min checkpoint cadence
if time.time() - self.last_checkpoint_time >= self.cfg["checkpoint_interval_sec"]:
print("[CADENCE] 30-minute interval elapsed. Triggering intermediate checkpoint & downloads.")
self.save_checkpoint(force_download=True)
self.last_checkpoint_time = time.time()
# Save report at current N
self.save_checkpoint(force_download=False)
if all_lengths_have_repeats:
print("\n[SUCCESS] All sequence lengths [4..64] have confirmed repeats!")
self.save_checkpoint(force_download=True)
break
else:
next_n = self.current_n * 2
print(f"\n[EXPANSION] Certain lengths have NO repeats in N={self.current_n}. Doubling horizon to N={next_n}...")
self.current_n = next_n
# =================================================================
# 4. REPORT GENERATION (TXT, MD, HTML)
# =================================================================
def generate_reports(self):
# 1. Text Report
with open(self.cfg["report_txt"], "w") as f:
f.write("PI HEXADECIMAL SUBSTRING REPETITION REPORT\n")
f.write(f"Timestamp: {time.strftime('%Y-%m-%d %H:%M:%S')} | Search Horizon N: {self.current_n}\n")
f.write("=" * 86 + "\n")
f.write(f"{'Len':<4} | {'Repeat?':<7} | {'Distinct':<8} | {'First Found Sequence':<20} | {'Idx 1':<8} | {'Idx 2':<8}\n")
f.write("-" * 86 + "\n")
for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
if L in self.results:
r = self.results[L]
rep = "YES" if r["has_repeat"] else "NO"
seq = r["first_repeated_sequence"] or "NONE"
idx1 = str(r["first_index"]) if r["first_index"] is not None else "-"
idx2 = str(r["repeat_index"]) if r["repeat_index"] is not None else "-"
f.write(f"{L:<4} | {rep:<7} | {r['repeat_sequence_count']:<8} | {seq:<20} | {idx1:<8} | {idx2:<8}\n")
# 2. Markdown Report
with open(self.cfg["report_md"], "w") as f:
f.write("# $\\pi$ Hexadecimal Substring Repetition Audit\n\n")
f.write(f"- **Current Search Horizon ($N$):** {self.current_n:,} digits\n")
f.write(f"- **Generated At:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("| Length | Repeat Detected? | Unique Repeated Strings | Total Events | First Repeated Substring | First Index | Repeat Index | Distance |\n")
f.write("| :--- | :---: | :---: | :---: | :--- | :---: | :---: | :---: |\n")
for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
if L in self.results:
r = self.results[L]
rep = "**YES**" if r["has_repeat"] else "NO"
seq = f"`{r['first_repeated_sequence']}`" if r["first_repeated_sequence"] else "—"
i1 = r["first_index"] if r["first_index"] is not None else "—"
i2 = r["repeat_index"] if r["repeat_index"] is not None else "—"
dist = r["distance"] if r["distance"] is not None else "—"
f.write(f"| {L} | {rep} | {r['repeat_sequence_count']} | {r['total_repeat_events']} | {seq} | {i1} | {i2} | {dist} |\n")
# 3. HTML Report with Interactive Styling
with open(self.cfg["report_html"], "w") as f:
f.write("""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pi Repetition Analysis</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 30px; background: #0d1117; color: #c9d1d9; }
h1, h2 { color: #58a6ff; }
table { border-collapse: collapse; width: 100%; margin-top: 20px; background: #161b22; }
th, td { border: 1px solid #30363d; padding: 10px; text-align: left; }
th { background: #21262d; color: #f0f6fc; }
tr:nth-child(even) { background: #1c2128; }
.yes { color: #3fb950; font-weight: bold; }
.no { color: #f85149; font-weight: bold; }
.code { font-family: monospace; background: #2b313a; padding: 2px 6px; border-radius: 4px; color: #ff7b72; }
.hist { display: flex; gap: 2px; height: 16px; align-items: flex-end; }
.bar { width: 8px; background: #58a6ff; }
</style>
</head>
<body>
<h1>&pi; Hexadecimal Substring Repetition Audit</h1>
<p>Search Horizon: <strong>""" + f"{self.current_n:,}" + """ digits</strong> | Checkpointed at: """ + time.strftime("%Y-%m-%d %H:%M:%S") + """</p>
<table>
<tr>
<th>Length (L)</th>
<th>Repeated?</th>
<th>Distinct Repeats</th>
<th>First Repeated Sequence</th>
<th>First Index</th>
<th>Repeat Index</th>
<th>Numeral Histogram (0 to F)</th>
</tr>""")
for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
if L in self.results:
r = self.results[L]
rep_cls = "yes" if r["has_repeat"] else "no"
rep_txt = "YES" if r["has_repeat"] else "NO"
seq = f'<span class="code">{r["first_repeated_sequence"]}</span>' if r["first_repeated_sequence"] else "—"
i1 = str(r["first_index"]) if r["first_index"] is not None else "—"
i2 = str(r["repeat_index"]) if r["repeat_index"] is not None else "—"
# Mini bar-chart for 0-F
hist_bars = ""
max_h = max(r["numeral_histogram"].values()) if r["has_repeat"] and max(r["numeral_histogram"].values()) > 0 else 1
for ch in HEX_CHARS:
val = r["numeral_histogram"].get(ch, 0)
h_px = int((val / max_h) * 16)
hist_bars += f'<div class="bar" style="height:{max(1, h_px)}px;" title="{ch}: {val}"></div>'
f.write(f"""
<tr>
<td><strong>{L}</strong></td>
<td class="{rep_cls}">{rep_txt}</td>
<td>{r['repeat_sequence_count']:,}</td>
<td>{seq}</td>
<td>{i1}</td>
<td>{i2}</td>
<td><div class="hist">{hist_bars}</div></td>
</tr>""")
f.write("""
</table>
</body>
</html>""")
if __name__ == "__main__":
analyzer = PiDataScienceAnalyzer(CONFIG)
analyzer.execute_search()