Seal independent proper poses and block uncorrected blind-package release

This commit is contained in:
Frank14f committed 2026-11-14 19:57:58 +08:00
1 parent 6d61c08686
commit 039d4c490f
20 files changed
+452 -4

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
"""Package completed anonymous surfaces/views; identity mapping stays sealed."""
from pathlib import Path
import csv,hashlib,json,os,shutil,sys,time,resource
from zipfile import ZipFile,ZipInfo,ZIP_DEFLATED
from g1_blind_geometry import UNITS,validate_pair
ROOT=Path('artifacts/s2-g1-blind120-2026-11-14')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
start=time.monotonic();done=json.loads((ROOT/'custodian/batch-complete.json').read_text());assert done['all_pass'] and done['parts']==232
posed_done=json.loads((ROOT/'custodian/pose-batch-complete.json').read_text());assert posed_done['all_pass'] and posed_done['exports']==240
pose_seals=json.loads((ROOT/'public/pose-seals.json').read_text())
assert sha(ROOT/'custodian/pose-plan-v1.json')==pose_seals['pose_plan_sha256']
assert sha(ROOT/'custodian/pose-mapping-v1.json')==pose_seals['pose_mapping_sha256']
mapping=json.loads((ROOT/'custodian/sampling-and-mapping.json').read_text());public=json.loads((ROOT/'public/sample-summary-and-seals.json').read_text())
assert len(mapping['pairs'])==120 and len({r['anonymous_pair_id'] for r in mapping['pairs']})==120
assert len(mapping['unique_cases'])==232 and {r[k] for r in mapping['pairs'] for k in ['a','b']}==set(mapping['unique_cases'])
assert len({tuple(sorted((r['a'],r['b']))) for r in mapping['pairs']})==120
for record in public['sealed_files']:
assert sha(ROOT/'custodian'/record['file'])==record['sha256'], 'Sealed custody input changed'
seal=next(r['sha256'] for r in public['sealed_files'] if r['file']=='sampling-and-mapping.json');assert sha(ROOT/'custodian/sampling-and-mapping.json')==seal
bundle=ROOT/'blind-package';bundle.mkdir(exist_ok=False);ids=[];records=[]
for row in mapping['pairs']:
pid=row['anonymous_pair_id'];ids.append(pid);pair=bundle/'pairs'/pid;views=bundle/'views'/pid;pair.mkdir(parents=True);views.mkdir(parents=True)
for side in ['left','right']:
src=ROOT/'custodian/posed'/pid/side
receipt=json.loads((src/'receipt.json').read_text())
t=receipt['transform'];assert abs(t['determinant']-1)<1e-12 and t['orthogonality_max_abs']<1e-12
assert max(t['edge_error_over_bbox_diagonal'],t['double_area_error_over_bbox_diagonal_squared'])<=1e-10
assert receipt['same_posed_coordinates_for_ply_and_png'] and receipt['archive_reads']==0
for record in receipt['files']:
p=src/record['name'];assert p.stat().st_size==record['bytes'] and sha(p)==record['sha256']
shutil.copyfile(src/'surface.ply',pair/f'{side}.ply')
for name in ['overview','detail-grid']:shutil.copyfile(src/f'{name}.png',views/f'{side}-{name}.png')
(pair/'units.txt').write_text(UNITS)
files=[{'name':p.name,'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted(pair.iterdir())]
(pair/'manifest.json').write_text(json.dumps({'format':'blind-surface-pair-v1','anonymous_pair_id':pid,'files':files},indent=2)+'\n');validate_pair(pair)
print(json.dumps({'packaged_pairs':len(ids)}),flush=True) if len(ids)%20==0 else None
pages=bundle/'review-pairs';pages.mkdir()
for pid in ids:
(pages/(pid+'.md')).write_text(f'# Anonymous pair {pid}\n\nRelation: unassigned. Record local evidence or unresolved. Original coordinate units; compare axes, not pixel size.\n\n![Left overview](../views/{pid}/left-overview.png)\n\n![Right overview](../views/{pid}/right-overview.png)\n\n![Left fixed detail grid](../views/{pid}/left-detail-grid.png)\n\n![Right fixed detail grid](../views/{pid}/right-detail-grid.png)\n\n[Left full surface](../pairs/{pid}/left.ply) · [Right full surface](../pairs/{pid}/right.ply)\n')
(bundle/'review-index.md').write_text('# Anonymous review index\n\nAll labels are blank. Full instructions: [README](README.md). Attestation: [unsigned template](reviewer-attestation.md).\n\n'+'\n'.join(f'- [Pair {i+1}: {pid}](review-pairs/{pid}.md)' for i,pid in enumerate(ids))+'\n')
with (bundle/'blank-review.csv').open('w') as f:
w=csv.writer(f,lineterminator='\n');w.writerow(['anonymous_pair_id','relation','local_evidence','resolvable','unresolved_reason','reviewer','review_version'])
for pid in ids:w.writerow([pid,'','','','','',''])
(bundle/'README.md').write_text('''# Geometry-only blind review\n\n120 anonymous pairs. Every relation is unassigned. Do not infer a positive relation from inclusion. Use rigid / template / variant / unrelated / unresolved, and record local geometric evidence. A shared-parent claim requiring source provenance can remain unresolved; no provenance is supplied in this blind view.\n\nOpen index.html locally for uniform views and detail grids; original surface files are in pairs/. Each exported instance has an independent random translation and proper rotation applied for blinding. Original units, physical lengths, boundary triangles and mirror relationships are preserved. No fitted registration, rescaling, reflection or simplification was applied. Source VTU has no explicit physical-unit tag, so axes are original numerical coordinate units, not a universal mm declaration. Views center the object for display only. Separate views fit their own extents; compare numeric axes rather than pixel size.\n\nFour overview views (XY/XZ/YZ/oblique) and four fixed oblique quadrant crops are supplied. Crops are systematic, not certified hole/bridge detections. Edge-on projections may be narrow; rasterization can show tessellation/antialias marks. A dark/white pixel is not topology evidence. Full PLY surface is authoritative; if a relation or local hole/bridge is unresolved, say so and request a zoom by anonymous ID.\n\nNo source key, identities, ranks, residuals, process settings, fields or reference labels are included. Vertex/triangle counts and geometric shape remain visible and can still enable re-identification; posing is a mitigation, not guaranteed anonymity. Counts were not hidden by remeshing because that could alter holes and bridges. The reviewer must not consult census, Zenodo or identity materials. blank-review.csv is empty by design. Complete reviewer-attestation.md and freeze/commit it with the labels before the prescribed witnessed unblinding.\n''')
(bundle/'reviewer-attestation.md').write_text('# Reviewer attestation\n\nI did not consult the census, the Zenodo files, or any identity material during review.\n\nReviewer: ____________________\n\nDate: ____________________\n\nSignature / explicit confirmation: ____________________\n\nFrozen labels commit / version: ____________________\n\nCommit this completed attestation together with frozen blind labels before unblinding. This template is unsigned.\n')
html='''<!doctype html><html lang="zh"><meta charset="utf-8"><title>匿名几何复核</title><style>body{font:16px system-ui;margin:24px;background:#f4f5f7;color:#152333}header{position:sticky;top:0;background:#fff;padding:12px;z-index:2}button,select{font:inherit;margin:4px;padding:8px}main{display:grid;grid-template-columns:1fr 1fr;gap:12px}img{width:100%;background:white;cursor:zoom-in}a{color:#17698b}.note{max-width:1000px;line-height:1.5}dialog{width:95vw;height:95vh}dialog img{width:auto;max-width:none}</style><header><button onclick="move(-1)">上一对</button><select id="which" onchange="show(this.selectedIndex)"></select><button onclick="move(1)">下一对</button><select id="mode" onchange="show(i)"><option value="overview">统一视图</option><option value="detail-grid">固定分区细节</option></select><span id="counter"></span></header><p class="note">仅凭几何填写关系与局部依据。图轴为原坐标单位;分别自适应显示,像素尺寸不能直接比较。点击图片放大。看不清的关系、孔或薄桥可记未决。<a href="blank-review.csv">下载空白判定表</a> · <a href="reviewer-attestation.md">审阅声明(与判定一起冻结)</a> · <a href="README.md">完整性说明</a></p><h3 id="label"></h3><main><section><h3>左件 <a id="leftmesh">完整表面</a></h3><img id="left" onclick="zoom(this.src)"></section><section><h3>右件 <a id="rightmesh">完整表面</a></h3><img id="right" onclick="zoom(this.src)"></section></main><dialog id="zoom"><button onclick="document.getElementById('zoom').close()">关闭</button><div><img id="large"></div></dialog><script>const ids=IDS;let i=0;const w=document.getElementById('which');ids.forEach((x,n)=>{const o=document.createElement('option');o.textContent=String(n+1);w.appendChild(o)});function show(n){i=(n+ids.length)%ids.length;w.selectedIndex=i;const id=ids[i],m=document.getElementById('mode').value;document.getElementById('label').textContent=id;document.getElementById('counter').textContent=`${i+1} / ${ids.length}`;for(const s of ['left','right']){document.getElementById(s).src=`views/${id}/${s}-${m}.png`;document.getElementById(s+'mesh').href=`pairs/${id}/${s}.ply`}}function move(d){show(i+d)}function zoom(src){document.getElementById('large').src=src;document.getElementById('zoom').showModal()}show(0);</script></html>'''
(bundle/'index.html').write_text(html.replace('IDS',json.dumps(ids)))
for p in sorted(bundle.rglob('*')):
if p.is_file():records.append({'path':str(p.relative_to(bundle)),'bytes':p.stat().st_size,'sha256':sha(p)})
(bundle/'manifest.json').write_text(json.dumps({'scope':'anonymous geometry and blank review only','pairs':120,'files':records},indent=2)+'\n')
archive=ROOT/'blind-package.zip'
with ZipFile(archive,'x',compression=ZIP_DEFLATED,compresslevel=6) as z:
for p in sorted(bundle.rglob('*')):
if p.is_file():
info=ZipInfo(str(p.relative_to(bundle)),date_time=(1980,1,1,0,0,0));info.external_attr=0o100644<<16;info.compress_type=ZIP_DEFLATED;z.writestr(info,p.read_bytes())
# Byte equality verifies all archive entries, fixed timestamps, no identity path.
with ZipFile(archive) as z:
for entry in z.infolist():
assert entry.date_time==(1980,1,1,0,0,0) and not entry.filename.startswith('/') and '..' not in Path(entry.filename).parts
assert z.read(entry.filename)==(bundle/entry.filename).read_bytes()
report={'status':'120_BLIND_PAIRS_PACKAGED_NOT_REVIEWED','pairs':120,'unique_geometry_parts':232,'blind_files':len(records)+1,'blind_bytes':sum(r['bytes'] for r in records)+(bundle/'manifest.json').stat().st_size,'zip_bytes':archive.stat().st_size,'zip_sha256':sha(archive),'bundle_manifest_sha256':sha(bundle/'manifest.json'),'sampling_mapping_seal':seal,'all_pair_schemas_and_hashes_pass':True,'zip_entries_full_byte_check_pass':True,'zip_timestamps_normalized':True,'blank_labels':True,'reviewer_attestation_template_unsigned':True,'proper_pose_blinding':True,'pose_plan_sha256':pose_seals['pose_plan_sha256'],'pose_mapping_sha256':pose_seals['pose_mapping_sha256'],'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start,'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024}
(ROOT/'public/package-result.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report))
if __name__=='__main__':main()
+29
View File
@@ -0,0 +1,29 @@
"""Proper rigid posing of stored surface geometry; no source archive access."""
import numpy as np
from g1_blind_geometry import surface
def read_surface(path):
lines=path.read_text('ascii').splitlines();n=int(lines[2].split()[-1]);nf=int(lines[6].split()[-1])
expected=['ply','format ascii 1.0',f'element vertex {n}','property double x','property double y','property double z',f'element face {nf}','property list uchar int vertex_indices','end_header']
if lines[:9]!=expected or len(lines)!=9+n+nf:raise ValueError('Unexpected geometry-only PLY schema')
x=np.array([[float(v) for v in s.split()] for s in lines[9:9+n]],dtype=np.float64)
rows=[s.split() for s in lines[9+n:]]
if any(len(v)!=4 or v[0]!='3' for v in rows):raise ValueError('Non-triangle PLY')
f=np.array([[int(v) for v in s[1:]] for s in rows],dtype=np.int64);xx,ff=surface(x,f)
if len(xx)!=n or not np.array_equal(ff,f):raise ValueError('Unexpected unused/reindexed vertices')
return x,f
def pose(x,f,rotation,unit_translation):
r=np.asarray(rotation,dtype=np.float64);u=np.asarray(unit_translation,dtype=np.float64)
if r.shape!=(3,3) or u.shape!=(3,) or not np.isfinite(r).all() or not np.isfinite(u).all():raise ValueError('Invalid pose')
det=float(np.linalg.det(r));orth=float(np.max(np.abs(r.T@r-np.eye(3))))
if abs(det-1)>1e-12 or orth>1e-12:raise ValueError('Only proper orthogonal rotations allowed')
center=(x.max(0)+x.min(0))/2;scale=float(np.linalg.norm(x.max(0)-x.min(0)))
if not np.isfinite(scale) or scale<=0:raise ValueError('Invalid translation scale')
t=scale*u;y=(x-center)@r.T+t
a=x[f];b=y[f];e=np.roll(a,-1,axis=1)-a;ee=np.roll(b,-1,axis=1)-b
edge=float(np.max(np.abs(np.linalg.norm(e,axis=2)-np.linalg.norm(ee,axis=2)))/scale)
area=float(np.max(np.abs(np.linalg.norm(np.cross(a[:,1]-a[:,0],a[:,2]-a[:,0]),axis=1)-np.linalg.norm(np.cross(b[:,1]-b[:,0],b[:,2]-b[:,0]),axis=1)))/scale**2)
if not np.isfinite(y).all() or max(edge,area)>1e-10:raise ValueError('Rigid geometry invariant failed')
transform={'rotation':r.tolist(),'source_center':center.tolist(),'random_translation':t.tolist(),'affine_translation':(t-center@r.T).tolist(),'translation_scale':scale,'formula':'(x-source_center) @ rotation.T + random_translation','determinant':det,'orthogonality_max_abs':orth,'edge_error_over_bbox_diagonal':edge,'double_area_error_over_bbox_diagonal_squared':area,'numerical_tolerance':1e-10,'vertices':len(x),'triangles':len(f)}
return y,transform
+25
View File
@@ -0,0 +1,25 @@
"""Pose one export instance from the completed stored surface; never re-extract."""
from pathlib import Path
import hashlib,json,sys,resource,time
import numpy as np
from g1_blind_pose import read_surface,pose
from g1_blind_geometry import ply_bytes
from render_g1_blind_surface import render_surface
ROOT=Path('artifacts/s2-g1-blind120-2026-11-14')
def main():
start=time.monotonic();index=int(sys.argv[1]);contract=json.loads((ROOT/'pose-contract.json').read_text())
for p,h in contract['source_sha256'].items():
if hashlib.sha256(Path(p).read_bytes()).hexdigest()!=h:raise ValueError('Pose code changed')
planfile=ROOT/'custodian/pose-plan-v1.json'
if hashlib.sha256(planfile.read_bytes()).hexdigest()!=contract['pose_plan_sha256']:raise ValueError('Pose plan changed')
if hashlib.sha256((ROOT/'custodian/sampling-and-mapping.json').read_bytes()).hexdigest()!=contract['sampling_mapping_sha256']:raise ValueError('Sampling mapping changed')
row=json.loads(planfile.read_text())['exports'][index];old=json.loads((ROOT/'custodian/sampling-and-mapping.json').read_text());pair=next(r for r in old['pairs'] if r['anonymous_pair_id']==row['anonymous_pair_id']);case=pair[row['side']]
asset=hashlib.sha256(bytes.fromhex(old['anonymous_id_secret_hex'])+b'asset\0'+case.encode()).hexdigest()[:32];src=ROOT/'custodian/geometry'/asset
original=json.loads((src/'receipt.json').read_text());digest=next(x['sha256'] for x in original['files'] if x['name']=='surface.ply')
if hashlib.sha256((src/'surface.ply').read_bytes()).hexdigest()!=digest:raise ValueError('Stored surface changed')
x,f=read_surface(src/'surface.ply');y,transform=pose(x,f,row['rotation'],row['translation_unit_vector'])
out=ROOT/'custodian/posed'/row['anonymous_pair_id']/row['side'];out.mkdir(parents=True,exist_ok=False)
(out/'surface.ply').write_bytes(ply_bytes(y,f));render_surface(y,f,out)
receipt={'index':index,'anonymous_pair_id':row['anonymous_pair_id'],'side':row['side'],'transform':transform,'source_surface_sha256':digest,'source_asset_id':asset,'files':[{'name':p.name,'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in sorted(out.iterdir())],'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start,'archive_reads':0,'registration':False,'same_posed_coordinates_for_ply_and_png':True}
(out/'receipt.json').write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps({'index':index,'status':'POSED_AND_INVARIANTS_PASS','cpu_seconds':receipt['cpu_seconds']}))
if __name__=='__main__':main()
+25
View File
@@ -0,0 +1,25 @@
"""Sequential presentation correction under existing E1 ledger; no extraction."""
from pathlib import Path
import json,fcntl,os,sys,resource,hashlib
from s2_e1_supervisor import supervise,save
ROOT=Path('artifacts/s2-g1-blind120-2026-11-14')
def main():
os.environ['MPLCONFIGDIR']=str((ROOT/'matplotlib-cache').resolve());private=ROOT/'custodian';c=json.loads((ROOT/'pose-contract.json').read_text())
with (private/'pose-batch.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (private/'pose-batch-started.json').exists():raise FileExistsError('No silent pose retry')
assert json.loads((private/'batch-complete.json').read_text())['parts']==232
save(private/'pose-batch-started.json',{'exports':240,'scope':'rigid presentation correction of existing surfaces only'})
last=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]);receipts=[]
for i in range(240):
ledger=json.loads((ROOT/'ledger.json').read_text());left=min(57600-ledger['cpu_seconds_charged'],28800-(ledger['cpu_seconds_charged']-1725.366982))
if left<=0:save(private/'pose-batch-stopped.json',{'reason':'CPU exhausted before next export','completed':i});return
r=supervise([sys.executable,'tools/pose_g1_blind_surface.py',str(i)],ROOT,f'blind-pose-{i:03}',dict(total_cpu_seconds=57600,job_cpu_seconds=min(1800,left),job_wall_seconds=1800,tree_rss_bytes=1342177280,disk_bytes=8*1024**3,max_processes=8),poll=.1)
now=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]);own=now-last;last=now;ledger=json.loads((ROOT/'ledger.json').read_text());ledger['cpu_seconds_charged']+=own;ledger['attempts'].append({'name':f'pose-supervisor-self-{i:03}','cpu_seconds':own,'status':'MEASURED_SELF_CPU'});save(ROOT/'ledger.json',ledger)
receipts.append(r);print(json.dumps({'index':i,'status':r['status'],'worker_cpu_seconds':r['cpu_seconds'],'supervisor_cpu_seconds':own,'peak_rss_bytes':r['peak_tree_rss_bytes']}),flush=True)
if r['status']!='PASS' or ledger['cpu_seconds_charged']>=57600 or ledger['cpu_seconds_charged']-1725.366982>=28800:save(private/'pose-batch-stopped.json',{'reason':'failure or budget reached; no retry','index':i});return
rows=[json.loads(p.read_text()) for p in sorted((private/'posed').glob('*/*/receipt.json'))];assert len(rows)==240
final=private/'pose-mapping-v1.json';save(final,{'plan_sha256':c['pose_plan_sha256'],'transforms':[{'anonymous_pair_id':r['anonymous_pair_id'],'side':r['side'],'transform':r['transform'],'source_asset_id':r['source_asset_id']} for r in rows]});final.chmod(0o600)
save(ROOT/'public/pose-seals.json',{'status':'240_EXPORTS_PROPERLY_POSED_NOT_YET_PACKAGED','pose_plan_sha256':c['pose_plan_sha256'],'pose_mapping_sha256':hashlib.sha256(final.read_bytes()).hexdigest(),'all_invariants_pass':True,'max_edge_roundoff_over_diagonal':max(r['transform']['edge_error_over_bbox_diagonal'] for r in rows),'min_rotation_determinant':min(r['transform']['determinant'] for r in rows),'max_rotation_determinant':max(r['transform']['determinant'] for r in rows),'e1_charged_seconds':ledger['cpu_seconds_charged']})
save(private/'pose-batch-complete.json',{'exports':240,'all_pass':True,'worker_cpu_seconds':sum(r['cpu_seconds'] for r in receipts),'e1_total_charged_seconds':ledger['cpu_seconds_charged']})
if __name__=='__main__':main()
+49
View File
@@ -0,0 +1,49 @@
"""Full tiny synthetic package: pose gate, seals, geometry-only view and attestation."""
import contextlib,io,json,tempfile,unittest
from pathlib import Path
from PIL import Image
import numpy as np
import build_g1_blind120_package as b
from g1_blind_geometry import ply_bytes
def save(p,x):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(json.dumps(x))
class PackageTest(unittest.TestCase):
def test_unposed_package_blocked(self):
old=b.ROOT
with tempfile.TemporaryDirectory() as t:
b.ROOT=Path(t);save(b.ROOT/'custodian/batch-complete.json',{'parts':232,'all_pass':True})
try:
with self.assertRaises(FileNotFoundError):b.main()
self.assertFalse((b.ROOT/'blind-package').exists())
finally:b.ROOT=old
def test_whole_synthetic_package_and_blank_labels(self):
old=b.ROOT
with tempfile.TemporaryDirectory() as t:
b.ROOT=Path(t);root=b.ROOT;cases=[f'synthetic-{i}' for i in range(232)]
pairs=[(cases[2*i],cases[2*i+1]) for i in range(116)]+[(cases[0],cases[2]),(cases[1],cases[3]),(cases[4],cases[6]),(cases[5],cases[7])]
rows=[{'a':a,'b':c,'left':a,'right':c,'anonymous_pair_id':f'{i:032x}'} for i,(a,c) in enumerate(pairs)]
save(root/'custodian/sampling-and-mapping.json',{'pairs':rows,'unique_cases':cases});save(root/'custodian/geometry-source-index.json',{'fixture':True})
save(root/'public/sample-summary-and-seals.json',{'sealed_files':[{'file':n,'sha256':b.sha(root/'custodian'/n)} for n in ['sampling-and-mapping.json','geometry-source-index.json']]})
save(root/'custodian/batch-complete.json',{'parts':232,'all_pass':True});save(root/'custodian/pose-batch-complete.json',{'exports':240,'all_pass':True})
for n in ['pose-plan-v1.json','pose-mapping-v1.json']:save(root/'custodian'/n,{'synthetic_fixture':True})
save(root/'public/pose-seals.json',{'pose_plan_sha256':b.sha(root/'custodian/pose-plan-v1.json'),'pose_mapping_sha256':b.sha(root/'custodian/pose-mapping-v1.json')})
for row in rows:
for side in ['left','right']:
d=root/'custodian/posed'/row['anonymous_pair_id']/side;d.mkdir(parents=True)
(d/'surface.ply').write_bytes(ply_bytes(np.array([[0.,0,0],[1,0,0],[0,1,0]]),np.array([[0,1,2]])))
for name in ['overview','detail-grid']:Image.new('RGB',(1,1),'white').save(d/(name+'.png'))
files=[{'name':p.name,'bytes':p.stat().st_size,'sha256':b.sha(p)} for p in sorted(d.iterdir())]
save(d/'receipt.json',{'files':files,'transform':{'determinant':1.,'orthogonality_max_abs':0.,'edge_error_over_bbox_diagonal':0.,'double_area_error_over_bbox_diagonal_squared':0.},'archive_reads':0,'same_posed_coordinates_for_ply_and_png':True})
try:
with contextlib.redirect_stdout(io.StringIO()):b.main()
r=json.loads((root/'public/package-result.json').read_text());self.assertEqual(r['pairs'],120);self.assertTrue(r['proper_pose_blinding']);self.assertTrue(r['zip_entries_full_byte_check_pass'])
self.assertEqual(len(list((root/'blind-package/review-pairs').glob('*.md'))),120)
import csv
with (root/'blind-package/blank-review.csv').open() as f:labels=list(csv.DictReader(f))
self.assertEqual(len(labels),120);self.assertTrue(all(not v for row in labels for k,v in row.items() if k!='anonymous_pair_id'))
self.assertIn('This template is unsigned',(root/'blind-package/reviewer-attestation.md').read_text())
self.assertNotIn('synthetic-',(root/'blind-package/manifest.json').read_text())
save(root/'custodian/pose-mapping-v1.json',{'changed':True})
with self.assertRaises(AssertionError):b.main()
finally:b.ROOT=old
if __name__=='__main__':unittest.main()
+17
View File
@@ -0,0 +1,17 @@
import unittest
import numpy as np
from scipy.spatial.transform import Rotation
from g1_blind_pose import pose
class PoseTests(unittest.TestCase):
def setUp(self):self.x=np.array([[2.,3,4],[3.,3,4],[2.,5,4],[2.,3,7]]);self.f=np.array([[0,1,2],[0,1,3],[0,2,3],[1,2,3]])
def test_scale_distances_and_inverse(self):
r=Rotation.from_rotvec([.3,.5,.1]).as_matrix();y,m=pose(self.x,self.f,r,[.2,-.1,.7]);back=(y-np.array(m['random_translation']))@r+np.array(m['source_center']);np.testing.assert_allclose(back,self.x,rtol=0,atol=1e-12);self.assertLess(m['edge_error_over_bbox_diagonal'],1e-12)
def test_reflection_rejected(self):
with self.assertRaises(ValueError):pose(self.x,self.f,np.diag([-1,1,1]),[0,0,0])
def test_scale_change_rejected(self):
with self.assertRaises(ValueError):pose(self.x,self.f,2*np.eye(3),[0,0,0])
def test_seed_children_stable_and_mirror_parity(self):
two=np.random.SeedSequence([2026111413]).spawn(2);three=np.random.SeedSequence([2026111413]).spawn(3)
for a,b in zip(two,three):np.testing.assert_array_equal(a.generate_state(8),b.generate_state(8))
rng=np.random.Generator(np.random.PCG64(three[2]));a=Rotation.random(random_state=rng).as_matrix();b=Rotation.random(random_state=rng).as_matrix();self.assertFalse(np.allclose(a,b));self.assertAlmostEqual(np.linalg.det(b@np.diag([-1,1,1])@a.T),-1)
if __name__=='__main__':unittest.main()