RegalFire's picture
RegalFire verified synthetic computational benchmark v1
7424015 verified
Raw History Blame Contribute Delete
15.8 kB
"""Independent RegalFire label validators. Does not import generator or its oracles."""
import argparse
from collections import Counter, deque, defaultdict
import heapq
import json
from pathlib import Path
import zlib
from jsonschema import Draft202012Validator
from common import NAMES,FAMILIES,enc,sha,semantic,split,strict,schema,write_json
def assert_true(ok,reason):
if not ok:raise ValueError(reason)
def grid_info(inp):
grid=inp['grid'];h,w=len(grid),len(grid[0]);assert_true(all(len(row)==w for row in grid),'nonrectangular_grid')
free={(y,x) for y,row in enumerate(grid) for x,v in enumerate(row) if v=='.'}
return grid,h,w,free
def relaxation(grid,costs,start,target):
h,w=len(grid),len(grid[0]);dist={tuple(start):0}
# Bellman-style relaxations over all directed adjacent vertices, unlike A*.
for _ in range(h*w):
changed=False
for y in range(h):
for x in range(w):
if grid[y][x]!='.' or (y,x) not in dist:continue
value=dist[(y,x)]
for v in [(y-1,x),(y,x-1),(y+1,x),(y,x+1)]:
a,b=v
if 0<=a<h and 0<=b<w and grid[a][b]=='.' and value+costs[a][b]<dist.get(v,10**12):
dist[v]=value+costs[a][b];changed=True
if not changed:break
return dist.get(tuple(target))
def check_path(grid,costs,start,goal,result,best):
assert_true(result['cost']==best,'path_cost_oracle_disagreement')
if best is None:assert_true(result['path'] is None,'unreachable_path');return
path=result['path'];assert_true(path and path[0]==start and path[-1]==goal,'bad_endpoints')
for p in path:
assert_true(len(p)==2 and 0<=p[0]<len(grid) and 0<=p[1]<len(grid[0]) and grid[p[0]][p[1]]=='.','illegal_path_cell')
assert_true(all(abs(a[0]-b[0])+abs(a[1]-b[1])==1 for a,b in zip(path,path[1:])),'illegal_path_step')
assert_true(sum(costs[y][x] for y,x in path[1:])==best,'witness_cost_disagreement')
def nav(inp,out):
g,h,w,free=grid_info(inp);costs=inp['costs'];s,t,edit=inp['start'],inp['goal'],inp['edit']
assert_true(tuple(s) in free and tuple(t) in free and s!=t,'invalid_endpoints')
assert_true(len(costs)==h and all(len(row)==w for row in costs),'cost_dimensions')
assert_true(0<=edit[0]<h and 0<=edit[1]<w and edit not in [s,t],'invalid_edit')
changed=list(g);y,x=edit;row=list(changed[y]);row[x]='.' if row[x]=='#' else '#';changed[y]=''.join(row)
before=relaxation(g,costs,s,t);after=relaxation(changed,costs,s,t)
assert_true(before!=after,'noncritical_edit')
check_path(g,costs,s,t,out['before'],before);check_path(changed,costs,s,t,out['after'],after)
assert_true(out['reachability_changed']==((before is None)!=(after is None)),'reachability_label')
assert_true(set(out)=={'before','after','reachability_changed'},'expected_schema')
def goal_distances(free,goal):
d={tuple(goal):0};q=deque([tuple(goal)])
while q:
a=q.popleft()
for b in [(a[0]-1,a[1]),(a[0]+1,a[1]),(a[0],a[1]-1),(a[0],a[1]+1)]:
if b in free and b not in d:d[b]=d[a]+1;q.append(b)
return d
def joint_astar(free,starts,goals):
start=tuple(map(tuple,starts));target=tuple(map(tuple,goals));d0=goal_distances(free,target[0]);d1=goal_distances(free,target[1])
if start[0] not in d0 or start[1] not in d1:return None,None
lb=max(d0[start[0]],d1[start[1]])
adjacency={p:[p]+[v for v in [(p[0],p[1]-1),(p[0]-1,p[1]),(p[0],p[1]+1),(p[0]+1,p[1])] if v in free] for p in free}
queue=[(lb,0,start)];best={start:0}
while queue:
_,cost,p=heapq.heappop(queue)
if best[p]!=cost:continue
if p==target:return cost,lb
choices0=[p[0]] if p[0]==target[0] else adjacency[p[0]]
choices1=[p[1]] if p[1]==target[1] else adjacency[p[1]]
for a in choices0:
for b in choices1:
if a==b or (a==p[1] and b==p[0]):continue
state=(a,b);new=cost+1
if new<best.get(state,10**9):
best[state]=new;heapq.heappush(queue,(new+max(d0.get(a,10000),d1.get(b,10000)),new,state))
return None,lb
def coord(inp,out):
_,_,_,free=grid_info(inp);s,t=inp['starts'],inp['goals']
assert_true(all(tuple(p) in free for p in s+t) and s[0]!=s[1] and t[0]!=t[1],'invalid_agent_endpoints')
optimum,lower=joint_astar(free,s,t)
assert_true(out['optimal_makespan']==optimum and out['independent_lower_bound']==lower,'joint_oracle_disagreement')
assert_true(out['coordination_overhead']==(optimum-lower if optimum is not None else None),'overhead_label')
if optimum is None:assert_true(out['plan'] is None,'infeasible_plan');return
plan=out['plan'];assert_true(len(plan)==optimum+1 and plan[0]==s and plan[-1]==t,'joint_witness_length')
for state in plan:assert_true(len(state)==2 and state[0]!=state[1] and all(tuple(p) in free for p in state),'vertex_conflict_or_invalid_cell')
for a,b in zip(plan,plan[1:]):
assert_true(not (a[0]==b[1] and a[1]==b[0]),'edge_swap')
for j in range(2):
assert_true(sum(abs(x-y) for x,y in zip(a[j],b[j]))<=1,'agent_teleport')
if a[j]==t[j]:assert_true(b[j]==t[j],'left_absorbing_goal')
assert_true(set(out)=={'plan','optimal_makespan','independent_lower_bound','coordination_overhead'},'expected_schema')
def reads(inp,out):
lines=inp['fastq'].split('\n');assert_true(len(lines)==4,'FASTQ_not_four_lines')
h,s,sep,q=lines;assert_true(h in ['@synthetic_read','synthetic_read'],'non_synthetic_header')
failures=set()
if not h or h[0]!='@':failures.add('header')
if sep!='+':failures.add('separator')
if set(s)-set('ACGTN'):failures.add('alphabet')
if len(q)!=len(s):failures.add('quality_length')
if not all('!'<=c<='J' for c in q):failures.add('quality_ascii')
expected={'valid_fastq':not failures,'errors':sorted(failures),'passed_filter':False,'trimmed_sequence':None,'trimmed_quality':None,'quality_sum':None,'length':None,'n_count':None,'gc_count':None}
if not failures:
policy=inp['policy'];qualities=[ord(c)-ord('!') for c in q]
kept=[i+1 for i,value in enumerate(qualities) if value>=policy['trim_q_min']]
stop=max(kept,default=0);s=s[:stop];q=q[:stop]
counts=Counter(s);total=sum(qualities[:stop])
passing=stop>=policy['min_length'] and counts['N']<=policy['max_n'] and total>=stop*policy['mean_q_min']
expected.update(passed_filter=passing,trimmed_sequence=s,trimmed_quality=q,quality_sum=total,length=stop,n_count=counts['N'],gc_count=counts['G']+counts['C'])
assert_true(enc(expected)==enc(out),'read_QC_oracle_disagreement')
def myers(a,b):
if not a:return len(b)
masks={}
for i,letter in enumerate(a):masks[letter]=masks.get(letter,0)|(1<<i)
positive=~0;negative=0;score=len(a);top=1<<(len(a)-1)
for letter in b:
equal=masks.get(letter,0);vertical=equal|negative
horizontal=(((equal&positive)+positive)^positive)|equal
plus=negative|~(horizontal|positive);minus=positive&horizontal
if plus&top:score+=1
if minus&top:score-=1
plus=(plus<<1)|1;minus<<=1
positive=minus|~(vertical|plus);negative=plus&vertical
return score
def align(inp,out):
a,b=inp['a'],inp['b'];distance=myers(a,b)
assert_true(inp['source_sequence']==a,'source_sequence_mismatch')
assert_true(out['edit_distance']==distance and out['within_threshold']==(distance<=inp['threshold']),'alignment_oracle_disagreement')
aa,bb=out['aligned_a'],out['aligned_b']
assert_true(len(aa)==len(bb) and aa.replace('-','')==a and bb.replace('-','')==b,'alignment_witness_sequence')
assert_true(all(not(x=='-' and y=='-') for x,y in zip(aa,bb)),'double_gap')
assert_true(sum(x!=y for x,y in zip(aa,bb))==distance,'nonoptimal_alignment_witness')
assert_true(set(out)=={'edit_distance','within_threshold','aligned_a','aligned_b'},'expected_schema')
def intervals(inp,out):
def positions(item):
assert_true(item['contig'] in inp['contigs'] and item['contig'].startswith('synthetic_'),'invalid_synthetic_contig')
start=item['start'];end=item['end']
if item['basis']=='one_closed':
assert_true(1<=start<=end,'invalid_one_based_interval');start-=1
assert_true(0<=start<=end<=inp['contigs'][item['contig']],'out_of_bounds_interval')
return set(range(start,end)),start,end
q=inp['query'];qset,a,b=positions(q);matches=[];covered=set()
for i,f in enumerate(inp['features']):
fset,_,_=positions(f)
if f['contig']!=q['contig'] or (inp['same_strand'] and f['strand']!=q['strand']):continue
overlap=fset&qset
if overlap:matches.append({'feature_index':i,'overlap_bases':len(overlap)});covered |= overlap
expected={'query_bed':[a,b],'matches':matches,'union_overlap_bases':len(covered),'query_length':len(qset)}
assert_true(enc(expected)==enc(out),'interval_oracle_disagreement')
CHECKS={'nav':nav,'coord':coord,'reads':reads,'align':align,'intervals':intervals}
class NearAudit:
def __init__(self):self.buckets=defaultdict(list);self.flagged=[];self.examined=0
def add(self,row,kind):
if kind not in ['reads','align']:return
seq=row['input']['source_sequence'] if kind=='align' else row['input']['fastq'].split('\n')[1]
grams={seq[i:i+7] for i in range(len(seq)-6)}
if not grams:return
bottom=sorted({zlib.crc32(g.encode()) for g in grams})[:4];seen=set()
for i,key in enumerate(bottom):
bucket=self.buckets[(i,key)]
for old,oldgrams in bucket[-25:]:
if old['id'] in seen:continue
seen.add(old['id']);self.examined+=1
score=len(grams&oldgrams)/len(grams|oldgrams)
if score>=.85 and row['group_id']!=old['group_id'] and row['split']!=old['split']:
self.flagged.append({'left':old['id'],'right':row['id'],'jaccard':score})
bucket.append(({'id':row['id'],'group_id':row['group_id'],'split':row['split']},grams))
if len(bucket)>25:del bucket[0]
def validate(kind,path,count,out):
path=Path(path);out=Path(out);out.mkdir(parents=True,exist_ok=True)
rejected=[];total=0;ids=set();fingerprints=set();groups={};splits=Counter();families=Counter();labels=Counter();near=NearAudit()
validator=Draft202012Validator(schema(kind))
if not path.is_file():rejected.append({'line':0,'reasons':['missing_dataset_file']})
else:
with path.open(encoding='utf-8') as stream:
for line_number,line in enumerate(stream,1):
total+=1
try:
row=strict(line);validator.validate(row)
assert_true(row['id']==kind.upper()+f'-{line_number-1:07d}' and row['index']==line_number-1,'id_or_index_sequence')
assert_true(row['id'] not in ids,'duplicate_id');ids.add(row['id'])
fp,group=semantic(kind,row['input'])
assert_true(row['fingerprint']==fp and fp not in fingerprints,'duplicate_or_invalid_semantic_fingerprint');fingerprints.add(fp)
assert_true(group==row['group_id'] and split(group)==row['split'],'group_split_mismatch')
assert_true(group not in groups or groups[group]==row['split'],'split_leakage');groups[group]=row['split']
if kind=='coord' and row['family']=='crossing':
a,b=row['input']['starts']
assert_true(a[0]==b[0] and abs(a[1]-b[1])>=2 and row['input']['goals']==row['input']['starts'][::-1],'crossing_family_contract')
if kind=='coord' and row['family']=='adjacent_swap':
a,b=row['input']['starts']
assert_true(abs(a[0]-b[0])+abs(a[1]-b[1])==1 and row['input']['goals']==row['input']['starts'][::-1],'swap_family_contract')
CHECKS[kind](row['input'],row['expected']);near.add(row,kind)
splits[row['split']]+=1;families[row['family']]+=1
if kind=='nav':labels['reachability_changed' if row['expected']['reachability_changed'] else 'cost_only_changed']+=1
elif kind=='coord':labels['solvable' if row['expected']['optimal_makespan'] is not None else 'unsolvable']+=1
elif kind=='reads':labels['format_invalid' if not row['expected']['valid_fastq'] else 'filter_pass' if row['expected']['passed_filter'] else 'filter_fail']+=1
elif kind=='align':labels['within_threshold' if row['expected']['within_threshold'] else 'outside_threshold']+=1
else:labels['overlap' if row['expected']['union_overlap_bases'] else 'no_overlap']+=1
except Exception as exc:
rejected.append({'line':line_number,'raw':line.rstrip('\n'),'reasons':[type(exc).__name__+': '+str(exc)[:500]]})
if total%1000==0:print(f'{kind}: independently checked {total}/{count}',flush=True)
problems=[]
if total!=count:problems.append('record_count')
if rejected:problems.append('rejected_records')
if near.flagged:problems.append('near_duplicate_cross_split_candidates')
if set(families)!=set(FAMILIES[kind]) or any(n!=count//5 for n in families.values()):problems.append('family_distribution')
if any(splits[k]==0 for k in ['train','validation','test']):problems.append('missing_split')
report={'brand':'RegalFire','kind':kind,'status':'PASS' if not problems else 'FAIL','expected_records':count,'records_read':total,'accepted':sum(families.values()),'rejected':len(rejected),'problems':problems,
'unique_ids':len(ids),'unique_fingerprints':len(fingerprints),'unique_source_groups':len(groups),'splits':dict(splits),'families':dict(families),'labels':dict(labels),
'dataset_sha256':sha(path.read_text(encoding='utf-8')) if path.exists() else None,
'near_duplicate_audit':{'scope':'DNA 7-mer bottom-4 CRC sketches; at most 25 previous candidates per bucket; Jaccard >=0.85 flags cross-split source groups. Not exhaustive homology testing. Grid symmetry and interval translation are exact semantic canonical checks.','candidate_pairs_examined':near.examined,'cross_split_flags':near.flagged},
'privacy_scope':'All originals are procedural; synthetic headers/contigs checked. No external biological records or game assets. Computational fixtures only, not clinical or experimentally established biology.'}
write_json(out/'validation_report.json',report);write_json(out/'stats.json',{k:report[k] for k in ['records_read','splits','families','labels','unique_source_groups']})
(out/'rejected.jsonl').write_text(''.join(enc(r)+'\n' for r in rejected),encoding='utf-8')
(out/'QA_REPORT.md').write_text('# RegalFire independent computational QA\n\nStatus: '+report['status']+'\n\n```json\n'+json.dumps(report,indent=2)+'\n```\n\nGenerator and validator label algorithms are separately implemented. Shared code covers serialization, schema and semantic identity only. Independent code is not independent human or biological validation. Seed reproducibility and file packaging integrity are separate recorded gates.\n',encoding='utf-8')
print(enc({k:report[k] for k in ['kind','status','accepted','rejected','problems']}),flush=True)
return report
def main():
p=argparse.ArgumentParser();p.add_argument('--kind',choices=NAMES,required=True);p.add_argument('--dataset',type=Path,required=True);p.add_argument('--count',type=int,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args()
return 0 if validate(a.kind,a.dataset,a.count,a.out)['status']=='PASS' else 1
if __name__=='__main__':raise SystemExit(main())