"""Freeze low- and high-density scenes using only prior training components."""
import json,random
from pathlib import Path
from diatom_pilot.ude_breadth_dataset import UDEBreadthDataset
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/breadth-diverse-scenes';B=R/'results/r112/academy-backgrounds-v2/manifest.json'
def main():
 assert not (O/'protocol.json').exists();data=UDEBreadthDataset('prior_training_components');assert len(data)==784 and len({x['source_species'] for x,p in data.entries})==137;rng=random.Random(11292026);order=list(range(len(data)));rng.shuffle(order);bg=[]
 for r in json.loads(B.read_text())['records']:
  for x in r['images']:bg.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(bg)==192;rng.shuffle(bg);counts=[2,4,6,8,10,12,14]*14;assert len(counts)==98 and sum(counts)==784;offset=0;scenes=[]
 for si,n in enumerate(counts):
  mode='separated' if n==2 else ('clustered' if si%2==0 else 'spread');anchor=[rng.randrange(170,598),rng.randrange(170,598)];items=[]
  for j,idx in enumerate(order[offset:offset+n]):
   entry,partition=data.entries[idx];assert partition=='training';r={'training_index':idx,'annotation_id':entry['annotation_id'],'source_name':entry['source_species'],'source_genus':entry['source_genus'],'source_site_component':entry['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)}
   if mode=='separated':r['prefer_edge']=bool(j==0 and si%4==0)
   else:
    if j==0 and si%4==0:center=[rng.choice([0,767]),rng.randrange(768)]
    elif mode=='clustered' and j<5:center=[max(0,min(767,anchor[0]+rng.randrange(-60,61))),max(0,min(767,anchor[1]+rng.randrange(-60,61)))]
    else:center=[rng.randrange(768),rng.randrange(768)]
    r['center_xy']=center
   items.append(r)
  offset+=n;scenes.append({'id':f'scene-{si:04d}','mode':mode,'background':bg[si],'placement_seed':11293000+si,'instances':items})
 files=['research/r112_breadth_scenes_select.py','research/r112_breadth_scenes_render.py','research/r112_scaleup_scene_render.py','research/r112_scaleup_separated_render.py','research/r112_weak_scenes.py','research/r112_scaleup_synthetic_compare.py','diatom_pilot/ude_scaleup_dataset.py','diatom_pilot/ude_breadth_dataset.py','results/r112/species-breadth/assets.json','results/r112/species-breadth/verify.json','results/r112/species-breadth/selection.json','results/r112/species-breadth/prior-split-exposure.json','results/r112/species-breadth/reader-verify.json','results/r112/species-breadth/mask-hypotheses/verify.json','results/r112/species-scaleup/location-partitions.json',str(B.relative_to(R))];p={'format':'r112-breadth-diverse-scenes-v1','inputs_sha256':{f:sha(R/f) for f in files},'selection':'All 784 unique breadth crops from the earlier 80-name training-component groups, 137 source-name strings, shuffled into 98 scenes with 2,4,6,8,10,12 or 14 insertions (14 scenes of each count). Earlier tuning/check location groups are excluded as sources. The already-exposed earlier split remains development only, not independent. Backgrounds reuse 98 previously used Academy fields/planes.','placement':'Two-insertion scenes use deterministic rejection sampling to prevent intersections between inserted projected supports and ensure >=15% in-frame support; 4–14 instances use either clustered or spread randomized centers and periodic edge placement. Background organisms may overlap any insertions.','rendering':'Prior grayscale transmission proxy with 0.09 µm/px nominal source and recorded Academy OME XY scale, varied rotation, opacity and contrast. Separate projected center-mask supports may overlap; no contrast-boost variant.','labels':'Background is unknown everywhere, including under insertions. Source names are public-author labels, not independently reconciled with Academy taxonomy. All masks are unverified shared-model proposals, not ground-truth or visibility masks.','limitations':'Reused public sources and Academy backgrounds, not an independent benchmark. Some source-name strings have only one or two eligible examples; possible synonyms are unresolved. Some projections may be clipped or imperceptible, and sources may include neighbors. Optics and true Z-stack effects are not simulated.','scenes':scenes};(O/'protocol.json').write_text(json.dumps(p,indent=2)+'\n');print('frozen',len(scenes),'fields and',offset,'training-component source uses')
if __name__=='__main__':main()
