MartialTerran commited on
Commit
35575ba
·
verified ·
1 Parent(s): 98b7ed8

Create Pi_Hex_DataScience_V1.0.py

Browse files
Files changed (1) hide show
  1. Pi_Hex_DataScience_V1.0.py +361 -0
Pi_Hex_DataScience_V1.0.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PiDataScience_V1.0.py
3
+ Standalone Data Science Suite for Substring Collision & Repetition Analysis in Pi (Base 16).
4
+
5
+ Features:
6
+ - Fast Chudnovsky Binary-Splitting Hex Generator (CPU-optimized, zero external libraries).
7
+ - Exhaustive Substring Collision Engine for lengths L in [4, 64].
8
+ - Exponential Search Expansion: Doubles search horizon N whenever repeats are absent.
9
+ - Full Telemetry: Counts, first-incident coordinates, and 0-F digit histograms.
10
+ - Safety & Persistence: 30-min checkpoints, auto-download in Colab, resume capability,
11
+ and a hardcoded 3-hour maximum runtime budget.
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import time
17
+ import json
18
+ import math
19
+ from typing import Dict, List, Tuple, Any, Optional
20
+
21
+ # =====================================================================
22
+ # 1. RUNTIME BUDGET & PERSISTENCE CONFIGURATION
23
+ # =====================================================================
24
+
25
+ CONFIG = {
26
+ "min_length": 4,
27
+ "max_length": 64,
28
+ "initial_n": 2000, # Starting search horizon
29
+ "max_n_limit": 2000000, # Safety ceiling (2 million hex places)
30
+ "checkpoint_interval_sec": 1800, # 1800 = 30 minutes
31
+ "max_runtime_sec": 10800, # 10800 = 3 hours hard ceiling
32
+ "checkpoint_file": "pi_datascience_checkpoint.json",
33
+ "report_txt": "pi_repetition_report.txt",
34
+ "report_md": "pi_repetition_report.md",
35
+ "report_html": "pi_repetition_report.html",
36
+ }
37
+
38
+ HEX_CHARS = "0123456789ABCDEF"
39
+
40
+ # =====================================================================
41
+ # 2. HIGH-SPEED PI HEXADECIMAL ENGINE (CHUDNOVSKY BINARY SPLIT)
42
+ # =====================================================================
43
+
44
+ def chudnovsky_hex_pi(num_hex_digits: int) -> str:
45
+ """
46
+ Computes num_hex_digits of Pi after decimal in Base 16 using binary splitting.
47
+ Pure Python arbitrary-precision integers (extremely fast on standard CPU).
48
+ """
49
+ # Number of decimal digits needed ~ num_hex_digits * 1.204
50
+ digits_dec = int(num_hex_digits * 1.21) + 50
51
+ C = 640320
52
+ C3_OVER_24 = C**3 // 24
53
+
54
+ def bs(a, b):
55
+ if b - a == 1:
56
+ if a == 0:
57
+ Pab = 1
58
+ Qab = 1
59
+ else:
60
+ Pab = (6*a - 5) * (2*a - 1) * (6*a - 1)
61
+ Qab = a**3 * C3_OVER_24
62
+ Tab = Pab * (13591409 + 545140134 * a)
63
+ if a & 1:
64
+ Tab = -Tab
65
+ return Pab, Qab, Tab
66
+ else:
67
+ m = (a + b) // 2
68
+ Pam, Qam, Tam = bs(a, m)
69
+ Pmb, Qmb, Tmb = bs(m, b)
70
+ Pab = Pam * Pmb
71
+ Qab = Qam * Qmb
72
+ Tab = Qmb * Tam + Pam * Tmb
73
+ return Pab, Qab, Tab
74
+
75
+ # Digits per term ~ 14.18 decimal digits
76
+ terms = int(digits_dec / 14.181647462725477) + 2
77
+ P, Q, T = bs(0, terms)
78
+
79
+ one_shift = 1 << (num_hex_digits * 4 + 64)
80
+ # sqrt(10005) via integer Newton-Raphson
81
+ target = 10005 * (1 << (num_hex_digits * 8 + 128))
82
+ x = int(math.isqrt(target))
83
+ sqrt_10005 = x
84
+
85
+ pi_val = (Q * 426880 * sqrt_10005) // T
86
+ # Shift right 64 bits of guard precision
87
+ hex_str = f"{pi_val >> 64:x}"
88
+
89
+ # 3 is the integer part; fractional part follows
90
+ return hex_str[1:num_hex_digits + 1].upper()
91
+
92
+ # =====================================================================
93
+ # 3. REPETITION & DATA SCIENCE ENGINE
94
+ # =====================================================================
95
+
96
+ class PiDataScienceAnalyzer:
97
+ def __init__(self, cfg: Dict[str, Any]):
98
+ self.cfg = cfg
99
+ self.start_time = time.time()
100
+ self.last_checkpoint_time = self.start_time
101
+ self.current_n = cfg["initial_n"]
102
+ self.results: Dict[int, Dict[str, Any]] = {}
103
+
104
+ # Load existing checkpoint if available
105
+ self.load_checkpoint()
106
+
107
+ def load_checkpoint(self):
108
+ ckpt_file = self.cfg["checkpoint_file"]
109
+ if os.path.exists(ckpt_file):
110
+ try:
111
+ with open(ckpt_file, "r") as f:
112
+ data = json.load(f)
113
+ self.current_n = data.get("current_n", self.cfg["initial_n"])
114
+ self.results = {int(k): v for k, v in data.get("results", {}).items()}
115
+ print(f"[RECOVERY] Loaded checkpoint from {ckpt_file}. Resuming at N={self.current_n}")
116
+ except Exception as e:
117
+ print(f"[WARNING] Could not load checkpoint: {e}. Starting fresh.")
118
+
119
+ def save_checkpoint(self, force_download: bool = False):
120
+ ckpt_file = self.cfg["checkpoint_file"]
121
+ data = {
122
+ "current_n": self.current_n,
123
+ "elapsed_sec": time.time() - self.start_time,
124
+ "results": self.results,
125
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
126
+ }
127
+ with open(ckpt_file, "w") as f:
128
+ json.dump(data, f, indent=2)
129
+ print(f"[CHECKPOINT] Saved state at N={self.current_n} to {ckpt_file}")
130
+
131
+ # Generate all reports
132
+ self.generate_reports()
133
+
134
+ # Auto-download in Colab
135
+ if force_download or "google.colab" in sys.modules:
136
+ self.trigger_colab_downloads()
137
+
138
+ def trigger_colab_downloads(self):
139
+ try:
140
+ from google.colab import files
141
+ print("[COLAB] Auto-initiating file download...")
142
+ files.download(self.cfg["checkpoint_file"])
143
+ files.download(self.cfg["report_txt"])
144
+ files.download(self.cfg["report_md"])
145
+ files.download(self.cfg["report_html"])
146
+ except Exception:
147
+ pass # Non-colab environments simply retain files on disk
148
+
149
+ def analyze_length(self, pi_stream: str, length: int) -> Dict[str, Any]:
150
+ """Examines substring repetitions for a given length L."""
151
+ seen: Dict[str, int] = {}
152
+ repeats: Dict[str, List[int]] = {}
153
+ first_rep_seq = None
154
+ first_rep_idx1 = None
155
+ first_rep_idx2 = None
156
+
157
+ total_substrings = len(pi_stream) - length + 1
158
+ for i in range(total_substrings):
159
+ sub = pi_stream[i:i + length]
160
+ if sub in seen:
161
+ if sub not in repeats:
162
+ repeats[sub] = [seen[sub], i]
163
+ if first_rep_seq is None:
164
+ first_rep_seq = sub
165
+ first_rep_idx1 = seen[sub]
166
+ first_rep_idx2 = i
167
+ else:
168
+ repeats[sub].append(i)
169
+ else:
170
+ seen[sub] = i
171
+
172
+ has_repeat = len(repeats) > 0
173
+
174
+ # Compute histogram of hex numerals across repeating sequences
175
+ hist = {c: 0 for c in HEX_CHARS}
176
+ for seq, occurrences in repeats.items():
177
+ mult = len(occurrences)
178
+ for ch in seq:
179
+ hist[ch] += mult
180
+
181
+ return {
182
+ "length": length,
183
+ "has_repeat": has_repeat,
184
+ "repeat_sequence_count": len(repeats),
185
+ "total_repeat_events": sum(len(indices) for indices in repeats.values()),
186
+ "first_repeated_sequence": first_rep_seq,
187
+ "first_index": first_rep_idx1,
188
+ "repeat_index": first_rep_idx2,
189
+ "distance": (first_rep_idx2 - first_rep_idx1) if first_rep_idx1 is not None else None,
190
+ "numeral_histogram": hist,
191
+ "evaluated_at_n": len(pi_stream)
192
+ }
193
+
194
+ def execute_search(self):
195
+ print("=" * 84)
196
+ print(f"PiDataScience_V1.0 Search Engine Started [Base 16]")
197
+ print(f"Lengths: {self.cfg['min_length']} to {self.cfg['max_length']} | Initial N: {self.current_n}")
198
+ print("=" * 84)
199
+
200
+ while True:
201
+ elapsed = time.time() - self.start_time
202
+ if elapsed >= self.cfg["max_runtime_sec"]:
203
+ print(f"[TIMEOUT] Reached hard maximum runtime budget of {self.cfg['max_runtime_sec']}s. Finalizing.")
204
+ self.save_checkpoint(force_download=True)
205
+ break
206
+
207
+ if self.current_n > self.cfg["max_n_limit"]:
208
+ print(f"[LIMIT] Reached safety limit N={self.cfg['max_n_limit']}. Stopping search expansion.")
209
+ self.save_checkpoint(force_download=True)
210
+ break
211
+
212
+ print(f"\n>>> Generating {self.current_n} hex digits of Pi via Chudnovsky...")
213
+ t0 = time.time()
214
+ pi_stream = chudnovsky_hex_pi(self.current_n)
215
+ print(f">>> Generated {len(pi_stream)} digits in {time.time() - t0:.2f}s. Scanning lengths {self.cfg['min_length']}..{self.cfg['max_length']}...")
216
+
217
+ all_lengths_have_repeats = True
218
+
219
+ for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
220
+ # If length was already solved and repeated in an earlier smaller N, keep that record
221
+ if L in self.results and self.results[L]["has_repeat"]:
222
+ continue
223
+
224
+ res = self.analyze_length(pi_stream, L)
225
+ self.results[L] = res
226
+
227
+ status = "YES" if res["has_repeat"] else "NO"
228
+ info = ""
229
+ if res["has_repeat"]:
230
+ info = f"Count: {res['repeat_sequence_count']:4d} | First: '{res['first_repeated_sequence']}' @ [{res['first_index']} -> {res['repeat_index']}]"
231
+ else:
232
+ all_lengths_have_repeats = False
233
+ info = "No collision detected in current window."
234
+
235
+ print(f" Length {L:02d}: [{status:<3}] {info}")
236
+
237
+ # Check 30-min checkpoint cadence
238
+ if time.time() - self.last_checkpoint_time >= self.cfg["checkpoint_interval_sec"]:
239
+ print("[CADENCE] 30-minute interval elapsed. Triggering intermediate checkpoint & downloads.")
240
+ self.save_checkpoint(force_download=True)
241
+ self.last_checkpoint_time = time.time()
242
+
243
+ # Save report at current N
244
+ self.save_checkpoint(force_download=False)
245
+
246
+ if all_lengths_have_repeats:
247
+ print("\n[SUCCESS] All sequence lengths [4..64] have confirmed repeats!")
248
+ self.save_checkpoint(force_download=True)
249
+ break
250
+ else:
251
+ next_n = self.current_n * 2
252
+ print(f"\n[EXPANSION] Certain lengths have NO repeats in N={self.current_n}. Doubling horizon to N={next_n}...")
253
+ self.current_n = next_n
254
+
255
+ # =================================================================
256
+ # 4. REPORT GENERATION (TXT, MD, HTML)
257
+ # =================================================================
258
+
259
+ def generate_reports(self):
260
+ # 1. Text Report
261
+ with open(self.cfg["report_txt"], "w") as f:
262
+ f.write("PI HEXADECIMAL SUBSTRING REPETITION REPORT\n")
263
+ f.write(f"Timestamp: {time.strftime('%Y-%m-%d %H:%M:%S')} | Search Horizon N: {self.current_n}\n")
264
+ f.write("=" * 86 + "\n")
265
+ f.write(f"{'Len':<4} | {'Repeat?':<7} | {'Distinct':<8} | {'First Found Sequence':<20} | {'Idx 1':<8} | {'Idx 2':<8}\n")
266
+ f.write("-" * 86 + "\n")
267
+ for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
268
+ if L in self.results:
269
+ r = self.results[L]
270
+ rep = "YES" if r["has_repeat"] else "NO"
271
+ seq = r["first_repeated_sequence"] or "NONE"
272
+ idx1 = str(r["first_index"]) if r["first_index"] is not None else "-"
273
+ idx2 = str(r["repeat_index"]) if r["repeat_index"] is not None else "-"
274
+ f.write(f"{L:<4} | {rep:<7} | {r['repeat_sequence_count']:<8} | {seq:<20} | {idx1:<8} | {idx2:<8}\n")
275
+
276
+ # 2. Markdown Report
277
+ with open(self.cfg["report_md"], "w") as f:
278
+ f.write("# $\\pi$ Hexadecimal Substring Repetition Audit\n\n")
279
+ f.write(f"- **Current Search Horizon ($N$):** {self.current_n:,} digits\n")
280
+ f.write(f"- **Generated At:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
281
+ f.write("| Length | Repeat Detected? | Unique Repeated Strings | Total Events | First Repeated Substring | First Index | Repeat Index | Distance |\n")
282
+ f.write("| :--- | :---: | :---: | :---: | :--- | :---: | :---: | :---: |\n")
283
+ for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
284
+ if L in self.results:
285
+ r = self.results[L]
286
+ rep = "**YES**" if r["has_repeat"] else "NO"
287
+ seq = f"`{r['first_repeated_sequence']}`" if r["first_repeated_sequence"] else "—"
288
+ i1 = r["first_index"] if r["first_index"] is not None else "—"
289
+ i2 = r["repeat_index"] if r["repeat_index"] is not None else "—"
290
+ dist = r["distance"] if r["distance"] is not None else "—"
291
+ f.write(f"| {L} | {rep} | {r['repeat_sequence_count']} | {r['total_repeat_events']} | {seq} | {i1} | {i2} | {dist} |\n")
292
+
293
+ # 3. HTML Report with Interactive Styling
294
+ with open(self.cfg["report_html"], "w") as f:
295
+ f.write("""<!DOCTYPE html>
296
+ <html>
297
+ <head>
298
+ <meta charset="utf-8">
299
+ <title>Pi Repetition Analysis</title>
300
+ <style>
301
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 30px; background: #0d1117; color: #c9d1d9; }
302
+ h1, h2 { color: #58a6ff; }
303
+ table { border-collapse: collapse; width: 100%; margin-top: 20px; background: #161b22; }
304
+ th, td { border: 1px solid #30363d; padding: 10px; text-align: left; }
305
+ th { background: #21262d; color: #f0f6fc; }
306
+ tr:nth-child(even) { background: #1c2128; }
307
+ .yes { color: #3fb950; font-weight: bold; }
308
+ .no { color: #f85149; font-weight: bold; }
309
+ .code { font-family: monospace; background: #2b313a; padding: 2px 6px; border-radius: 4px; color: #ff7b72; }
310
+ .hist { display: flex; gap: 2px; height: 16px; align-items: flex-end; }
311
+ .bar { width: 8px; background: #58a6ff; }
312
+ </style>
313
+ </head>
314
+ <body>
315
+ <h1>&pi; Hexadecimal Substring Repetition Audit</h1>
316
+ <p>Search Horizon: <strong>""" + f"{self.current_n:,}" + """ digits</strong> | Checkpointed at: """ + time.strftime("%Y-%m-%d %H:%M:%S") + """</p>
317
+ <table>
318
+ <tr>
319
+ <th>Length (L)</th>
320
+ <th>Repeated?</th>
321
+ <th>Distinct Repeats</th>
322
+ <th>First Repeated Sequence</th>
323
+ <th>First Index</th>
324
+ <th>Repeat Index</th>
325
+ <th>Numeral Histogram (0 to F)</th>
326
+ </tr>""")
327
+ for L in range(self.cfg["min_length"], self.cfg["max_length"] + 1):
328
+ if L in self.results:
329
+ r = self.results[L]
330
+ rep_cls = "yes" if r["has_repeat"] else "no"
331
+ rep_txt = "YES" if r["has_repeat"] else "NO"
332
+ seq = f'<span class="code">{r["first_repeated_sequence"]}</span>' if r["first_repeated_sequence"] else "—"
333
+ i1 = str(r["first_index"]) if r["first_index"] is not None else "—"
334
+ i2 = str(r["repeat_index"]) if r["repeat_index"] is not None else "—"
335
+
336
+ # Mini bar-chart for 0-F
337
+ hist_bars = ""
338
+ max_h = max(r["numeral_histogram"].values()) if r["has_repeat"] and max(r["numeral_histogram"].values()) > 0 else 1
339
+ for ch in HEX_CHARS:
340
+ val = r["numeral_histogram"].get(ch, 0)
341
+ h_px = int((val / max_h) * 16)
342
+ hist_bars += f'<div class="bar" style="height:{max(1, h_px)}px;" title="{ch}: {val}"></div>'
343
+
344
+ f.write(f"""
345
+ <tr>
346
+ <td><strong>{L}</strong></td>
347
+ <td class="{rep_cls}">{rep_txt}</td>
348
+ <td>{r['repeat_sequence_count']:,}</td>
349
+ <td>{seq}</td>
350
+ <td>{i1}</td>
351
+ <td>{i2}</td>
352
+ <td><div class="hist">{hist_bars}</div></td>
353
+ </tr>""")
354
+ f.write("""
355
+ </table>
356
+ </body>
357
+ </html>""")
358
+
359
+ if __name__ == "__main__":
360
+ analyzer = PiDataScienceAnalyzer(CONFIG)
361
+ analyzer.execute_search()