Official Codebase of 3DCodeVerse
Python
"""
iou_compute.py -- run in the cadquery env.
For each model, compare OUR converted geometry against DeepCAD's official
ground-truth mesh:
- ours: tessellate our STEP (cadquery/OCP)
- gt: load DeepCAD's STL (generated by gen_gt_stl.py)
- metrics: voxel IoU (occupancy, aligned to a shared grid) + Chamfer distance
(surface point samples, scale-normalized).
High IoU => our CadQuery conversion faithfully reproduces DeepCAD's geometry.
Writes iou_results.json: {id: {iou, chamfer, ours_vol, gt_vol}}.
"""
import os
import sys
import json
import argparse
import tempfile
import subprocess
from pathlib import Path
from joblib import Parallel, delayed
from tqdm import tqdm
WORKER_SRC = r'''
import sys, os, json
import numpy as np
import trimesh
import cadquery as cq
def step_mesh(step):
shape = cq.importers.importStep(step).val()
v, f = shape.tessellate(0.05)
return trimesh.Trimesh(np.array([[p.x,p.y,p.z] for p in v]), np.array(f), process=False)
def voxel_iou(m1, m2, res=48):
lo = np.minimum(m1.bounds[0], m2.bounds[0])
hi = np.maximum(m1.bounds[1], m2.bounds[1])
pitch = max(float((hi-lo).max())/res, 1e-6)
def occ(m):
try:
v = m.voxelized(pitch).fill()
except Exception:
v = m.voxelized(pitch)
idx = np.round((v.points - lo)/pitch).astype(int)
return set(map(tuple, idx.tolist()))
s1, s2 = occ(m1), occ(m2)
u = len(s1 | s2)
return (len(s1 & s2)/u) if u else 0.0
def chamfer(m1, m2, n=2000):
p1 = m1.sample(n); p2 = m2.sample(n)
# scale by gt bbox diagonal so it's comparable across models
scale = float(np.linalg.norm(m2.bounds[1]-m2.bounds[0])) or 1.0
from scipy.spatial import cKDTree
d12 = cKDTree(p2).query(p1)[0]; d21 = cKDTree(p1).query(p2)[0]
return float((d12.mean()+d21.mean())/2.0/scale)
for line in open(sys.argv[1]):
line=line.rstrip("\n")
if not line: continue
step, gt = line.split("\t")
sub=os.path.basename(os.path.dirname(step)); name=os.path.splitext(os.path.basename(step))[0]
mid=f"{sub}/{name}"
try:
mo = step_mesh(step)
mg = trimesh.load(gt, force="mesh")
iou = voxel_iou(mo, mg)
cd = chamfer(mo, mg)
out = {"id": mid, "iou": round(iou,4), "chamfer": round(cd,5),
"ours_vol": round(float(mo.volume),4), "gt_vol": round(float(mg.volume),4)}
print(json.dumps(out), flush=True)
except Exception as e:
print(json.dumps({"id": mid, "iou": None, "detail": str(e)[:150]}), flush=True)
'''
def run_chunk(ids, step_dir, gt_dir, py_exe, worker_path):
lines = []
for mid in ids:
sub, name = mid.split("/")
step = str(Path(step_dir) / sub / (name + ".step"))
gt = str(Path(gt_dir) / sub / (name + ".stl"))
lines.append(f"{step}\t{gt}")
with tempfile.NamedTemporaryFile("w", suffix=".tsv", delete=False) as mf:
mf.write("\n".join(lines))
manifest = mf.name
res = []
try:
pr = subprocess.run([py_exe, worker_path, manifest], capture_output=True,
text=True, timeout=30 * len(ids) + 60)
for line in pr.stdout.splitlines():
line = line.strip()
if line:
try:
res.append(json.loads(line))
except Exception:
pass
except subprocess.TimeoutExpired:
pass
finally:
os.unlink(manifest)
done = {r["id"] for r in res}
for mid in ids:
if mid not in done:
res.append({"id": mid, "iou": None, "detail": "crash"})
return res
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--step_dir", required=True)
ap.add_argument("--gt_dir", required=True)
ap.add_argument("--ids", required=True)
ap.add_argument("--workers", type=int, default=40)
ap.add_argument("--chunk", type=int, default=32)
ap.add_argument("--python", default=sys.executable)
ap.add_argument("--out", default="iou_results.json")
ap.add_argument("--limit", type=int, default=0)
args = ap.parse_args()
ids = [l.strip() for l in open(args.ids) if l.strip()]
if args.limit:
ids = ids[: args.limit]
worker_path = str(Path(tempfile.gettempdir()) / "_iou_worker.py")
Path(worker_path).write_text(WORKER_SRC)
chunks = [ids[i:i + args.chunk] for i in range(0, len(ids), args.chunk)]
print(f"Computing IoU for {len(ids)} models in {len(chunks)} chunks...")
results = Parallel(n_jobs=args.workers)(
delayed(run_chunk)(c, args.step_dir, args.gt_dir, args.python, worker_path)
for c in tqdm(chunks)
)
flat = {r["id"]: r for chunk in results for r in chunk}
ious = [r["iou"] for r in flat.values() if r.get("iou") is not None]
import statistics
if ious:
ious_sorted = sorted(ious)
print(f"IoU: n={len(ious)} mean={statistics.mean(ious):.3f} "
f"median={statistics.median(ious):.3f} "
f">0.9: {100*sum(i>0.9 for i in ious)/len(ious):.1f}% "
f">0.7: {100*sum(i>0.7 for i in ious)/len(ious):.1f}% "
f"<0.5: {100*sum(i<0.5 for i in ious)/len(ious):.1f}%")
json.dump(flat, open(args.out, "w"))
if __name__ == "__main__":
main()