Datasets:
Download generator/make.py from RegalFire/BioAlign-EditDistance-HardCases-10K: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/datasets/RegalFire/BioAlign-EditDistance-HardCases-10K/resolve/main/generator/make.py
- Command line
-
hf download hf://datasets/RegalFire/BioAlign-EditDistance-HardCases-10K/generator/make.py
-
curl -L -o make.py https://huggingface.co/datasets/RegalFire/BioAlign-EditDistance-HardCases-10K/resolve/main/generator/make.py
14.4 kB
| """RegalFire original procedural fixture generators. Independent validation lives in check.py.""" | |
| import argparse | |
| from collections import deque | |
| import heapq | |
| import json | |
| from pathlib import Path | |
| import random | |
| import sys | |
| from common import * | |
| def astar(grid,costs,start,goal): | |
| h,w=len(grid),len(grid[0]); start=tuple(start); goal=tuple(goal) | |
| distance={start:0}; parent={}; queue=[(0,0,start)] | |
| while queue: | |
| _,cost,cell=heapq.heappop(queue) | |
| if distance[cell]!=cost: continue | |
| if cell==goal: | |
| path=[list(cell)] | |
| while cell!=start: cell=parent[cell]; path.append(list(cell)) | |
| return {'cost':cost,'path':path[::-1]} | |
| y,x=cell | |
| for dy,dx in [(1,0),(-1,0),(0,1),(0,-1)]: | |
| b=(y+dy,x+dx) | |
| if 0<=b[0]<h and 0<=b[1]<w and grid[b[0]][b[1]]=='.': | |
| d=cost+costs[b[0]][b[1]] | |
| if d<distance.get(b,10**9): | |
| distance[b]=d; parent[b]=cell | |
| heapq.heappush(queue,(d+abs(b[0]-goal[0])+abs(b[1]-goal[1]),d,b)) | |
| return {'cost':None,'path':None} | |
| def nav(r,family): | |
| h,w=r.randint(6,10),r.randint(6,10); wall=r.randint(2,w-3) | |
| gap=0 if family=='boundary_gap' else r.randint(1,h-2) | |
| if family=='two_gap_detour': gap=1 | |
| g=[['#' if r.random()<.22 else '.' for _ in range(w)] for _ in range(h)] | |
| for y in range(h): g[y][wall]='#' | |
| rows=[gap,h-2] if family=='two_gap_detour' else [gap] | |
| for y in rows: | |
| for x in range(w): g[y][x]='.' | |
| start=[r.randrange(h),r.randrange(wall)]; goal=[r.randrange(h),r.randint(wall+1,w-1)] | |
| if family=='two_gap_detour': start[0]=goal[0]=1 | |
| for p in [start,goal]: | |
| for row in rows: | |
| for y in range(min(p[0],row),max(p[0],row)+1): g[y][p[1]]='.' | |
| if family=='gap_open': g[gap][wall]='#' | |
| grid=[''.join(row) for row in g] | |
| costs=[[r.randint(1,5) if family=='weighted_gap_close' else 1 for x in range(w)] for y in range(h)] | |
| before=astar(grid,costs,start,goal) | |
| changed=[list(row) for row in grid]; changed[gap][wall]='.' if changed[gap][wall]=='#' else '#' | |
| after=astar([''.join(row) for row in changed],costs,start,goal) | |
| if before['cost']==after['cost']: raise ValueError('edit not critical') | |
| return {'grid':grid,'costs':costs,'start':start,'goal':goal,'edit':[gap,wall]}, {'before':before,'after':after,'reachability_changed':(before['cost'] is None)!=(after['cost'] is None)} | |
| def neighbors(grid,p,goal=None): | |
| y,x=p; options=[] | |
| for dy,dx in [(0,0),(1,0),(-1,0),(0,1),(0,-1)]: | |
| yy,xx=y+dy,x+dx | |
| if 0<=yy<len(grid) and 0<=xx<len(grid[0]) and grid[yy][xx]=='.': options.append((yy,xx)) | |
| return [p] if goal is not None and p==goal else options | |
| def single(grid,start,goal): | |
| q=deque([(tuple(start),0)]); seen={tuple(start)} | |
| while q: | |
| p,d=q.popleft() | |
| if p==tuple(goal): return d | |
| for b in neighbors(grid,p): | |
| if b not in seen: seen.add(b);q.append((b,d+1)) | |
| return None | |
| def joint_bfs(grid,starts,goals): | |
| start=tuple(map(tuple,starts)); target=tuple(map(tuple,goals)); q=deque([start]); parent={start:None} | |
| moves={tuple([y,x]):neighbors(grid,(y,x)) for y in range(len(grid)) for x in range(len(grid[0])) if grid[y][x]=='.'} | |
| while q: | |
| p=q.popleft() | |
| if p==target: | |
| plan=[] | |
| while p is not None: plan.append([list(p[0]),list(p[1])]);p=parent[p] | |
| return plan[::-1] | |
| for a in ([p[0]] if p[0]==target[0] else moves[p[0]]): | |
| for b in ([p[1]] if p[1]==target[1] else moves[p[1]]): | |
| state=(a,b) | |
| if a==b or (a==p[1] and b==p[0]) or state in parent: continue | |
| parent[state]=p;q.append(state) | |
| return None | |
| def coord(r,family): | |
| h,w=r.choice([4,5,6]),r.choice([4,5,6]) | |
| grid=[['#' if r.random()<.28 else '.' for _ in range(w)] for _ in range(h)] | |
| if family in ['bottleneck','separated']: | |
| wall=w//2 | |
| for y in range(h): grid[y][wall]='#' | |
| if family=='bottleneck': grid[r.randrange(h)][wall]='.' | |
| free=[[y,x] for y in range(h) for x in range(w) if grid[y][x]=='.'] | |
| if len(free)<8: raise ValueError('too few cells') | |
| starts=r.sample(free,2) | |
| if family=='adjacent_swap': | |
| adjacent=[p for p in free if abs(p[0]-starts[0][0])+abs(p[1]-starts[0][1])==1] | |
| if not adjacent: raise ValueError('no neighbor') | |
| starts[1]=r.choice(adjacent);goals=starts[::-1] | |
| elif family in ['bottleneck','separated']: | |
| left=[p for p in free if p[1]<w//2];right=[p for p in free if p[1]>w//2] | |
| if not left or not right: raise ValueError('empty region') | |
| starts=[r.choice(left),r.choice(right)];goals=starts[::-1] | |
| elif family=='crossing': | |
| rows=[[p for p in free if p[0]==y] for y in range(h)] | |
| candidates=[row for row in rows if len(row)>=2 and row[-1][1]-row[0][1]>=2] | |
| if not candidates:raise ValueError('no crossing row') | |
| row=r.choice(candidates);starts=[row[0],row[-1]];goals=starts[::-1] | |
| else: goals=r.sample([p for p in free if p not in starts],2) | |
| grid=[''.join(row) for row in grid] | |
| lower=[single(grid,s,g) for s,g in zip(starts,goals)] | |
| plan=joint_bfs(grid,starts,goals) if all(x is not None for x in lower) else None | |
| lb=max(lower) if all(x is not None for x in lower) else None | |
| cost=len(plan)-1 if plan else None | |
| return {'grid':grid,'starts':starts,'goals':goals}, {'plan':plan,'optimal_makespan':cost,'independent_lower_bound':lb,'coordination_overhead':cost-lb if cost is not None else None} | |
| def read_label(fastq,policy): | |
| header,seq,sep,qual=fastq.split('\n'); errors=[] | |
| if not header.startswith('@'): errors.append('header') | |
| if sep!='+': errors.append('separator') | |
| if any(x not in 'ACGTN' for x in seq): errors.append('alphabet') | |
| if len(seq)!=len(qual): errors.append('quality_length') | |
| if any(not 33<=ord(q)<=74 for q in qual): errors.append('quality_ascii') | |
| if errors: return {'valid_fastq':False,'errors':sorted(errors),'passed_filter':False,'trimmed_sequence':None,'trimmed_quality':None,'quality_sum':None,'length':None,'n_count':None,'gc_count':None} | |
| end=len(seq) | |
| while end>0 and ord(qual[end-1])-33<policy['trim_q_min']: end-=1 | |
| seq=seq[:end];qual=qual[:end];total=sum(ord(x)-33 for x in qual) | |
| return {'valid_fastq':True,'errors':[],'passed_filter':len(seq)>=policy['min_length'] and seq.count('N')<=policy['max_n'] and total>=policy['mean_q_min']*len(seq), | |
| 'trimmed_sequence':seq,'trimmed_quality':qual,'quality_sum':total,'length':len(seq),'n_count':seq.count('N'),'gc_count':seq.count('G')+seq.count('C')} | |
| def reads(r,family): | |
| policy={'min_length':r.randint(20,50),'max_n':r.randint(0,3),'mean_q_min':r.randint(18,28),'trim_q_min':r.randint(4,15)} | |
| length=r.randint(24,90) | |
| if family=='length_boundary': length=policy['min_length']+r.choice([-1,0,1]) | |
| seq=''.join(r.choices('ACGT',k=length));q=[r.randint(30,41) for _ in seq] | |
| if family=='quality_boundary': | |
| level=policy['mean_q_min']+r.choice([-1,0,1]);q=[level for _ in seq] | |
| if family=='ambiguous_bases': | |
| count=policy['max_n']+r.choice([0,1]);idx=r.sample(range(length),count);s=list(seq) | |
| for i in idx:s[i]='N' | |
| seq=''.join(s) | |
| if family=='clean': | |
| tail=r.randint(1,8);q[-tail:]=[2]*tail | |
| qual=''.join(chr(x+33) for x in q);header='@synthetic_read';sep='+' | |
| if family=='malformed_record': | |
| error=r.choice(['header','separator','alphabet','quality_length','quality_ascii']) | |
| if error=='header':header='synthetic_read' | |
| elif error=='separator':sep='-' | |
| elif error=='alphabet':seq=seq[:-1]+'X' | |
| elif error=='quality_length':qual=qual[:-1] | |
| else:qual=qual[:-1]+chr(32) | |
| fastq='\n'.join([header,seq,sep,qual]) | |
| return {'fastq':fastq,'policy':policy},read_label(fastq,policy) | |
| def alignment(a,b): | |
| n,m=len(a),len(b);d=[[0]*(m+1) for _ in range(n+1)] | |
| for i in range(n+1):d[i][0]=i | |
| for j in range(m+1):d[0][j]=j | |
| for i in range(1,n+1): | |
| for j in range(1,m+1):d[i][j]=min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]!=b[j-1])) | |
| aa=[];bb=[];i=n;j=m | |
| while i or j: | |
| if i and j and d[i][j]==d[i-1][j-1]+(a[i-1]!=b[j-1]):aa.append(a[i-1]);bb.append(b[j-1]);i-=1;j-=1 | |
| elif i and d[i][j]==d[i-1][j]+1:aa.append(a[i-1]);bb.append('-');i-=1 | |
| else:aa.append('-');bb.append(b[j-1]);j-=1 | |
| return d[n][m],''.join(aa[::-1]),''.join(bb[::-1]) | |
| def align(r,family): | |
| rand=lambda n:''.join(r.choices('ACGT',k=n)) | |
| if family=='homopolymer':a=rand(10)+r.choice('ACGT')*r.randint(8,16)+rand(10) | |
| elif family=='tandem_repeat':a=rand(9)+rand(3)*r.randint(3,7)+rand(9) | |
| else:a=rand(r.randint(24,50)) | |
| if family=='literal_N':a=a[:10]+'NN'+a[12:] | |
| source=a | |
| if family=='reverse_complement':b=rc(a) | |
| else: | |
| b=list(a) | |
| for _ in range(r.randint(1,5)): | |
| pos=r.randrange(len(b));operation=r.choice(['sub','ins','del']) | |
| if operation=='sub':b[pos]=r.choice('ACGTN' if family=='literal_N' else 'ACGT') | |
| elif operation=='ins':b.insert(pos,r.choice('ACGT')) | |
| else:b.pop(pos) | |
| b=''.join(b) | |
| distance,aa,bb=alignment(a,b);threshold=max(0,distance+r.choice([-1,0,1])) | |
| return {'a':a,'b':b,'source_sequence':source,'threshold':threshold},{'edit_distance':distance,'within_threshold':distance<=threshold,'aligned_a':aa,'aligned_b':bb} | |
| def interval_label(inp): | |
| def bed(v):return v['start']-(v['basis']=='one_closed'),v['end'] | |
| q=inp['query'];a,b=bed(q);matches=[];segments=[] | |
| for i,f in enumerate(inp['features']): | |
| if f['contig']!=q['contig'] or (inp['same_strand'] and f['strand']!=q['strand']):continue | |
| c,d=bed(f);lo,hi=max(a,c),min(b,d) | |
| if lo<hi:matches.append({'feature_index':i,'overlap_bases':hi-lo});segments.append((lo,hi)) | |
| covered=0;end=-1 | |
| for lo,hi in sorted(segments):covered+=max(0,hi-max(lo,end));end=max(end,hi) | |
| return {'query_bed':[a,b],'matches':matches,'union_overlap_bases':covered,'query_length':b-a} | |
| def intervals(r,family): | |
| contigs={'synthetic_A':r.randint(600,1800),'synthetic_B':r.randint(600,1800)} | |
| c=r.choice(list(contigs));a=r.randint(20,contigs[c]-200);b=a+r.randint(5,80) | |
| q={'contig':c,'start':a,'end':b,'strand':r.choice(['+','-']),'basis':'zero_half_open'} | |
| features=[] | |
| for _ in range(r.randint(5,12)): | |
| cc=r.choice(list(contigs));x=r.randint(0,contigs[cc]-120);features.append({'contig':cc,'start':x,'end':x+r.randint(1,120),'strand':r.choice(['+','-']),'basis':'zero_half_open'}) | |
| def feature(start,end,strand=None):return {'contig':c,'start':start,'end':end,'strand':strand or q['strand'],'basis':'zero_half_open'} | |
| if family=='touching_boundary':features[:2]=[feature(max(0,a-r.randint(1,20)),a),feature(b,b+r.randint(1,40))] | |
| elif family=='nested':features[:2]=[feature(a-5,b+5),feature(a+1,b-1)] | |
| elif family=='overlapping_blocks':features[:3]=[feature(a-3,a+3),feature(a+1,b),feature(b-2,b+3)] | |
| elif family=='stranded':features[:2]=[feature(a,b,'+'),feature(a,b,'-')] | |
| else:features[0]=feature(a,b) | |
| for f in features+[q]: | |
| if r.random()<.5 or family=='coordinate_conversion':f['start']+=1;f['basis']='one_closed' | |
| inp={'contigs':contigs,'features':features,'query':q,'same_strand':family=='stranded' or r.choice([True,False])} | |
| return inp,interval_label(inp) | |
| MAKERS={'nav':nav,'coord':coord,'reads':reads,'align':align,'intervals':intervals} | |
| def generate(kind,out,count,seed,resume=False): | |
| out=Path(out) | |
| if out.exists() and not resume:raise ValueError('output exists; use --resume') | |
| out.mkdir(parents=True,exist_ok=True);chunks=out/'chunks';chunks.mkdir(exist_ok=True) | |
| binding={'kind':kind,'count':count,'seed':seed,'source_sha256':sha(Path(__file__).read_text(encoding='utf-8')),'common_sha256':sha(Path(__file__).with_name('common.py').read_text(encoding='utf-8'))} | |
| if (out/'config.json').exists() and strict((out/'config.json').read_text())!=binding:raise ValueError('resume parameters/source mismatch') | |
| write_json(out/'config.json',binding) | |
| seen=set();total=0 | |
| for file in sorted(chunks.glob('*.jsonl')): | |
| for line in file.read_text(encoding='utf-8').splitlines(): | |
| row=strict(line) | |
| if row['index']!=total or row['fingerprint'] in seen:raise ValueError('invalid checkpoint shard') | |
| seen.add(row['fingerprint']);total+=1 | |
| if total>count:raise ValueError('count below checkpoint size') | |
| attempts=0 | |
| while total<count: | |
| batch=[];start=total | |
| while len(batch)<min(500,count-start): | |
| i=total;family=FAMILIES[kind][i%5] | |
| for retry in range(1000): | |
| try: | |
| inp,expected=MAKERS[kind](random.Random(seed+i*1009+retry*100000003),family) | |
| fp,group=semantic(kind,inp) | |
| if fp in seen:continue | |
| seen.add(fp);break | |
| except ValueError:continue | |
| else:raise ValueError('cannot produce unique record') | |
| attempts+=retry | |
| batch.append({'id':kind.upper()+f'-{i:07d}','index':i,'seed':seed,'family':family,'input':inp,'expected':expected,'fingerprint':fp,'group_id':group,'split':split(group),'provenance':provenance(kind)}) | |
| total+=1 | |
| temp=chunks/f'{start:07d}.jsonl.tmp';temp.write_text(''.join(enc(x)+'\n' for x in batch),encoding='utf-8');temp.replace(chunks/f'{start:07d}.jsonl') | |
| write_json(out/'checkpoint.json',{'committed_records':total,'target':count,'attempt_retries_this_run':attempts}) | |
| print(f'{kind}: generated {total}/{count}',flush=True) | |
| with (out/'dataset.jsonl.tmp').open('w',encoding='utf-8',newline='\n') as dest: | |
| for file in sorted(chunks.glob('*.jsonl')):dest.write(file.read_text(encoding='utf-8')) | |
| (out/'dataset.jsonl.tmp').replace(out/'dataset.jsonl') | |
| return total | |
| def main(): | |
| p=argparse.ArgumentParser();p.add_argument('--kind',choices=NAMES,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--count',type=int,required=True);p.add_argument('--seed',type=int,default=20261001);p.add_argument('--resume',action='store_true');a=p.parse_args() | |
| if not 100<=a.count<=100000:raise ValueError('count must be 100-100000') | |
| generate(a.kind,a.out,a.count,a.seed,a.resume) | |
| if __name__=='__main__':main() | |