"""Freeze a source-unique, training-only multi-instance development recipe."""
import 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];D=R/'results/r112/species-scaleup';O=R/'results/r112/scaleup-crowded-scenes';B=R/'results/r112/academy-backgrounds-v2/manifest.json'
def main():
 target=O/'protocol.json';assert not target.exists();dataset=UDEScaleupDataset('training');entries=dataset.entries;assert len(entries)==2830 and len({x['annotation_id'] for x in entries})==2830
 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=random.Random(11277226);order=list(range(len(entries)));rng.shuffle(order);rng.shuffle(bg);scenes=[];counts=[4,6,8,10,12,14,16]*40+[8,10,12];assert len(counts)==283 and sum(counts)==2830;offset=0
 for si in range(283):
  background=bg[si%len(bg)];anchor=[rng.randrange(170,598),rng.randrange(170,598)];instances=[]
  for j,idx in enumerate(order[offset:offset+counts[si]]):
   entry=entries[idx]
   if j==0 and si%3==0:center=[rng.choice([0,767]),rng.randrange(768)]
   elif 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)]
   instances.append({'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),'center_xy':center,'opacity':round(rng.uniform(.3,.9),8),'contrast_exponent':round(rng.uniform(.7,1.3),8)})
  offset+=counts[si];scenes.append({'id':f'scene-{si:04d}','background':background,'instances':instances})
 paths=['research/r112_scaleup_scene_select.py','research/r112_scaleup_scene_render.py','research/r112_weak_scenes.py','diatom_pilot/ude_scaleup_dataset.py','results/r112/species-scaleup/selection.json','results/r112/species-scaleup/assets.json','results/r112/species-scaleup/verify.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-crowded-scenes-v1','seed':11277226,'inputs_sha256':{x:sha(R/x) for x in paths},'selection':'All 2830 training-partition crops once each, shuffled into 283 scenes with 4, 6, 8, 10, 12, 14 or 16 instances each; no tuning or check image pixels accessed. Backgrounds are 192 previously used Academy fields/planes from eight development slides, reused cyclically; they may contain other diatoms and are unknown, not negatives. First five centers cluster; first item in each third scene is edge-centered.','rendering':'Grayscale 768x768, source nominal 0.09 um/pixel resampled to per-slide OME XY scale and rotated. Each unverified center mask supplies a separate projected support. Transparent transmission proxy multiplies the existing floating-point canvas, opacity 0.3–0.9 and exponent 0.7–1.3, with clip/round once at the end. This is not calibrated microscope optics or actual hidden anatomy; no contrast-proxy enhancement is used.','labels':'All original background regions are unknown and can include diatoms, including under inserted supports. Projected masks are unverified model hypotheses, overlapping supports are not mutually exclusive; support is not visibility, validated instance geometry or ground-truth background. Source names are author-reviewed UDE labels, not independently reconciled with Academy taxonomy.','limits':'Development only. This is not an independent test set or proof of taxonomic and optical realism; source crop neighbors may be pasted, masks can be wrong, and forced edge centers may yield zero or tiny in-frame support. Two-dimensional scenes do not simulate Z stacks; reused field sites and source locations cannot establish independent generalization. Must inspect and obtain expert validation before treating these as quality training targets.','scenes':scenes};target.write_text(json.dumps(p,indent=2)+'\n');print('frozen',len(scenes),'scenes',sum(len(s['instances']) for s in scenes),'source uses')
if __name__=='__main__':main()
