"""Independent arithmetic/constraint oracle and small brute-force counterexamples.""" import collections,itertools,json,math,random,subprocess from pathlib import Path random.seed(930177) cases=[] for case in range(100): rows=[] for g in range(random.randint(3,6)): for i in range(random.randint(1,4)):rows.append({'id':f'{g}-{i}','group':f'g{g}','label':random.choice(['A','B']),'text':f'unique {g} {i}'}) cases.append({'rows':rows,'percentages':random.choice([[80,10,10],[50,25,25],[34,33,33]]),'seed':random.randrange(500)}) reports=json.loads(subprocess.run(['node','oracle_driver.mjs'],input=json.dumps(cases),text=True,capture_output=True,check=True,cwd=Path(__file__).parent).stdout) def objective(rows,assignment,ratios): N=len(rows);labels=sorted({r['label'] for r in rows});L=len(labels);ns=collections.Counter(assignment[r['group']] for r in rows);nl=collections.Counter(r['label'] for r in rows);cells=collections.Counter((r['label'],assignment[r['group']])for r in rows) total=sum((ns[s]-N*p/100)**2/(N*max(1,N*p/100))for s,p in enumerate(ratios)) return total+sum((cells[l,s]-nl[l]*p/100)**2/(L*nl[l]*max(1,nl[l]*p/100)) for l in labels for s,p in enumerate(ratios)) nonoptimal=[];trace_cells=0 for case,report in zip(cases,reports): rows=case['rows'];groups=sorted({r['group']for r in rows});assert report['total_records']==len(rows);assignment={r['group']:['train','validation','test'].index(r['split'])for r in report['assignments']};assert len(assignment)==len(groups)and set(assignment.values())=={0,1,2} assert math.isclose(objective(rows,assignment,case['percentages']),report['objective'],abs_tol=1e-12) assert {a['id']for a in report['assignments']}=={r['id']for r in rows} for g in groups:assert len({a['split']for a in report['assignments']if a['group']==g})==1 for item in report['labels']: for cell in item['splits']: s=['train','validation','test'].index(cell['split']);assert cell['actual_records']==sum(r['label']==item['label']and assignment[r['group']]==s for r in rows) # Verify each considered incremental objective using only already-allocated rows, fixed final target denominators. labels=sorted({r['label']for r in rows});nl=collections.Counter(r['label']for r in rows);N=len(rows);L=len(labels);totals=[0,0,0];cells=collections.Counter();seen=set() def fnv(key): h=2166136261 for b in (str(case['seed'])+'\0'+key).encode():h=((h^b)*16777619)&0xffffffff return h ordered=sorted(groups,key=lambda g:(-sum(r['group']==g for r in rows),fnv(g),g)) assert [x['unit']for x in report['allocation_trace']]==ordered for ordinal,step in enumerate(report['allocation_trace']): members=[r for r in rows if r['group']==step['unit']];counts=collections.Counter(r['label'] for r in members) empty=[s for s in range(3)if s not in seen];forced=len(groups)-ordinal==len(empty) expected=empty if forced else [0,1,2] assert step['forced_nonempty']==forced assert [x['split']for x in step['considered']]==[['train','validation','test'][s]for s in expected] choices=[] for s in range(3): p=case['percentages'][s]/100;t=N*p;delta=((totals[s]+len(members)-t)**2-(totals[s]-t)**2)/(N*max(1,t)) delta+=sum(((cells[l,s]+n-nl[l]*p)**2-(cells[l,s]-nl[l]*p)**2)/(L*nl[l]*max(1,nl[l]*p))for l,n in counts.items());choices.append(delta) for choice in step['considered']: s=['train','validation','test'].index(choice['split']);assert math.isclose(choice['delta'],choices[s],abs_tol=1e-12);trace_cells+=1 s=['train','validation','test'].index(step['chosen_split']);assert s in expected;assert choices[s]<=min(choices[q]for q in expected)+1e-12;totals[s]+=len(members) for l,n in counts.items():cells[l,s]+=n seen.add(s) best=math.inf;best_assignment=None for values in itertools.product(range(3),repeat=len(groups)): if set(values)!={0,1,2}:continue assign=dict(zip(groups,values));loss=objective(rows,assign,case['percentages']) if lossbest+1e-12:nonoptimal.append({'case':case,'greedy_assignment':assignment,'greedy_objective':report['objective'],'optimal_assignment':best_assignment,'optimal_objective':best}) assert nonoptimal out={'status':'PASS','cases':100,'considered_deltas_checked':trace_cells,'nonoptimal_greedy_cases':len(nonoptimal),'counterexample':nonoptimal[0],'scope':'exhaustive optimality only for these 3–6 group synthetic cases; greedy not globally optimal'} Path(__file__).with_name('reference-results.json').write_text(json.dumps(out,indent=2)+'\n');print({k:v for k,v in out.items()if k!='counterexample'})