import html,json
from pathlib import Path
import numpy as np
from PIL import Image
import matplotlib;matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon,Rectangle
R=Path(__file__).resolve().parents[1];O=R/'results/r95/partial';d=json.loads((O/'results.json').read_text());rows=d['records'];assert len(rows)==19;mf=json.loads((O/'training-manifest.json').read_text())['records'];examples=[r for r in mf if r['hidden']][:3];assert len(examples)==3
fig,axes=plt.subplots(1,3,figsize=(13,4.3),constrained_layout=True)
for ax,r in zip(axes,examples):
 ax.imshow(np.asarray(Image.open(R/r['image']).convert('RGB')));lines=(R/r['label']).read_text().splitlines()
 for line in lines:
  xy=np.asarray([float(x) for x in line.split()[1:]]).reshape(-1,2)*512;ax.add_patch(Polygon(xy,fill=False,edgecolor='#00b47c',linewidth=2))
 hidden=np.asarray([float(x) for x in r['hidden']['source_polygon_line'].split()[1:]]).reshape(-1,2)*512;ax.add_patch(Polygon(hidden,fill=False,edgecolor='#ed793c',linewidth=2));x0,y0,x1,y1=r['hidden']['bbox_xyxy_half_open'];ax.add_patch(Rectangle((x0,y0),x1-x0,y1-y0,fill=False,edgecolor='#ffd535',linewidth=2,linestyle='--'));ax.set_title(f"{r['group']} field {r['id']}");ax.set_xlim(0,512);ax.set_ylim(512,0);ax.axis('off')
fig.savefig(O/'hidden-examples.png',dpi=130);plt.close(fig)
table=[]
for cat,label in [('real','Gündüz real'),('synthetic','Gündüz synthetic')]:
 a=[r for r in rows if r['category']==cat];den=sum(r['references'] for r in a)
 for th in ('0.5','0.75'):
  v=[sum(r['scores'][name]['30'][th]['matched'] for r in a) for name in ('standard','oracle','full','baseline')];table.append(f'<tr><td>{label} ({len(a)} cases)</td><td>{th}</td>'+''.join(f'<td>{n}/{den}</td>' for n in v)+'</tr>')
sections=[]
for r in rows:
 v=[r['scores'][name]['30']['0.5']['matched'] for name in ('standard','oracle','full','baseline')];sections.append(f'<section><h3>{html.escape(r["name"])}</h3><p>{r["references"]} source regions. Top-30 matches: partial standard {v[0]}, partial oracle-ignore {v[1]}, full-label control {v[2]}, SAM+Cellpose {v[3]}. <a href="/{html.escape(r["source"])}">Source image</a> · <a href="{r["archive"]}">Both partial-model mask arrays</a></p><img src="{r["image"]}" alt="Source regions and predictions from both partial-label models and controls"></section>')
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R95 controlled missing-label test</title><style>body{font:16px/1.55 system-ui;max-width:1250px;margin:2em auto;padding:0 1em;color:#18342f}a{color:#006b59}img{max-width:100%}.box{background:#fff2d6;padding:1em}section{border-top:1px solid #ccc}td,th{padding:.4em;border:1px solid #bbc}table{border-collapse:collapse}</style><a href="/results/board.html">Research board</a> · <a href="/results/l83/">Loss-gradient check</a> · <a href="/results/r95/mixed/">Full-label pilot</a><h1>R95: What if known objects are left unlabeled?</h1><p class="box">The ignore boxes in this experiment are an <strong>oracle</strong>: they use the true location of deliberately hidden source annotations. They cannot locate genuinely unknown diatoms. All 19 evaluation cases were previously viewed; real source references have no severe intersections, and synthetic crossings are not physical microscopy. This is not evidence of human-level or severe real-overlap performance.</p><p>Start from 28 training images and 47 source polygons. Hide the last known polygon in each of 14 multi-label images, leaving 33 visible labels. Train identical 12-epoch models with either standard loss or classification-anchor ignore inside the known hidden polygons' bounding boxes. Compare with the earlier 12-epoch full-label run and the existing SAM/Cellpose proposal stream. These intentionally hidden labels are distinct from any additional genuinely unannotated objects.</p><img src="hidden-examples.png" alt="Three training examples showing retained polygons, deliberately hidden polygons and their oracle ignore boxes"><p>Green outlines are retained source labels; orange outlines are deliberately hidden source labels; yellow dashed rectangles are oracle ignore regions. Original source labels may themselves be incomplete.</p><table><tr><th>Cases</th><th>IoU</th><th>Partial labels, standard</th><th>Partial labels, oracle-ignore</th><th>All source labels</th><th>SAM + Cellpose</th></tr>'''+''.join(table)+'''</table><p>Counts are one-to-one source/visible-region matches at a budget of 30 masks per field. At IoU 0.5 two real fields changed in opposite directions under ignore, so equal totals do not mean identical predictions. The standard/ignore models emitted 31/42 masks on real fields and 23/27 on synthetic scenes. Unmatched masks are not verified false positives because references may be incomplete.</p><p>Instrumentation confirmed the custom criterion was called in 84 training batches, ignored 25,855 negative-anchor occurrences, preserved 281 positive-anchor occurrences in ignored regions, and checked pixel alignment for all 336 training-image presentations. These are repeated training occurrences, not distinct biological objects. A separate gradient control verified direct classification-loss behavior. Shared model weights can still affect ignored regions, and the instance-mask loss inside labeled boxes was unchanged.</p><p>Sources: <a href="https://doi.org/10.5281/zenodo.7079005">River Menne data</a>, CC BY 4.0; <a href="https://zenodo.org/records/21295927">Khanom diatoms</a>, CC BY 4.0; <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Gündüz evaluation diatoms</a>, CC BY-NC-SA 4.0. Starting-model, software and local Academy background terms also apply.</p><p><a href="protocol.json">Protocol</a> · <a href="training-manifest.json">Hidden labels and ignore boxes</a> · <a href="training-run.json">Training and instrumentation</a> · <a href="results.json">All scores and masks</a> · <a href="verify.log">Verification</a> · <a href="/research/R95.md">Research note</a></p><h2>Evaluation comparisons</h2>'''+''.join(sections)+'</html>')
