"""Repair exactly the 64 overlapping new unions; preserve the failed V1. The members and unaffected unions are reused. A union is a set, so repeated coordinates must be removed before assigning uniform weight to each slot. Every changed certificate gets a new kernel check and a plain integer check. """ from collections import Counter import hashlib import json from pathlib import Path import sys import time import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE / 'tightcert')) import tightcert as tc T0 = time.process_time() original = HERE / 'union1088.json' out = json.loads(original.read_text()) def fast_f1(D, qs): d = np.asarray(D, dtype=np.int64) return len(D) - sum(int(np.bincount(np.concatenate(((-d) % q, (-d-2) % q)), minlength=q).max()) for q in qs) def plain_f1(D, qs): return len(D) - sum(max(sum((s+b) % q == 0 or (s+b+2) % q == 0 for s in D) for b in range(q)) for q in qs) def fit(xs, ys): n = len(xs) sx, sy = sum(xs), sum(ys) sxx, sxy = sum(x*x for x in xs), sum(x*y for x,y in zip(xs,ys)) m = (n*sxy-sx*sy)/(n*sxx-sx*sx) c = (sy-m*sx)/n return m, c, max(abs(y-m*x-c) for x,y in zip(xs,ys)) changed = 0 for rec in out['unions']: p, N = rec['p'], rec['common_N'] raw = sorted(s for a in rec['members'] for s in out['member_slots']['%d:%d' % (p,a)][:N]) U = sorted(set(raw)) rec['source_multiset_size'] = len(raw) rec['duplicates_removed'] = len(raw)-len(U) if U == raw: continue assert p == 223 changed += 1 qs = [q for q in range(p+1, 2*p+1) if tc.is_prime(q)] rec['source_multiset_F1'] = rec['F1_union'] f1 = fast_f1(U, qs) assert f1 == plain_f1(U, qs) and f1 > 0 cert = {'kind': 'noncoverable', 'rule': 'counting', 'slots': U, 'weights': [1]*len(U), 'ratio': [len(U)-f1,len(U)]} kernel_ok = bool(tc.verify(cert, U, qs)[0]) assert kernel_ok rec.update(union_size=len(U), F1_union=f1, F1_per_k=f1/rec['k'], gain_over_members=f1-rec['member_F1_sum'], U_sha256=hashlib.sha256(','.join(map(str,U)).encode()).hexdigest(), kernel_verify_ok=kernel_ok, independent_check=True) rec['certificate'] = {'kind': cert['kind'], 'rule': cert['rule'], 'weights_len': len(U), 'weights_all_one': True, 'ratio': cert['ratio']} assert changed == 64 # Only prime 223's affected summaries can change. The other two fits remain # identically the reported source objects, rather than being recomputed. rows = [r for r in out['unions'] if r['p'] == 223] ks = list(range(2,9)) mins = {str(k): min(r['F1_per_k'] for r in rows if r['k']==k) for k in ks} means = {str(k): sum(r['F1_per_k'] for r in rows if r['k']==k) / sum(r['k']==k for r in rows) for k in ks} umin = {str(k): min(r['F1_union'] for r in rows if r['k']==k) for k in ks} umax = {str(k): max(r['F1_union'] for r in rows if r['k']==k) for k in ks} b,c,res = fit(ks,[umin[str(k)] for k in ks]) d,ceiling,rescaled_res = fit([1/k for k in ks],[mins[str(k)] for k in ks]) f = out['fit']['223'] f.update(F1_per_k_min=mins, F1_per_k_mean=means, F1_union_min_by_k=umin, F1_union_max_by_k=umax, F1_union_min_increments=[umin[str(k+1)]-umin[str(k)] for k in ks[:-1]], min_nondecreasing=all(mins[str(k)]<=mins[str(k+1)] for k in ks[:-1]), min_positive=all(mins[str(k)]>0 for k in ks), affine_min_union_slope_b=b, affine_min_union_intercept=c, affine_min_union_max_residual=res, per_k_vs_inv_k_intercept=ceiling, per_k_vs_inv_k_slope=d, per_k_vs_inv_k_max_residual=rescaled_res, b_over_mean_N_F=b/f['N_F_mean']) out['summary']['b_by_prime']['223'] = b out['summary']['b_over_mean_N_F_by_prime']['223'] = b/f['N_F_mean'] out['summary']['min_nondecreasing_at_every_prime'] = all( f['min_nondecreasing'] and f['min_positive'] for f in out['fit'].values()) out['repair'] = {'kind': 'true_set_union_v2', 'affected_prime': 223, 'affected_unions': changed, 'original_artifact_sha256': hashlib.sha256(original.read_bytes()).hexdigest(), 'max_duplicate_entries': max(r['duplicates_removed'] for r in out['unions'])} out['definitions'] = out['definitions'].replace('then sorted concatenation, |U|=k*N', 'then sorted set union, |U|<=k*N') out['artifact_note'] += ' V1 failed the member-disjointness check at p223. V2 deduplicates ' out['artifact_note'] += '64 unions and freshly checks their uniform-weight certificates; ' out['artifact_note'] += 'all members and 677 unaffected union measurements are preserved.' out['outcome'] = 'success: all 741 true set unions have exact uniform-weight certificates; ' out['outcome'] += 'the original concatenation failed at p223 and is preserved separately.' before = json.loads(original.read_text()) assert out['members'] == before['members'] and out['member_slots'] == before['member_slots'] assert all(out['fit'][str(p)] == before['fit'][str(p)] for p in (199,211)) for new, old in zip(out['unions'],before['unions']): if not new['duplicates_removed']: assert {k:v for k,v in new.items() if k not in ('duplicates_removed','source_multiset_size')} == old text = json.dumps(out,sort_keys=True,indent=2)+'\n' target = Path(sys.argv[1]) if len(sys.argv)>1 else HERE/'union1088-v2.json' target.write_text(text,newline='\n') print(json.dumps({'changed_unions':changed,'preserved_unions':741-changed, 'cpu_seconds':time.process_time()-T0}),file=sys.stderr)