#!/usr/bin/env python3 """Bounded, checkpointed driver for the unchanged published kstar.c. Run in this directory: python3 run4568.py THREADS. Scientific inputs are local. Stdout is a small final summary; progress and timing go to stderr. """ import collections, hashlib, json, math, os, pathlib, resource, subprocess, sys, time P = pathlib.Path(__file__).resolve().parent os.chdir(P) THREADS = int(sys.argv[1]) START = time.monotonic() CPU_LIMIT = 14000 WALL_LIMIT = 3540 def cpu(): own = resource.getrusage(resource.RUSAGE_SELF) child = resource.getrusage(resource.RUSAGE_CHILDREN) return own.ru_utime + own.ru_stime + child.ru_utime + child.ru_stime def save(name, obj): temp = P / (name + '.tmp') temp.write_text(json.dumps(obj, sort_keys=True, separators=(',', ':')) + '\n') temp.replace(P / name) def batch(rows): remaining = int(CPU_LIMIT - cpu() - 2) if remaining < 10 or time.monotonic() - START > WALL_LIMIT: raise TimeoutError('execution budget reached') def limit(): resource.setrlimit(resource.RLIMIT_CPU, (remaining, remaining)) inp = ''.join(f"{base} {prime} {len(rs)} {' '.join(map(str,rs))}\n" for base,prime,rs in rows) res = subprocess.run([str(P/'kstar'), str(THREADS)], input=inp, text=True, capture_output=True, check=True, preexec_fn=limit, timeout=max(1, WALL_LIMIT-(time.monotonic()-START))) lines = res.stdout.splitlines() assert len(lines) == len(rows) out = [] for line,(base,prime,rs) in zip(lines,rows): vals = list(map(int,line.split())) assert vals[:-1] == [base,prime,*rs] assert vals[-1] >= 0 out.append(vals[-1]) return out def progress(stage, n, total): data = {'stage':stage,'done':n,'total':total,'cpu_seconds':round(cpu(),3), 'wall_seconds':round(time.monotonic()-START,3)} save('progress4568.json',data) print(json.dumps(data),file=sys.stderr,flush=True) assert hashlib.sha256((P/'kstar.c').read_bytes()).hexdigest() == '4d3faa05291d3533890f6fb2ad11b8b5d22e1697ba85bcb86b713ce531ac7aba' assert hashlib.sha256((P/'keep4567.json').read_bytes()).hexdigest() == 'aff5f769c45dd65eb3d518abe040c76be0f0b2fb2930d39a075559772c290fba' import sweep2775 as sw g = batch([r for r,_ in sw.GATES]) assert g == [v for _,v in sw.GATES] h = json.loads((P/'src_hard-210-4.json').read_text()) rows = [(210,1,r['R']) for r in h['rows']] + [(210,r['p'],r['R']) for r in h['hard_rows_measured']] expected = [r['A'] for r in h['rows']] + [r['B'] for r in h['hard_rows_measured']] assert batch(rows) == expected save('gates4568.json',{'custody_expected': [v for _,v in sw.GATES], 'custody_observed':g,'additional_values':len(rows),'mismatches':0}) original = (P/'keep4567.json').read_bytes() regen = subprocess.run([sys.executable,'fresh4567.py'],capture_output=True,text=True,check=True,timeout=90) (P/'regeneration4568.out').write_text(regen.stdout) (P/'regeneration4568.err').write_text(regen.stderr) assert (P/'keep4567.json').read_bytes() == original population = json.loads(original)['rows'] assert len(population)==4000 arows=[]; brows=[]; eligible=[]; stopped=None try: for start in range(0,len(population),48): block=population[start:start+48] vals=batch([(30,1,r['R']) for r in block]) for r,v in zip(block,vals): assert v <= r['Ahat'], ('capacity violation',r,v) arows.append(dict(r,A=v)) save('A4568.json',arows) progress('A',len(arows),len(population)) thresholds=json.loads((P/'dgate30.json').read_text())['thresholds'] for r in arows: assert r['A']<=60, 'D gate table insufficient' for prime in r['p_kept']: threshold=thresholds[str(prime)]['min_A_drop2_permitted'] if threshold is not None and r['A']>=threshold: eligible.append({'R':r['R'],'p':prime,'A':r['A'],'M':r['M'],'Mp':r['M']*prime}) eligible.sort(key=lambda r:(r['Mp'],r['R'],r['p'])) save('eligible4568.json',eligible) for start in range(0,len(eligible),12): block=eligible[start:start+12] vals=batch([(30,r['p'],r['R']) for r in block]) brows += [dict(r,B=v,rise=v-r['A']) for r,v in zip(block,vals)] save('B4568.json',brows) progress('B',len(brows),len(eligible)) except (TimeoutError,subprocess.TimeoutExpired) as e: stopped=type(e).__name__ summary={'A_complete':len(arows)==len(population),'A_count':len(arows),'B_count':len(brows), 'B_eligible':len(eligible),'B_complete':len(arows)==len(population) and len(brows)==len(eligible), 'max_Mp_reached':max((r['Mp'] for r in brows),default=0), 'first_unrun':eligible[len(brows)] if len(brows)