"""Evaluate a frozen Point or Trace subset, never combine unlike metrics.""" import argparse from collections import defaultdict import json from pathlib import Path import numpy as np from .core_metrics import score from .io import ROOT, indexed, read_jsonl, sha256, write_json, write_jsonl POINT_TASKS = ['object_grounding', 'spatial_reference', 'affordance', 'placement_surface'] TRACE_TASKS = ['object_trajectory', 'end_effector_trajectory'] def mean_or_none(values): return float(np.mean(values)) if values and all(v is not None for v in values) else None def cluster_ci(rows, key, factor=1.): groups = defaultdict(list) for row in rows: groups[row['group_id']].append(row.get(key)) values = list(groups.values()) if not values: return None sums = np.array([sum(x for x in g if x is not None) for g in values]) counts = np.array([sum(x is not None for x in g) for g in values]) rng = np.random.default_rng(20261115) ids = rng.integers(0, len(values), size=(2000, len(values))) denominators = counts[ids].sum(1) ok = denominators > 0 if not ok.any(): return None estimates = sums[ids].sum(1)[ok] / denominators[ok] return (factor*np.quantile(estimates, [.025, .975])).tolist() def bucket_summary(rows, trace): out = dict(n=len(rows), valid=sum(r['valid'] for r in rows), valid_pct=100*sum(r['valid'] for r in rows)/len(rows), valid_cluster_ci95_pct=cluster_ci(rows, 'valid', 100)) if trace: for key in ['rmse_m', 'mae_m']: values = [r[key] for r in rows if r[key] is not None] label = key.replace('_m', '_cm') out[label+'_valid_mean'] = 100*float(np.mean(values)) if values else None out[label+'_valid_median'] = 100*float(np.median(values)) if values else None out[label+'_valid_cluster_ci95'] = cluster_ci(rows, key, 100) else: for cm in [1, 2, 5, 10]: out[f'agreement_{cm}cm_pct'] = 100*float(np.mean([r[f'agreement_{cm}cm'] for r in rows])) out['agreement_5cm_cluster_ci95_pct'] = cluster_ci(rows, 'agreement_5cm', 100) # Spatial reference has no authoritative full target mask; do not invent one. out['projection_hit_pct'] = (100*float(np.mean([r['projection_hit_fraction'] for r in rows])) if all('projection_hit_fraction' in r for r in rows) else None) return out def summarize(rows, benchmark): trace = benchmark == 'trace' groups = defaultdict(list) tasks = defaultdict(list) for row in rows: groups[(row['task'], row['source'], row['label_tier'])].append(row) tasks[row['task']].append(row) buckets = [dict(task=t, source=s, label_tier=l, **bucket_summary(rs, trace)) for (t, s, l), rs in sorted(groups.items())] task_reports = [] for task, rs in sorted(tasks.items()): r = dict(task=task, **bucket_summary(rs, trace)) if trace: sources = defaultdict(list) for row in rs: sources[row['source']].append(row) source_means = [bucket_summary(v, True) for v in sources.values()] for key in ['rmse_cm_valid_mean', 'mae_cm_valid_mean']: r[key.replace('_valid_mean', '_source_macro_valid_mean')] = mean_or_none([s[key] for s in source_means]) task_reports.append(r) out = dict(buckets=buckets, tasks=task_reports, all_predictions_valid=all(r['valid'] for r in rows), invalid_count=sum(not r['valid'] for r in rows)) by_task = {r['task']: r for r in task_reports} if trace: for key in ['rmse_cm_source_macro_valid_mean', 'mae_cm_source_macro_valid_mean']: out[key.replace('_source_macro', '_task_source_macro')] = mean_or_none([by_task.get(t, {}).get(key) for t in TRACE_TASKS]) out['ranking_note'] = 'Errors are valid-output-only; compare validity alongside errors. An all-invalid bucket makes its macro error undefined, not zero.' else: out['four_task_reference_agreement_5cm_pct'] = mean_or_none([by_task.get(t, {}).get('agreement_5cm_pct') for t in POINT_TASKS]) out['three_region_task_acc_5cm_pct'] = mean_or_none([by_task.get(t, {}).get('agreement_5cm_pct') for t in POINT_TASKS if t != 'spatial_reference']) out['spatial_reference_note'] = 'Sparse positive-reference agreement, not complete region accuracy; excluded from three-region-task accuracy.' return out def main(): p = argparse.ArgumentParser() p.add_argument('--data', type=Path, required=True, help='data/core_v2/point or data/core_v2/trace') p.add_argument('--split', choices=['dev', 'test'], default='test') p.add_argument('--predictions', type=Path, required=True) p.add_argument('--output', type=Path, required=True) p.add_argument('--allow-incomplete', action='store_true') args = p.parse_args() manifest = json.loads((args.data/'manifest.json').read_text()) if manifest['version'] != 'robo3d-core-v2': raise ValueError('This evaluator is only for core-v2; use evaluate_existing for v1') benchmark = manifest['benchmark'] if benchmark not in ['point', 'trace']: raise ValueError('Unknown benchmark') checksums = json.loads((args.data/'checksums.json').read_text()) for name in ['manifest.json', f'{args.split}_inputs.jsonl', f'{args.split}_gold.jsonl']: if sha256(args.data/name) != checksums[name]: raise ValueError('Release manifest changed: ' + name) for name, digest in manifest.get('scoring_code_sha256', {}).items(): if sha256(ROOT/'bench'/name) != digest: raise ValueError('Frozen scorer changed; publish a new protocol: ' + name) inputs = indexed(read_jsonl(args.data/f'{args.split}_inputs.jsonl')) gold = indexed(read_jsonl(args.data/f'{args.split}_gold.jsonl')) predictions = indexed(read_jsonl(args.predictions)) if inputs.keys() != gold.keys() or predictions.keys()-inputs.keys(): raise ValueError('Input/gold/prediction IDs mismatch') missing = inputs.keys()-predictions.keys() if missing and not args.allow_incomplete: raise ValueError(f'Missing {len(missing)} predictions; no official result') rows = [] for qid, sample in inputs.items(): if qid not in predictions: continue jp = gold[qid]['judge'] if sha256(args.data/jp) != checksums[jp]: raise ValueError('Judge changed: ' + jp) judge = json.loads((args.data/jp).read_text()) if judge.get('geometry') and sha256(args.data/judge['geometry']) != checksums[judge['geometry']]: raise ValueError('Judge geometry changed') rows.append(score(sample, gold[qid], predictions[qid], args.data)) summary = summarize(rows, benchmark) report = dict(complete=not missing, benchmark=benchmark, protocol='robo3d-core-v2', expected=len(inputs), attempted=len(rows), missing=len(missing), coordinates='initial OpenCV camera XYZ; meters or source estimated meters; reported in cm', manifest_sha256=sha256(args.data/'manifest.json'), predictions_sha256=sha256(args.predictions), trajectory_alignment=manifest.get('trajectory_resampling'), **summary) if missing: report = dict(complete=False, official_score=None, partial_diagnostic=report) write_jsonl(args.output/'per_question.jsonl', rows) write_json(args.output/'report.json', report) trace = benchmark == 'trace' lines = [f'# Robo3D-{benchmark.title()} results', '', f'Complete: {not missing}; predictions: {len(rows)}/{len(inputs)}.', '', 'Stored-annotation agreement only. Estimated depth is not calibrated physical ground truth.'] if trace: lines += ['', '| Task | Source | N | Valid (%) | 3D RMSE (cm) | XYZ MAE (cm) |', '|---|---|---:|---:|---:|---:|'] for b in summary['buckets']: vals = ['undefined' if b[k] is None else f'{b[k]:.4f}' for k in ['rmse_cm_valid_mean', 'mae_cm_valid_mean']] lines.append(f"| {b['task']} | {b['source']} | {b['n']} | {b['valid_pct']:.2f} | {' | '.join(vals)} |") lines += ['', 'RMSE = sqrt(mean_t(||pred-ref||²)); MAE = mean over t and XYZ of absolute coordinate errors.', 'Both paths are independently resampled to 64 points by 3D arc length. MAE is not ADE.', 'Errors exclude invalid predictions; validity must always accompany them. No ADE, FDE, Fréchet, threshold success or reward score is used.'] else: lines += ['', '| Task | Source | N | Valid (%) | A@2cm | A@5cm | A@10cm |', '|---|---|---:|---:|---:|---:|---:|'] for b in summary['buckets']: vals = [f"{b[f'agreement_{cm}cm_pct']:.2f}" for cm in [2, 5, 10]] lines.append(f"| {b['task']} | {b['source']} | {b['n']} | {b['valid_pct']:.2f} | {' | '.join(vals)} |") lines += ['', 'Spatial reference uses non-exhaustive positive examples: its agreement is NOT full region accuracy.', 'The four-task index is reference agreement; the three-region-task accuracy excludes spatial reference. Invalid answers score zero.'] lines += ['', 'Group bootstrap 95% confidence intervals and task/source macro statistics are in report.json.'] if missing: lines += ['', '**Incomplete diagnostic; not an official comparison.**'] (args.output/'report.md').write_text('\n'.join(lines)+'\n') print(json.dumps(report, indent=2)) if __name__ == '__main__': main()