"""Freeze location-component separated partitions for the 4,000-crop development pool."""
import collections,hashlib,json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 out=O/'location-partitions.json';assert not out.exists();s=json.loads((O/'selection.json').read_text());assets=json.loads((O/'assets.json').read_text());assert assets['selection_sha256']==sha(O/'selection.json') and len(s['records'])==len(assets['records'])==4000;records=s['records'];names=sorted({r['source_species'] for r in records});groups=sorted({r['site_component'] for r in records});assert len(names)==80 and len(groups)==120;ni={x:i for i,x in enumerate(names)};gi={x:i for i,x in enumerate(groups)};M=np.zeros((len(groups),len(names)),dtype=np.int16)
 for r in records:M[gi[r['site_component']],ni[r['source_species']]]+=1
 rng=np.random.default_rng(20261212);u=rng.random((4096,len(groups)));assign=np.where(u<.70,0,np.where(u<.85,1,2));counts=np.stack([(assign==p).astype(np.int16)@M for p in (0,1,2)],axis=1);total=counts.sum(axis=2);valid=(total[:,0]>=2000)&(total[:,0]<=3200)&(total[:,1]>=400)&(total[:,1]<=1000)&(total[:,2]>=400)&(total[:,2]<=1000);coverage=((counts[:,0,:]>=20)&(counts[:,1,:]>=3)&(counts[:,2,:]>=3)).sum(axis=1);penalty=np.abs(total[:,0]-2800)+np.abs(total[:,1]-600)+np.abs(total[:,2]-600);scores=np.where(valid,coverage*100000-penalty,-10**12);assert valid.any();idx=int(np.argmax(scores));chosen=assign[idx];labels=('training','tuning','check');group_partition={g:labels[int(chosen[i])] for i,g in enumerate(groups)};rows=[{'annotation_id':r['annotation_id'],'source_species':r['source_species'],'site_component':r['site_component'],'partition':group_partition[r['site_component']]} for r in records];per_name={name:{labels[p]:int(counts[idx,p,ni[name]]) for p in range(3)} for name in names};summary={p:sum(x['partition']==p for x in rows) for p in labels};result={'format':'r112-scaleup-location-partitions-v1','selection_sha256':sha(O/'selection.json'),'assets_sha256':sha(O/'assets.json'),'seed':20261212,'assignment':'Metadata only: 4,096 seeded random assignments of 120 conservative location components (nominal 70/15/15); among assignments with 50–80% training and 10–25% each tuning/check crops, maximize source-name strings with at least 20/3/3 crops and then minimize total deviation from 70/15/15 crop counts. All images in a location component stay together.','status':'All three partitions are development material. These sources/locations were previously accessed or selected; some individual crops appeared in earlier synthetic comparisons, and all are being processed for unverified mask proposals. The check partition is not an independent biological or Academy test and must not be used to claim generalization.','warning':'Location components are conservative site/coordinate proxies and may overmerge or miss related samples. Names and masks require independent verification; no name normalization, expert mask or negative-background labels are asserted. The old UDE test-candidate components and the separately protected candidate-unseen locations are excluded from this entire selection.','counts':summary,'source_name_strings':len(names),'names_meeting_20_3_3':int(coverage[idx]),'component_counts':{p:sum(x==p for x in group_partition.values()) for p in labels},'per_name':per_name,'group_partition':group_partition,'records':rows};out.write_text(json.dumps(result,indent=2)+'\n');print('partitions',summary,'components',result['component_counts'],'names meeting 20/3/3',int(coverage[idx]),'/',len(names))
if __name__=='__main__':main()
