Upload 9 files
Browse files- README.txt +126 -0
- __init__.py +18 -0
- batch.py +132 -0
- explanation.txt +119 -0
- extraction.py +118 -0
- graph_data.py +502 -0
- inference.py +151 -0
- model.py +106 -0
- server.py +172 -0
README.txt
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
HEG BRep Component Identification — Distribution Bundle
|
| 2 |
+
=========================================================
|
| 3 |
+
|
| 4 |
+
This folder is a self-contained Windows distribution. It runs without any
|
| 5 |
+
pre-installed Python or conda. Drop the whole folder next to your viewer's
|
| 6 |
+
installer; the viewer launches `heg_brep_service.bat` as a child process and
|
| 7 |
+
talks to it over localhost HTTP.
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
Contents
|
| 11 |
+
--------
|
| 12 |
+
heg_brep_service.bat Launches the classification service. Prints
|
| 13 |
+
`READY port=<N>` to stdout once models are loaded.
|
| 14 |
+
Use `--device cpu` (default) or `--device cuda`.
|
| 15 |
+
heg_brep_batch.bat Optional batch CLI: STEP folder -> Excel report.
|
| 16 |
+
Useful for offline regression testing.
|
| 17 |
+
python\ Conda-packed Python 3.10 environment (~2 GB).
|
| 18 |
+
Includes pythonocc-core, occwl, torch (CPU),
|
| 19 |
+
torch_geometric, fastapi, uvicorn, numpy, MKL.
|
| 20 |
+
heg_brep\ The classification package (model, inference,
|
| 21 |
+
extraction, server, batch CLI).
|
| 22 |
+
BRepExtractor\ STEP -> NPZ feature extraction pipeline.
|
| 23 |
+
models\ Three checkpoints used by the two-pass classifier:
|
| 24 |
+
pass1.pt (parent), elbow.pt, tee.pt.
|
| 25 |
+
csharp_sample\ Reference C# integration: HegBrepClient.cs is a
|
| 26 |
+
drop-in async client; Program.cs is a smoke test
|
| 27 |
+
(build with `dotnet build`).
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
Quick smoke test
|
| 31 |
+
----------------
|
| 32 |
+
From this folder, in a regular cmd.exe:
|
| 33 |
+
|
| 34 |
+
heg_brep_batch.bat C:\path\to\step_folder C:\path\to\out.xlsx
|
| 35 |
+
|
| 36 |
+
Or run the service standalone and poke it with curl:
|
| 37 |
+
|
| 38 |
+
heg_brep_service.bat
|
| 39 |
+
(waits ~10-15s; prints `READY port=51571`)
|
| 40 |
+
curl http://127.0.0.1:51571/health
|
| 41 |
+
curl -X POST http://127.0.0.1:51571/classify ^
|
| 42 |
+
-H "Content-Type: application/json" ^
|
| 43 |
+
-d "{\"step_path\":\"C:\\path\\to\\part.step\"}"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
Service HTTP API
|
| 47 |
+
----------------
|
| 48 |
+
GET /health
|
| 49 |
+
-> {"status":"ok","models_loaded":true,"device":"cpu","uptime_sec":...}
|
| 50 |
+
|
| 51 |
+
POST /classify Single STEP file -> classification result.
|
| 52 |
+
Body: {"step_path": "C:\\full\\path\\to\\part.step",
|
| 53 |
+
"npz_keep_dir": "optional\\persist\\dir"}
|
| 54 |
+
Resp: {"status":"ok",
|
| 55 |
+
"final_label": "4_tee_wf",
|
| 56 |
+
"final_conf": 0.9997,
|
| 57 |
+
"route": "tee",
|
| 58 |
+
"pass1_argmax": "tee", "pass1_conf": 1.0,
|
| 59 |
+
"pass2_argmax": "4_tee_wf", "pass2_predicted": "4_tee_wf",
|
| 60 |
+
"pass2_conf": 0.9997,
|
| 61 |
+
"npz_path": "...", "step_path": "..."}
|
| 62 |
+
|
| 63 |
+
POST /classify_batch Multiple STEPs in one call. Same JSON schema,
|
| 64 |
+
but body is `{"step_paths": ["...", "..."]}`.
|
| 65 |
+
|
| 66 |
+
POST /shutdown Graceful exit. The host (your viewer) should call
|
| 67 |
+
this on exit so the python.exe child doesn't linger.
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
Performance budget (RTX 3050 laptop, --device cpu)
|
| 71 |
+
--------------------------------------------------
|
| 72 |
+
Service startup: ~10-15s (OCC + torch + 3 models cold-load)
|
| 73 |
+
First /classify call: ~1.0s (single STEP extract + inference)
|
| 74 |
+
Warm /classify calls: ~0.8s (warm OCC stack, varies with STEP size)
|
| 75 |
+
|
| 76 |
+
Switch to `--device cuda` for ~5-10x faster inference if the target machine
|
| 77 |
+
has CUDA 12.x drivers + a supported GPU. With CPU torch (default), no NVIDIA
|
| 78 |
+
runtime is required.
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
Output label space
|
| 82 |
+
------------------
|
| 83 |
+
Pass-1 (parent classifier): elbow | tee | pipe | miscellaneous
|
| 84 |
+
Pass-2 elbow specialist: 1_elbow_wf | 2_elbow_pef | 3_elbow_sf | 8_elbow_misc
|
| 85 |
+
Pass-2 tee specialist: 4_tee_wf | 5_tee_pef | 6_tee_sf | 9_tee_misc
|
| 86 |
+
|
| 87 |
+
For pipe / miscellaneous routes the response has `final_label="random"` with
|
| 88 |
+
the pass-1 confidence (no specialist exists for those families).
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
C# integration
|
| 92 |
+
--------------
|
| 93 |
+
See csharp_sample/HegBrepClient.cs for a drop-in async client. Typical usage:
|
| 94 |
+
|
| 95 |
+
var client = new HegBrepClient();
|
| 96 |
+
await client.StartAsync(@"C:\Program Files\YourViewer\heg_brep\heg_brep_service.bat");
|
| 97 |
+
// Later, when user clicks "Identify":
|
| 98 |
+
var r = await client.ClassifyAsync(@"C:\tmp\selection.step");
|
| 99 |
+
label.Text = $"{r.FinalLabel} ({r.FinalConf:P1})";
|
| 100 |
+
// On viewer exit:
|
| 101 |
+
await client.StopAsync();
|
| 102 |
+
|
| 103 |
+
The client spawns the .bat as a child process, reads the `READY port=<N>`
|
| 104 |
+
line from its stdout, then POSTs to http://127.0.0.1:<N>/classify. Stderr is
|
| 105 |
+
forwarded to Debug.WriteLine for your logger to capture.
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
Troubleshooting
|
| 109 |
+
---------------
|
| 110 |
+
* "DLL load failed" on first run.
|
| 111 |
+
The bat sets PATH to include python\Library\bin where MKL / OCC DLLs
|
| 112 |
+
live. If you launch python.exe directly without the bat, you'll hit this.
|
| 113 |
+
|
| 114 |
+
* Cold service start takes 30+ seconds.
|
| 115 |
+
The first run after extracting the zip is slow because Windows loads each
|
| 116 |
+
DLL from disk for the first time. Subsequent starts are ~5-10s once the
|
| 117 |
+
OS file cache is warm.
|
| 118 |
+
|
| 119 |
+
* "Bodies which are not closed are not supported".
|
| 120 |
+
Upstream extractor limitation. Some STEP files (typically Inventor
|
| 121 |
+
exports without explicit BREP closure) cannot be processed. The HTTP
|
| 122 |
+
response is {"status": "extraction_failed", "error": "..."}.
|
| 123 |
+
|
| 124 |
+
* `KMP_DUPLICATE_LIB_OK=TRUE` warning.
|
| 125 |
+
Set automatically. Coexists fine with both OpenMP runtimes; the warning
|
| 126 |
+
is overly conservative for inference.
|
__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HEG BRep two-pass component-identification pipeline (unified, in-process)."""
|
| 2 |
+
import os
|
| 3 |
+
# Two OpenMP runtimes (MKL's libiomp5md + torch's libomp) get loaded into the
|
| 4 |
+
# same process because conda's numpy and pip-installed torch don't share an OMP
|
| 5 |
+
# build. The duplicate-load check is overly conservative for inference workloads;
|
| 6 |
+
# allow it.
|
| 7 |
+
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
|
| 8 |
+
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
PACKAGE_ROOT = Path(__file__).resolve().parent
|
| 12 |
+
REPO_ROOT = PACKAGE_ROOT.parent
|
| 13 |
+
|
| 14 |
+
DEFAULT_PASS1_MODEL = REPO_ROOT / "brep_two_pass" / "artifacts" / "pass1_parent_brep_v1" / "best_model_halfedge.pt"
|
| 15 |
+
DEFAULT_ELBOW_MODEL = REPO_ROOT / "artifacts_he_elbow_only_v4" / "best_model_halfedge.pt"
|
| 16 |
+
DEFAULT_TEE_MODEL = REPO_ROOT / "artifacts_he_tee_only_v1" / "best_model_halfedge.pt"
|
| 17 |
+
DEFAULT_FEATURE_LIST = REPO_ROOT / "BRepExtractor" / "feature_lists" / "all.json"
|
| 18 |
+
DEFAULT_BREPEXTRACTOR_DIR = REPO_ROOT / "BRepExtractor"
|
batch.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch CLI: STEP folder -> Excel. Single process, models loaded once."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import argparse
|
| 4 |
+
import sys
|
| 5 |
+
import tempfile
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, List
|
| 9 |
+
|
| 10 |
+
from openpyxl import Workbook
|
| 11 |
+
|
| 12 |
+
from heg_brep import (
|
| 13 |
+
DEFAULT_PASS1_MODEL, DEFAULT_ELBOW_MODEL, DEFAULT_TEE_MODEL, REPO_ROOT,
|
| 14 |
+
)
|
| 15 |
+
from heg_brep.inference import LoadedModel, TwoPassClassifier
|
| 16 |
+
from heg_brep.extraction import extract_folder_to_npz
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
COLUMNS = [
|
| 20 |
+
"file_name", "file_path", "stem", "status",
|
| 21 |
+
"pass1_argmax", "pass1_conf", "route",
|
| 22 |
+
"pass2_argmax", "pass2_predicted", "pass2_conf",
|
| 23 |
+
"final_label", "final_conf", "npz_path", "note",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_args() -> argparse.Namespace:
|
| 28 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 29 |
+
ap.add_argument("step_folder")
|
| 30 |
+
ap.add_argument("output_excel", nargs="?", default=None,
|
| 31 |
+
help="Defaults to ./brep_two_pass_<timestamp>.xlsx")
|
| 32 |
+
ap.add_argument("--pass1_model", default=str(DEFAULT_PASS1_MODEL))
|
| 33 |
+
ap.add_argument("--elbow_model", default=str(DEFAULT_ELBOW_MODEL))
|
| 34 |
+
ap.add_argument("--tee_model", default=str(DEFAULT_TEE_MODEL))
|
| 35 |
+
ap.add_argument("--device", default="cpu", choices=["cpu", "cuda"])
|
| 36 |
+
ap.add_argument("--pass2_min_conf", type=float, default=0.85)
|
| 37 |
+
ap.add_argument("--pass2_tau", type=float, default=0.0)
|
| 38 |
+
ap.add_argument("--num_workers", type=int, default=1)
|
| 39 |
+
ap.add_argument("--max_file_mb", type=float, default=None)
|
| 40 |
+
ap.add_argument("--npz_dir", default=None, help="Persist NPZs here (default: temp).")
|
| 41 |
+
return ap.parse_args()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def write_excel(rows: List[Dict[str, object]], output_excel: Path) -> None:
|
| 45 |
+
wb = Workbook()
|
| 46 |
+
ws = wb.active
|
| 47 |
+
ws.title = "brep_two_pass"
|
| 48 |
+
ws.append(COLUMNS)
|
| 49 |
+
for r in rows:
|
| 50 |
+
ws.append([r.get(c, "") for c in COLUMNS])
|
| 51 |
+
for col in ws.columns:
|
| 52 |
+
letter = col[0].column_letter
|
| 53 |
+
max_len = max((len(str(c.value)) if c.value is not None else 0 for c in col), default=0)
|
| 54 |
+
ws.column_dimensions[letter].width = min(max(12, max_len + 2), 70)
|
| 55 |
+
output_excel.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
wb.save(output_excel)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main() -> int:
|
| 60 |
+
args = parse_args()
|
| 61 |
+
step_folder = Path(args.step_folder).expanduser().resolve()
|
| 62 |
+
if not step_folder.is_dir():
|
| 63 |
+
raise FileNotFoundError(f"step_folder not found: {step_folder}")
|
| 64 |
+
|
| 65 |
+
output_excel = (Path(args.output_excel).expanduser().resolve()
|
| 66 |
+
if args.output_excel
|
| 67 |
+
else REPO_ROOT / f"brep_two_pass_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx")
|
| 68 |
+
npz_dir = (Path(args.npz_dir).expanduser().resolve() if args.npz_dir
|
| 69 |
+
else Path(tempfile.mkdtemp(prefix="heg_brep_npz_")))
|
| 70 |
+
|
| 71 |
+
print(f"Extracting STEP files in {step_folder} -> {npz_dir}")
|
| 72 |
+
t0 = datetime.now()
|
| 73 |
+
summary = extract_folder_to_npz(
|
| 74 |
+
step_folder, output_dir=npz_dir,
|
| 75 |
+
num_workers=args.num_workers, max_file_mb=args.max_file_mb,
|
| 76 |
+
)
|
| 77 |
+
print(f" extraction took {(datetime.now() - t0).total_seconds():.1f}s "
|
| 78 |
+
f"({len(summary['ok_stems'])} OK, {len(summary['skipped'])} skipped)")
|
| 79 |
+
|
| 80 |
+
print(f"Loading models on {args.device}...")
|
| 81 |
+
t0 = datetime.now()
|
| 82 |
+
pass1 = LoadedModel(Path(args.pass1_model), device=args.device)
|
| 83 |
+
elbow = LoadedModel(Path(args.elbow_model), device=args.device) if Path(args.elbow_model).exists() else None
|
| 84 |
+
tee = LoadedModel(Path(args.tee_model), device=args.device) if Path(args.tee_model).exists() else None
|
| 85 |
+
clf = TwoPassClassifier(pass1=pass1, elbow=elbow, tee=tee,
|
| 86 |
+
pass2_min_conf=args.pass2_min_conf, pass2_tau=args.pass2_tau)
|
| 87 |
+
print(f" models loaded in {(datetime.now() - t0).total_seconds():.1f}s")
|
| 88 |
+
|
| 89 |
+
print(f"Classifying {len(summary['step_paths'])} files...")
|
| 90 |
+
t0 = datetime.now()
|
| 91 |
+
rows: List[Dict[str, object]] = []
|
| 92 |
+
ok = pass1_failed = pass2_failed = extraction_failed = 0
|
| 93 |
+
for sp in summary["step_paths"]:
|
| 94 |
+
stem = sp.stem
|
| 95 |
+
base = {c: "" for c in COLUMNS}
|
| 96 |
+
base.update({"file_name": sp.name, "file_path": str(sp), "stem": stem})
|
| 97 |
+
npz = npz_dir / f"{stem}.npz"
|
| 98 |
+
if not npz.exists():
|
| 99 |
+
base["status"] = "EXTRACTION_FAILED"
|
| 100 |
+
base["note"] = summary["skipped"].get(stem, "NPZ missing after extraction")
|
| 101 |
+
extraction_failed += 1
|
| 102 |
+
rows.append(base); continue
|
| 103 |
+
base["npz_path"] = str(npz)
|
| 104 |
+
try:
|
| 105 |
+
result = clf.classify_npz(npz)
|
| 106 |
+
except Exception as exc:
|
| 107 |
+
base["status"] = "INFERENCE_FAILED"
|
| 108 |
+
base["note"] = str(exc)[:500]
|
| 109 |
+
pass1_failed += 1
|
| 110 |
+
rows.append(base); continue
|
| 111 |
+
base.update({k: result.get(k, "") for k in result})
|
| 112 |
+
# Round confidences for the spreadsheet
|
| 113 |
+
for k in ("pass1_conf", "pass2_conf", "final_conf"):
|
| 114 |
+
v = base.get(k)
|
| 115 |
+
base[k] = round(float(v), 6) if isinstance(v, (int, float)) else v
|
| 116 |
+
base["status"] = "OK"
|
| 117 |
+
ok += 1
|
| 118 |
+
rows.append(base)
|
| 119 |
+
|
| 120 |
+
elapsed = (datetime.now() - t0).total_seconds()
|
| 121 |
+
print(f" inference took {elapsed:.1f}s ({elapsed / max(1, len(rows)):.2f}s/file)")
|
| 122 |
+
|
| 123 |
+
write_excel(rows, output_excel)
|
| 124 |
+
print(f"Saved Excel: {output_excel}")
|
| 125 |
+
print(f"Summary -> total: {len(rows)} | OK: {ok} | "
|
| 126 |
+
f"extraction_failed: {extraction_failed} | inference_failed: {pass1_failed}")
|
| 127 |
+
print(f"NPZ dir: {npz_dir}")
|
| 128 |
+
return 0
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
sys.exit(main())
|
explanation.txt
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
HEG BRep Component Identifier — integration brief
|
| 2 |
+
What it is
|
| 3 |
+
A self-contained Windows folder (~2.1 GB unpacked) that runs an ML classifier for STEP-format CAD parts. Given a STEP file path, it returns a component label (elbow, tee, pipe, miscellaneous, plus a subtype for elbows/tees).
|
| 4 |
+
|
| 5 |
+
It is not a DLL. It's a local HTTP service that runs as a child process of our viewer. The classifier is a PyTorch model behind a FastAPI server. The whole Python stack — interpreter, OCC kernel, torch, model weights — is bundled inside the folder. No Python install required on the user's machine.
|
| 6 |
+
|
| 7 |
+
Architecture
|
| 8 |
+
|
| 9 |
+
┌──────────────────────────┐ ┌──────────────────────────────┐
|
| 10 |
+
│ Our C# 3D Viewer │ spawn child + stdout │ heg_brep_service.bat │
|
| 11 |
+
│ (parent process) │ ───────────────────────► │ (our launcher) │
|
| 12 |
+
│ │ │ └─► python.exe │
|
| 13 |
+
│ On viewer startup: │ read line: │ └─► FastAPI server │
|
| 14 |
+
│ - Process.Start(bat) │ ◄───────────────────────│ on 127.0.0.1 │
|
| 15 |
+
│ - read "READY port=N" │ "READY port=51571" │ :random_port │
|
| 16 |
+
│ │ │ │
|
| 17 |
+
│ On user click: │ POST /classify │ Loads models once at │
|
| 18 |
+
│ - HttpClient.PostAsync │ ───────────────────────► │ startup. Per-request: │
|
| 19 |
+
│ - JSON body │ ◄─────────────────────── │ STEP → OCC features → │
|
| 20 |
+
│ {step_path: "..."} │ JSON response │ GNN classifier → JSON │
|
| 21 |
+
│ │ │ │
|
| 22 |
+
│ On viewer exit: │ POST /shutdown │ │
|
| 23 |
+
│ - StopAsync() │ ───────────────────────► │ Graceful exit │
|
| 24 |
+
└──────────────────────────┘ └──────────────────────────────┘
|
| 25 |
+
Two key properties:
|
| 26 |
+
|
| 27 |
+
One process per viewer instance. Service lifetime == viewer lifetime.
|
| 28 |
+
Loopback only. Binds to 127.0.0.1, never exposed to the network. No firewall prompts.
|
| 29 |
+
The API contract
|
| 30 |
+
Endpoint Method Body Returns
|
| 31 |
+
/health GET — {"status":"ok","models_loaded":true,"device":"cpu","uptime_sec":...}
|
| 32 |
+
/classify POST {"step_path":"C:\\full\\path.step"} classification JSON (below)
|
| 33 |
+
/classify_batch POST {"step_paths":["...","..."]} {"results":[...]}
|
| 34 |
+
/shutdown POST — {"status":"shutting_down"} (service exits ~200ms later)
|
| 35 |
+
Successful /classify response:
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
{
|
| 39 |
+
"status": "ok",
|
| 40 |
+
"final_label": "4_tee_wf",
|
| 41 |
+
"final_conf": 0.9997,
|
| 42 |
+
"route": "tee",
|
| 43 |
+
"pass1_argmax": "tee", "pass1_conf": 1.0,
|
| 44 |
+
"pass2_argmax": "4_tee_wf", "pass2_predicted": "4_tee_wf", "pass2_conf": 0.9997,
|
| 45 |
+
"step_path": "C:\\...\\part.step",
|
| 46 |
+
"npz_path": "C:\\Users\\...\\AppData\\Local\\Temp\\heg_brep_npz_xxx\\part.npz"
|
| 47 |
+
}
|
| 48 |
+
Error responses (HTTP 200 with an error status field, not HTTP 4xx — so the C# code branches on status):
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
{"step_path": "...", "status": "extraction_failed", "error": "Bodies which are not closed are not supported"}
|
| 52 |
+
{"step_path": "...", "status": "inference_failed", "error": "..."}
|
| 53 |
+
{"step_path": "...", "status": "error", "error": "step_path not found"}
|
| 54 |
+
Label space
|
| 55 |
+
Pass-1 (parent classifier): elbow / tee / pipe / miscellaneous
|
| 56 |
+
Pass-2 elbow subtypes: 1_elbow_wf / 2_elbow_pef / 3_elbow_sf / 8_elbow_misc
|
| 57 |
+
Pass-2 tee subtypes: 4_tee_wf / 5_tee_pef / 6_tee_sf / 9_tee_misc
|
| 58 |
+
Pipe / miscellaneous: final_label is random (no specialist for these families). Use pass1_argmax if you need the parent label.
|
| 59 |
+
*_wf = welded fitting, *_pef / *_sf = other manufacturing subtypes, *_misc = within-family unclassified.
|
| 60 |
+
|
| 61 |
+
What you need to implement in C#
|
| 62 |
+
There's a working reference client in dist/heg_brep_dist/csharp_sample/ (~150 lines). It targets .NET 6 but works on .NET Framework 4.7.2+ with no changes. Usage:
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
var client = new HegBrepClient();
|
| 66 |
+
|
| 67 |
+
// At viewer startup (or lazily on first identify request — your call):
|
| 68 |
+
await client.StartAsync(@"C:\Program Files\OurViewer\heg_brep\heg_brep_service.bat");
|
| 69 |
+
|
| 70 |
+
// When the user clicks "Identify component":
|
| 71 |
+
var stepPath = await ExportCurrentSelectionToTempStep(); // your existing OCC export
|
| 72 |
+
var result = await client.ClassifyAsync(stepPath);
|
| 73 |
+
labelControl.Text = $"{result.FinalLabel} ({result.FinalConf:P1})";
|
| 74 |
+
|
| 75 |
+
// On viewer shutdown:
|
| 76 |
+
await client.StopAsync();
|
| 77 |
+
The client class handles: spawning the bat, reading the READY port=N line from stdout, posting JSON, parsing responses, graceful shutdown with a Kill fallback.
|
| 78 |
+
|
| 79 |
+
Performance budget
|
| 80 |
+
Measured on a developer laptop (RTX 3050, but service runs on CPU):
|
| 81 |
+
|
| 82 |
+
Event Cost
|
| 83 |
+
Service startup 10–15 s (paid once per viewer launch)
|
| 84 |
+
First /classify after startup ~1.0 s
|
| 85 |
+
Subsequent /classify calls ~0.8 s (dominated by OCC feature extraction; inference itself is ~50 ms)
|
| 86 |
+
For UX, recommend you start the service eagerly at viewer launch (hide behind splash) or lazily on first Identify click (show a "warming up..." spinner for ~10 s).
|
| 87 |
+
|
| 88 |
+
Failure modes you must handle
|
| 89 |
+
Service won't start (heg_brep_service.bat exits before READY line) → log stderr (the client forwards it to Debug.WriteLine), surface error to user, do not retry in a tight loop.
|
| 90 |
+
STEP fails extraction ("Bodies which are not closed are not supported" is the most common one — Inventor exports sometimes hit this). Branch on status != "ok".
|
| 91 |
+
Service hangs / takes too long — HegBrepClient has a 60-second timeout. If ClassifyAsync throws TaskCanceledException, the service is wedged. Call StopAsync() and restart.
|
| 92 |
+
Service crashes mid-session — process exits, next ClassifyAsync will throw a connection error. Recovery: catch, call StartAsync() again, retry once.
|
| 93 |
+
A small supervisor that restarts the service on crash (max 3 retries per session) is a reasonable addition.
|
| 94 |
+
|
| 95 |
+
What's in the bundle
|
| 96 |
+
|
| 97 |
+
heg_brep_dist/
|
| 98 |
+
├── heg_brep_service.bat ← what you Process.Start
|
| 99 |
+
├── heg_brep_batch.bat ← offline regression-test tool, irrelevant for the viewer
|
| 100 |
+
├── README.txt ← detailed docs
|
| 101 |
+
├── python/ ← bundled Python 3.10 env (do not modify)
|
| 102 |
+
├── heg_brep/ ← our Python code
|
| 103 |
+
├── BRepExtractor/ ← STEP→features pipeline
|
| 104 |
+
├── models/ ← 3 model files (~94 MB total)
|
| 105 |
+
└── csharp_sample/ ← HegBrepClient.cs + Program.cs (copy into your project)
|
| 106 |
+
Installer should drop this whole folder somewhere under the viewer's install dir (e.g. Program Files\OurViewer\heg_brep\) and never modify it. Updates ship as a new folder replacement; viewer code doesn't change.
|
| 107 |
+
|
| 108 |
+
Constraints / non-goals
|
| 109 |
+
Windows x64 only. Linux / macOS / 32-bit not supported.
|
| 110 |
+
CPU inference by default. A CUDA variant exists (separate ~2 GB bundle) if customers have NVIDIA GPUs — currently not packaged.
|
| 111 |
+
STEP input only. Other CAD formats (IGES, JT, native Inventor/SolidWorks) would need a converter layer first.
|
| 112 |
+
Single-threaded service. Don't fire concurrent /classify calls from multiple viewer threads — they'll serialize anyway. If you need parallelism, queue requests in C#.
|
| 113 |
+
Questions to send back
|
| 114 |
+
If anything in the contract is unclear, the things most worth raising before coding starts:
|
| 115 |
+
|
| 116 |
+
Where in the installer layout should heg_brep_dist/ live? That determines the path you pass to StartAsync.
|
| 117 |
+
Eager vs. lazy service startup — affects splash-screen design.
|
| 118 |
+
How does the viewer currently export a selected solid to a STEP file? (We need a file path, not in-memory geometry, in v1.)
|
| 119 |
+
Logging — should service stderr go to the viewer's existing log file, or to its own file alongside the bundle?
|
extraction.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""In-process STEP -> NPZ extraction (no subprocess)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
import tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
from heg_brep import DEFAULT_BREPEXTRACTOR_DIR, DEFAULT_FEATURE_LIST
|
| 10 |
+
|
| 11 |
+
# Make the BRepExtractor package importable (it is laid out as `pipeline.*`)
|
| 12 |
+
if str(DEFAULT_BREPEXTRACTOR_DIR) not in sys.path:
|
| 13 |
+
sys.path.insert(0, str(DEFAULT_BREPEXTRACTOR_DIR))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _load_feature_schema(feature_list: Path) -> dict:
|
| 17 |
+
with open(feature_list, "r") as fp:
|
| 18 |
+
return json.load(fp)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def extract_step_to_npz(step_file: Path,
|
| 22 |
+
output_dir: Optional[Path] = None,
|
| 23 |
+
feature_list: Path = DEFAULT_FEATURE_LIST) -> Path:
|
| 24 |
+
"""Extract a single STEP to an NPZ. Returns the produced NPZ path.
|
| 25 |
+
|
| 26 |
+
Raises RuntimeError if extraction fails or the file is skipped.
|
| 27 |
+
"""
|
| 28 |
+
from pipeline.extract_brep_extractor_data_from_step import extract_brep_extractor_features
|
| 29 |
+
|
| 30 |
+
step_file = Path(step_file).expanduser().resolve()
|
| 31 |
+
if not step_file.exists():
|
| 32 |
+
raise FileNotFoundError(step_file)
|
| 33 |
+
if output_dir is None:
|
| 34 |
+
output_dir = Path(tempfile.mkdtemp(prefix="heg_brep_npz_"))
|
| 35 |
+
output_dir = Path(output_dir).expanduser().resolve()
|
| 36 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
|
| 38 |
+
schema = _load_feature_schema(feature_list)
|
| 39 |
+
ok = extract_brep_extractor_features(step_file, output_dir, schema, mesh_dir=None, seg_dir=None)
|
| 40 |
+
npz = output_dir / f"{step_file.stem}.npz"
|
| 41 |
+
if not ok or not npz.exists():
|
| 42 |
+
reason = _last_skip_reason_for(step_file, output_dir) or "unknown extraction failure"
|
| 43 |
+
raise RuntimeError(f"Extraction failed for {step_file.name}: {reason}")
|
| 44 |
+
return npz
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def extract_folder_to_npz(step_folder: Path,
|
| 48 |
+
output_dir: Optional[Path] = None,
|
| 49 |
+
feature_list: Path = DEFAULT_FEATURE_LIST,
|
| 50 |
+
num_workers: int = 1,
|
| 51 |
+
max_file_mb: Optional[float] = None) -> Dict[str, object]:
|
| 52 |
+
"""Extract every STEP under `step_folder` to NPZ. Returns a summary dict
|
| 53 |
+
with: npz_dir, ok_stems, skipped (dict of stem -> reason), step_paths."""
|
| 54 |
+
from pipeline.extract_brep_extractor_data_from_step import extract_brep_extractor_data_from_step
|
| 55 |
+
|
| 56 |
+
step_folder = Path(step_folder).expanduser().resolve()
|
| 57 |
+
if not step_folder.is_dir():
|
| 58 |
+
raise FileNotFoundError(step_folder)
|
| 59 |
+
if output_dir is None:
|
| 60 |
+
output_dir = Path(tempfile.mkdtemp(prefix="heg_brep_npz_"))
|
| 61 |
+
output_dir = Path(output_dir).expanduser().resolve()
|
| 62 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
|
| 64 |
+
step_paths = _list_step_files(step_folder)
|
| 65 |
+
extract_brep_extractor_data_from_step(
|
| 66 |
+
step_path=step_folder,
|
| 67 |
+
output_path=output_dir,
|
| 68 |
+
mesh_dir=None,
|
| 69 |
+
seg_dir=None,
|
| 70 |
+
feature_list_path=feature_list,
|
| 71 |
+
force_regeneration=False,
|
| 72 |
+
max_file_mb=max_file_mb,
|
| 73 |
+
num_workers=max(1, int(num_workers)),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
skipped = _all_skip_reasons(output_dir)
|
| 77 |
+
ok_stems = []
|
| 78 |
+
for sp in step_paths:
|
| 79 |
+
if (output_dir / f"{sp.stem}.npz").exists():
|
| 80 |
+
ok_stems.append(sp.stem)
|
| 81 |
+
return {
|
| 82 |
+
"npz_dir": output_dir,
|
| 83 |
+
"step_paths": step_paths,
|
| 84 |
+
"ok_stems": ok_stems,
|
| 85 |
+
"skipped": skipped,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _list_step_files(folder: Path) -> List[Path]:
|
| 90 |
+
out = set()
|
| 91 |
+
for pattern in ("*.stp", "*.step", "*.STP", "*.STEP"):
|
| 92 |
+
for p in folder.glob(pattern): out.add(p.resolve())
|
| 93 |
+
for p in folder.glob(f"**/{pattern}"): out.add(p.resolve())
|
| 94 |
+
return sorted(out)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _all_skip_reasons(npz_dir: Path) -> Dict[str, str]:
|
| 98 |
+
log = npz_dir / "skipped.jsonl"
|
| 99 |
+
out: Dict[str, str] = {}
|
| 100 |
+
if not log.exists():
|
| 101 |
+
return out
|
| 102 |
+
with log.open("r") as fp:
|
| 103 |
+
for line in fp:
|
| 104 |
+
line = line.strip()
|
| 105 |
+
if not line: continue
|
| 106 |
+
try:
|
| 107 |
+
rec = json.loads(line)
|
| 108 |
+
except json.JSONDecodeError:
|
| 109 |
+
continue
|
| 110 |
+
f = rec.get("file", "")
|
| 111 |
+
if f:
|
| 112 |
+
out[Path(f).stem] = str(rec.get("reason", "skipped"))
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _last_skip_reason_for(step_file: Path, npz_dir: Path) -> Optional[str]:
|
| 117 |
+
reasons = _all_skip_reasons(npz_dir)
|
| 118 |
+
return reasons.get(step_file.stem)
|
graph_data.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utility helpers for loading BRep extractor-processed STEP data as PyG graphs.
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import re
|
| 9 |
+
from typing import Dict, Iterable, List, Tuple
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from torch_geometric.data import HeteroData
|
| 14 |
+
|
| 15 |
+
# Backward-compatible default label mapping used by earlier checkpoints.
|
| 16 |
+
DEFAULT_LABELS: Dict[str, int] = {"pipe": 0, "elbow": 1, "tjoint": 2, "random": 3}
|
| 17 |
+
LABELS: Dict[str, int] = DEFAULT_LABELS.copy()
|
| 18 |
+
STEP_EXTS = ("*.step", "*.stp", "*.STEP", "*.STP")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _class_sort_key(class_name: str) -> Tuple[int, int, str]:
|
| 22 |
+
"""
|
| 23 |
+
Sort class names numerically when they have prefixes like `0_random`,
|
| 24 |
+
then lexicographically for the remaining part.
|
| 25 |
+
"""
|
| 26 |
+
match = re.match(r"^\s*(\d+)(?:[_\-\s]+(.*))?$", class_name)
|
| 27 |
+
if match:
|
| 28 |
+
suffix = (match.group(2) or "").strip().lower()
|
| 29 |
+
return (0, int(match.group(1)), suffix)
|
| 30 |
+
return (1, 10**9, class_name.lower())
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _iter_step_files(step_root: Path) -> List[Path]:
|
| 34 |
+
files_set = set()
|
| 35 |
+
for pattern in STEP_EXTS:
|
| 36 |
+
for step_file in step_root.glob(pattern):
|
| 37 |
+
files_set.add(step_file.resolve())
|
| 38 |
+
for step_file in step_root.glob(f"**/{pattern}"):
|
| 39 |
+
files_set.add(step_file.resolve())
|
| 40 |
+
return sorted(files_set)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def discover_step_classes(step_root: Path) -> List[str]:
|
| 44 |
+
"""
|
| 45 |
+
Discover class names from top-level folders under `step_root` that contain
|
| 46 |
+
STEP files.
|
| 47 |
+
"""
|
| 48 |
+
step_root = Path(step_root)
|
| 49 |
+
if not step_root.exists():
|
| 50 |
+
raise FileNotFoundError(f"STEP root does not exist: {step_root}")
|
| 51 |
+
|
| 52 |
+
class_names = set()
|
| 53 |
+
for step_file in _iter_step_files(step_root):
|
| 54 |
+
rel = step_file.relative_to(step_root)
|
| 55 |
+
if len(rel.parts) < 2:
|
| 56 |
+
# Ignore STEP files placed directly under step_root.
|
| 57 |
+
continue
|
| 58 |
+
class_names.add(rel.parts[0])
|
| 59 |
+
|
| 60 |
+
if not class_names:
|
| 61 |
+
raise RuntimeError(f"No STEP class folders found under {step_root}")
|
| 62 |
+
return sorted(class_names, key=_class_sort_key)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def build_class_labels(step_root: Path) -> Dict[str, int]:
|
| 66 |
+
"""
|
| 67 |
+
Build a deterministic {class_name -> class_id} mapping from step_root.
|
| 68 |
+
"""
|
| 69 |
+
classes = discover_step_classes(step_root)
|
| 70 |
+
return {name: idx for idx, name in enumerate(classes)}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def build_label_metadata(
|
| 74 |
+
step_root: Path,
|
| 75 |
+
labels: Dict[str, int] | None = None,
|
| 76 |
+
) -> Tuple[Dict[str, int], Dict[str, int], Dict[str, Tuple[str, ...]]]:
|
| 77 |
+
"""
|
| 78 |
+
Build label metadata from STEP folder structure.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
- labels: {class_name: class_id}
|
| 82 |
+
- stem_to_label: {npz_stem: class_id}
|
| 83 |
+
- collisions: {stem: (class_name_a, class_name_b, ...)} for stems that
|
| 84 |
+
appear in more than one class folder. The chosen label follows the same
|
| 85 |
+
overwrite behavior as extractor output naming (`<stem>.npz`).
|
| 86 |
+
"""
|
| 87 |
+
step_root = Path(step_root)
|
| 88 |
+
if labels is None:
|
| 89 |
+
labels = build_class_labels(step_root)
|
| 90 |
+
if not labels:
|
| 91 |
+
raise RuntimeError("No labels were provided/discovered for STEP classes.")
|
| 92 |
+
|
| 93 |
+
stem_to_label: Dict[str, int] = {}
|
| 94 |
+
stem_to_class: Dict[str, str] = {}
|
| 95 |
+
collisions = defaultdict(set)
|
| 96 |
+
|
| 97 |
+
for step_file in _iter_step_files(step_root):
|
| 98 |
+
rel = step_file.relative_to(step_root)
|
| 99 |
+
if len(rel.parts) < 2:
|
| 100 |
+
continue
|
| 101 |
+
class_name = rel.parts[0]
|
| 102 |
+
if class_name not in labels:
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
stem = step_file.stem
|
| 106 |
+
prev_class = stem_to_class.get(stem)
|
| 107 |
+
if prev_class is not None and prev_class != class_name:
|
| 108 |
+
collisions[stem].update((prev_class, class_name))
|
| 109 |
+
|
| 110 |
+
stem_to_class[stem] = class_name
|
| 111 |
+
stem_to_label[stem] = int(labels[class_name])
|
| 112 |
+
|
| 113 |
+
if not stem_to_label:
|
| 114 |
+
raise RuntimeError(
|
| 115 |
+
f"No STEP files found under {step_root} for classes: {tuple(labels)}"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
collision_out = {
|
| 119 |
+
stem: tuple(sorted(classes, key=_class_sort_key))
|
| 120 |
+
for stem, classes in collisions.items()
|
| 121 |
+
}
|
| 122 |
+
return labels, stem_to_label, collision_out
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def build_label_map(step_root: Path, labels: Dict[str, int] | None = None) -> Dict[str, int]:
|
| 126 |
+
"""
|
| 127 |
+
Build a mapping from STEP file stem to integer label.
|
| 128 |
+
"""
|
| 129 |
+
_, stem_to_label, _ = build_label_metadata(step_root, labels)
|
| 130 |
+
return stem_to_label
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _flatten(arr: np.ndarray) -> np.ndarray:
|
| 134 |
+
return np.asarray(arr, dtype=np.float32).reshape(arr.shape[0], -1)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _coedge_grid_stats(coedge_grids: np.ndarray) -> np.ndarray:
|
| 138 |
+
"""
|
| 139 |
+
Summarize coedge point grids into compact, less position-sensitive stats.
|
| 140 |
+
Input shape is expected as [N, C, U] (typically C=12).
|
| 141 |
+
|
| 142 |
+
Returns [N, 28]:
|
| 143 |
+
- channel mean (C=12)
|
| 144 |
+
- channel std (C=12)
|
| 145 |
+
- xyz path length, xyz chord length, tortuosity, xyz bbox diag (4)
|
| 146 |
+
"""
|
| 147 |
+
grids = np.asarray(coedge_grids, dtype=np.float32)
|
| 148 |
+
if grids.ndim != 3:
|
| 149 |
+
raise RuntimeError(f"Expected coedge grids with ndim=3, got shape {grids.shape}")
|
| 150 |
+
n, c, u = grids.shape
|
| 151 |
+
|
| 152 |
+
mean_c = grids.mean(axis=2)
|
| 153 |
+
std_c = grids.std(axis=2)
|
| 154 |
+
|
| 155 |
+
if c >= 3 and u >= 2:
|
| 156 |
+
xyz = grids[:, 0:3, :].transpose(0, 2, 1) # [N, U, 3]
|
| 157 |
+
dif = xyz[:, 1:, :] - xyz[:, :-1, :]
|
| 158 |
+
seg_len = np.linalg.norm(dif, axis=2)
|
| 159 |
+
path_len = seg_len.sum(axis=1)
|
| 160 |
+
chord = np.linalg.norm(xyz[:, -1, :] - xyz[:, 0, :], axis=1)
|
| 161 |
+
bbox_diag = np.linalg.norm(xyz.max(axis=1) - xyz.min(axis=1), axis=1)
|
| 162 |
+
tort = path_len / (chord + 1e-6)
|
| 163 |
+
else:
|
| 164 |
+
path_len = np.zeros(n, dtype=np.float32)
|
| 165 |
+
chord = np.zeros(n, dtype=np.float32)
|
| 166 |
+
tort = np.ones(n, dtype=np.float32)
|
| 167 |
+
bbox_diag = np.zeros(n, dtype=np.float32)
|
| 168 |
+
|
| 169 |
+
shape_stats = np.stack([path_len, chord, tort, bbox_diag], axis=1).astype(np.float32)
|
| 170 |
+
return np.concatenate([mean_c, std_c, shape_stats], axis=1).astype(np.float32)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _face_grid_stats(face_grids: np.ndarray) -> np.ndarray:
|
| 174 |
+
"""
|
| 175 |
+
Summarize face point grids into compact stats per face.
|
| 176 |
+
Returns [F, 10]: xyz_mean (3), xyz_std (3), nrm_mean (3), mask_frac (1).
|
| 177 |
+
"""
|
| 178 |
+
face_grids = np.asarray(face_grids, dtype=np.float32)
|
| 179 |
+
f = face_grids.shape[0]
|
| 180 |
+
xyz = face_grids[:, 0:3, :, :].reshape(f, 3, -1)
|
| 181 |
+
nrm = face_grids[:, 3:6, :, :].reshape(f, 3, -1)
|
| 182 |
+
msk = face_grids[:, 6, :, :].reshape(f, -1)
|
| 183 |
+
|
| 184 |
+
mask = (msk > 0.5).astype(np.float32)
|
| 185 |
+
mask_frac = mask.mean(axis=1, keepdims=True)
|
| 186 |
+
w = mask / (mask.sum(axis=1, keepdims=True) + 1e-6)
|
| 187 |
+
|
| 188 |
+
xyz_mean = (xyz * w[:, None, :]).sum(axis=2)
|
| 189 |
+
xyz_var = (w[:, None, :] * (xyz - xyz_mean[:, :, None]) ** 2).sum(axis=2)
|
| 190 |
+
xyz_std = np.sqrt(np.maximum(xyz_var, 1e-12))
|
| 191 |
+
nrm_mean = (nrm * w[:, None, :]).sum(axis=2)
|
| 192 |
+
return np.concatenate([xyz_mean, xyz_std, nrm_mean, mask_frac], axis=1)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _build_face_neighbors(
|
| 196 |
+
coedge_face: np.ndarray,
|
| 197 |
+
coedge_edge: np.ndarray,
|
| 198 |
+
num_faces: int,
|
| 199 |
+
) -> List[set[int]]:
|
| 200 |
+
"""
|
| 201 |
+
Build face-face adjacency from shared model edges.
|
| 202 |
+
"""
|
| 203 |
+
neighbors: List[set[int]] = [set() for _ in range(max(0, int(num_faces)))]
|
| 204 |
+
if num_faces <= 0 or coedge_face.size == 0 or coedge_edge.size == 0:
|
| 205 |
+
return neighbors
|
| 206 |
+
|
| 207 |
+
edge_to_faces: Dict[int, set[int]] = defaultdict(set)
|
| 208 |
+
for face_id, edge_id in zip(coedge_face.tolist(), coedge_edge.tolist()):
|
| 209 |
+
if face_id < 0 or face_id >= num_faces or edge_id < 0:
|
| 210 |
+
continue
|
| 211 |
+
edge_to_faces[int(edge_id)].add(int(face_id))
|
| 212 |
+
|
| 213 |
+
for attached_faces in edge_to_faces.values():
|
| 214 |
+
if len(attached_faces) < 2:
|
| 215 |
+
continue
|
| 216 |
+
face_list = list(attached_faces)
|
| 217 |
+
for src in face_list:
|
| 218 |
+
for dst in face_list:
|
| 219 |
+
if src != dst:
|
| 220 |
+
neighbors[src].add(dst)
|
| 221 |
+
return neighbors
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _derive_torus_like_features(
|
| 225 |
+
face_feats: np.ndarray,
|
| 226 |
+
coedge_face: np.ndarray,
|
| 227 |
+
coedge_edge: np.ndarray,
|
| 228 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 229 |
+
"""
|
| 230 |
+
Derive robust torus-like signals from primitive flags + face adjacency.
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
- face_ctx [F, 3]: bspline_core_flag, torus_like_flag, cyl_neighbor_count_norm
|
| 234 |
+
- global_ctx [3]: torus_like_face_fraction, torus_like_area_fraction, bspline_core_fraction
|
| 235 |
+
"""
|
| 236 |
+
num_faces = int(face_feats.shape[0])
|
| 237 |
+
if num_faces == 0:
|
| 238 |
+
return np.zeros((0, 3), dtype=np.float32), np.zeros(3, dtype=np.float32)
|
| 239 |
+
|
| 240 |
+
feat_dim = int(face_feats.shape[1]) if face_feats.ndim == 2 else 0
|
| 241 |
+
if feat_dim > 5:
|
| 242 |
+
area = np.clip(np.asarray(face_feats[:, 5], dtype=np.float32), 0.0, None)
|
| 243 |
+
else:
|
| 244 |
+
area = np.ones((num_faces,), dtype=np.float32)
|
| 245 |
+
area_sum = float(area.sum())
|
| 246 |
+
if area_sum <= 1e-8:
|
| 247 |
+
area_frac = np.full((num_faces,), 1.0 / max(1, num_faces), dtype=np.float32)
|
| 248 |
+
else:
|
| 249 |
+
area_frac = area / (area_sum + 1e-8)
|
| 250 |
+
|
| 251 |
+
cylinder_mask = face_feats[:, 1] > 0.5 if feat_dim > 1 else np.zeros((num_faces,), dtype=bool)
|
| 252 |
+
torus_mask = face_feats[:, 4] > 0.5 if feat_dim > 4 else np.zeros((num_faces,), dtype=bool)
|
| 253 |
+
nurbs_mask = face_feats[:, 6] > 0.5 if feat_dim > 6 else np.zeros((num_faces,), dtype=bool)
|
| 254 |
+
|
| 255 |
+
neighbors = _build_face_neighbors(coedge_face, coedge_edge, num_faces)
|
| 256 |
+
cyl_neighbor_count = np.zeros((num_faces,), dtype=np.float32)
|
| 257 |
+
for i, nbrs in enumerate(neighbors):
|
| 258 |
+
if nbrs:
|
| 259 |
+
cyl_neighbor_count[i] = float(sum(1 for n in nbrs if cylinder_mask[n]))
|
| 260 |
+
|
| 261 |
+
cyl_neighbor_den = max(1.0, float(cyl_neighbor_count.max()))
|
| 262 |
+
cyl_neighbor_count_norm = (cyl_neighbor_count / cyl_neighbor_den).astype(np.float32)
|
| 263 |
+
|
| 264 |
+
# Treat large BSpline faces near cylinders as torus-like elbow core candidates.
|
| 265 |
+
bspline_core_mask = nurbs_mask & (area_frac >= 0.03) & (cyl_neighbor_count >= 1.0)
|
| 266 |
+
torus_like_mask = torus_mask | bspline_core_mask
|
| 267 |
+
|
| 268 |
+
face_ctx = np.stack(
|
| 269 |
+
[
|
| 270 |
+
bspline_core_mask.astype(np.float32),
|
| 271 |
+
torus_like_mask.astype(np.float32),
|
| 272 |
+
cyl_neighbor_count_norm,
|
| 273 |
+
],
|
| 274 |
+
axis=1,
|
| 275 |
+
).astype(np.float32)
|
| 276 |
+
global_ctx = np.array(
|
| 277 |
+
[
|
| 278 |
+
float(np.mean(torus_like_mask)),
|
| 279 |
+
float(np.sum(area_frac[torus_like_mask])),
|
| 280 |
+
float(np.mean(bspline_core_mask)),
|
| 281 |
+
],
|
| 282 |
+
dtype=np.float32,
|
| 283 |
+
)
|
| 284 |
+
return face_ctx, global_ctx
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def compute_global_geom_features(data) -> np.ndarray:
|
| 288 |
+
"""
|
| 289 |
+
Compute compact global geometry descriptors from face/coedge point samples.
|
| 290 |
+
Returns [5] float32: pca_ev_ratio_1/2/3, line_fit_rmse, plane_fit_rmse.
|
| 291 |
+
"""
|
| 292 |
+
points = []
|
| 293 |
+
face_grids = np.asarray(data["face_point_grids"], dtype=np.float32)
|
| 294 |
+
if face_grids.size:
|
| 295 |
+
xyz = face_grids[:, 0:3, :, :].transpose(0, 2, 3, 1).reshape(-1, 3)
|
| 296 |
+
mask = face_grids[:, 6, :, :].reshape(-1) > 0.5
|
| 297 |
+
if mask.any():
|
| 298 |
+
points.append(xyz[mask])
|
| 299 |
+
|
| 300 |
+
coedge_grids = np.asarray(data["coedge_point_grids"], dtype=np.float32)
|
| 301 |
+
if coedge_grids.size:
|
| 302 |
+
co_xyz = coedge_grids[:, 0:3, :].transpose(0, 2, 1).reshape(-1, 3)
|
| 303 |
+
points.append(co_xyz)
|
| 304 |
+
|
| 305 |
+
if not points:
|
| 306 |
+
return np.zeros(5, dtype=np.float32)
|
| 307 |
+
|
| 308 |
+
pts = np.concatenate(points, axis=0)
|
| 309 |
+
if pts.shape[0] < 3:
|
| 310 |
+
return np.zeros(5, dtype=np.float32)
|
| 311 |
+
pts = pts[np.isfinite(pts).all(axis=1)]
|
| 312 |
+
if pts.shape[0] < 3:
|
| 313 |
+
return np.zeros(5, dtype=np.float32)
|
| 314 |
+
|
| 315 |
+
mean = pts.mean(axis=0, keepdims=True)
|
| 316 |
+
centered = pts - mean
|
| 317 |
+
scale = np.sqrt(np.mean(np.sum(centered ** 2, axis=1)))
|
| 318 |
+
centered = centered / (scale + 1e-6)
|
| 319 |
+
cov = (centered.T @ centered) / max(1, centered.shape[0])
|
| 320 |
+
if not np.isfinite(cov).all():
|
| 321 |
+
return np.zeros(5, dtype=np.float32)
|
| 322 |
+
|
| 323 |
+
ev = np.linalg.eigvalsh(cov)
|
| 324 |
+
ev = np.sort(ev)[::-1]
|
| 325 |
+
ev = np.maximum(ev, 0.0)
|
| 326 |
+
total = ev.sum()
|
| 327 |
+
if not np.isfinite(total) or total <= 0.0:
|
| 328 |
+
return np.zeros(5, dtype=np.float32)
|
| 329 |
+
|
| 330 |
+
ratios = ev / total
|
| 331 |
+
line_rmse = np.sqrt(max(ev[1] + ev[2], 0.0))
|
| 332 |
+
plane_rmse = np.sqrt(max(ev[2], 0.0))
|
| 333 |
+
feats = np.array(
|
| 334 |
+
[ratios[0], ratios[1], ratios[2], line_rmse, plane_rmse],
|
| 335 |
+
dtype=np.float32,
|
| 336 |
+
)
|
| 337 |
+
if not np.isfinite(feats).all():
|
| 338 |
+
return np.zeros(5, dtype=np.float32)
|
| 339 |
+
return feats
|
| 340 |
+
|
| 341 |
+
def load_coedge_arrays(npz_path: Path) -> Dict[str, np.ndarray]:
|
| 342 |
+
"""
|
| 343 |
+
Load node features and adjacency indices from a BRep extractor npz.
|
| 344 |
+
Returns a dict with coedge/face/edge/global features and topology arrays.
|
| 345 |
+
"""
|
| 346 |
+
with np.load(npz_path) as data:
|
| 347 |
+
coedge_feats = _flatten(data["coedge_features"])
|
| 348 |
+
scale = np.asarray(data["coedge_scale_factors"], dtype=np.float32)[:, None]
|
| 349 |
+
reverse = np.asarray(data["coedge_reverse_flags"], dtype=np.float32)[:, None]
|
| 350 |
+
point_grids = _coedge_grid_stats(data["coedge_point_grids"]) # [N, compact_stats]
|
| 351 |
+
lcs = _flatten(data["coedge_lcs"]) # [N, 16]
|
| 352 |
+
|
| 353 |
+
face_idx = np.asarray(data["face"], dtype=np.int64)
|
| 354 |
+
edge_idx = np.asarray(data["edge"], dtype=np.int64)
|
| 355 |
+
face_feats = np.asarray(data["face_features"], dtype=np.float32) # [F, 7]
|
| 356 |
+
edge_feats = np.asarray(data["edge_features"], dtype=np.float32) # [E, 10]
|
| 357 |
+
|
| 358 |
+
face_grids = np.asarray(data["face_point_grids"], dtype=np.float32)
|
| 359 |
+
face_grid_stats = _face_grid_stats(face_grids)
|
| 360 |
+
face_ctx, global_ctx = _derive_torus_like_features(face_feats, face_idx, edge_idx)
|
| 361 |
+
|
| 362 |
+
coedge_x = np.concatenate(
|
| 363 |
+
[coedge_feats, scale, reverse, point_grids, lcs], axis=1
|
| 364 |
+
)
|
| 365 |
+
face_x = np.concatenate([face_feats, face_ctx, face_grid_stats], axis=1)
|
| 366 |
+
edge_x = edge_feats
|
| 367 |
+
next_index = np.asarray(data["next"], dtype=np.int64)
|
| 368 |
+
mate_index = np.asarray(data["mate"], dtype=np.int64)
|
| 369 |
+
global_legacy = compute_global_geom_features(data)
|
| 370 |
+
# Keep legacy 5 features as prefix; append torus-like robustness stats.
|
| 371 |
+
global_features = np.concatenate([global_legacy, global_ctx], axis=0).astype(np.float32)
|
| 372 |
+
|
| 373 |
+
return {
|
| 374 |
+
"coedge_x": coedge_x,
|
| 375 |
+
"face_x": face_x,
|
| 376 |
+
"edge_x": edge_x,
|
| 377 |
+
"next": next_index,
|
| 378 |
+
"mate": mate_index,
|
| 379 |
+
"coedge_face": face_idx,
|
| 380 |
+
"coedge_edge": edge_idx,
|
| 381 |
+
"global_x": global_features,
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def make_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor:
|
| 386 |
+
"""
|
| 387 |
+
Build a 2 x E tensor of edge indices (with both directions, deduplicated).
|
| 388 |
+
"""
|
| 389 |
+
pairs = np.stack([source, target], axis=1)
|
| 390 |
+
flipped = pairs[:, ::-1]
|
| 391 |
+
all_pairs = np.concatenate([pairs, flipped], axis=0)
|
| 392 |
+
all_pairs = np.unique(all_pairs, axis=0)
|
| 393 |
+
return torch.tensor(all_pairs.T, dtype=torch.long)
|
| 394 |
+
|
| 395 |
+
def make_directed_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor:
|
| 396 |
+
"""
|
| 397 |
+
Build a 2 x E tensor of directed edge indices (no deduplication).
|
| 398 |
+
"""
|
| 399 |
+
return torch.tensor(np.stack([source, target], axis=0), dtype=torch.long)
|
| 400 |
+
|
| 401 |
+
def make_bipartite_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor:
|
| 402 |
+
"""
|
| 403 |
+
Build a 2 x E tensor of directed bipartite edge indices (deduplicated).
|
| 404 |
+
"""
|
| 405 |
+
pairs = np.stack([source, target], axis=1)
|
| 406 |
+
pairs = np.unique(pairs, axis=0)
|
| 407 |
+
return torch.tensor(pairs.T, dtype=torch.long)
|
| 408 |
+
|
| 409 |
+
def make_heterodata(
|
| 410 |
+
coedge_x: np.ndarray,
|
| 411 |
+
face_x: np.ndarray,
|
| 412 |
+
edge_x: np.ndarray,
|
| 413 |
+
next_index: np.ndarray,
|
| 414 |
+
mate_index: np.ndarray,
|
| 415 |
+
coedge_face: np.ndarray,
|
| 416 |
+
coedge_edge: np.ndarray,
|
| 417 |
+
global_features: np.ndarray,
|
| 418 |
+
label: int | None,
|
| 419 |
+
norm_stats: Dict[str, Dict[str, np.ndarray | torch.Tensor]] | None = None,
|
| 420 |
+
) -> HeteroData:
|
| 421 |
+
"""
|
| 422 |
+
Create a PyG HeteroData graph for the coedge features/relations.
|
| 423 |
+
When mean/std are provided the features are normalised element-wise.
|
| 424 |
+
"""
|
| 425 |
+
def _normalize(x_arr: np.ndarray, stats: Dict[str, np.ndarray | torch.Tensor] | None) -> torch.Tensor:
|
| 426 |
+
x_t = torch.tensor(x_arr, dtype=torch.float32)
|
| 427 |
+
if stats is None:
|
| 428 |
+
return x_t
|
| 429 |
+
mean = stats.get("mean")
|
| 430 |
+
std = stats.get("std")
|
| 431 |
+
if mean is None or std is None:
|
| 432 |
+
return x_t
|
| 433 |
+
mean_t = torch.as_tensor(mean, dtype=torch.float32)
|
| 434 |
+
std_t = torch.as_tensor(std, dtype=torch.float32)
|
| 435 |
+
return (x_t - mean_t) / std_t
|
| 436 |
+
|
| 437 |
+
coedge_stats = norm_stats.get("coedge") if norm_stats else None
|
| 438 |
+
face_stats = norm_stats.get("face") if norm_stats else None
|
| 439 |
+
edge_stats = norm_stats.get("edge") if norm_stats else None
|
| 440 |
+
|
| 441 |
+
x_coedge = _normalize(coedge_x, coedge_stats)
|
| 442 |
+
x_face = _normalize(face_x, face_stats)
|
| 443 |
+
x_edge = _normalize(edge_x, edge_stats)
|
| 444 |
+
|
| 445 |
+
idx = np.arange(coedge_x.shape[0], dtype=np.int64)
|
| 446 |
+
edge_next = make_directed_edge_index(idx, next_index)
|
| 447 |
+
edge_prev = make_directed_edge_index(next_index, idx)
|
| 448 |
+
edge_mate = make_edge_index(idx, mate_index)
|
| 449 |
+
edge_coedge_face = make_directed_edge_index(idx, coedge_face)
|
| 450 |
+
edge_face_coedge = make_directed_edge_index(coedge_face, idx)
|
| 451 |
+
edge_coedge_edge = make_directed_edge_index(idx, coedge_edge)
|
| 452 |
+
edge_edge_coedge = make_directed_edge_index(coedge_edge, idx)
|
| 453 |
+
edge_face_edge = make_bipartite_edge_index(coedge_face, coedge_edge)
|
| 454 |
+
edge_edge_face = make_bipartite_edge_index(coedge_edge, coedge_face)
|
| 455 |
+
|
| 456 |
+
data = HeteroData()
|
| 457 |
+
data["coedge"].x = x_coedge
|
| 458 |
+
data["face"].x = x_face
|
| 459 |
+
data["edge"].x = x_edge
|
| 460 |
+
data["global"].x = torch.tensor(global_features, dtype=torch.float32).view(1, -1)
|
| 461 |
+
data["coedge", "next", "coedge"].edge_index = edge_next
|
| 462 |
+
data["coedge", "prev", "coedge"].edge_index = edge_prev
|
| 463 |
+
data["coedge", "mate", "coedge"].edge_index = edge_mate
|
| 464 |
+
data["coedge", "to_face", "face"].edge_index = edge_coedge_face
|
| 465 |
+
data["face", "to_coedge", "coedge"].edge_index = edge_face_coedge
|
| 466 |
+
data["coedge", "to_edge", "edge"].edge_index = edge_coedge_edge
|
| 467 |
+
data["edge", "to_coedge", "coedge"].edge_index = edge_edge_coedge
|
| 468 |
+
data["face", "to_edge", "edge"].edge_index = edge_face_edge
|
| 469 |
+
data["edge", "to_face", "face"].edge_index = edge_edge_face
|
| 470 |
+
if label is not None:
|
| 471 |
+
data.y = torch.tensor([int(label)], dtype=torch.long)
|
| 472 |
+
return data
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def compute_feature_stats(npz_paths: Iterable[Path]) -> Dict[str, np.ndarray]:
|
| 476 |
+
"""
|
| 477 |
+
Compute mean and std (per feature dimension) across all node features in the dataset.
|
| 478 |
+
"""
|
| 479 |
+
totals = {"coedge": 0, "face": 0, "edge": 0}
|
| 480 |
+
sum_vec: Dict[str, np.ndarray | None] = {"coedge": None, "face": None, "edge": None}
|
| 481 |
+
sum_sq: Dict[str, np.ndarray | None] = {"coedge": None, "face": None, "edge": None}
|
| 482 |
+
|
| 483 |
+
for path in npz_paths:
|
| 484 |
+
graph = load_coedge_arrays(path)
|
| 485 |
+
for key, x in (("coedge", graph["coedge_x"]), ("face", graph["face_x"]), ("edge", graph["edge_x"])):
|
| 486 |
+
if sum_vec[key] is None:
|
| 487 |
+
sum_vec[key] = np.zeros(x.shape[1], dtype=np.float64)
|
| 488 |
+
sum_sq[key] = np.zeros(x.shape[1], dtype=np.float64)
|
| 489 |
+
sum_vec[key] += x.sum(axis=0)
|
| 490 |
+
sum_sq[key] += (x * x).sum(axis=0)
|
| 491 |
+
totals[key] += x.shape[0]
|
| 492 |
+
|
| 493 |
+
out = {}
|
| 494 |
+
for key in ("coedge", "face", "edge"):
|
| 495 |
+
if sum_vec[key] is None or totals[key] == 0:
|
| 496 |
+
raise RuntimeError(f"Cannot compute feature stats: no {key} features observed.")
|
| 497 |
+
mean = sum_vec[key] / totals[key]
|
| 498 |
+
var = sum_sq[key] / totals[key] - mean * mean
|
| 499 |
+
var = np.maximum(var, 1e-12)
|
| 500 |
+
std = np.sqrt(var)
|
| 501 |
+
out[key] = {"mean": mean.astype(np.float32), "std": std.astype(np.float32)}
|
| 502 |
+
return out
|
inference.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Loaded-model wrapper + classify helpers. All in-process; no subprocess."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Dict
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
from heg_brep.model import HalfEdgeGNN, resolve_reject_label
|
| 11 |
+
from heg_brep.graph_data import load_coedge_arrays, make_heterodata
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _align_2d(x: np.ndarray, target_dim: int) -> np.ndarray:
|
| 15 |
+
cur = int(x.shape[1])
|
| 16 |
+
if cur == target_dim:
|
| 17 |
+
return x
|
| 18 |
+
if cur > target_dim:
|
| 19 |
+
return x[:, :target_dim]
|
| 20 |
+
pad = np.zeros((x.shape[0], target_dim - cur), dtype=x.dtype)
|
| 21 |
+
return np.concatenate([x, pad], axis=1)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _align_1d(x: np.ndarray, target_dim: int) -> np.ndarray:
|
| 25 |
+
cur = int(x.shape[0])
|
| 26 |
+
if cur == target_dim:
|
| 27 |
+
return x
|
| 28 |
+
if cur > target_dim:
|
| 29 |
+
return x[:target_dim]
|
| 30 |
+
pad = np.zeros((target_dim - cur,), dtype=x.dtype)
|
| 31 |
+
return np.concatenate([x, pad], axis=0)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LoadedModel:
|
| 35 |
+
"""A pass1 / elbow / tee checkpoint loaded into memory once."""
|
| 36 |
+
|
| 37 |
+
def __init__(self, ckpt_path: Path, device: str = "cpu"):
|
| 38 |
+
try:
|
| 39 |
+
ckpt = torch.load(str(ckpt_path), map_location="cpu", weights_only=False)
|
| 40 |
+
except TypeError:
|
| 41 |
+
ckpt = torch.load(str(ckpt_path), map_location="cpu")
|
| 42 |
+
if "global_in" not in ckpt or "gating_dim" not in ckpt:
|
| 43 |
+
raise RuntimeError(f"Checkpoint {ckpt_path} missing gating metadata.")
|
| 44 |
+
stats = ckpt["stats"]
|
| 45 |
+
if not all(k in stats for k in ("coedge", "face", "edge")):
|
| 46 |
+
raise RuntimeError(f"Checkpoint {ckpt_path} missing heterograph stats.")
|
| 47 |
+
coedge_in = ckpt.get("coedge_in", ckpt.get("node_in"))
|
| 48 |
+
face_in = ckpt.get("face_in")
|
| 49 |
+
edge_in = ckpt.get("edge_in")
|
| 50 |
+
if coedge_in is None or face_in is None or edge_in is None:
|
| 51 |
+
raise RuntimeError(f"Checkpoint {ckpt_path} missing input dims.")
|
| 52 |
+
labels = ckpt["labels"]
|
| 53 |
+
model = HalfEdgeGNN(
|
| 54 |
+
coedge_in=coedge_in, face_in=face_in, edge_in=edge_in,
|
| 55 |
+
global_in=ckpt["global_in"], hidden=ckpt["hp"]["hidden"],
|
| 56 |
+
layers=ckpt["hp"]["layers"], dropout=ckpt["hp"]["dropout"],
|
| 57 |
+
num_classes=len(labels), gating_dim=ckpt["gating_dim"],
|
| 58 |
+
).to(device)
|
| 59 |
+
model.load_state_dict(ckpt["state_dict"])
|
| 60 |
+
model.eval()
|
| 61 |
+
self.model = model
|
| 62 |
+
self.device = device
|
| 63 |
+
self.coedge_in = int(coedge_in)
|
| 64 |
+
self.face_in = int(face_in)
|
| 65 |
+
self.edge_in = int(edge_in)
|
| 66 |
+
self.global_in = int(ckpt["global_in"])
|
| 67 |
+
self.stats = stats
|
| 68 |
+
self.labels = labels
|
| 69 |
+
self.inv_labels = {v: k for k, v in labels.items()}
|
| 70 |
+
self.reject_label = resolve_reject_label(labels, None)
|
| 71 |
+
|
| 72 |
+
@torch.no_grad()
|
| 73 |
+
def predict(self, npz_path: Path, min_conf: float = 0.0, tau: float = 0.0) -> Dict[str, object]:
|
| 74 |
+
g = load_coedge_arrays(npz_path)
|
| 75 |
+
g["coedge_x"] = _align_2d(g["coedge_x"], self.coedge_in)
|
| 76 |
+
g["face_x"] = _align_2d(g["face_x"], self.face_in)
|
| 77 |
+
g["edge_x"] = _align_2d(g["edge_x"], self.edge_in)
|
| 78 |
+
g["global_x"] = _align_1d(g["global_x"], self.global_in)
|
| 79 |
+
data = make_heterodata(
|
| 80 |
+
g["coedge_x"], g["face_x"], g["edge_x"],
|
| 81 |
+
g["next"], g["mate"], g["coedge_face"], g["coedge_edge"],
|
| 82 |
+
g["global_x"], label=None, norm_stats=self.stats,
|
| 83 |
+
)
|
| 84 |
+
data["coedge"].batch = torch.zeros(data["coedge"].x.size(0), dtype=torch.long)
|
| 85 |
+
data["global"].batch = torch.zeros(1, dtype=torch.long)
|
| 86 |
+
data["face"].batch = torch.zeros(data["face"].x.size(0), dtype=torch.long)
|
| 87 |
+
data["edge"].batch = torch.zeros(data["edge"].x.size(0), dtype=torch.long)
|
| 88 |
+
logits = self.model(data.to(self.device))
|
| 89 |
+
probs = F.softmax(logits, dim=-1).cpu().numpy()[0]
|
| 90 |
+
pred = int(probs.argmax())
|
| 91 |
+
conf = float(probs[pred])
|
| 92 |
+
argmax_label = self.inv_labels[pred]
|
| 93 |
+
effective_tau = max(tau, min_conf)
|
| 94 |
+
if conf < effective_tau and self.reject_label is not None:
|
| 95 |
+
predicted_label = self.reject_label
|
| 96 |
+
else:
|
| 97 |
+
predicted_label = argmax_label
|
| 98 |
+
return {
|
| 99 |
+
"argmax_label": argmax_label,
|
| 100 |
+
"argmax_conf": conf,
|
| 101 |
+
"predicted_label": predicted_label,
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
ELBOW_ROUTES = {"elbow"}
|
| 106 |
+
TEE_ROUTES = {"tee"}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class TwoPassClassifier:
|
| 110 |
+
"""Convenience wrapper that owns all three models and routes pass1 → pass2."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, pass1: LoadedModel,
|
| 113 |
+
elbow: "LoadedModel | None",
|
| 114 |
+
tee: "LoadedModel | None",
|
| 115 |
+
pass2_min_conf: float = 0.85,
|
| 116 |
+
pass2_tau: float = 0.0):
|
| 117 |
+
self.pass1 = pass1
|
| 118 |
+
self.elbow = elbow
|
| 119 |
+
self.tee = tee
|
| 120 |
+
self.pass2_min_conf = pass2_min_conf
|
| 121 |
+
self.pass2_tau = pass2_tau
|
| 122 |
+
|
| 123 |
+
def classify_npz(self, npz_path: Path) -> Dict[str, object]:
|
| 124 |
+
p1 = self.pass1.predict(npz_path, min_conf=0.0, tau=0.0)
|
| 125 |
+
route = str(p1["argmax_label"]).strip().lower()
|
| 126 |
+
out = {
|
| 127 |
+
"pass1_argmax": p1["argmax_label"],
|
| 128 |
+
"pass1_conf": float(p1["argmax_conf"]),
|
| 129 |
+
"route": route,
|
| 130 |
+
"pass2_argmax": "",
|
| 131 |
+
"pass2_predicted": "",
|
| 132 |
+
"pass2_conf": None,
|
| 133 |
+
"final_label": "",
|
| 134 |
+
"final_conf": None,
|
| 135 |
+
}
|
| 136 |
+
if route in ELBOW_ROUTES and self.elbow is not None:
|
| 137 |
+
specialist = self.elbow
|
| 138 |
+
elif route in TEE_ROUTES and self.tee is not None:
|
| 139 |
+
specialist = self.tee
|
| 140 |
+
else:
|
| 141 |
+
# pipe / miscellaneous: no specialist, passthrough as random
|
| 142 |
+
out["final_label"] = "random"
|
| 143 |
+
out["final_conf"] = out["pass1_conf"]
|
| 144 |
+
return out
|
| 145 |
+
p2 = specialist.predict(npz_path, min_conf=self.pass2_min_conf, tau=self.pass2_tau)
|
| 146 |
+
out["pass2_argmax"] = p2["argmax_label"]
|
| 147 |
+
out["pass2_predicted"] = p2["predicted_label"]
|
| 148 |
+
out["pass2_conf"] = float(p2["argmax_conf"])
|
| 149 |
+
out["final_label"] = p2["predicted_label"]
|
| 150 |
+
out["final_conf"] = out["pass2_conf"]
|
| 151 |
+
return out
|
model.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HalfEdge GNN model definition (moved from brep_two_pass/scripts/03_infer_halfedge.py)."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch_geometric.nn import (
|
| 9 |
+
HeteroConv, SAGEConv, JumpingKnowledge, BatchNorm,
|
| 10 |
+
global_mean_pool, global_max_pool,
|
| 11 |
+
)
|
| 12 |
+
from torch_geometric.data import HeteroData
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def resolve_reject_label(labels, requested: Optional[str]) -> Optional[str]:
|
| 16 |
+
if requested:
|
| 17 |
+
return requested
|
| 18 |
+
lower_to_name = {name.lower(): name for name in labels}
|
| 19 |
+
for candidate in ("random", "unknown", "other", "misc"):
|
| 20 |
+
if candidate in lower_to_name:
|
| 21 |
+
return lower_to_name[candidate]
|
| 22 |
+
for name in labels:
|
| 23 |
+
lower = name.lower()
|
| 24 |
+
if "random" in lower or "unknown" in lower:
|
| 25 |
+
return name
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class HalfEdgeGNN(nn.Module):
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
coedge_in: int, face_in: int, edge_in: int, global_in: int,
|
| 33 |
+
hidden=256, layers=6, dropout=0.2, num_classes=3,
|
| 34 |
+
jk_mode="cat", gating_dim=None,
|
| 35 |
+
):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.convs = nn.ModuleList(); self.bns = nn.ModuleList()
|
| 38 |
+
self.encoders = nn.ModuleDict({
|
| 39 |
+
"coedge": nn.Sequential(nn.Linear(coedge_in, hidden), nn.ReLU(), nn.Dropout(dropout)),
|
| 40 |
+
"face": nn.Sequential(nn.Linear(face_in, hidden), nn.ReLU(), nn.Dropout(dropout)),
|
| 41 |
+
"edge": nn.Sequential(nn.Linear(edge_in, hidden), nn.ReLU(), nn.Dropout(dropout)),
|
| 42 |
+
})
|
| 43 |
+
for _ in range(layers):
|
| 44 |
+
conv = HeteroConv({
|
| 45 |
+
('coedge','next','coedge'): SAGEConv((hidden, hidden), hidden),
|
| 46 |
+
('coedge','prev','coedge'): SAGEConv((hidden, hidden), hidden),
|
| 47 |
+
('coedge','mate','coedge'): SAGEConv((hidden, hidden), hidden),
|
| 48 |
+
('coedge','to_face','face'): SAGEConv((hidden, hidden), hidden),
|
| 49 |
+
('face','to_coedge','coedge'): SAGEConv((hidden, hidden), hidden),
|
| 50 |
+
('coedge','to_edge','edge'): SAGEConv((hidden, hidden), hidden),
|
| 51 |
+
('edge','to_coedge','coedge'): SAGEConv((hidden, hidden), hidden),
|
| 52 |
+
('face','to_edge','edge'): SAGEConv((hidden, hidden), hidden),
|
| 53 |
+
('edge','to_face','face'): SAGEConv((hidden, hidden), hidden),
|
| 54 |
+
}, aggr='sum')
|
| 55 |
+
self.convs.append(conv)
|
| 56 |
+
self.bns.append(nn.ModuleDict({
|
| 57 |
+
"coedge": BatchNorm(hidden),
|
| 58 |
+
"face": BatchNorm(hidden),
|
| 59 |
+
"edge": BatchNorm(hidden),
|
| 60 |
+
}))
|
| 61 |
+
self.jk = JumpingKnowledge(mode=jk_mode)
|
| 62 |
+
self.jk_out = hidden * layers if jk_mode == "cat" else hidden
|
| 63 |
+
if gating_dim is None:
|
| 64 |
+
gating_dim = hidden
|
| 65 |
+
self.gating_dim = gating_dim
|
| 66 |
+
self.pool_in = self.jk_out * 2
|
| 67 |
+
self.proj = nn.Identity() if self.pool_in == gating_dim else nn.Linear(self.pool_in, gating_dim)
|
| 68 |
+
|
| 69 |
+
self.global_mlp = nn.Sequential(
|
| 70 |
+
nn.Linear(global_in, gating_dim),
|
| 71 |
+
nn.ReLU(), nn.Dropout(0.3),
|
| 72 |
+
nn.Linear(gating_dim, 2 * gating_dim),
|
| 73 |
+
)
|
| 74 |
+
self.head = nn.Sequential(
|
| 75 |
+
nn.Linear(gating_dim, hidden),
|
| 76 |
+
nn.ReLU(), nn.Dropout(dropout),
|
| 77 |
+
nn.Linear(hidden, num_classes),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def forward(self, data: HeteroData):
|
| 81 |
+
x = {
|
| 82 |
+
"coedge": self.encoders["coedge"](data["coedge"].x),
|
| 83 |
+
"face": self.encoders["face"](data["face"].x),
|
| 84 |
+
"edge": self.encoders["edge"](data["edge"].x),
|
| 85 |
+
}
|
| 86 |
+
outs = []
|
| 87 |
+
for conv, bn in zip(self.convs, self.bns):
|
| 88 |
+
x_new = conv(x, data.edge_index_dict)
|
| 89 |
+
x = {k: F.relu(bn[k](x_new[k]) + x[k]) for k in x}
|
| 90 |
+
outs.append(x["coedge"])
|
| 91 |
+
xj = self.jk(outs)
|
| 92 |
+
batch = data['coedge'].batch
|
| 93 |
+
g_mean = global_mean_pool(xj, batch)
|
| 94 |
+
g_max = global_max_pool(xj, batch)
|
| 95 |
+
g = torch.cat([g_mean, g_max], dim=-1)
|
| 96 |
+
g0 = self.proj(g)
|
| 97 |
+
global_x = data["global"].x
|
| 98 |
+
if global_x.dim() == 1:
|
| 99 |
+
global_x = global_x.view(1, -1)
|
| 100 |
+
if global_x.size(0) != g0.size(0):
|
| 101 |
+
raise RuntimeError(f"Global feature batch mismatch: {global_x.size(0)} vs {g0.size(0)}")
|
| 102 |
+
gb = self.global_mlp(global_x)
|
| 103 |
+
gamma, beta = gb.chunk(2, dim=-1)
|
| 104 |
+
gamma = torch.sigmoid(gamma)
|
| 105 |
+
g_mod = g0 * gamma + beta
|
| 106 |
+
return self.head(g_mod)
|
server.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local FastAPI service: STEP-file-in, classification-out. One process, models loaded once.
|
| 2 |
+
|
| 3 |
+
Designed to be launched by a C# host app as a child process. The service binds to
|
| 4 |
+
127.0.0.1 only; never exposes a network-facing port.
|
| 5 |
+
|
| 6 |
+
Startup protocol:
|
| 7 |
+
- Bind a free port (default: OS-assigned via --port 0).
|
| 8 |
+
- Once models are loaded and the server is accepting requests, write
|
| 9 |
+
`READY port=<PORT>` to stdout (single line). The host reads that line to learn
|
| 10 |
+
where to connect.
|
| 11 |
+
- On `POST /shutdown` (or SIGTERM), drain in-flight requests and exit.
|
| 12 |
+
|
| 13 |
+
Endpoints:
|
| 14 |
+
GET /health -> service / model state
|
| 15 |
+
POST /classify {step_path} -> single STEP classification
|
| 16 |
+
POST /classify_batch {paths} -> multiple in one call (sequential, single-process)
|
| 17 |
+
POST /shutdown -> graceful exit
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
import argparse
|
| 21 |
+
import os
|
| 22 |
+
import sys
|
| 23 |
+
import tempfile
|
| 24 |
+
import threading
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import List, Optional
|
| 28 |
+
|
| 29 |
+
from fastapi import FastAPI, HTTPException
|
| 30 |
+
from pydantic import BaseModel
|
| 31 |
+
import uvicorn
|
| 32 |
+
|
| 33 |
+
from heg_brep import (
|
| 34 |
+
DEFAULT_PASS1_MODEL, DEFAULT_ELBOW_MODEL, DEFAULT_TEE_MODEL,
|
| 35 |
+
)
|
| 36 |
+
from heg_brep.inference import LoadedModel, TwoPassClassifier
|
| 37 |
+
from heg_brep.extraction import extract_step_to_npz
|
| 38 |
+
|
| 39 |
+
# Eagerly import the BRepExtractor pipeline at startup. Without this, the first
|
| 40 |
+
# /classify call pays ~20-30s of OCC + occwl + igl cold-import cost — terrible
|
| 41 |
+
# UX for an interactive viewer.
|
| 42 |
+
import pipeline.extract_brep_extractor_data_from_step # noqa: F401
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class State:
|
| 46 |
+
classifier: Optional[TwoPassClassifier] = None
|
| 47 |
+
started_at: float = 0.0
|
| 48 |
+
device: str = "cpu"
|
| 49 |
+
pass2_min_conf: float = 0.85
|
| 50 |
+
pass2_tau: float = 0.0
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
app = FastAPI(title="HEG BRep component identification")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ClassifyRequest(BaseModel):
|
| 57 |
+
step_path: str
|
| 58 |
+
# Optional override: persist the NPZ to disk for inspection.
|
| 59 |
+
npz_keep_dir: Optional[str] = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class ClassifyBatchRequest(BaseModel):
|
| 63 |
+
step_paths: List[str]
|
| 64 |
+
npz_keep_dir: Optional[str] = None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@app.get("/health")
|
| 68 |
+
def health():
|
| 69 |
+
return {
|
| 70 |
+
"status": "ok",
|
| 71 |
+
"models_loaded": State.classifier is not None,
|
| 72 |
+
"device": State.device,
|
| 73 |
+
"uptime_sec": round(time.time() - State.started_at, 2),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _classify_one(step_path: str, npz_keep_dir: Optional[str]) -> dict:
|
| 78 |
+
if State.classifier is None:
|
| 79 |
+
raise HTTPException(status_code=503, detail="models not loaded yet")
|
| 80 |
+
sp = Path(step_path).expanduser()
|
| 81 |
+
if not sp.exists():
|
| 82 |
+
return {"step_path": str(sp), "status": "error", "error": "step_path not found"}
|
| 83 |
+
out_dir = Path(npz_keep_dir).expanduser().resolve() if npz_keep_dir \
|
| 84 |
+
else Path(tempfile.mkdtemp(prefix="heg_brep_npz_"))
|
| 85 |
+
try:
|
| 86 |
+
npz = extract_step_to_npz(sp, out_dir)
|
| 87 |
+
except Exception as exc:
|
| 88 |
+
return {"step_path": str(sp), "status": "extraction_failed", "error": str(exc)[:500]}
|
| 89 |
+
try:
|
| 90 |
+
result = State.classifier.classify_npz(npz)
|
| 91 |
+
except Exception as exc:
|
| 92 |
+
return {"step_path": str(sp), "status": "inference_failed", "error": str(exc)[:500],
|
| 93 |
+
"npz_path": str(npz)}
|
| 94 |
+
result.update({"step_path": str(sp), "status": "ok", "npz_path": str(npz)})
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@app.post("/classify")
|
| 99 |
+
def classify(req: ClassifyRequest):
|
| 100 |
+
return _classify_one(req.step_path, req.npz_keep_dir)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@app.post("/classify_batch")
|
| 104 |
+
def classify_batch(req: ClassifyBatchRequest):
|
| 105 |
+
return {"results": [_classify_one(p, req.npz_keep_dir) for p in req.step_paths]}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@app.post("/shutdown")
|
| 109 |
+
def shutdown():
|
| 110 |
+
threading.Thread(target=lambda: (time.sleep(0.2), os._exit(0)), daemon=True).start()
|
| 111 |
+
return {"status": "shutting_down"}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _load_models(args) -> None:
|
| 115 |
+
pass1 = LoadedModel(Path(args.pass1_model), device=args.device)
|
| 116 |
+
elbow = LoadedModel(Path(args.elbow_model), device=args.device) if Path(args.elbow_model).exists() else None
|
| 117 |
+
tee = LoadedModel(Path(args.tee_model), device=args.device) if Path(args.tee_model).exists() else None
|
| 118 |
+
State.classifier = TwoPassClassifier(
|
| 119 |
+
pass1=pass1, elbow=elbow, tee=tee,
|
| 120 |
+
pass2_min_conf=args.pass2_min_conf, pass2_tau=args.pass2_tau,
|
| 121 |
+
)
|
| 122 |
+
State.device = args.device
|
| 123 |
+
State.pass2_min_conf = args.pass2_min_conf
|
| 124 |
+
State.pass2_tau = args.pass2_tau
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def parse_args() -> argparse.Namespace:
|
| 128 |
+
ap = argparse.ArgumentParser(description="HEG BRep classification service")
|
| 129 |
+
ap.add_argument("--host", default="127.0.0.1")
|
| 130 |
+
ap.add_argument("--port", type=int, default=0,
|
| 131 |
+
help="Port to bind. 0 = let the OS pick. The chosen port is "
|
| 132 |
+
"printed to stdout as a single line `READY port=<N>`.")
|
| 133 |
+
ap.add_argument("--pass1_model", default=str(DEFAULT_PASS1_MODEL))
|
| 134 |
+
ap.add_argument("--elbow_model", default=str(DEFAULT_ELBOW_MODEL))
|
| 135 |
+
ap.add_argument("--tee_model", default=str(DEFAULT_TEE_MODEL))
|
| 136 |
+
ap.add_argument("--device", default="cpu", choices=["cpu", "cuda"])
|
| 137 |
+
ap.add_argument("--pass2_min_conf", type=float, default=0.85)
|
| 138 |
+
ap.add_argument("--pass2_tau", type=float, default=0.0)
|
| 139 |
+
return ap.parse_args()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def main() -> int:
|
| 143 |
+
args = parse_args()
|
| 144 |
+
State.started_at = time.time()
|
| 145 |
+
print(f"[heg_brep] loading models from:", file=sys.stderr)
|
| 146 |
+
print(f" pass1: {args.pass1_model}", file=sys.stderr)
|
| 147 |
+
print(f" elbow: {args.elbow_model}", file=sys.stderr)
|
| 148 |
+
print(f" tee : {args.tee_model}", file=sys.stderr)
|
| 149 |
+
print(f" device: {args.device}", file=sys.stderr)
|
| 150 |
+
t0 = time.time()
|
| 151 |
+
_load_models(args)
|
| 152 |
+
print(f"[heg_brep] models loaded in {time.time() - t0:.1f}s", file=sys.stderr)
|
| 153 |
+
|
| 154 |
+
# Bind socket up front so we can tell the parent which port we got.
|
| 155 |
+
import socket
|
| 156 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 157 |
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 158 |
+
sock.bind((args.host, int(args.port)))
|
| 159 |
+
bound_port = sock.getsockname()[1]
|
| 160 |
+
print(f"READY port={bound_port}", flush=True)
|
| 161 |
+
|
| 162 |
+
config = uvicorn.Config(app=app, host=args.host, port=bound_port, log_level="warning")
|
| 163 |
+
server = uvicorn.Server(config)
|
| 164 |
+
# uvicorn doesn't accept an already-bound socket in the simple Config API; close
|
| 165 |
+
# ours and let uvicorn rebind. Race window is fine because we're loopback only.
|
| 166 |
+
sock.close()
|
| 167 |
+
server.run()
|
| 168 |
+
return 0
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
if __name__ == "__main__":
|
| 172 |
+
sys.exit(main())
|