-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_summary.py
More file actions
executable file
·380 lines (316 loc) · 13.7 KB
/
log_summary.py
File metadata and controls
executable file
·380 lines (316 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
import re
import math
import sys
import os
from dataclasses import dataclass, field
from typing import Optional
from fractions import Fraction
# ══════════════════════════════════════════════════════════════════════════════
# DATA
# ══════════════════════════════════════════════════════════════════════════════
@dataclass
class PrimeRun:
p: int
k: int
steps: list = field(default_factory=list)
step1_s_size: Optional[int] = None
final_s_zero: bool = False
counter_example: bool = False
counter_example_mod: Optional[int] = None
counter_example_s_size: Optional[int] = None
seeds: list = field(default_factory=list)
subproof_done: bool = False
# ══════════════════════════════════════════════════════════════════════════════
# PARSING
# ══════════════════════════════════════════════════════════════════════════════
LOG_EXTENSIONS = {".log", ".txt", ""}
def collect_log_files(path: str) -> list[str]:
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
files = [
e.path
for e in sorted(os.scandir(path), key=lambda e: e.name)
if e.is_file()
and not e.name.startswith(".")
and os.path.splitext(e.name)[1].lower() in LOG_EXTENSIONS
]
if not files:
print(f"No log files found in directory: {path}")
sys.exit(1)
return files
print(f"Error: '{path}' is neither a file nor a directory.")
sys.exit(1)
def parse_log(path: str) -> list[PrimeRun]:
runs: list[PrimeRun] = []
current: Optional[PrimeRun] = None
pending_trying: Optional[tuple] = None
re_thread = re.compile(r"^\[THREAD\s+\d+\]\s*(.*)$")
re_params = re.compile(r"Parameters:\s*p\s*=\s*(\d+),\s*k\s*=\s*(\d+)")
re_trying = re.compile(r"trying\s+(\d+):\s*T\s+size\s*=\s*(\d+)")
re_trying_inline = re.compile(
r"trying\s+(\d+):\s*T\s+size\s*=\s*(\d+)\s*=>\s*\([nl]=(\d+)\):\s*S\s+size\s*=\s*(\d+)"
)
re_forcing = re.compile(r"Forcing\s+Lift\s+c=(\d+):\s*T\s+size\s*=\s*(\d+)")
re_findcover = re.compile(r"^\[FindCover\]\s*(.*)$")
re_lift = re.compile(r"^\[Lift\]\s*(.*)$")
re_substep = re.compile(r"^\[\d+\.\d+\]\s*(.*)$")
re_step_generic = re.compile(
r"Step(?:\s+[\d.]+)?\s+\([nl]=(\d+)\):\s*S\s+size\s*=\s*(\d+)"
)
re_result_simple = re.compile(
r"=>\s*\([nl]=(\d+)\):\s*S\s+size\s*=\s*(\d+)"
)
re_result_squeeze = re.compile(
r"=>\s*squeezing\s*\([nl]=(\d+)\):\s*S\s+size\s*=\s*(\d+)"
)
re_strategy_size = re.compile(
r"(?:Squeeze|Force\s+\d+|Resolve\s+\w+|Print(?:\s+\d+)?).*?S\.size\(\)\s*=\s*(\d+)"
)
re_counter = re.compile(r"Counter\s+Example\s+Mod\s+(\d+)")
re_seeds = re.compile(r"seeds\s*:(.*)")
re_step_plain = re.compile(r"Step\s+([\d.]+)$")
re_squeezing = re.compile(
r"\[\d+\.\d+\]\s*squeezing\s*\(l=(\d+)\):\s*S\s+size\s*=\s*(\d+)"
)
re_subproof_done = re.compile(r"subproof\s+mod\s+(\d+)\s+done", re.IGNORECASE)
def flush():
nonlocal pending_trying
if current is not None and pending_trying is not None:
current.steps.append((*pending_trying, -1, -1))
pending_trying = None
with open(path) as f:
for raw in f:
raw = raw.rstrip()
m = re_thread.match(raw)
line = m.group(1) if m else raw
m = re_findcover.match(line)
line = m.group(1) if m else line
m = re_lift.match(line)
if m:
line = m.group(1)
m2 = re_substep.match(line)
if m2:
line = m2.group(1)
if not line:
continue
if "Time elapsed" in line or line.startswith("Time:"):
continue
if line.startswith("Doing Strategy"):
continue
if m := re_params.search(line):
flush()
if current is not None:
runs.append(current)
current = PrimeRun(p=int(m.group(1)), k=int(m.group(2)))
pending_trying = None
continue
if current is None:
continue
if m := re_step_generic.search(line):
n = int(m.group(1))
s_size = int(m.group(2))
if current.step1_s_size is None and n == 1:
current.step1_s_size = s_size
current.steps.append((-1, -1, n, s_size))
if s_size == 0:
current.final_s_zero = True
pending_trying = None
continue
if m := re_trying_inline.search(line):
current.steps.append(
(int(m.group(1)), int(m.group(2)),
int(m.group(3)), int(m.group(4)))
)
pending_trying = None
if int(m.group(4)) == 0:
current.final_s_zero = True
continue
if m := re_forcing.search(line):
if pending_trying is not None:
current.steps.append((*pending_trying, -1, -1))
pending_trying = (int(m.group(1)), int(m.group(2)))
continue
if m := re_trying.search(line):
if pending_trying is not None:
current.steps.append((*pending_trying, -1, -1))
pending_trying = (int(m.group(1)), int(m.group(2)))
continue
if m := re_result_squeeze.search(line):
n = int(m.group(1))
s_size = int(m.group(2))
current.steps.append((-1, -1, n, s_size))
if s_size == 0:
current.final_s_zero = True
pending_trying = None
continue
if m := re_result_simple.search(line):
n = int(m.group(1))
s_size = int(m.group(2))
current.steps.append((-1, -1, n, s_size))
if s_size == 0:
current.final_s_zero = True
pending_trying = None
continue
if m := re_strategy_size.search(line):
s_size = int(m.group(1))
current.steps.append((-1, -1, -1, s_size))
if s_size == 0:
current.final_s_zero = True
pending_trying = None
continue
if m := re_seeds.search(line):
current.seeds = [
frozenset(int(x) for x in g.split())
for g in re.findall(r"\(([^)]+)\)", m.group(1))
]
continue
if m := re_counter.search(line):
current.counter_example = True
current.counter_example_mod = int(m.group(1))
if current.steps and current.steps[-1][3] >= 0:
current.counter_example_s_size = current.steps[-1][3]
continue
if m := re_step_plain.match(line):
pending_trying = None
continue
if m := re_squeezing.search(line):
n = int(m.group(1))
s_size = int(m.group(2))
current.steps.append((-1, -1, n, s_size))
if s_size == 0:
current.final_s_zero = True
pending_trying = None
continue
if m := re_subproof_done.search(line):
if int(m.group(1)) == current.p:
current.subproof_done = True
continue
flush()
if current is not None:
runs.append(current)
return runs
# ══════════════════════════════════════════════════════════════════════════════
# VERIFYING
# ══════════════════════════════════════════════════════════════════════════════
def is_prime(n: int) -> bool:
if n < 2:
return False
if n < 4:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def check_seed(seed, p, k):
target = set(range(1, k + 1))
for a in range(1, p):
image = set((a * s) % p for s in seed)
if len(image) != k:
continue
abs_image = set(min(x, p - x) for x in image)
if abs_image == target:
return True, a
return False, None
def fractional_part(x: Fraction) -> Fraction:
return x - math.floor(x)
def r_vector(t: Fraction, n: int, k: int) -> tuple:
return tuple(
math.floor(n * fractional_part(j * t))
for j in range(1, k + 1)
)
def all_r_vectors_rational(n: int, k: int, p: int) -> list[tuple]:
seen = set()
for m in range(p):
x = Fraction(m, p)
seen.add(r_vector(x, n, k))
return list(seen)
def valid_resolve_modulo(p, k) -> bool:
return set(all_r_vectors_rational(k + 1, k, k + 1)).issubset(
set(all_r_vectors_rational(k + 1, k, p))
)
def is_primes_enough(primes: list[int], k: int):
uniq = sorted(set(primes))
s = sum(math.log(p) for p in uniq)
binom = k * (k + 1) / 2.0
threshold = k * math.log((binom ** (k - 1)) / k)
return s > threshold, s, threshold
# ══════════════════════════════════════════════════════════════════════════════
# OUTPUT
# ══════════════════════════════════════════════════════════════════════════════
def format_run(run: PrimeRun):
lines = [f" p={run.p} k={run.k}"]
prev_s = run.step1_s_size
for _, _, n, s in run.steps:
prev = f"{prev_s}" if prev_s is not None else "?"
n_str = str(n) if n >= 0 else "?"
lines.append(f" Prev S={prev:>8} => n={n_str:>3} S={s:>8}")
prev_s = s
if prev_s == 0 or run.subproof_done:
lines.append(" => success")
return True, "\n".join(lines)
if run.counter_example:
if not is_prime(run.k + 1):
lines.append(" Cannot resolve remaining seed (k+1 not prime)")
return False, "\n".join(lines)
if not valid_resolve_modulo(run.p, run.k):
lines.append(" Invalid resolve modulo")
return False, "\n".join(lines)
results = [check_seed(seed, run.p, run.k) for seed in run.seeds]
ok = all(r[0] for r in results)
lines.append(f" ** REMAINING SEEDS [{'resolvable' if ok else 'UNRESOLVABLE'}] **")
return ok, "\n".join(lines)
return False, "\n".join(lines + [" END OF BLOCK - UNKNOWN RESULT"])
def print_results(runs: list[PrimeRun], label: str, detail: bool = True):
if not runs:
print("No parameter blocks found.")
return
k = runs[0].k
formatted = [format_run(r) for r in runs]
if detail:
print("=" * 60)
print(f"PER-PRIME DETAIL [{label}]")
print("=" * 60)
for _, txt in formatted:
print(txt)
print()
valid = [r.p for r, (ok, _) in zip(runs, formatted) if ok]
invalid = [r.p for r, (ok, _) in zip(runs, formatted) if not ok]
ok, s, thresh = is_primes_enough(valid, k)
print("=" * 60)
print(f"PROOF SUMMARY [{label}]")
print("=" * 60)
print(f"k = {k}")
print(f"valid primes = {sorted(set(valid))}")
print(f"invalid primes = {sorted(set(invalid))}")
print(f"log prod = {s:.6f}")
print(f"threshold = {thresh:.6f}")
print(f"PROOF: {'YES' if ok else 'NO'}")
# ══════════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════════
def main():
if len(sys.argv) != 2:
print(f"usage: python {os.path.basename(__file__)} <logfile|folder>")
sys.exit(1)
input_path = sys.argv[1]
log_files = collect_log_files(input_path)
if os.path.isdir(input_path):
all_runs = []
for path in log_files:
runs = parse_log(path)
if runs:
print_results(runs, os.path.basename(path))
print()
all_runs.extend(runs)
if len(all_runs) > 1:
print_results(all_runs, "ALL FILES", detail=False)
else:
print_results(parse_log(input_path), os.path.basename(input_path))
if __name__ == "__main__":
main()