"""Freeze balanced development-only source selection for separated fields."""
import collections,json,random
from pathlib import Path
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/scaleup-separated-scenes';B=R/'results/r112/academy-backgrounds-v2/manifest.json'
def main():
 assert not (O/'protocol.json').exists();data=UDEScaleupDataset('training');pool=collections.defaultdict(list)
 for i,x in enumerate(data.entries):pool[x['source_species']].append(i)
 assert len(pool)==80;rng=random.Random(11279227);names=sorted(pool);extra=set(rng.sample(names,64));indices=[]
 for name in names:
  rng.shuffle(pool[name]);indices.extend(pool[name][:4+(name in extra)])
 assert len(indices)==len(set(indices))==384;rng.shuffle(indices);backgrounds=[]
 for r in json.loads(B.read_text())['records']:
  for x in r['images']:backgrounds.append({'slide':r['slide'],'site_index':r['site_index'],'origin_xy':r['origin_xy'],'z_index':x['z_index'],'path':str((B.parent/x['path']).relative_to(R)),'sha256':x['sha256'],'um_per_pixel_xy':r['um_per_pixel_xy']})
 assert len(backgrounds)==192;rng.shuffle(backgrounds);offset=0;scenes=[]
 for i,bg in enumerate(backgrounds):
  n=1+i%3;instances=[]
  for j,idx in enumerate(indices[offset:offset+n]):
   r=data.entries[idx];instances.append({'training_index':idx,'annotation_id':r['annotation_id'],'source_name':r['source_species'],'source_genus':r['source_genus'],'source_site_component':r['source_site_component'],'rotation_ccw_degrees':rng.randrange(0,360,15),'opacity':round(rng.uniform(.3,.9),8),'contrast_exponent':round(rng.uniform(.7,1.3),8),'prefer_edge':bool(j==0 and i%4==0)})
  offset+=n;scenes.append({'id':f'scene-{i:04d}','background':bg,'placement_seed':11279000+i,'instances':instances})
 assert offset==384;files=['research/r112_scaleup_separated_select.py','research/r112_scaleup_separated_render.py','research/r112_scaleup_scene_render.py','research/r112_weak_scenes.py','research/r112_scaleup_synthetic_compare.py','diatom_pilot/ude_scaleup_dataset.py','results/r112/species-scaleup/assets.json','results/r112/species-scaleup/verify.json','results/r112/species-scaleup/selection.json','results/r112/species-scaleup/location-partitions.json','results/r112/species-scaleup/partition-verify.json','results/r112/species-scaleup/mask-hypotheses/verify.json',str(B.relative_to(R))];p={'format':'r112-scaleup-separated-scenes-v1','inputs_sha256':{x:sha(R/x) for x in files},'selection':'384 unique training crops, 4 or 5 per 80 source-name strings, shuffled by metadata before image access; one to three source inserts on each of 192 previously used Academy development background planes. All sources also appear in the crowded development set. No tuning/check pixels.','placement':'Transform native source to Academy XY scale and rotate; draw candidate centers reproducibly, up to 100 attempts per item and up to 30 complete scene retries. Reject inserted support if it intersects another inserted support, has zero pixels, or has <15% of its transformed support in frame. For the first item of every fourth scene, candidate center is on a field edge. Fixed algorithm, report all attempts and actual centers. Fail rather than claim success if no layout found.','rendering':'Same grayscale floating-point multiplicative transmission proxy as crowded set, one rounding at end, opacity 0.3–0.9 and exponent 0.7–1.3; inserted projected masks are not verified anatomy. No capped contrast enhancement.','labels':'Background organisms remain unknown everywhere, including under inserted supports; inserted supports are unverified model proposals, not masks of confirmed anatomy or visibility. Source taxon names are public UDE dataset authors’ labels, not reconciled with Academy concepts.','limitations':'Separated only among synthetic projected supports. Background can contain other diatoms overlapping insertions; scene may look crowded. Reused backgrounds and all sources are previously used development examples, not independent evaluation. Optics, labels, masks, biology and species identifiability are not validated; single planes are not a physical Z-stack.','scenes':scenes};(O/'protocol.json').write_text(json.dumps(p,indent=2)+'\n');print('frozen',len(scenes),'scenes,',offset,'training sources')
if __name__=='__main__':main()
