feat(whucad): WHUCAD vector → FTC translator toolset under tools/research
Decode the WHUCAD h5 vector sequences (256-level quantized CATIA/DeepCAD
command matrices) and translate them into SimpleCADAPI FTC sources,
mirroring the histjson tool suite:
- whucad_vec.py self-contained decoder (numpy only; differential-
checked against the original cadlib, 1419/1419 exact)
- whucad_select.py Topo/Select history references -> ql predicates
- whucad_to_ftc.py translator (keyword-form call emission, histjson
convention; unsupported forms annotated, never
approximated)
- whucad_profile.py feature/curve/select-form distribution + coverage
- whucad_validate.py sampled build + BRep-truth volume reconciliation
(scale-corrected: vectors carry no absolute scale)
- whucad_batch.py whole-dataset batch entry point
- check_port.py differential check vs the original cadlib decode
- test_whucad_translation_output.py output-contract tests (embedded
vectors; no dataset download needed)
Full-dataset run: 146,331 models -> 146,331 .py, 424,947 features decoded,
380,074 feature blocks emitted (89.4%). pyproject gains a 'whucad' extra
(h5py).
This commit is contained in:
@@ -53,6 +53,7 @@ examples/histcad/
|
||||
# Research tool scan outputs (generated by tools/research scripts)
|
||||
tools/research/out/
|
||||
tools/research/histjson/out/
|
||||
tools/research/whucad/out/
|
||||
tools/research/cadqueryftc/out/
|
||||
.venv-cq/
|
||||
|
||||
|
||||
@@ -48,6 +48,9 @@ editor = []
|
||||
inspect = [
|
||||
"matplotlib>=3.7.0",
|
||||
]
|
||||
whucad = [
|
||||
"h5py>=3.8",
|
||||
]
|
||||
gmsh = [
|
||||
"gmsh>=4.15,<5",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""WHUCAD translator output contracts.
|
||||
|
||||
Translated WHUCAD sources are training data: they contain the model and
|
||||
nothing else — no solver checks, no runtime fallback, no diagnostics. These
|
||||
tests pin that purity plus the dialect corrections (signed extrude span,
|
||||
quantization decode, cap/wall reference convention) on hand-built vectors,
|
||||
so no dataset download is needed to run them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
_TOOLS = Path(__file__).resolve().parent.parent / "tools" / "research" / "whucad"
|
||||
if str(_TOOLS) not in sys.path:
|
||||
sys.path.insert(0, str(_TOOLS))
|
||||
|
||||
|
||||
def _load(name: str):
|
||||
spec = importlib.util.spec_from_file_location(name, _TOOLS / f"{name}.py")
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault(name, module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wvec():
|
||||
return _load("whucad_vec")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def to_ftc():
|
||||
return _load("whucad_to_ftc")
|
||||
|
||||
|
||||
def _row(cmd: int, args: List[int]) -> np.ndarray:
|
||||
assert len(args) == 32 # N_ARGS: 5 sketch + 14 body + 9 finish + 4 select
|
||||
return np.array([cmd] + args)
|
||||
|
||||
|
||||
def _pad(*values: int) -> List[int]:
|
||||
return list(values) + [-1] * (32 - len(values))
|
||||
|
||||
|
||||
def _cylinder_vec() -> np.ndarray:
|
||||
"""SOL, Circle, Ext — the quantized rows of a one-cylinder pad."""
|
||||
quant = lambda v: int(round((v + 1.0) / 2.0 * 256)) # noqa: E731
|
||||
size_q = 128 # sketch size → 1.0
|
||||
circle = _row(2, _pad(160, 128, -1, -1, 32)) # center (32,0), r=32
|
||||
ext = _row(7, _pad(-1, -1, -1, -1, -1, # sketch arg pads
|
||||
128, 128, 128, # plane theta/phi/gamma = 0
|
||||
128, 128, 128, # sketch pos = (0,0,0)
|
||||
size_q, # sketch size
|
||||
quant(0.5), quant(0.0), # extents
|
||||
0, 0, -1, -1, # extent types, pad
|
||||
0)) # AddFeatureOperation
|
||||
return np.array([
|
||||
_row(6, _pad()), # SOL
|
||||
circle,
|
||||
ext,
|
||||
])
|
||||
|
||||
|
||||
def test_decode_cylinder(wvec):
|
||||
features = wvec.decode_vec(_cylinder_vec(), is_numerical=True)
|
||||
assert [f.kind for f in features] == ["Ext"]
|
||||
feature = features[0]
|
||||
assert feature.operation == "AddFeatureOperation"
|
||||
assert feature.extent_one == pytest.approx(0.5)
|
||||
assert feature.extent_two == pytest.approx(0.0)
|
||||
plan = feature.sketch
|
||||
assert plan.plane_origin == pytest.approx((0.0, 0.0, 0.0), abs=1e-9)
|
||||
assert plan.plane_normal == pytest.approx((0.0, 0.0, 1.0), abs=1e-9)
|
||||
(loop,) = plan.profile.loops
|
||||
(circle,) = loop.curves
|
||||
# denormalize: (p - 128) * size / 95 with size = 1.0
|
||||
assert circle.center == pytest.approx((32.0 / 95.0, 0.0), abs=1e-9)
|
||||
assert circle.radius == pytest.approx(32.0 / 95.0, abs=1e-9)
|
||||
|
||||
|
||||
def test_translate_cylinder_emits_feature_block(to_ftc, wvec):
|
||||
features = wvec.decode_vec(_cylinder_vec(), is_numerical=True)
|
||||
source = to_ftc.translate_features(features, "0000/test")
|
||||
assert "@scad.part(id='whucad-0000-test'" in source
|
||||
assert "# ---- feature: ext-1 (build, profile=geometry) ----" in source
|
||||
assert "scad.make_sketch_rsketch(name='f0'" in source
|
||||
assert "scad.add_circle_rsketch(sketch=s, entity_id='f0_e0_0'" in source
|
||||
assert "scad.make_face_from_sketch_rface(sketch=s, profile=0)" in source
|
||||
assert "scad.extrude_rsolid(profile=f0_face, direction=(0.0, 0.0, 1.0), distance=0.5)" in source
|
||||
assert "bodies = [f0_tool]" in source
|
||||
|
||||
|
||||
def test_translated_source_is_pure_training_data(to_ftc, wvec):
|
||||
features = wvec.decode_vec(_cylinder_vec(), is_numerical=True)
|
||||
source = to_ftc.translate_features(features, "0000/test")
|
||||
body = source.split("def build()")[1]
|
||||
assert "assert " not in body
|
||||
assert "print(" not in body
|
||||
assert "except Exception" not in body # only _merge_bodies carries one, above build
|
||||
assert source.count("try:") <= 1
|
||||
|
||||
|
||||
def test_unsupported_feature_annotated_not_dropped_silently(to_ftc, wvec):
|
||||
features = wvec.decode_vec(_cylinder_vec(), is_numerical=True)
|
||||
features.append(wvec.UnsupportedFeature("Mirror", ""))
|
||||
source = to_ftc.translate_features(features, "0000/test")
|
||||
assert "# step 1: unsupported Mirror (Mirror)" in source
|
||||
assert "# ---- feature: mirror-" not in source
|
||||
|
||||
|
||||
def test_cylinder_build_volume(to_ftc, wvec, tmp_path):
|
||||
"""Execute the translated source inside the repo tree; the built volume
|
||||
must match the decoded cylinder analytically."""
|
||||
features = wvec.decode_vec(_cylinder_vec(), is_numerical=True)
|
||||
source = to_ftc.translate_features(features, "0000/test")
|
||||
module_path = _TOOLS / "out" / "_cases" / "test_contract.py"
|
||||
module_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
module_path.write_text(source)
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("test_contract", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
result = module.build()
|
||||
body = result.value.body
|
||||
radius = 32.0 / 95.0
|
||||
expected = math.pi * radius * radius * 0.5
|
||||
assert body.get_volume() == pytest.approx(expected, rel=1e-7)
|
||||
finally:
|
||||
module_path.unlink(missing_ok=True)
|
||||
@@ -0,0 +1,114 @@
|
||||
# WHUCAD → SimpleCADAPI FTC 翻译工具
|
||||
|
||||
把 WHUCAD 数据集的向量化 CAD 序列(h5 `vec` 命令矩阵,DeepCAD/CATIA 风格的
|
||||
256 级量化表示)翻译成 SimpleCADAPI 的 FTC(Feature Tree Convention)Python
|
||||
源码。翻译产物用于合成训练数据。架构与 `tools/research/histjson/`(HistCAD
|
||||
翻译)完全同构:翻译器只做翻译,验收与审计在外部工具。
|
||||
|
||||
```
|
||||
tools/research/whucad/
|
||||
├── whucad_vec.py # 解码器:vec → 特征对象(自包含 port,仅 numpy/h5py)
|
||||
├── whucad_select.py # Topo/Select 拓扑引用 → ql 几何谓词选择器
|
||||
├── whucad_to_ftc.py # 翻译器:特征对象 → FTC 源码(只做翻译)
|
||||
├── whucad_profile.py # 数据画像:特征/曲线/extent/选择形态分布 + 覆盖率
|
||||
├── whucad_validate.py # 验收:执行产物 + 与官方 BRep 真值对体积(抽样)
|
||||
├── check_port.py # 开发工具:解码器与原版 cadlib 的差分校验
|
||||
└── out/ # 报告与真值缓存(gitignored)
|
||||
test/test_whucad_translation_output.py # 输出契约测试(内嵌向量,无需数据集)
|
||||
```
|
||||
|
||||
**职责墙(设计铁律,同 histjson)**:翻译器只做翻译——数据里有什么就译什么,
|
||||
不求解、不挑层级、不回落、产物里没有任何检查代码。译不出的形式跳过并在头部
|
||||
注记(`# step N: unsupported ...`),一切"译得对不对"的问题由 validate /
|
||||
profile 回答。调用发射与 histjson 采纳同一约定:simplecadapi 调用一律用
|
||||
关键字参数形式(`scad.add_line_rsketch(sketch=s, entity_id=..., start=...,
|
||||
end=...)`),布尔行除外(`cut/union/intersect` 保持位置形式,同上游)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 与 HistCAD 管线的差异
|
||||
|
||||
| | HistCAD(histjson) | WHUCAD(本目录) |
|
||||
| --- | --- | --- |
|
||||
| 输入 | 带约束通道的序列 JSON | h5 `vec` 整数命令矩阵(无约束) |
|
||||
| 草图 | line/circle/arc/ellipse/nurbs + 19 类约束 | line/circle/arc/spline(无约束) |
|
||||
| 特征 | 只有拉伸 | Pad/旋转/旋转切/抽壳/倒角/圆角/孔/镜像/拔模 |
|
||||
| 拓扑引用 | 无 | Topo/Select:"第 n 个特征的第 m 个面" |
|
||||
| 坐标 | 毫米浮点 | 256 级量化 + 单位立方归一化(**绝对尺度不在数据里**) |
|
||||
|
||||
量化带来的两个直接推论:
|
||||
|
||||
- FTC 产物是**归一化尺度**的模型(包围盒 ~1.5),不是原始毫米尺度。
|
||||
- 体积对账必须做尺度校正(bbox 对角线比值)后比较,容差比 histcad 的 1e-3
|
||||
放宽(数据量化噪声 ~0.4%/维度)。
|
||||
|
||||
## 2. 如何使用
|
||||
|
||||
```bash
|
||||
# 单个 case:h5 → FTC 源码
|
||||
.venv/bin/python tools/research/whucad/whucad_to_ftc.py <model.h5> [--out PATH]
|
||||
|
||||
# 数据画像:特征/曲线/选择形态分布 + 翻译覆盖率(抽样一个子目录即可)
|
||||
.venv/bin/python tools/research/whucad/whucad_profile.py <vec_dir> [--limit N]
|
||||
|
||||
# 抽样验收:翻译 → 进程内执行 → 下载对应 BRep 真值 → 尺度校正后对体积
|
||||
.venv/bin/python tools/research/whucad/whucad_validate.py \
|
||||
--vec-dir <WHUCAD>/data/vec/0000 --count 40 --stride 23 \
|
||||
[--uids a,b,c] [--report out/whucad_validate.json]
|
||||
```
|
||||
|
||||
`whucad_vec.py` 是原版 `fazhihe/WHUCAD` cadlib 解码路径的忠实 port(不依赖
|
||||
torch/matplotlib)。`check_port.py` 在全部样例上与原版 cadlib 差分对比
|
||||
(曲线、平面、参数、Select 树逐值相等):
|
||||
|
||||
```bash
|
||||
.venv/bin/python tools/research/whucad/check_port.py # 1419/1419 一致(0000 目录实测)
|
||||
```
|
||||
|
||||
## 3. 翻译覆盖(data/vec/0000 全量 1419 模型实测,profile 报告)
|
||||
|
||||
| 特征 | 映射 | 状态 |
|
||||
| --- | --- | --- |
|
||||
| Ext / Pocket | 面提升 + `extrude_rsolid` + 布尔(add/cut/intersect,双侧 union 技巧,负向 extent 翻越草图面) | ✅ |
|
||||
| Rev / Groove | `revolve_rsolid`,轴 = 草图第 no 条线(数据集 Wire/Sketch 引用,1-based) | ✅(双侧旋转除外) |
|
||||
| Hole | 圆草图 + 拉伸 cut | ✅(`OffsetLimit` 底) |
|
||||
| Chamfer / Fillet(棱边引用) | 两面交边解析(圆 = 面×柱,直线 = 面×面共享端点)→ `ql.edges()` 谓词 | ✅ |
|
||||
| Chamfer / Fillet(整面引用) | 帽面圆边 / 侧壁全边界边 → 逐边谓词 | ✅ |
|
||||
| Shell(外部厚度 = 0) | `shell_rsolid` + `ql.faces()` 谓词 | ✅ |
|
||||
| Mirror / Draft | 无 FTC 映射 | 注记跳过 |
|
||||
| Shell(外部厚度 > 0) | FTC 无外部厚度参数 | 注记跳过 |
|
||||
| 旋转体(Shaft)的面/侧壁引用、弧线侧壁、UpTo 系拉伸终点 | 待第二期 | 注记跳过 |
|
||||
|
||||
特征级覆盖率 **79.1%**(4095 特征中 857 个注记跳过);模型级 **49.0%** 全量
|
||||
翻译、其余部分翻译(跳过的特征主要是 Mirror / 外部厚度抽壳 / 旋转体引用)。
|
||||
|
||||
## 4. 抽样验收结果(40 例,stride 23,对官方 BRep 真值)
|
||||
|
||||
- **全量翻译的 16 例:构建成功的 10 例体积全部对上(10 pass / 0 mismatch)**,
|
||||
其中含倒角/圆角的盒体达到机器精度(rel 8.4e-14 / 1.1e-8),曲面模型在量化
|
||||
噪声水平(1e-3 ~ 1.4e-2)。
|
||||
- 6 例 build_error 全部是 OCC 内核限制(与 histcad 已知 C 类同源):并集切向
|
||||
接触违反单流形契约、圆角半径 ≈ 轮廓圆角弧半径一半时相切退化
|
||||
(r=0.035 能过、r=0.039 失败的实测阈值)、抽壳边界厚度。
|
||||
- 22 例带跳过注记的模型体积必然偏差(缺的就是被跳过特征的贡献)——偏差即
|
||||
跳过清单,逐 case 在报告 `skipped_features` 字段可查。
|
||||
|
||||
## 5. 移植与校准笔记(为什么这样译)
|
||||
|
||||
- **2D → 实坐标**:`p_real = (p − 128) × sketch_size/95`,95 = 256/2×0.75−1,
|
||||
与数据集自己的 CATIA 重建(`profile.denormalize(sketch_size)`)一致;
|
||||
3D = 草图面原点 + x_axis·px + y_axis·py(CoordSystem 原点即 sketch_pos)。
|
||||
- **帽面编号**(对官方 BRep 实测校准):`no=0` 侧壁(携 Wire 引用)、`no=1`
|
||||
近帽(草图面侧)、`no=2` 远帽;帽/壁棱边倒角的两条腿按"帽面锚定 l1"约定,
|
||||
00000004 实测机器精度验证。
|
||||
- **旋转轴**:`Wire/Sketch#body_no` 的第 no 条曲线(1-based 全局曲线序号),
|
||||
CATIA FirstAngle/SecondAngle 换算后单侧扫掠直接映射 FTC `angle`。
|
||||
- **Validate 的 bbox**:必须用 `BRepBndLib.AddOptimal_s(shape, box, False,
|
||||
False)` + `SetGap(0)`——默认包围盒对曲面外扩 ~7%,会把尺度校正整个带偏。
|
||||
|
||||
## 6. 已知边界
|
||||
|
||||
- FTC `@scad.part` 装饰器可能在独立命名空间重建函数,`module.BODIES` 不一定
|
||||
回写——validate 已按 Part 返回值兜底(histcad 同款)。
|
||||
- 多体(不相交)模型经 `_merge_bodies` 合并,体积对账按单实体真值口径。
|
||||
- WHUCAD-2026 新版若改格式,只需替换 `whucad_vec.py` 一个模块。
|
||||
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Differential check: whucad_vec.py port vs the original WHUCAD cadlib decode.
|
||||
|
||||
Run from CADIR root with the WHUCAD clone available:
|
||||
|
||||
.venv/bin/python tools/research/whucad/check_port.py [glob]
|
||||
|
||||
Compares, per feature: kind order, quantized curve geometry, plane frame,
|
||||
extents/angles, finish params, and the select trees. Dev-only script; the
|
||||
production tool never imports the original cadlib.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import glob as _glob
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# original WHUCAD cadlib clone (fazhihe/WHUCAD), e.g. .../WHUCAD containing cadlib/
|
||||
_WHUCAD_CLONE = os.environ.get("WHUCAD_REPO", "")
|
||||
|
||||
import whucad_vec as mine # noqa: E402
|
||||
|
||||
# the original cadlib is importable only after --whucad-repo is on sys.path
|
||||
# (done in main); resolved lazily by _load_original()
|
||||
theirs = None
|
||||
ARGS_N = 256
|
||||
|
||||
|
||||
def _load_original():
|
||||
global theirs, ARGS_N
|
||||
if theirs is None:
|
||||
import importlib
|
||||
|
||||
theirs = importlib.import_module("cadlib.CAD_Class")
|
||||
ARGS_N = importlib.import_module("cadlib.macro").ARGS_N
|
||||
return theirs
|
||||
|
||||
|
||||
def curve_sig(c) -> tuple:
|
||||
if isinstance(c, theirs.Line):
|
||||
return ("Line", tuple(np.round(c.start_point, 6)), tuple(np.round(c.end_point, 6)))
|
||||
if isinstance(c, theirs.Circle):
|
||||
return ("Circle", tuple(np.round(c.center, 6)), round(float(c.radius), 6))
|
||||
if isinstance(c, theirs.Arc):
|
||||
return ("Arc", tuple(np.round(c.center, 6)), round(float(c.radius), 6),
|
||||
round(float(c.start_arc), 6), round(float(c.end_arc), 6))
|
||||
if isinstance(c, theirs.Spline):
|
||||
return ("Spline", tuple(tuple(np.round(p, 6)) for p in c.point_list))
|
||||
return (type(c).__name__,)
|
||||
|
||||
|
||||
def loop_sig(loop) -> tuple:
|
||||
return tuple(curve_sig(c) for c in loop.children)
|
||||
|
||||
|
||||
def profile_sig(profile) -> tuple:
|
||||
return tuple(loop_sig(loop) for loop in profile.children)
|
||||
|
||||
|
||||
def select_sig(s) -> tuple:
|
||||
return (s.select_type, s.body_type, s.body_no, s.no,
|
||||
tuple(select_sig(x) for x in s.operation_list),
|
||||
tuple(select_sig(x) for x in s.no_shared_included),
|
||||
tuple((k, tuple(select_sig(x) for x in v)) for k, v in s.all_oriented_included.items()))
|
||||
|
||||
|
||||
def my_curve_sig(c) -> tuple:
|
||||
if isinstance(c, mine.Line):
|
||||
return ("Line", tuple(np.round(c.start_point, 6)), tuple(np.round(c.end_point, 6)))
|
||||
if isinstance(c, mine.Circle):
|
||||
return ("Circle", tuple(np.round(c.center, 6)), round(float(c.radius), 6))
|
||||
if isinstance(c, mine.Arc):
|
||||
return ("Arc", tuple(np.round(c.center, 6)), round(float(c.radius), 6),
|
||||
round(float(c.start_arc), 6), round(float(c.end_arc), 6))
|
||||
if isinstance(c, mine.Spline):
|
||||
return ("Spline", tuple(tuple(np.round(p, 6)) for p in c.point_list))
|
||||
return (type(c).__name__,)
|
||||
|
||||
|
||||
def my_loop_sig(loop) -> tuple:
|
||||
return tuple(my_curve_sig(c) for c in loop.curves)
|
||||
|
||||
|
||||
def my_profile_sig(profile) -> tuple:
|
||||
return tuple(my_loop_sig(loop) for loop in profile.loops)
|
||||
|
||||
|
||||
def my_select_sig(s) -> tuple:
|
||||
return (s.select_type, s.body_type, s.body_no, s.no,
|
||||
tuple(my_select_sig(x) for x in s.operation_list),
|
||||
tuple(my_select_sig(x) for x in s.no_shared_included),
|
||||
tuple((k, tuple(my_select_sig(x) for x in v)) for k, v in s.all_oriented_included.items()))
|
||||
|
||||
|
||||
def compare_case(vec: np.ndarray) -> list:
|
||||
problems = []
|
||||
m_features = mine.decode_vec(vec, is_numerical=True)
|
||||
t_seq = theirs.Macro_Seq.from_vector(vec, is_numerical=True, n=ARGS_N)
|
||||
t_features = t_seq.extrude_operation
|
||||
|
||||
kinds_m = [f.kind for f in m_features]
|
||||
kinds_t = [type(f).__name__ for f in t_features]
|
||||
kinds_m = [{'Ext': 'Extrude', 'Rev': 'Revolve'}.get(k, k) for k in kinds_m]
|
||||
if kinds_m != kinds_t:
|
||||
problems.append(f"kind mismatch: {kinds_m} vs {kinds_t}")
|
||||
return problems
|
||||
kinds_t = kinds_m # aligned below
|
||||
|
||||
for mf, tf in zip(m_features, t_features):
|
||||
if isinstance(mf, mine.UnsupportedFeature):
|
||||
continue
|
||||
if isinstance(mf, mine.ExtrudeFeature):
|
||||
t = tf
|
||||
if mf.operation != t.operation:
|
||||
problems.append(f"op {mf.operation} vs {t.operation}")
|
||||
for a, b in (("extent_one", t.extent_one), ("extent_two", t.extent_two)):
|
||||
got = getattr(mf, a)
|
||||
if abs(got - float(b)) > 1e-9:
|
||||
problems.append(f"{a} {got} vs {b}")
|
||||
if (mf.extent_type1, mf.extent_type2) != (t.extent_type1, t.extent_type2):
|
||||
problems.append(f"ext types {(mf.extent_type1, mf.extent_type2)} vs {(t.extent_type1, t.extent_type2)}")
|
||||
if my_profile_sig(mf.sketch.profile_quantized) != profile_sig(t.sketch_profile):
|
||||
problems.append(f"profile mismatch: {my_profile_sig(mf.sketch.profile_quantized)} vs {profile_sig(t.sketch_profile)}")
|
||||
if not np.allclose(mf.sketch.plane_origin, t.sketch_plane.origin, atol=1e-9):
|
||||
problems.append(f"origin {mf.sketch.plane_origin} vs {t.sketch_plane.origin}")
|
||||
if not np.allclose(mf.sketch.plane_x_axis, t.sketch_plane.x_axis, atol=1e-7):
|
||||
problems.append(f"x_axis {mf.sketch.plane_x_axis} vs {t.sketch_plane.x_axis}")
|
||||
sels_m = [my_select_sig(s) for s in mf.select_list]
|
||||
sels_t = [select_sig(s) for s in (t.select_list or [])]
|
||||
if sels_m != sels_t:
|
||||
problems.append(f"selects {sels_m} vs {sels_t}")
|
||||
elif isinstance(mf, mine.RevolveFeature):
|
||||
t = tf
|
||||
for a, b in (("angle_one", t.angle_one), ("angle_two", t.angle_two)):
|
||||
if abs(getattr(mf, a) - float(b)) > 1e-6:
|
||||
problems.append(f"{a} {getattr(mf, a)} vs {b}")
|
||||
if my_profile_sig(mf.sketch.profile_quantized) != profile_sig(t.sketch_profile):
|
||||
problems.append("profile mismatch (rev)")
|
||||
if my_select_sig(mf.axis_select) != select_sig(t.select_list[0]):
|
||||
problems.append("axis select mismatch")
|
||||
elif isinstance(mf, mine.FinishFeature):
|
||||
t = tf
|
||||
sels_m = [my_select_sig(s) for s in mf.select_list]
|
||||
sels_t = [select_sig(s) for s in t.select_list]
|
||||
if sels_m != sels_t:
|
||||
problems.append(f"selects {sels_m} vs {sels_t}")
|
||||
for key, tval in (("thickness", t.thickness), ("second_thickness", t.second_thickness)) if mf.kind == 'Shell' else ():
|
||||
if abs(mf.params[key] - float(tval)) > 1e-9:
|
||||
problems.append(f"{key} {mf.params[key]} vs {tval}")
|
||||
if mf.kind == 'Chamfer':
|
||||
if abs(mf.params['length1'] - float(t.length1)) > 1e-9 or abs(mf.params['angle_or_length2'] - float(t.angle_or_length2)) > 1e-9:
|
||||
problems.append(f"chamfer params {mf.params} vs ({t.length1}, {t.angle_or_length2})")
|
||||
if mf.kind == 'Fillet':
|
||||
if abs(mf.params['radius'] - float(t.radius)) > 1e-9:
|
||||
problems.append(f"radius {mf.params['radius']} vs {t.radius}")
|
||||
elif isinstance(mf, mine.HoleFeature):
|
||||
t = tf
|
||||
if not np.allclose(mf.point_pos, t.point_pos, atol=1e-9):
|
||||
problems.append(f"hole pos {mf.point_pos} vs {t.point_pos}")
|
||||
if abs(mf.radius - float(t.radius)) > 1e-9 or abs(mf.depth - float(t.depth)) > 1e-9:
|
||||
problems.append(f"hole r/d {mf.radius}/{mf.depth} vs {t.radius}/{t.depth}")
|
||||
if my_select_sig(mf.plane_ref) != select_sig(t.plane_ref):
|
||||
problems.append("hole plane_ref mismatch")
|
||||
return problems
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("glob", nargs="?", default="data/vec/0000/*.h5",
|
||||
help="h5 glob relative to --whucad-repo (default: data/vec/0000/*.h5)")
|
||||
parser.add_argument("--whucad-repo", default=_WHUCAD_CLONE or "../WHUCAD",
|
||||
help="clone of fazhihe/WHUCAD containing cadlib/ (or set WHUCAD_REPO)")
|
||||
args = parser.parse_args()
|
||||
if not Path(args.whucad_repo, "cadlib").is_dir():
|
||||
parser.error(f"--whucad-repo {args.whucad_repo!r} has no cadlib/ — pass the WHUCAD clone path")
|
||||
sys.path.insert(0, str(Path(args.whucad_repo).resolve()))
|
||||
|
||||
paths = sorted(_glob.glob(str(Path(args.whucad_repo) / args.glob)))
|
||||
_load_original()
|
||||
n_fail = 0
|
||||
kind_counts: dict = {}
|
||||
for p in paths:
|
||||
import h5py
|
||||
with h5py.File(p, "r") as fp:
|
||||
vec = fp["vec"][:].astype(int)
|
||||
try:
|
||||
problems = compare_case(vec)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
problems = [f"exception: {exc!r}"]
|
||||
try:
|
||||
feats = mine.decode_vec(vec, is_numerical=True)
|
||||
for f in feats:
|
||||
kind_counts[f.kind] = kind_counts.get(f.kind, 0) + 1
|
||||
except Exception:
|
||||
pass
|
||||
if problems:
|
||||
n_fail += 1
|
||||
print(f"FAIL {Path(p).name}: {problems[:3]}")
|
||||
print(f"\nchecked {len(paths)} cases, {n_fail} with problems")
|
||||
print("feature kinds decoded:", dict(sorted(kind_counts.items())))
|
||||
return 1 if n_fail else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Batch-translate the whole WHUCAD vec dataset into FTC .py sources.
|
||||
|
||||
Walks every h5 under --vec-root, decodes, translates, and writes one
|
||||
``<uid>.ftc.py`` per model under --out (mirroring the 0000.../0103 folder
|
||||
layout). Aggregates model/feature counts and prints a summary. The output
|
||||
directory receives .py files only.
|
||||
|
||||
Usage:
|
||||
.venv/bin/python tools/research/whucad/whucad_batch.py \
|
||||
--vec-root /path/to/WHUCAD/data/vec --out /path/to/whucad_ftc_py \
|
||||
[--workers 8]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import sys
|
||||
from collections import Counter
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
_TOOLS = Path(__file__).resolve().parent
|
||||
if str(_TOOLS) not in sys.path:
|
||||
sys.path.insert(0, str(_TOOLS))
|
||||
|
||||
import whucad_vec as wvec # noqa: E402
|
||||
from whucad_to_ftc import translate_features # noqa: E402
|
||||
|
||||
|
||||
def translate_one(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
src, dst = payload["src"], payload["dst"]
|
||||
stats: Dict[str, Any] = {"uid": payload["uid"], "ok": False}
|
||||
try:
|
||||
features = wvec.load_h5(src)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
stats["error"] = f"decode: {exc}"[:200]
|
||||
return stats
|
||||
stats["features_decoded"] = len(features)
|
||||
try:
|
||||
source = translate_features(features, payload["uid"])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
stats["error"] = f"translate: {exc}"[:200]
|
||||
return stats
|
||||
dst_path = Path(dst)
|
||||
dst_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
dst_path.write_text(source)
|
||||
stats["ok"] = True
|
||||
stats["features_emitted"] = source.count("# ---- feature:")
|
||||
stats["features_skipped"] = source.count("# step ")
|
||||
kinds = Counter()
|
||||
for feature in features:
|
||||
kinds[getattr(feature, "kind", type(feature).__name__)] += 1
|
||||
stats["kinds"] = dict(kinds)
|
||||
return stats
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vec-root", type=Path, required=True,
|
||||
help="root of the WHUCAD h5 tree, e.g. <clone>/data/vec")
|
||||
parser.add_argument("--out", type=Path, required=True,
|
||||
help="output root; .py files land under <out>/<folder>/<uid>.ftc.py")
|
||||
parser.add_argument("--workers", type=int, default=8)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
jobs = []
|
||||
for h5 in sorted(args.vec_root.rglob("*.h5")):
|
||||
uid = f"{h5.parent.name}/{h5.stem}"
|
||||
dst = args.out / h5.parent.name / f"{h5.stem}.ftc.py"
|
||||
jobs.append({"src": str(h5), "dst": str(dst), "uid": uid})
|
||||
print(f"found {len(jobs)} h5 models under {args.vec_root}")
|
||||
|
||||
if args.out.exists():
|
||||
shutil.rmtree(args.out)
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
totals = {
|
||||
"models": len(jobs), "written": 0, "errors": 0, "empty": 0,
|
||||
"features_decoded": 0, "features_emitted": 0, "features_skipped": 0,
|
||||
}
|
||||
kinds_total: Counter = Counter()
|
||||
error_samples = []
|
||||
|
||||
done = 0
|
||||
with ProcessPoolExecutor(max_workers=args.workers) as pool:
|
||||
for stats in pool.map(translate_one, jobs, chunksize=64):
|
||||
done += 1
|
||||
if not stats["ok"]:
|
||||
totals["errors"] += 1
|
||||
if len(error_samples) < 10:
|
||||
error_samples.append((stats["uid"], stats.get("error", "")))
|
||||
continue
|
||||
totals["written"] += 1
|
||||
totals["features_decoded"] += stats["features_decoded"]
|
||||
totals["features_emitted"] += stats["features_emitted"]
|
||||
totals["features_skipped"] += stats["features_skipped"]
|
||||
if stats["features_emitted"] == 0:
|
||||
totals["empty"] += 1
|
||||
for kind, count in stats["kinds"].items():
|
||||
kinds_total[kind] += count
|
||||
if done % 10000 == 0:
|
||||
print(f" ... {done}/{len(jobs)}")
|
||||
|
||||
print("\n==== 批量翻译汇总 ====")
|
||||
print(f"模型总数: {totals['models']}")
|
||||
print(f"成功写出 .py: {totals['written']}")
|
||||
print(f"解码/翻译错误: {totals['errors']}")
|
||||
print(f"全跳过模型(空): {totals['empty']}")
|
||||
print(f"特征总数(解码): {totals['features_decoded']}")
|
||||
print(f"特征块(译出): {totals['features_emitted']}")
|
||||
print(f"特征跳过(注记): {totals['features_skipped']}")
|
||||
print("特征类型分布:", dict(sorted(kinds_total.items())))
|
||||
for uid, err in error_samples:
|
||||
print(f" ! {uid}: {err}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Profile WHUCAD vector data: feature/curve/extent/select-shape distributions
|
||||
and which forms the FTC translator supports.
|
||||
|
||||
Run over any set of h5 files (a sampled folder is enough):
|
||||
|
||||
.venv/bin/python tools/research/whucad/whucad_profile.py \
|
||||
/path/to/WHUCAD/data/vec/0000 [--limit N] [--out PATH]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import sys
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import whucad_select as wsel # noqa: E402
|
||||
import whucad_to_ftc # noqa: E402
|
||||
import whucad_vec as w # noqa: E402
|
||||
|
||||
|
||||
def profile_path(path: str, limit: Optional[int] = None) -> dict:
|
||||
stats: dict = {}
|
||||
counters = {key: collections.Counter() for key in (
|
||||
"feature_kinds", "curves", "extent_types", "rev_axis", "rev_angles",
|
||||
"shell_forms", "select_shapes", "unsupported", "model_status",
|
||||
"features_per_model", "loops_per_sketch")}
|
||||
|
||||
paths = sorted(glob(str(Path(path) / "*.h5")))
|
||||
if limit:
|
||||
paths = paths[:limit]
|
||||
|
||||
for h5_path in paths:
|
||||
try:
|
||||
features = w.load_h5(h5_path)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
counters["model_status"][f"decode_error: {type(exc).__name__}"] += 1
|
||||
continue
|
||||
counters["features_per_model"][len(features)] += 1
|
||||
translated = whucad_to_ftc.Translator(features, "profile")
|
||||
emittable = 0
|
||||
for index, feature in enumerate(features):
|
||||
counters["feature_kinds"][feature.kind] += 1
|
||||
if isinstance(feature, w.ExtrudeFeature):
|
||||
counters["extent_types"][f"{feature.extent_type1}/{feature.extent_type2}"] += 1
|
||||
counters["loops_per_sketch"][len(feature.sketch.profile.loops)] += 1
|
||||
for loop in feature.sketch.profile.loops:
|
||||
for curve in loop.curves:
|
||||
counters["curves"][type(curve).__name__] += 1
|
||||
if isinstance(feature, w.RevolveFeature):
|
||||
axis = feature.axis_select
|
||||
counters["rev_axis"][f"{axis.select_type}/{axis.body_type}"] += 1
|
||||
counters["rev_angles"][f"two_sided={feature.angle_two > 1e-9}"] += 1
|
||||
for loop in feature.sketch.profile.loops:
|
||||
for curve in loop.curves:
|
||||
counters["curves"][type(curve).__name__] += 1
|
||||
if isinstance(feature, w.FinishFeature) and feature.kind == "Shell":
|
||||
counters["shell_forms"][f"external_thickness={feature.params['second_thickness'] > 1e-9}"] += 1
|
||||
if isinstance(feature, w.FinishFeature):
|
||||
for select in feature.select_list:
|
||||
counters["select_shapes"][_select_shape(feature.kind, select)] += 1
|
||||
try:
|
||||
translated._emit_feature(index, feature)
|
||||
emittable += 1
|
||||
except (whucad_to_ftc.UnsupportedForm, wsel.UnsupportedSelect) as exc:
|
||||
counters["unsupported"][f"{feature.kind}: {exc}"] += 1
|
||||
counters["model_status"]["ok" if emittable == len(features) else "partial"] += 1
|
||||
|
||||
for key, counter in counters.items():
|
||||
stats[key] = dict(counter.most_common())
|
||||
stats["scanned"] = len(paths)
|
||||
return stats
|
||||
|
||||
|
||||
def _select_shape(kind: str, select: w.Select, depth: int = 0) -> str:
|
||||
if depth > 2:
|
||||
return "..."
|
||||
shape = f"{kind}:{select.select_type}/{select.body_type}"
|
||||
if select.operation_list:
|
||||
shape += "(" + ",".join(_select_shape(kind, s, depth + 1) for s in select.operation_list) + ")"
|
||||
return shape
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("vec_dir")
|
||||
parser.add_argument("--limit", type=int, default=None)
|
||||
parser.add_argument("--out", type=Path, default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
stats = profile_path(args.vec_dir, args.limit)
|
||||
text = json.dumps(stats, indent=2, ensure_ascii=False)
|
||||
print(text)
|
||||
if args.out:
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out.write_text(text)
|
||||
print(f"wrote {args.out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,453 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Translate WHUCAD Topo/Select references into FTC ``ql`` selector source.
|
||||
|
||||
WHUCAD references topology by history — "face #no of the #body_no feature of
|
||||
type body_type", plus derived edges ("the edge shared by these two faces").
|
||||
The translator resolves those references analytically from the decoded
|
||||
construction history (it already knows every face it emits) and emits a
|
||||
``ql`` geometric-predicate selector — the same pattern as the repository's
|
||||
hand-written examples. Resolution here is bookkeeping of known geometry, not
|
||||
solving; whether the emitted selector matches the intended face at build time
|
||||
is a question for whucad_validate.py.
|
||||
|
||||
Canonical face numbering (calibrated against the dataset's own CATIA
|
||||
reconstruction and the packaged BRep truth — see README):
|
||||
no == 0 lateral face swept from the sketch wire (the Select carries the
|
||||
``Wire/Sketch`` reference in ``operation_list``)
|
||||
no == 1 near cap (cap on the sketch plane side)
|
||||
no == 2 far cap (cap at the far end of the extrusion)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, List, Optional, Sequence, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from whucad_vec import Circle, ExtrudeFeature, Line, RevolveFeature, Select
|
||||
|
||||
_TOL = 1e-4 # predicate tolerance, normalized-model units (bbox ~1.5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# face/edge descriptors (analytic facts about faces the translator emits)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PlaneFace:
|
||||
point: np.ndarray # a point on the plane (the cap centroid lies on it)
|
||||
normal: np.ndarray
|
||||
area: float
|
||||
kind: str = "PLANE"
|
||||
|
||||
|
||||
@dataclass
|
||||
class CylinderFace:
|
||||
center: np.ndarray # face centroid: axis point at mid height
|
||||
axis: np.ndarray
|
||||
radius: float
|
||||
height: float
|
||||
kind: str = "CYLINDER"
|
||||
|
||||
@property
|
||||
def area(self) -> float:
|
||||
return 2.0 * math.pi * self.radius * self.height
|
||||
|
||||
|
||||
@dataclass
|
||||
class EdgeDesc:
|
||||
kind: str # "CIRCLE" | "LINE"
|
||||
center: np.ndarray # circle center / segment midpoint
|
||||
length: float
|
||||
direction: Optional[np.ndarray] = None # LINE only
|
||||
reference_normal: Optional[np.ndarray] = None # chamfer reference face
|
||||
|
||||
|
||||
def circle_edge(center, radius: float, reference_normal=None) -> EdgeDesc:
|
||||
return EdgeDesc("CIRCLE", np.asarray(center, dtype=float),
|
||||
2.0 * math.pi * radius, None, reference_normal)
|
||||
|
||||
|
||||
FaceDesc = Any # PlaneFace | CylinderFace
|
||||
|
||||
|
||||
def to3d(plan, p2d) -> np.ndarray:
|
||||
return (np.asarray(plan.plane_origin, dtype=float)
|
||||
+ plan.plane_x_axis * float(p2d[0]) + plan.plane_y_axis * float(p2d[1]))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# canonical faces of an extrude-like feature
|
||||
|
||||
|
||||
def loop_area(points: Sequence[Tuple[float, float]]) -> float:
|
||||
"""|area| of a polygon sample of a loop (the predicate needs a stable
|
||||
fingerprint within tolerance, not an exact integral)."""
|
||||
pts = np.asarray(points, dtype=float)
|
||||
if len(pts) < 3:
|
||||
return 0.0
|
||||
x, y = pts[:, 0], pts[:, 1]
|
||||
return abs(float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) / 2.0)
|
||||
|
||||
|
||||
def curve_samples(curve, n: int = 24) -> List[Tuple[float, float]]:
|
||||
if isinstance(curve, Line):
|
||||
return [tuple(curve.start_point), tuple(curve.end_point)]
|
||||
if isinstance(curve, Circle):
|
||||
c, r = curve.center, curve.radius
|
||||
return [(c[0] + r * math.cos(2 * math.pi * i / n),
|
||||
c[1] + r * math.sin(2 * math.pi * i / n)) for i in range(n)]
|
||||
pts = []
|
||||
a0 = curve.start_arc
|
||||
span = (curve.end_arc - curve.start_arc) % (2.0 * math.pi)
|
||||
for i in range(n):
|
||||
a = a0 + span * i / (n - 1)
|
||||
pts.append((curve.center[0] + curve.radius * math.cos(a),
|
||||
curve.center[1] + curve.radius * math.sin(a)))
|
||||
return pts
|
||||
|
||||
|
||||
def _loop_area(plan, loop) -> float:
|
||||
samples: List[Tuple[float, float]] = []
|
||||
for curve in loop.curves:
|
||||
samples.extend(curve_samples(curve))
|
||||
return loop_area(samples)
|
||||
|
||||
|
||||
def _wire_curve(feature, wire_no: int):
|
||||
"""Curve #wire_no (1-based, flat across the profile's loops)."""
|
||||
curves = [c for loop in feature.sketch.profile.loops for c in loop.curves]
|
||||
if not 1 <= wire_no <= len(curves):
|
||||
raise UnsupportedSelect(f"wire #{wire_no} out of range")
|
||||
return curves[wire_no - 1]
|
||||
|
||||
|
||||
def _lateral_face(feature: ExtrudeFeature, wire_no: int) -> FaceDesc:
|
||||
"""The face swept from sketch curve #wire_no: a cylinder wall for a
|
||||
circle, a plane wall for a line."""
|
||||
plan = feature.sketch
|
||||
curve = _wire_curve(feature, wire_no)
|
||||
low, high = extrude_span(feature)
|
||||
height = high - low
|
||||
mid_offset = (low + high) / 2.0
|
||||
if isinstance(curve, Circle):
|
||||
center3 = to3d(plan, curve.center)
|
||||
mid = center3 + plan.plane_normal * mid_offset
|
||||
return CylinderFace(mid, plan.plane_normal, float(curve.radius), abs(height))
|
||||
if isinstance(curve, Line):
|
||||
p0 = to3d(plan, curve.start_point)
|
||||
p1 = to3d(plan, curve.end_point)
|
||||
direction = p1 - p0
|
||||
length = float(np.linalg.norm(direction))
|
||||
if length < 1e-9:
|
||||
raise UnsupportedSelect("degenerate wire line")
|
||||
direction = direction / length
|
||||
# outward normal of a CCW loop wall: line direction × extrude normal
|
||||
normal = np.cross(direction, plan.plane_normal)
|
||||
mid = p0 + direction * (length / 2.0) + plan.plane_normal * mid_offset
|
||||
return PlaneFace(mid, normal, length * abs(height))
|
||||
raise UnsupportedSelect("lateral face over an arc wire")
|
||||
|
||||
|
||||
def extrude_span(feature: ExtrudeFeature) -> Tuple[float, float]:
|
||||
"""Signed span of the extrusion along the plane normal: [−e2, +e1].
|
||||
Negative extents (inverted pads) cross the sketch plane."""
|
||||
return (-float(feature.extent_two), float(feature.extent_one))
|
||||
|
||||
|
||||
def cap_face_desc(feature: ExtrudeFeature, face_no: int) -> PlaneFace:
|
||||
"""Near (1) / far (2) cap face descriptor — no lateral construction, so
|
||||
polygon-loop pads resolve without a lateral-wall form."""
|
||||
plan = feature.sketch
|
||||
area = _loop_area(plan, plan.profile.loops[0])
|
||||
low, high = extrude_span(feature)
|
||||
n = plan.plane_normal
|
||||
if face_no == 1:
|
||||
return PlaneFace(plan.plane_origin + n * low, -n, area)
|
||||
if face_no == 2:
|
||||
return PlaneFace(plan.plane_origin + n * high, n, area)
|
||||
raise UnsupportedSelect(f"cap no={face_no}")
|
||||
|
||||
|
||||
def extrude_face_descs(feature: ExtrudeFeature, wire_no: int = 1) -> List[FaceDesc]:
|
||||
"""[lateral, near cap, far cap] of an extrude feature."""
|
||||
lateral = _lateral_face(feature, wire_no)
|
||||
return [lateral, cap_face_desc(feature, 1), cap_face_desc(feature, 2)]
|
||||
|
||||
|
||||
class UnsupportedSelect(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# feature registry (body_no → decoded feature, 1-based within each body kind)
|
||||
|
||||
|
||||
class FeatureRegistry:
|
||||
"""Maps (body_type, body_no) onto the features decoded before the current
|
||||
one — the same history the dataset's references point into."""
|
||||
|
||||
_BODY_KIND = {"Pad": "Ext", "Shaft": "Rev", "Pocket": "Pocket", "Groove": "Groove"}
|
||||
|
||||
def __init__(self, features: Sequence[object]):
|
||||
self._by_kind: dict = {}
|
||||
self._all = list(features)
|
||||
|
||||
def lookup(self, select: Select) -> object:
|
||||
kind = self._BODY_KIND.get(select.body_type)
|
||||
if kind is None:
|
||||
raise UnsupportedSelect(f"body_type {select.body_type}")
|
||||
bucket = [f for f in self._all if getattr(f, "kind", None) == kind]
|
||||
if not 1 <= select.body_no <= len(bucket):
|
||||
raise UnsupportedSelect(f"{select.body_type}#{select.body_no} out of range")
|
||||
return bucket[select.body_no - 1]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# select tree resolution
|
||||
|
||||
|
||||
def resolve_face(select: Select, registry: FeatureRegistry) -> Tuple[object, FaceDesc, int]:
|
||||
"""Resolve a Face leaf select to (source feature, face descriptor, no)."""
|
||||
if select.operation_list:
|
||||
wire_ref = select.operation_list[0]
|
||||
if select.no == 0 and wire_ref.select_type == "Wire":
|
||||
feature = registry.lookup(select)
|
||||
if not isinstance(feature, (ExtrudeFeature, RevolveFeature)):
|
||||
raise UnsupportedSelect("wire face of a non-sketch feature")
|
||||
if isinstance(feature, ExtrudeFeature):
|
||||
return feature, _lateral_face(feature, wire_ref.no), 0
|
||||
raise UnsupportedSelect("lateral face of a revolve")
|
||||
raise UnsupportedSelect(f"derived face form no={select.no}")
|
||||
feature = registry.lookup(select)
|
||||
if not isinstance(feature, (ExtrudeFeature, RevolveFeature)):
|
||||
raise UnsupportedSelect(f"face of {select.body_type}")
|
||||
if select.body_type != "Pad":
|
||||
raise UnsupportedSelect(f"face numbering of {select.body_type}")
|
||||
if not 0 <= select.no <= 2:
|
||||
raise UnsupportedSelect(f"face no={select.no}")
|
||||
if len(feature.sketch.profile.loops) != 1:
|
||||
raise UnsupportedSelect("cap numbering of a multi-loop pad")
|
||||
return feature, cap_face_desc(feature, select.no), select.no
|
||||
|
||||
|
||||
def lateral_boundary_edges(select: Select, registry: FeatureRegistry) -> List[EdgeDesc]:
|
||||
"""A Face leaf naming the lateral wall (no == 0) appears two ways: with a
|
||||
Wire reference (any wall) or bare on single-circle pads. Both mean
|
||||
"every edge of that wall" — cap joints + vertical corners for a line
|
||||
wall, the rims for a circular wall."""
|
||||
if select.no != 0:
|
||||
raise UnsupportedSelect("lateral leaf form")
|
||||
feature = registry.lookup(select)
|
||||
if not isinstance(feature, ExtrudeFeature):
|
||||
raise UnsupportedSelect("lateral face of a revolve")
|
||||
if select.operation_list:
|
||||
if select.operation_list[0].select_type != "Wire":
|
||||
raise UnsupportedSelect("lateral leaf form")
|
||||
return wire_boundary_edges(feature, select.operation_list[0].no)
|
||||
loops = feature.sketch.profile.loops
|
||||
if len(loops) != 1 or len(loops[0].curves) != 1 or not isinstance(loops[0].curves[0], Circle):
|
||||
raise UnsupportedSelect("lateral leaf on a multi-curve pad")
|
||||
return wire_boundary_edges(feature, 1)
|
||||
|
||||
|
||||
def wire_boundary_edges(feature: ExtrudeFeature, wire_no: int) -> List[EdgeDesc]:
|
||||
"""All boundary edges of the wall swept from sketch curve #wire_no."""
|
||||
plan = feature.sketch
|
||||
curve = _wire_curve(feature, wire_no)
|
||||
low, high = extrude_span(feature)
|
||||
n = plan.plane_normal
|
||||
if isinstance(curve, Circle):
|
||||
center3 = to3d(plan, curve.center)
|
||||
return [circle_edge(center3 + n * low, float(curve.radius), -n),
|
||||
circle_edge(center3 + n * high, float(curve.radius), n)]
|
||||
if isinstance(curve, Line):
|
||||
p0 = to3d(plan, curve.start_point)
|
||||
p1 = to3d(plan, curve.end_point)
|
||||
wall_normal = np.cross((p1 - p0) / np.linalg.norm(p1 - p0), n)
|
||||
descs = []
|
||||
for offset, ref in ((low, -n), (high, n)):
|
||||
a = p0 + n * offset
|
||||
b = p1 + n * offset
|
||||
direction = (b - a) / np.linalg.norm(b - a)
|
||||
descs.append(EdgeDesc("LINE", (a + b) / 2.0, float(np.linalg.norm(b - a)),
|
||||
direction, ref))
|
||||
for point in (curve.start_point, curve.end_point):
|
||||
base = to3d(plan, point)
|
||||
a = base + n * low
|
||||
b = base + n * high
|
||||
direction = (b - a) / np.linalg.norm(b - a)
|
||||
descs.append(EdgeDesc("LINE", (a + b) / 2.0, float(np.linalg.norm(b - a)),
|
||||
direction, wall_normal))
|
||||
return descs
|
||||
raise UnsupportedSelect("wall over an arc wire")
|
||||
|
||||
|
||||
def resolve_edge(select: Select, registry: FeatureRegistry) -> EdgeDesc:
|
||||
"""Edge select: body_type None, operation_list = the two bounding faces.
|
||||
The span is taken from the wire geometry at the referenced cap."""
|
||||
if select.select_type != "Edge" or len(select.operation_list) != 2:
|
||||
raise UnsupportedSelect("edge form")
|
||||
subs = select.operation_list
|
||||
resolved = [resolve_face(sub, registry) for sub in subs]
|
||||
(fa, da, na), (fb, db, nb) = resolved
|
||||
if isinstance(da, CylinderFace) and isinstance(db, CylinderFace):
|
||||
raise UnsupportedSelect("edge between two cylinder walls")
|
||||
cylinder = next((d for d in (da, db) if isinstance(d, CylinderFace)), None)
|
||||
if cylinder is not None:
|
||||
plane = db if isinstance(da, CylinderFace) else da
|
||||
return _circle_edge_of(cylinder, plane,
|
||||
reference_normal=_cap_normal(resolved))
|
||||
if isinstance(da, PlaneFace) and isinstance(db, PlaneFace):
|
||||
wall_subs = [(sub, res) for sub, res in zip(subs, resolved)
|
||||
if res[2] == 0 and sub.operation_list]
|
||||
if len(wall_subs) == 2:
|
||||
return _wall_wall_edge(wall_subs[0][1][0], wall_subs[1][1][0],
|
||||
[sub.operation_list[0].no for sub, _ in wall_subs],
|
||||
reference_normal=_cap_normal(resolved))
|
||||
for sub, (feature, desc, no) in zip(subs, resolved):
|
||||
if no == 0 and sub.operation_list:
|
||||
wire_no = sub.operation_list[0].no
|
||||
cap_no = nb if no == na else na
|
||||
if cap_no not in (1, 2):
|
||||
raise UnsupportedSelect("wall/wall edge")
|
||||
return wire_line_edge(feature, wire_no, cap_no,
|
||||
reference_normal=_cap_normal(resolved))
|
||||
raise UnsupportedSelect("line edge without cap/wire pair")
|
||||
raise UnsupportedSelect("edge between " + da.kind + " and " + db.kind)
|
||||
|
||||
|
||||
def _wall_wall_edge(feature_a: ExtrudeFeature, feature_b: ExtrudeFeature,
|
||||
wire_nos: List[int], reference_normal) -> EdgeDesc:
|
||||
"""Vertical corner edge where two adjacent walls meet: the shared wire
|
||||
endpoint of the two referenced lines (same pad), spanning the extrusion."""
|
||||
if feature_a is not feature_b:
|
||||
raise UnsupportedSelect("wall/wall edge across features")
|
||||
plan = feature_a.sketch
|
||||
curve_a = _wire_curve(feature_a, wire_nos[0])
|
||||
curve_b = _wire_curve(feature_a, wire_nos[1])
|
||||
if not (isinstance(curve_a, Line) and isinstance(curve_b, Line)):
|
||||
raise UnsupportedSelect("wall/wall edge over a curved wire")
|
||||
shared = _shared_point(curve_a, curve_b)
|
||||
if shared is None:
|
||||
raise UnsupportedSelect("wall lines do not share an endpoint")
|
||||
base = to3d(plan, shared)
|
||||
low, high = extrude_span(feature_a)
|
||||
a = base + plan.plane_normal * low
|
||||
b = base + plan.plane_normal * high
|
||||
direction = (b - a) / np.linalg.norm(b - a)
|
||||
return EdgeDesc("LINE", (a + b) / 2.0, float(np.linalg.norm(b - a)),
|
||||
direction, reference_normal)
|
||||
|
||||
|
||||
def _shared_point(curve_a: Line, curve_b: Line, tol: float = 1e-6):
|
||||
for pa in (curve_a.start_point, curve_a.end_point):
|
||||
for pb in (curve_b.start_point, curve_b.end_point):
|
||||
if abs(pa[0] - pb[0]) <= tol and abs(pa[1] - pb[1]) <= tol:
|
||||
return (float(pa[0]), float(pa[1]))
|
||||
return None
|
||||
|
||||
|
||||
def _cap_normal(resolved) -> Optional[np.ndarray]:
|
||||
"""Convention: the cap face anchors the chamfer's first leg when one of
|
||||
the two bounding faces is a cap; otherwise the planar face anchors (the
|
||||
vector itself does not record the anchoring — CATIA resolved it from
|
||||
edge orientation; see README)."""
|
||||
for _, desc, no in resolved:
|
||||
if isinstance(desc, PlaneFace) and no in (1, 2):
|
||||
return desc.normal
|
||||
for _, desc, _ in resolved:
|
||||
if isinstance(desc, PlaneFace):
|
||||
return desc.normal
|
||||
return None
|
||||
|
||||
|
||||
def _circle_edge_of(cyl: CylinderFace, plane: PlaneFace, reference_normal=None) -> EdgeDesc:
|
||||
n = plane.normal
|
||||
d = float(np.dot(plane.point, n))
|
||||
denom = float(np.dot(cyl.axis, n))
|
||||
if abs(denom) < 1e-9:
|
||||
# cylinder axis parallel to the plane: no circle intersection
|
||||
raise UnsupportedSelect("cylinder axis parallel to plane")
|
||||
t = (d - float(np.dot(cyl.center, n))) / denom
|
||||
center = cyl.center + cyl.axis * t
|
||||
return circle_edge(center, cyl.radius, reference_normal=reference_normal)
|
||||
|
||||
|
||||
def wire_line_edge(feature: ExtrudeFeature, wire_no: int, cap_no: int,
|
||||
reference_normal) -> EdgeDesc:
|
||||
"""The edge between wall(curve #wire_no) and cap(cap_no) of a pad whose
|
||||
referenced wire curve is a line."""
|
||||
plan = feature.sketch
|
||||
curve = _wire_curve(feature, wire_no)
|
||||
if not isinstance(curve, Line):
|
||||
raise UnsupportedSelect("wall wire is not a single line")
|
||||
p0 = to3d(plan, curve.start_point)
|
||||
p1 = to3d(plan, curve.end_point)
|
||||
low, high = extrude_span(feature)
|
||||
offset = plan.plane_normal * (high if cap_no == 2 else low)
|
||||
p0, p1 = p0 + offset, p1 + offset
|
||||
center = (p0 + p1) / 2.0
|
||||
direction = p1 - p0
|
||||
length = float(np.linalg.norm(direction))
|
||||
return EdgeDesc("LINE", center, length, direction / length, reference_normal)
|
||||
|
||||
|
||||
def cap_boundary_edge(feature: ExtrudeFeature, face_no: int) -> EdgeDesc:
|
||||
"""Boundary circle of cap face `face_no` (1=near, 2=far) of a circular
|
||||
single-loop pad; used when a chamfer/fillet selects the cap face."""
|
||||
loop = feature.sketch.profile.loops[0]
|
||||
if len(loop.curves) != 1 or not isinstance(loop.curves[0], Circle):
|
||||
raise UnsupportedSelect("cap boundary of a non-circular loop")
|
||||
circle = loop.curves[0]
|
||||
center3 = to3d(feature.sketch, circle.center)
|
||||
n = feature.sketch.plane_normal
|
||||
low, high = extrude_span(feature)
|
||||
if face_no == 1:
|
||||
center, normal = center3 + n * low, -n
|
||||
elif face_no == 2:
|
||||
center, normal = center3 + n * high, n
|
||||
else:
|
||||
raise UnsupportedSelect(f"cap no={face_no}")
|
||||
return circle_edge(center, float(circle.radius), reference_normal=normal)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ql source emission
|
||||
|
||||
|
||||
def face_predicate_lines(var: str, desc: FaceDesc, indent: str) -> List[str]:
|
||||
"""ql.faces().where(...) chain that pins the described face."""
|
||||
lines = [f"{var} = (", f"{indent}ql.faces()",
|
||||
f'{indent}.where(ql.prop("geom.type", "==", "{desc.kind}"))']
|
||||
if isinstance(desc, PlaneFace):
|
||||
for axis, value in zip("xyz", desc.normal):
|
||||
lines.append(f'{indent}.where(ql.prop("geom.normal.{axis}", ">=", {value - _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.normal.{axis}", "<=", {value + _TOL:.9f}))')
|
||||
# the centroid of a planar face lies on its plane
|
||||
axis = int(np.argmax(np.abs(desc.normal)))
|
||||
value = float(np.dot(desc.point, desc.normal))
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{"xyz"[axis]}", ">=", {value - _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{"xyz"[axis]}", "<=", {value + _TOL:.9f}))')
|
||||
else:
|
||||
for axis, value in zip("xyz", desc.center):
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{axis}", ">=", {value - _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{axis}", "<=", {value + _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.area", ">=", {desc.area * 0.98:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.area", "<=", {desc.area * 1.02:.9f}))')
|
||||
lines.append(f"{indent})")
|
||||
return lines
|
||||
|
||||
|
||||
def edge_predicate_lines(var: str, desc: EdgeDesc, indent: str) -> List[str]:
|
||||
lines = [f"{var} = (", f"{indent}ql.edges()",
|
||||
f'{indent}.where(ql.prop("geom.type", "==", "{desc.kind}"))']
|
||||
for axis, value in zip("xyz", desc.center):
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{axis}", ">=", {value - _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.center.{axis}", "<=", {value + _TOL:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.length", ">=", {desc.length * 0.98:.9f}))')
|
||||
lines.append(f'{indent}.where(ql.prop("geom.length", "<=", {desc.length * 1.02:.9f}))')
|
||||
lines.append(f"{indent})")
|
||||
return lines
|
||||
@@ -0,0 +1,398 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Translate decoded WHUCAD feature sequences into SimpleCADAPI FTC sources.
|
||||
|
||||
One feature block per WHUCAD operation (sketch → promotion → extrude/revolve →
|
||||
boolean), following the Feature Tree Convention: block headers
|
||||
``# ---- feature: <slug> (<role>) ----`` and explicit dataflow rebinding.
|
||||
Topology references (Chamfer/Fillet/Shell selects) become ``ql`` geometric
|
||||
predicates via whucad_select.py.
|
||||
|
||||
Translated sources are TRAINING DATA: they contain the model and nothing
|
||||
else. The translator ONLY translates — unsupported forms are skipped with a
|
||||
header annotation (never approximated); whether the result matches the
|
||||
packaged BRep truth is a question for whucad_validate.py.
|
||||
|
||||
Usage:
|
||||
python tools/research/whucad/whucad_to_ftc.py <model.h5> [--out PATH]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Optional, Sequence, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
import whucad_select as wsel
|
||||
import whucad_vec as w
|
||||
from whucad_vec import (ExtrudeFeature, FinishFeature, HoleFeature, Line,
|
||||
RevolveFeature, Spline)
|
||||
|
||||
_FMT_DIGITS = 9
|
||||
|
||||
|
||||
def _fmt(value: float) -> str:
|
||||
return repr(round(float(value), _FMT_DIGITS))
|
||||
|
||||
|
||||
def _vec(values) -> str:
|
||||
return "(" + ", ".join(_fmt(v) for v in values) + ")"
|
||||
|
||||
|
||||
class UnsupportedForm(Exception):
|
||||
"""Sketch/feature form the translator does not map (data-driven)."""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# sketch emission
|
||||
|
||||
|
||||
class SketchEmitter:
|
||||
"""Emits sketch entity lines for one feature, mirroring the FTC sketch
|
||||
profile ordering (circles standalone; line/arc chains by pooled endpoints)."""
|
||||
|
||||
def __init__(self, name: str, plan: w.SketchPlan):
|
||||
self.name = name
|
||||
self.plan = plan
|
||||
self.lines: List[str] = []
|
||||
self.pool: dict = {}
|
||||
self.counter = 0
|
||||
plane = (
|
||||
"{'origin': " + _vec(plan.plane_origin)
|
||||
+ ", 'x_axis': " + _vec(plan.plane_x_axis)
|
||||
+ ", 'y_axis': " + _vec(plan.plane_y_axis) + "}"
|
||||
)
|
||||
self.lines.append(f"s = scad.make_sketch_rsketch(name={self.name!r}, plane={plane})")
|
||||
|
||||
def point(self, x: float, y: float) -> str:
|
||||
key = (round(x, 6), round(y, 6))
|
||||
for pid, (px, py) in self.pool.items():
|
||||
if (round(px, 6), round(py, 6)) == key:
|
||||
return pid
|
||||
self.counter += 1
|
||||
pid = f"{self.name}_p{self.counter}"
|
||||
self.pool[pid] = (float(x), float(y))
|
||||
self.lines.append(f"s = scad.add_point_rsketch(sketch=s, point_id={pid!r}, x={_fmt(x)}, y={_fmt(y)})")
|
||||
return pid
|
||||
|
||||
def emit(self) -> None:
|
||||
for loop_index, loop in enumerate(self.plan.profile.loops):
|
||||
for curve_index, curve in enumerate(loop.curves):
|
||||
eid = f"{self.name}_e{loop_index}_{curve_index}"
|
||||
if isinstance(curve, Line):
|
||||
start = self.point(curve.start_point[0], curve.start_point[1])
|
||||
end = self.point(curve.end_point[0], curve.end_point[1])
|
||||
self.lines.append(f"s = scad.add_line_rsketch(sketch=s, entity_id={eid!r}, start={start!r}, end={end!r})")
|
||||
elif isinstance(curve, w.Circle):
|
||||
center = self.point(curve.center[0], curve.center[1])
|
||||
self.lines.append(f"s = scad.add_circle_rsketch(sketch=s, entity_id={eid!r}, center={center!r}, radius={_fmt(curve.radius)})")
|
||||
elif isinstance(curve, w.Arc):
|
||||
cx, cy = float(curve.center[0]), float(curve.center[1])
|
||||
start_pt, end_pt = curve.start_point, curve.end_point
|
||||
mid = curve.mid_point
|
||||
# promotion sweeps counter-clockwise start→end, so order
|
||||
# the endpoints so the sweep passes through the mid point
|
||||
a0 = math.atan2(start_pt[1] - cy, start_pt[0] - cx)
|
||||
a1 = math.atan2(end_pt[1] - cy, end_pt[0] - cx)
|
||||
am = math.atan2(mid[1] - cy, mid[0] - cx)
|
||||
if not ((am - a0) % (2 * math.pi) <= (a1 - a0) % (2 * math.pi)):
|
||||
start_pt, end_pt = end_pt, start_pt
|
||||
start = self.point(start_pt[0], start_pt[1])
|
||||
end = self.point(end_pt[0], end_pt[1])
|
||||
center = self.point(cx, cy)
|
||||
self.lines.append(f"s = scad.add_arc_rsketch(sketch=s, entity_id={eid!r}, start={start!r}, end={end!r}, center={center!r})")
|
||||
elif isinstance(curve, Spline):
|
||||
raise UnsupportedForm("spline entity")
|
||||
else:
|
||||
raise UnsupportedForm(f"curve {type(curve).__name__}")
|
||||
|
||||
def face_lines(self, face_var: str) -> List[str]:
|
||||
if len(self.plan.profile.loops) != 1:
|
||||
raise UnsupportedForm(f"{len(self.plan.profile.loops)}-loop profile")
|
||||
return [f"{face_var} = scad.make_face_from_sketch_rface(sketch=s, profile=0)"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# feature helpers
|
||||
|
||||
|
||||
def _role(operation: str) -> str:
|
||||
return {"AddFeatureOperation": "add", "CutFeatureOperation": "subtract",
|
||||
"IntersectFeatureOperation": "intersect"}.get(operation, "build")
|
||||
|
||||
|
||||
def _axis_line(feature: RevolveFeature, history: List[Any]) -> Tuple[Tuple[float, ...], Tuple[float, ...]]:
|
||||
"""Axis line (origin point, unit direction) from the dataset's Wire/Sketch
|
||||
reference: curve #no of sketch #body_no (1-based over sketch features)."""
|
||||
ax = feature.axis_select
|
||||
if ax.select_type != "Wire" or ax.body_type != "Sketch":
|
||||
raise UnsupportedForm(f"axis {ax.select_type}/{ax.body_type}")
|
||||
bucket = [f for f in history if isinstance(f, (ExtrudeFeature, RevolveFeature))]
|
||||
if not 1 <= ax.body_no <= len(bucket):
|
||||
raise UnsupportedForm(f"axis sketch #{ax.body_no} out of range")
|
||||
plan = bucket[ax.body_no - 1].sketch
|
||||
curves = [c for loop in plan.profile.loops for c in loop.curves]
|
||||
if not 1 <= ax.no <= len(curves):
|
||||
raise UnsupportedForm(f"axis curve #{ax.no} out of range")
|
||||
curve = curves[ax.no - 1]
|
||||
if not isinstance(curve, Line):
|
||||
raise UnsupportedForm("non-line revolve axis")
|
||||
p0 = wsel.to3d(plan, curve.start_point)
|
||||
p1 = wsel.to3d(plan, curve.end_point)
|
||||
direction = p1 - p0
|
||||
norm = float(np.linalg.norm(direction))
|
||||
if norm < 1e-9:
|
||||
raise UnsupportedForm("degenerate axis")
|
||||
return tuple(p0), tuple(direction / norm)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# translator
|
||||
|
||||
|
||||
class Translator:
|
||||
def __init__(self, features: List[Any], uid: str):
|
||||
self.features = features
|
||||
self.uid = uid
|
||||
self.notes: List[str] = []
|
||||
self.first_solid = True
|
||||
|
||||
# -- driver --------------------------------------------------------------
|
||||
|
||||
def translate(self) -> str:
|
||||
lines: List[str] = [
|
||||
f'"""FTC source generated from WHUCAD {self.uid}."""',
|
||||
"",
|
||||
"import simplecadapi as scad",
|
||||
"",
|
||||
"BODIES = None # all solid bodies before single-solid merge",
|
||||
"",
|
||||
"",
|
||||
"def _merge_bodies(bodies):",
|
||||
" result = bodies[0]",
|
||||
" for extra in bodies[1:]:",
|
||||
" try:",
|
||||
" result = scad.union_rsolid(result, [extra])",
|
||||
" except Exception:",
|
||||
" pass # disjoint bodies stay outside the single-solid contract",
|
||||
" return result",
|
||||
"",
|
||||
"",
|
||||
f"@scad.part(id={'whucad-' + self.uid.replace('/', '-')!r}, revision='1.0.0')",
|
||||
"def build() -> scad.Part:",
|
||||
]
|
||||
if any(isinstance(f, FinishFeature) for f in self.features):
|
||||
lines.insert(2, "from simplecadapi import ql")
|
||||
|
||||
for index, feature in enumerate(self.features):
|
||||
try:
|
||||
lines.extend(self._emit_feature(index, feature))
|
||||
except (UnsupportedForm, wsel.UnsupportedSelect) as exc:
|
||||
kind = getattr(feature, "kind", type(feature).__name__)
|
||||
self.notes.append(f"step {index}: unsupported {kind} ({exc})")
|
||||
|
||||
if self.first_solid:
|
||||
# nothing translated — keep the source executable, empty part
|
||||
self.notes.append("model: no feature translated")
|
||||
lines.append(" bodies = []")
|
||||
lines.append(" global BODIES")
|
||||
lines.append(" BODIES = list(bodies)")
|
||||
lines.append(" return _merge_bodies(bodies)")
|
||||
header_notes = [f" # {note}" for note in self.notes]
|
||||
return "\n".join(lines[:6] + header_notes + lines[6:]) + "\n"
|
||||
|
||||
# -- feature dispatch ------------------------------------------------------
|
||||
|
||||
def _emit_feature(self, index: int, feature: Any) -> List[str]:
|
||||
if isinstance(feature, (ExtrudeFeature, RevolveFeature)):
|
||||
return self._emit_solid(index, feature)
|
||||
if isinstance(feature, HoleFeature):
|
||||
return self._emit_hole(index, feature)
|
||||
if isinstance(feature, FinishFeature):
|
||||
return self._emit_finish(index, feature)
|
||||
raise UnsupportedForm(getattr(feature, "kind", type(feature).__name__))
|
||||
|
||||
def _emit_solid(self, index: int, feature: Any) -> List[str]:
|
||||
name = f"f{index}"
|
||||
emitter = SketchEmitter(name, feature.sketch)
|
||||
emitter.emit()
|
||||
face_var = f"{name}_face"
|
||||
tool_var = f"{name}_tool"
|
||||
normal = feature.sketch.plane_normal
|
||||
if isinstance(feature, ExtrudeFeature):
|
||||
if (feature.extent_type1, feature.extent_type2) != ("OffsetLimit", "OffsetLimit"):
|
||||
raise UnsupportedForm(f"extent {feature.extent_type1}/{feature.extent_type2}")
|
||||
lines = emitter.face_lines(face_var)
|
||||
neg = (-normal[0], -normal[1], -normal[2])
|
||||
# signed span [−e2, +e1]; inverted pads (negative extents) cross
|
||||
# the sketch plane
|
||||
plus = feature.extent_one + max(-feature.extent_two, 0.0)
|
||||
minus = feature.extent_two + max(-feature.extent_one, 0.0)
|
||||
plus, minus = max(plus, 0.0), max(minus, 0.0)
|
||||
if plus > 0 and minus > 0:
|
||||
lines.append(
|
||||
f"{tool_var} = scad.union_rsolid(\n"
|
||||
f" scad.extrude_rsolid(profile={face_var}, direction={_vec(normal)}, distance={_fmt(plus)}),\n"
|
||||
f" [scad.extrude_rsolid(profile={face_var}, direction={_vec(neg)}, distance={_fmt(minus)})])"
|
||||
)
|
||||
elif plus > 0 or minus > 0:
|
||||
distance = plus if plus > 0 else minus
|
||||
direction = normal if plus > 0 else neg
|
||||
lines.append(f"{tool_var} = scad.extrude_rsolid(profile={face_var}, "
|
||||
f"direction={_vec(direction)}, distance={_fmt(distance)})")
|
||||
else:
|
||||
raise UnsupportedForm("zero-extent extrude")
|
||||
role = "build" if self.first_solid else _role(feature.operation)
|
||||
slug = f"{feature.kind.lower()}-{index + 1}"
|
||||
out = [f" # ---- feature: {slug} ({role}, profile=geometry) ----"]
|
||||
else:
|
||||
if feature.angle_two > 1e-9:
|
||||
raise UnsupportedForm("two-sided revolve")
|
||||
origin, axis_dir = _axis_line(feature, self.features)
|
||||
lines = emitter.face_lines(face_var)
|
||||
lines.append(f"{tool_var} = scad.revolve_rsolid(profile={face_var}, "
|
||||
f"axis={_vec(axis_dir)}, angle={_fmt(feature.angle_one)}, "
|
||||
f"origin={_vec(origin)})")
|
||||
role = "build" if self.first_solid else _role(feature.operation)
|
||||
slug = f"{feature.kind.lower()}-{index + 1}"
|
||||
out = [f" # ---- feature: {slug} ({role}, profile=geometry) ----"]
|
||||
out.extend(f" {line}" for line in emitter.lines)
|
||||
out.extend(f" {line}" for line in lines)
|
||||
out.extend(self._boolean_lines(feature.operation, tool_var))
|
||||
return out
|
||||
|
||||
def _boolean_lines(self, operation: str, tool_var: str) -> List[str]:
|
||||
out: List[str] = []
|
||||
if self.first_solid:
|
||||
out.append(f" bodies = [{tool_var}]")
|
||||
self.first_solid = False
|
||||
return out
|
||||
role = _role(operation)
|
||||
if role == "add":
|
||||
out.append(" _merged = False")
|
||||
out.append(" _next = []")
|
||||
out.append(" for _b in bodies:")
|
||||
out.append(" try:")
|
||||
out.append(f" _next.append(scad.union_rsolid(_b, [{tool_var}]))")
|
||||
out.append(" _merged = True")
|
||||
out.append(" except Exception:")
|
||||
out.append(" _next.append(_b)")
|
||||
out.append(" bodies = _next")
|
||||
out.append(" if not _merged:")
|
||||
out.append(f" bodies.extend([{tool_var}])")
|
||||
elif role == "subtract":
|
||||
out.append(f" bodies = [scad.cut_rsolid(_b, [{tool_var}]) for _b in bodies]")
|
||||
elif role == "intersect":
|
||||
out.append(f" bodies = [scad.intersect_rsolid(_b, {tool_var}) for _b in bodies]")
|
||||
else:
|
||||
out.append(f" bodies.extend([{tool_var}])")
|
||||
return out
|
||||
|
||||
def _emit_hole(self, index: int, feature: HoleFeature) -> List[str]:
|
||||
if feature.bottom_mode != "OffsetLimit":
|
||||
raise UnsupportedForm(f"hole bottom {feature.bottom_mode}")
|
||||
emitter = SketchEmitter(f"f{index}", feature.sketch)
|
||||
pid = emitter.point(float(feature.point_pos[0]), float(feature.point_pos[1]))
|
||||
emitter.lines.append(f"s = scad.add_circle_rsketch(sketch=s, entity_id='f{index}_e0', center={pid!r}, radius={_fmt(feature.radius)})")
|
||||
face_var = f"f{index}_face"
|
||||
tool_var = f"f{index}_tool"
|
||||
normal = feature.sketch.plane_normal
|
||||
lines = emitter.face_lines(face_var)
|
||||
lines.append(f"{tool_var} = scad.extrude_rsolid(profile={face_var}, "
|
||||
f"direction={_vec(normal)}, distance={_fmt(feature.depth)})")
|
||||
out = [f" # ---- feature: hole-{index + 1} (subtract, profile=geometry) ----"]
|
||||
out.extend(f" {line}" for line in emitter.lines)
|
||||
out.extend(f" {line}" for line in lines)
|
||||
out.extend(self._boolean_lines("CutFeatureOperation", tool_var))
|
||||
return out
|
||||
|
||||
def _emit_finish(self, index: int, feature: FinishFeature) -> List[str]:
|
||||
if self.first_solid:
|
||||
raise UnsupportedForm("modify feature before any solid feature")
|
||||
registry = wsel.FeatureRegistry(self.features)
|
||||
slug = f"{feature.kind.lower()}-{index + 1}"
|
||||
out = [f" # ---- feature: {slug} (modify, profile=geometry) ----"]
|
||||
out.append(" body = _merge_bodies(bodies)")
|
||||
if feature.kind in ("Chamfer", "Fillet"):
|
||||
for i, edge_desc in enumerate(self._edge_descs(feature, registry)):
|
||||
var = f"sel{i}"
|
||||
out.extend(f" {line}" for line in
|
||||
wsel.edge_predicate_lines(var, edge_desc, " "))
|
||||
if feature.kind == "Fillet":
|
||||
out.append(f" body = scad.fillet_rsolid(solid=body, edges={var}.exactly(1), "
|
||||
f"radius={_fmt(feature.params['radius'])})")
|
||||
else:
|
||||
if edge_desc.reference_normal is None:
|
||||
raise wsel.UnsupportedSelect("chamfer without anchor face")
|
||||
out.append(f" body = scad.chamfer_rsolid(solid=body, edges={var}.exactly(1), "
|
||||
f"distance={_fmt(feature.params['length1'])}, "
|
||||
f"angle={_fmt(math.degrees(math.atan2(feature.params['angle_or_length2'], feature.params['length1'])))}, "
|
||||
f"reference_direction={_vec(edge_desc.reference_normal)})")
|
||||
elif feature.kind == "Shell":
|
||||
# FTC shell maps the internal thickness only; the dataset's
|
||||
# external thickness (CATIA ExternalThickness) has no mapping
|
||||
if feature.params.get('second_thickness', 0.0) > 1e-9:
|
||||
raise UnsupportedForm("non-zero external shell thickness")
|
||||
if len(feature.select_list) != 1:
|
||||
raise wsel.UnsupportedSelect("multi-face shell")
|
||||
_, face_desc, _ = wsel.resolve_face(feature.select_list[0], registry)
|
||||
out.extend(f" {line}" for line in
|
||||
wsel.face_predicate_lines("sel", face_desc, " "))
|
||||
out.append(" body = scad.shell_rsolid(solid=body, faces_to_remove=sel.exactly(1), "
|
||||
f"thickness={_fmt(feature.params['thickness'])})")
|
||||
else:
|
||||
raise UnsupportedForm(feature.kind)
|
||||
out.append(" bodies = [body]")
|
||||
return out
|
||||
|
||||
def _edge_descs(self, feature: FinishFeature, registry: wsel.FeatureRegistry
|
||||
) -> List[wsel.EdgeDesc]:
|
||||
descs: List[wsel.EdgeDesc] = []
|
||||
for select in feature.select_list:
|
||||
if select.select_type == "Edge":
|
||||
descs.append(wsel.resolve_edge(select, registry))
|
||||
elif select.select_type == "Face" and not select.operation_list \
|
||||
and select.body_type == "Pad" and select.no in (1, 2):
|
||||
# a cap face: its single circular boundary
|
||||
source = registry.lookup(select)
|
||||
if not isinstance(source, ExtrudeFeature):
|
||||
raise wsel.UnsupportedSelect(f"cap edge of {select.body_type}")
|
||||
descs.append(wsel.cap_boundary_edge(source, select.no))
|
||||
elif select.select_type == "Face" and select.no == 0:
|
||||
# a lateral wall face: every edge of that wall
|
||||
descs.extend(wsel.lateral_boundary_edges(select, registry))
|
||||
else:
|
||||
raise wsel.UnsupportedSelect(f"{feature.kind} on {select.select_type}"
|
||||
f"/{select.body_type}#{select.no}")
|
||||
return descs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
|
||||
|
||||
def translate_features(features: List[Any], uid: str) -> str:
|
||||
for feature in features:
|
||||
feature._history = features
|
||||
return Translator(features, uid).translate()
|
||||
|
||||
|
||||
def main(argv: Optional[Sequence[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("h5_file", type=Path)
|
||||
parser.add_argument("--out", type=Path, default=None)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
uid = f"{args.h5_file.parent.name}/{args.h5_file.stem}"
|
||||
features = w.load_h5(args.h5_file)
|
||||
source = translate_features(features, uid)
|
||||
out_path = args.out or args.h5_file.with_suffix(".ftc.py")
|
||||
out_path.write_text(source)
|
||||
print(f"wrote {out_path} ({source.count(chr(10))} lines)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sampling validation: translate WHUCAD h5 → FTC, execute, reconcile volume
|
||||
against the packaged BRep truth (sampled download from the official mirror).
|
||||
|
||||
Because the released vectors are unit-cube normalized (absolute scale is not
|
||||
in the data), the FTC model and the BRep truth are compared shape-wise: the
|
||||
built solid is rescaled by the bbox-diagonal ratio before the volume check.
|
||||
|
||||
Usage:
|
||||
.venv/bin/python tools/research/whucad/whucad_validate.py \
|
||||
--vec-dir .../WHUCAD/data/vec/0000 --count 40 --stride 37 \
|
||||
[--truth-dir /tmp/whucad_truth] [--report out/whucad_validate.json]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
_TOOLS = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(_TOOLS))
|
||||
|
||||
import whucad_vec as wvec # noqa: E402
|
||||
from whucad_to_ftc import translate_features # noqa: E402
|
||||
|
||||
_TOLERANCE = 2e-2 # relative volume error (256-level quantization ≈ 0.4%/dim)
|
||||
|
||||
_TRUTH_URL = "https://gitee.com/fred926/whucad-brep/raw/master/Brep/{folder}/{uid}.stp"
|
||||
|
||||
|
||||
def _fetch_truth(uid: str, truth_dir: Path) -> Optional[Path]:
|
||||
folder = uid[:4]
|
||||
path = truth_dir / folder / f"{uid}.stp"
|
||||
if path.exists() and path.stat().st_size > 0:
|
||||
return path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
url = _TRUTH_URL.format(folder=folder, uid=uid)
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=60) as response, path.open("wb") as handle:
|
||||
handle.write(response.read())
|
||||
return path
|
||||
except Exception:
|
||||
path.unlink(missing_ok=True)
|
||||
return None
|
||||
|
||||
|
||||
def _bbox_diagonal(solid) -> float:
|
||||
from OCP.Bnd import Bnd_Box
|
||||
from OCP.BRepBndLib import BRepBndLib
|
||||
|
||||
box = Bnd_Box()
|
||||
box.SetGap(0.0)
|
||||
# optimal + no triangulation: the default Add uses surface control
|
||||
# points (and triangulation boxes overshoot) — curved faces come back
|
||||
# ~7% loose, corrupting the scale correction
|
||||
BRepBndLib.AddOptimal_s(solid, box, False, False)
|
||||
xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
|
||||
return math.dist((xmin, ymin, zmin), (xmax, ymax, zmax))
|
||||
|
||||
|
||||
def _solid_volume(shape) -> float:
|
||||
from OCP.BRepGProp import BRepGProp
|
||||
from OCP.GProp import GProp_GProps
|
||||
|
||||
props = GProp_GProps()
|
||||
BRepGProp.VolumeProperties_s(shape, props)
|
||||
return float(props.Mass())
|
||||
|
||||
|
||||
def _step_volume(path: Path) -> Optional[float]:
|
||||
from OCP.IFSelect import IFSelect_RetDone
|
||||
from OCP.STEPControl import STEPControl_Reader
|
||||
from OCP.TopAbs import TopAbs_SOLID
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
|
||||
reader = STEPControl_Reader()
|
||||
try:
|
||||
if reader.ReadFile(str(path)) != IFSelect_RetDone:
|
||||
return None
|
||||
reader.TransferRoots()
|
||||
shape = reader.OneShape()
|
||||
except Exception:
|
||||
return None
|
||||
volume = 0.0
|
||||
explorer = TopExp_Explorer(shape, TopAbs_SOLID)
|
||||
count = 0
|
||||
while explorer.More():
|
||||
volume += _solid_volume(explorer.Current())
|
||||
count += 1
|
||||
explorer.Next()
|
||||
return volume if volume > 0 and count == 1 else (volume if volume > 0 else None)
|
||||
|
||||
|
||||
def _build_volume(source: str, case_dir: Path, tag: str) -> Any:
|
||||
case_dir.mkdir(parents=True, exist_ok=True)
|
||||
module_path = case_dir / f"case_{tag}.py"
|
||||
module_path.write_text(source)
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(module_path.stem, module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
result = module.build()
|
||||
|
||||
solids = []
|
||||
# @scad.part may re-execute the source in its own namespace, in which
|
||||
# case module.BODIES is not written — fall back to the returned Part
|
||||
bodies = getattr(module, "BODIES", None)
|
||||
if bodies:
|
||||
solids = [b.wrapped for b in bodies]
|
||||
else:
|
||||
part = getattr(result, "part", result)
|
||||
body = getattr(part, "body", part)
|
||||
solid = getattr(body, "wrapped", None)
|
||||
if solid is None:
|
||||
return _ErrorVolume("build returned no solid")
|
||||
solids = [solid]
|
||||
volumes = [_solid_volume(s) for s in solids]
|
||||
volume = sum(volumes)
|
||||
if volume <= 0:
|
||||
return _ErrorVolume("empty build")
|
||||
return _Built(volume, _bbox_diagonal(solids[0]), len(solids))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
return _ErrorVolume(str(exc)[:300])
|
||||
finally:
|
||||
module_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
class _ErrorVolume(str):
|
||||
def __new__(cls, message: str) -> "_ErrorVolume":
|
||||
return super().__new__(cls, message)
|
||||
|
||||
|
||||
class _Built:
|
||||
def __init__(self, volume: float, diagonal: float, n_bodies: int):
|
||||
self.volume = volume
|
||||
self.diagonal = diagonal
|
||||
self.n_bodies = n_bodies
|
||||
|
||||
|
||||
def evaluate_case(payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
uid = payload["uid"]
|
||||
entry: Dict[str, Any] = {"uid": uid}
|
||||
try:
|
||||
features = wvec.decode_vec(payload["vec"], is_numerical=True)
|
||||
source = translate_features(features, f"{uid[:4]}/{uid}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
entry.update(status="translate_error", error=str(exc)[:300])
|
||||
return entry
|
||||
entry["feature_count"] = len(features)
|
||||
entry["skipped_features"] = source.count("# step ")
|
||||
built = _build_volume(source, Path(payload["case_dir"]), uid)
|
||||
if isinstance(built, _ErrorVolume):
|
||||
entry.update(status="build_error", error=str(built)[:300])
|
||||
return entry
|
||||
entry["built_volume"] = built.volume
|
||||
entry["built_diagonal"] = built.diagonal
|
||||
entry["n_bodies"] = built.n_bodies
|
||||
truth = _step_volume(Path(payload["truth_path"]))
|
||||
if truth is None:
|
||||
entry.update(status="step_missing")
|
||||
return entry
|
||||
entry["truth_volume"] = truth
|
||||
truth_diag = _step_diagonal(Path(payload["truth_path"]))
|
||||
scale = truth_diag / built.diagonal if built.diagonal > 0 and truth_diag else None
|
||||
if scale is None:
|
||||
entry.update(status="scale_unknown")
|
||||
return entry
|
||||
entry["scale"] = scale
|
||||
relative = abs(built.volume * scale ** 3 - truth) / truth
|
||||
entry["rel_error"] = relative
|
||||
entry["status"] = "pass" if relative <= _TOLERANCE else "volume_mismatch"
|
||||
return entry
|
||||
|
||||
|
||||
def _step_diagonal(path: Path) -> Optional[float]:
|
||||
from OCP.Bnd import Bnd_Box
|
||||
from OCP.BRepBndLib import BRepBndLib
|
||||
from OCP.IFSelect import IFSelect_RetDone
|
||||
from OCP.STEPControl import STEPControl_Reader
|
||||
|
||||
reader = STEPControl_Reader()
|
||||
try:
|
||||
if reader.ReadFile(str(path)) != IFSelect_RetDone:
|
||||
return None
|
||||
reader.TransferRoots()
|
||||
shape = reader.OneShape()
|
||||
box = Bnd_Box()
|
||||
box.SetGap(0.0)
|
||||
BRepBndLib.AddOptimal_s(shape, box, False, False)
|
||||
xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
|
||||
return math.dist((xmin, ymin, zmin), (xmax, ymax, zmax))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vec-dir", type=Path, required=True)
|
||||
parser.add_argument("--count", type=int, default=40)
|
||||
parser.add_argument("--stride", type=int, default=37)
|
||||
parser.add_argument("--uids", type=str, default="")
|
||||
parser.add_argument("--truth-dir", type=Path,
|
||||
default=_TOOLS / "out" / "truth")
|
||||
parser.add_argument("--report", type=Path, default=None)
|
||||
parser.add_argument("--workers", type=int, default=4)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
paths = sorted(args.vec_dir.glob("*.h5"))
|
||||
if args.uids:
|
||||
wanted = set(args.uids.split(","))
|
||||
paths = [p for p in paths if p.stem in wanted]
|
||||
else:
|
||||
paths = paths[:: args.stride][: args.count]
|
||||
|
||||
payloads = []
|
||||
skipped = []
|
||||
for path in paths:
|
||||
uid = path.stem
|
||||
truth = _fetch_truth(uid, args.truth_dir)
|
||||
if truth is None:
|
||||
skipped.append(uid)
|
||||
continue
|
||||
import h5py
|
||||
|
||||
with h5py.File(path, "r") as fp:
|
||||
vec = fp["vec"][:].astype(int)
|
||||
payloads.append({"uid": uid, "vec": vec, "truth_path": str(truth),
|
||||
"case_dir": str(_TOOLS / "out" / "_cases")})
|
||||
|
||||
print(f"evaluating {len(payloads)} cases ({len(skipped)} truth downloads failed)")
|
||||
results: List[Dict[str, Any]] = []
|
||||
with ProcessPoolExecutor(max_workers=args.workers) as pool:
|
||||
for result in pool.map(evaluate_case, payloads):
|
||||
status = result.get("status")
|
||||
extra = (f" rel={result.get('rel_error'):.3e}"
|
||||
if status in {"pass", "volume_mismatch"}
|
||||
else f" err={str(result.get('error', ''))[:110]}")
|
||||
print(f" {result['uid']}: {status}{extra}")
|
||||
results.append(result)
|
||||
|
||||
counts: Dict[str, int] = {}
|
||||
for result in results:
|
||||
counts[result["status"]] = counts.get(result["status"], 0) + 1
|
||||
print("summary:", dict(sorted(counts.items())))
|
||||
report = args.report or _TOOLS / "out" / "whucad_validate.json"
|
||||
report.parent.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(json.dumps({"counts": counts, "results": results}, indent=2))
|
||||
print(f"wrote {report}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,968 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Decode WHUCAD vector sequences (h5 `vec` arrays) into feature objects.
|
||||
|
||||
Self-contained port of fazhihe/WHUCAD ``cadlib`` decode paths (numpy only —
|
||||
no torch, no matplotlib). The decoded model is in the dataset's normalized
|
||||
units (the released vectors are quantized to 256 levels after unit-cube
|
||||
normalization); recovering the original absolute scale is impossible from the
|
||||
vector alone, so downstream FTC output is scale-normalized and validation
|
||||
compares shape, not absolute volume.
|
||||
|
||||
Conventions (verified against WHUCAD's own CATIA rebuild code):
|
||||
- quantized values: coordinates/lengths centered (v/256*2 - 1 → [-1, 1]);
|
||||
sketch size (v/256*2 → [0, 2]); angles full-range (v/256*2π or v/255*360);
|
||||
enum indices (extent type, operation, select/body type) NOT scaled.
|
||||
- profile 2D → real: denormalize(sketch_size): (p - 128) * size / 95,
|
||||
with 95 = 256/2 * NORM_FACTOR - 1 (the offset reverses normalize()'s
|
||||
centering of the profile start point at (128, 128)).
|
||||
- 3D assembly: origin = sketch_pos; p3 = origin + x_axis * px + y_axis * py.
|
||||
- revolve axis: OriginElements no=1 → sketch x axis (H), else y axis (V).
|
||||
|
||||
The decoder ONLY decodes — translation decisions live in whucad_to_ftc.py,
|
||||
audit/acceptance in whucad_profile.py / whucad_validate.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# macro constants (verbatim from cadlib/macro.py)
|
||||
|
||||
ALL_COMMANDS = ['Line', 'Arc', 'Circle', 'Spline', 'SCP', 'EOS', 'SOL', 'Ext', 'Rev', 'Pocket',
|
||||
'Groove', 'Shell', 'Chamfer', 'Fillet', 'Draft', 'Mirror', 'Hole', 'Topo',
|
||||
'Select', 'MirrorStart', 'NoSharedIncluded', 'NoSharedIncludedEnd',
|
||||
'AllOrientedIncluded1', 'AllOrientedIncluded2', 'AllOrientedIncludedEnd',
|
||||
'AllPartiallySharedIncluded', 'AllPartiallySharedIncludedEnd']
|
||||
LINE_IDX = ALL_COMMANDS.index('Line')
|
||||
ARC_IDX = ALL_COMMANDS.index('Arc')
|
||||
CIRCLE_IDX = ALL_COMMANDS.index('Circle')
|
||||
SPLINE_IDX = ALL_COMMANDS.index('Spline')
|
||||
SCP_IDX = ALL_COMMANDS.index('SCP')
|
||||
EOS_IDX = ALL_COMMANDS.index('EOS')
|
||||
SOL_IDX = ALL_COMMANDS.index('SOL')
|
||||
EXT_IDX = ALL_COMMANDS.index('Ext')
|
||||
REV_IDX = ALL_COMMANDS.index('Rev')
|
||||
POCKET_IDX = ALL_COMMANDS.index('Pocket')
|
||||
GROOVE_IDX = ALL_COMMANDS.index('Groove')
|
||||
SHELL_IDX = ALL_COMMANDS.index('Shell')
|
||||
CHAMFER_IDX = ALL_COMMANDS.index('Chamfer')
|
||||
FILLET_IDX = ALL_COMMANDS.index('Fillet')
|
||||
DRAFT_IDX = ALL_COMMANDS.index('Draft')
|
||||
MIRROR_IDX = ALL_COMMANDS.index('Mirror')
|
||||
HOLE_IDX = ALL_COMMANDS.index('Hole')
|
||||
TOPO_IDX = ALL_COMMANDS.index('Topo')
|
||||
SELECT_IDX = ALL_COMMANDS.index('Select')
|
||||
MIRROR_START_IDX = ALL_COMMANDS.index('MirrorStart')
|
||||
|
||||
BOOLEAN_OPERATIONS = ["AddFeatureOperation", "CutFeatureOperation", "IntersectFeatureOperation"]
|
||||
EXTENT_TYPE = ["OffsetLimit", "UpToNextLimit", "UpToLastLimit", "UpToPlaneLimit",
|
||||
"UpToSurfaceLimit", "UpThruNextLimit"]
|
||||
SELECT_TYPE = ["Wire", "Face", "Edge", "Multiply_Face", "Sub_Face"]
|
||||
BODY_TYPE = ["None", "OriginElements", "Sketch", "Pad", "Shaft", 'Pocket', "Add", "Remove",
|
||||
"Intersect", "Shell", "Chamfer", "EdgeFillet", "Mirror", "Hole"]
|
||||
|
||||
N_ARGS_SKETCH = 5
|
||||
N_ARGS_PLANE = 3
|
||||
N_ARGS_TRANS = 4
|
||||
N_ARGS_BODY_PARAM = 7
|
||||
N_ARGS_FINISH_PARAM = 9
|
||||
N_ARGS_SELECT_PARAM = 4
|
||||
N_ARGS_EXT = N_ARGS_PLANE + N_ARGS_TRANS + N_ARGS_BODY_PARAM
|
||||
N_ARGS = N_ARGS_SKETCH + N_ARGS_EXT + N_ARGS_FINISH_PARAM + N_ARGS_SELECT_PARAM
|
||||
|
||||
ARGS_N = 256
|
||||
NORM_FACTOR = 0.75
|
||||
# normalize(size=256) maps the profile bbox to (128 * NORM_FACTOR - 1)
|
||||
DENORM_SCALE_DENOM = ARGS_N / 2 * NORM_FACTOR - 1 # 95.0
|
||||
|
||||
|
||||
def _denorm_centered(v: float, n: int = ARGS_N) -> float:
|
||||
return v / n * 2.0 - 1.0
|
||||
|
||||
|
||||
def _denorm_size(v: float, n: int = ARGS_N) -> float:
|
||||
return v / n * 2.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# geometry helpers (port of cadlib/Geometry_utils.py, the decode-relevant part)
|
||||
|
||||
|
||||
def polar2cartesian(vec: Sequence[float]) -> np.ndarray:
|
||||
r = 1.0 if len(vec) == 2 else vec[2]
|
||||
theta, phi = vec[0], vec[1]
|
||||
return np.array([r * math.sin(theta) * math.cos(phi),
|
||||
r * math.sin(theta) * math.sin(phi),
|
||||
r * math.cos(theta)])
|
||||
|
||||
|
||||
def rotate_by_y(vec: Sequence[float], theta: float) -> np.ndarray:
|
||||
v = np.asarray(vec, dtype=float)
|
||||
return np.array([v[0] * math.cos(theta) + v[2] * math.sin(theta),
|
||||
v[1],
|
||||
-v[0] * math.sin(theta) + v[2] * math.cos(theta)])
|
||||
|
||||
|
||||
def rotate_by_z(vec: Sequence[float], phi: float) -> np.ndarray:
|
||||
v = np.asarray(vec, dtype=float)
|
||||
return np.array([v[0] * math.cos(phi) - v[1] * math.sin(phi),
|
||||
v[0] * math.sin(phi) + v[1] * math.cos(phi),
|
||||
v[2]])
|
||||
|
||||
|
||||
def polar_parameterization_inverse(theta: float, phi: float, gamma: float):
|
||||
normal_3d = polar2cartesian([theta, phi])
|
||||
ref_x = rotate_by_z(rotate_by_y(np.array([1.0, 0.0, 0.0]), theta), phi)
|
||||
ref_y = np.cross(normal_3d, ref_x)
|
||||
x_axis_3d = ref_x * math.cos(gamma) + ref_y * math.sin(gamma)
|
||||
return normal_3d, x_axis_3d
|
||||
|
||||
|
||||
def vec2arc(pos: Sequence[float], center: Sequence[float]) -> float:
|
||||
"""Angle (0~2pi) of vector (pos - center) against the x axis."""
|
||||
vec = np.array([pos[0] - center[0], pos[1] - center[1]])
|
||||
length = np.linalg.norm(vec)
|
||||
if length == 0:
|
||||
return 0.0
|
||||
cos_x = vec[0] / length
|
||||
cos_y = vec[1] / length
|
||||
if cos_y > 0:
|
||||
return math.acos(max(-1.0, min(1.0, cos_x)))
|
||||
if cos_y < 0:
|
||||
return math.pi * 2 - math.acos(max(-1.0, min(1.0, cos_x)))
|
||||
return 0.0 if cos_x >= 0 else math.pi
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# decoded curve model (quantized or real depending on stage; fields as in cadlib)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
start_point: np.ndarray
|
||||
end_point: np.ndarray
|
||||
|
||||
def reverse(self) -> None:
|
||||
self.start_point, self.end_point = self.end_point, self.start_point
|
||||
|
||||
def scale(self, s: float) -> None:
|
||||
self.start_point = self.start_point * s
|
||||
self.end_point = self.end_point * s
|
||||
|
||||
def shift(self, d: np.ndarray) -> None:
|
||||
self.start_point = self.start_point + d
|
||||
self.end_point = self.end_point + d
|
||||
|
||||
|
||||
@dataclass
|
||||
class Circle:
|
||||
center: np.ndarray
|
||||
radius: float
|
||||
|
||||
@property
|
||||
def start_point(self) -> np.ndarray:
|
||||
return np.array([self.center[0] - self.radius, self.center[1]])
|
||||
|
||||
@property
|
||||
def end_point(self) -> np.ndarray:
|
||||
return np.array([self.center[0] + self.radius, self.center[1]])
|
||||
|
||||
def scale(self, s: float) -> None:
|
||||
self.center = self.center * s
|
||||
self.radius = abs(self.radius * s)
|
||||
|
||||
def shift(self, d: np.ndarray) -> None:
|
||||
self.center = self.center + d
|
||||
|
||||
|
||||
@dataclass
|
||||
class Arc:
|
||||
center: np.ndarray
|
||||
radius: float
|
||||
start_arc: float
|
||||
end_arc: float
|
||||
mid_arc: float
|
||||
|
||||
@property
|
||||
def mid_point(self) -> np.ndarray:
|
||||
return self.center + self.radius * np.array([math.cos(self.mid_arc), math.sin(self.mid_arc)])
|
||||
|
||||
@property
|
||||
def start_point(self) -> np.ndarray:
|
||||
return np.array([self.center[0] + math.cos(self.start_arc) * self.radius,
|
||||
self.center[1] + math.sin(self.start_arc) * self.radius])
|
||||
|
||||
@property
|
||||
def end_point(self) -> np.ndarray:
|
||||
return np.array([self.center[0] + math.cos(self.end_arc) * self.radius,
|
||||
self.center[1] + math.sin(self.end_arc) * self.radius])
|
||||
|
||||
def reverse(self) -> None:
|
||||
self.start_arc, self.end_arc = self.end_arc, self.start_arc
|
||||
|
||||
def scale(self, s: float) -> None:
|
||||
self.center = self.center * s
|
||||
self.radius = abs(self.radius * s)
|
||||
|
||||
def shift(self, d: np.ndarray) -> None:
|
||||
self.center = self.center + d
|
||||
|
||||
|
||||
@dataclass
|
||||
class Spline:
|
||||
point_list: List[np.ndarray]
|
||||
|
||||
def reverse(self) -> None:
|
||||
self.point_list = list(reversed(self.point_list))
|
||||
|
||||
@property
|
||||
def start_point(self) -> np.ndarray:
|
||||
return self.point_list[0]
|
||||
|
||||
@property
|
||||
def end_point(self) -> np.ndarray:
|
||||
return self.point_list[-1]
|
||||
|
||||
def scale(self, s: float) -> None:
|
||||
self.point_list = [p * s for p in self.point_list]
|
||||
|
||||
def shift(self, d: np.ndarray) -> None:
|
||||
self.point_list = [p + d for p in self.point_list]
|
||||
|
||||
|
||||
Curve = Any # Line | Circle | Arc | Spline
|
||||
|
||||
|
||||
def _line_from_vector(vec: np.ndarray, start_point: np.ndarray) -> Line:
|
||||
return Line(np.asarray(start_point, dtype=float), np.asarray(vec[1:3], dtype=float))
|
||||
|
||||
|
||||
def _circle_from_vector(vec: np.ndarray) -> Circle:
|
||||
return Circle(np.asarray(vec[1:3], dtype=float), float(vec[5]))
|
||||
|
||||
|
||||
def _arc_from_vector(vec: np.ndarray, start_point: np.ndarray) -> Optional[Arc]:
|
||||
"""vec: single command row (1 + N_ARGS)."""
|
||||
end_point = np.asarray(vec[1:3], dtype=float)
|
||||
sweep_angle = float(vec[3]) / ARGS_N * 2.0 * math.pi
|
||||
clock_sign = int(vec[4])
|
||||
s2e = end_point - start_point
|
||||
if np.linalg.norm(s2e) == 0:
|
||||
return None
|
||||
radius = (np.linalg.norm(s2e) / 2.0) / math.sin(sweep_angle / 2.0)
|
||||
s2e_mid = (start_point + end_point) / 2.0
|
||||
vertical = np.cross(s2e, [0.0, 0.0, 1.0])[:2]
|
||||
vertical = vertical / np.linalg.norm(vertical)
|
||||
if clock_sign == 0:
|
||||
vertical = -vertical
|
||||
center_point = s2e_mid - vertical * (radius * math.cos(sweep_angle / 2.0))
|
||||
start_arc = vec2arc(start_point, center_point)
|
||||
end_arc = vec2arc(end_point, center_point)
|
||||
if clock_sign == 0:
|
||||
if end_arc < start_arc:
|
||||
mid_arc = (start_arc + end_arc) / 2.0
|
||||
else:
|
||||
mid_arc = (start_arc + end_arc + 2.0 * math.pi) / 2.0
|
||||
else:
|
||||
if start_arc < end_arc:
|
||||
mid_arc = (start_arc + end_arc) / 2.0
|
||||
else:
|
||||
mid_arc = (start_arc + end_arc + 2.0 * math.pi) / 2.0
|
||||
return Arc(center_point, radius, start_arc, end_arc, mid_arc)
|
||||
|
||||
|
||||
def _spline_from_vector(vec: np.ndarray, start_point: np.ndarray) -> Spline:
|
||||
point_list = [np.asarray(start_point, dtype=float)]
|
||||
for i in range(vec.shape[0]):
|
||||
point_list.append(np.asarray(vec[i][1:3], dtype=float))
|
||||
return Spline(point_list)
|
||||
|
||||
|
||||
def _curve_from_vector(vec: np.ndarray, start_point: np.ndarray) -> Optional[Curve]:
|
||||
"""Reconstruct one curve; illed arcs degrade to lines (as in their builder).
|
||||
|
||||
``vec`` is either a single command row (1-D) or a Spline row block (2-D).
|
||||
"""
|
||||
kind = int(vec[0][0]) if vec.ndim > 1 else int(vec[0])
|
||||
if kind == LINE_IDX:
|
||||
return _line_from_vector(vec, start_point)
|
||||
if kind == CIRCLE_IDX:
|
||||
return _circle_from_vector(vec)
|
||||
if kind == ARC_IDX:
|
||||
arc = _arc_from_vector(vec, start_point)
|
||||
if arc is None:
|
||||
return _line_from_vector(vec, start_point)
|
||||
return arc
|
||||
if kind == SPLINE_IDX:
|
||||
return _spline_from_vector(vec, start_point)
|
||||
raise ValueError(f"unsupported curve command {kind}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# loop / profile (quantized stage)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Loop:
|
||||
curves: List[Curve]
|
||||
|
||||
@property
|
||||
def start_point(self) -> np.ndarray:
|
||||
return self.curves[0].start_point
|
||||
|
||||
@property
|
||||
def end_point(self) -> np.ndarray:
|
||||
return self.curves[-1].end_point
|
||||
|
||||
@property
|
||||
def bbox(self) -> np.ndarray:
|
||||
boxes = []
|
||||
for c in self.curves:
|
||||
boxes.append(_curve_bbox(c))
|
||||
pts = np.concatenate(boxes, axis=0)
|
||||
return np.stack([pts.min(axis=0), pts.max(axis=0)], axis=0)
|
||||
|
||||
@property
|
||||
def bbox_size(self) -> float:
|
||||
lo, hi = self.bbox[0], self.bbox[1]
|
||||
return float(np.max(np.abs(np.concatenate([hi - self.start_point, lo - self.start_point]))))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Profile:
|
||||
loops: List[Loop]
|
||||
|
||||
@property
|
||||
def start_point(self) -> np.ndarray:
|
||||
return self.loops[0].start_point
|
||||
|
||||
@property
|
||||
def bbox_size(self) -> float:
|
||||
return max(loop.bbox_size for loop in self.loops)
|
||||
|
||||
|
||||
def _curve_bbox(c: Curve) -> np.ndarray:
|
||||
if isinstance(c, Circle):
|
||||
return np.stack([c.center - c.radius, c.center + c.radius], axis=0)
|
||||
if isinstance(c, Arc):
|
||||
pts = [c.start_point, c.end_point]
|
||||
a0, a1 = c.start_arc, c.end_arc
|
||||
span = (a1 - a0) % (2.0 * math.pi)
|
||||
for axis_angle, delta in ((0.0, 0.0), (math.pi / 2, 0.0), (math.pi, 0.0), (3 * math.pi / 2, 0.0)):
|
||||
if ((axis_angle - a0) % (2.0 * math.pi)) <= span:
|
||||
pts.append(c.center + c.radius * np.array([math.cos(axis_angle), math.sin(axis_angle)]))
|
||||
arr = np.stack(pts, axis=0)
|
||||
return np.stack([arr.min(axis=0), arr.max(axis=0)], axis=0)
|
||||
if isinstance(c, Line):
|
||||
return np.stack([c.start_point, c.end_point], axis=0)
|
||||
return np.stack([np.array(p, dtype=float) for p in c.point_list], axis=0)
|
||||
|
||||
|
||||
def _loop_from_vector(vec: np.ndarray, start_point: Optional[np.ndarray] = None) -> Loop:
|
||||
if start_point is None:
|
||||
for i in range(vec.shape[0]):
|
||||
if vec[i][0] == EOS_IDX:
|
||||
start_point = vec[i - 1][1:3]
|
||||
break
|
||||
curves: List[Curve] = []
|
||||
i = 0
|
||||
while i < vec.shape[0]:
|
||||
kind = vec[i][0]
|
||||
if kind == SOL_IDX:
|
||||
i += 1
|
||||
continue
|
||||
if kind == EOS_IDX:
|
||||
break
|
||||
if kind == SPLINE_IDX:
|
||||
j = i + 1
|
||||
while j < vec.shape[0] and vec[j][0] == SCP_IDX:
|
||||
j += 1
|
||||
curve = _curve_from_vector(vec[i:j], start_point)
|
||||
start_point = curve.end_point
|
||||
i = j - 1
|
||||
else:
|
||||
curve = _curve_from_vector(vec[i], start_point)
|
||||
start_point = vec[i][1:3]
|
||||
curves.append(curve)
|
||||
i += 1
|
||||
return Loop(curves)
|
||||
|
||||
|
||||
def _profile_from_vector(vec: np.ndarray) -> Profile:
|
||||
loops: List[Loop] = []
|
||||
command = vec[:, 0]
|
||||
end_idx = command.tolist().index(EOS_IDX)
|
||||
indices = np.where(command[:end_idx] == SOL_IDX)[0].tolist() + [end_idx]
|
||||
for i in range(len(indices) - 1):
|
||||
loop_vec = vec[indices[i]:indices[i + 1]]
|
||||
loop_vec = np.concatenate([loop_vec, np.array([EOS_IDX, *([-1] * N_ARGS)])[np.newaxis]], axis=0)
|
||||
if loop_vec[0][0] == SOL_IDX and loop_vec[1][0] not in (SOL_IDX, EOS_IDX):
|
||||
loops.append(_loop_from_vector(loop_vec))
|
||||
return Profile(loops)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# coord system
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoordSystem:
|
||||
origin: np.ndarray
|
||||
theta: float
|
||||
phi: float
|
||||
gamma: float
|
||||
|
||||
@staticmethod
|
||||
def from_quantized(vec6: np.ndarray) -> "CoordSystem":
|
||||
"""(theta, phi, gamma, ox, oy, oz) quantized → real."""
|
||||
theta, phi, gamma = (_denorm_centered(float(v)) * math.pi for v in vec6[:3])
|
||||
origin = np.array([_denorm_centered(float(v)) for v in vec6[3:6]])
|
||||
return CoordSystem(origin, theta, phi, gamma)
|
||||
|
||||
@property
|
||||
def normal(self) -> np.ndarray:
|
||||
return polar_parameterization_inverse(self.theta, self.phi, self.gamma)[0]
|
||||
|
||||
@property
|
||||
def x_axis(self) -> np.ndarray:
|
||||
return polar_parameterization_inverse(self.theta, self.phi, self.gamma)[1]
|
||||
|
||||
@property
|
||||
def y_axis(self) -> np.ndarray:
|
||||
return np.cross(self.normal, self.x_axis)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# select tree (faithful port of Select.to_select state machine)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Select:
|
||||
select_type: str
|
||||
body_type: str
|
||||
body_no: int
|
||||
no: int
|
||||
operation_list: List["Select"] = field(default_factory=list)
|
||||
no_shared_included: List["Select"] = field(default_factory=list)
|
||||
all_oriented_included: Dict[str, List["Select"]] = field(default_factory=dict)
|
||||
all_partially_included: List["Select"] = field(default_factory=list)
|
||||
|
||||
|
||||
def _to_select(vec: np.ndarray) -> "Select":
|
||||
"""Port of Select.to_select: parse ONE Topo→Select block into a single
|
||||
Select tree (mirrors their `return select_list[0]`)."""
|
||||
select_list: List[Select] = []
|
||||
no_shared_included: List[Select] = []
|
||||
partially_shared_included: List[Select] = []
|
||||
all_oriented_limits1: List[Select] = []
|
||||
all_oriented_limits2: List[Select] = []
|
||||
mirror_list: List[Select] = []
|
||||
mode = 0 # 0 select, 1 no_shared, 2 oriented limits1, 3 oriented limits2, 4 partially
|
||||
start_mirror = 0
|
||||
time_to_no_shared = False
|
||||
time_to_partially_shared = False
|
||||
time_to_all_oriented1 = False
|
||||
time_to_all_oriented2 = False
|
||||
|
||||
def flush_flags(target: Select) -> None:
|
||||
nonlocal time_to_no_shared, time_to_partially_shared, time_to_all_oriented1, time_to_all_oriented2
|
||||
if time_to_no_shared:
|
||||
time_to_no_shared = False
|
||||
target.no_shared_included = list(no_shared_included)
|
||||
no_shared_included.clear()
|
||||
if time_to_partially_shared:
|
||||
time_to_partially_shared = False
|
||||
target.all_partially_included = list(partially_shared_included)
|
||||
partially_shared_included.clear()
|
||||
if time_to_all_oriented1:
|
||||
time_to_all_oriented1 = False
|
||||
target.all_oriented_included['Limits1'] = list(all_oriented_limits1)
|
||||
all_oriented_limits1.clear()
|
||||
if time_to_all_oriented2:
|
||||
time_to_all_oriented2 = False
|
||||
target.all_oriented_included['Limits2'] = list(all_oriented_limits2)
|
||||
all_oriented_limits2.clear()
|
||||
|
||||
def bucket(mode: int) -> List[Select]:
|
||||
return {0: select_list, 1: no_shared_included, 2: all_oriented_limits1,
|
||||
3: all_oriented_limits2, 4: partially_shared_included}[mode]
|
||||
|
||||
def make(sel: np.ndarray, ops: List[Select], body: Optional[str] = None) -> Select:
|
||||
return Select(SELECT_TYPE[int(sel[0])],
|
||||
body if body is not None else BODY_TYPE[int(sel[1])],
|
||||
int(sel[2]), int(sel[3]), list(ops), [], {})
|
||||
|
||||
def pop_two(target: List[Select]) -> List[Select]:
|
||||
ops = [target.pop(-2), target.pop(-1)]
|
||||
return ops
|
||||
|
||||
for i in range(vec.shape[0]):
|
||||
row = vec[i]
|
||||
cmd = int(row[0])
|
||||
if cmd == TOPO_IDX:
|
||||
mode = 0
|
||||
elif cmd == MIRROR_START_IDX:
|
||||
start_mirror += 1
|
||||
elif cmd == ALL_COMMANDS.index('NoSharedIncluded'):
|
||||
mode = 1
|
||||
elif cmd == ALL_COMMANDS.index('AllOrientedIncluded1'):
|
||||
mode = 2
|
||||
elif cmd == ALL_COMMANDS.index('AllOrientedIncluded2'):
|
||||
mode = 3
|
||||
elif cmd == ALL_COMMANDS.index('AllPartiallySharedIncluded'):
|
||||
mode = 4
|
||||
elif cmd == ALL_COMMANDS.index('NoSharedIncludedEnd'):
|
||||
time_to_no_shared = True
|
||||
mode = 0
|
||||
elif cmd == ALL_COMMANDS.index('AllPartiallySharedIncludedEnd'):
|
||||
time_to_partially_shared = True
|
||||
mode = 0
|
||||
elif cmd == ALL_COMMANDS.index('AllOrientedIncludedEnd'):
|
||||
if mode == 2:
|
||||
time_to_all_oriented1 = True
|
||||
elif mode == 3:
|
||||
time_to_all_oriented2 = True
|
||||
mode = 0
|
||||
elif cmd == SELECT_IDX:
|
||||
sel = row[-4:]
|
||||
stype, btype = int(sel[0]), int(sel[1])
|
||||
if stype == SELECT_TYPE.index("Wire"):
|
||||
target = mirror_list if start_mirror > 0 else bucket(mode)
|
||||
target.append(make(sel, []))
|
||||
if start_mirror == 0 and mode == 0:
|
||||
flush_flags(select_list[-1])
|
||||
elif stype == SELECT_TYPE.index("Face"):
|
||||
if btype == BODY_TYPE.index("Shell"):
|
||||
ops = []
|
||||
if start_mirror > 0:
|
||||
ops.append(mirror_list.pop())
|
||||
mirror_list.append(make(sel, ops))
|
||||
elif mode == 0:
|
||||
ops.append(select_list.pop())
|
||||
select_list.append(make(sel, ops))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
ops.append(b.pop())
|
||||
b.append(make(sel, ops))
|
||||
elif btype in (BODY_TYPE.index("Chamfer"), BODY_TYPE.index("EdgeFillet")):
|
||||
if start_mirror > 0:
|
||||
ops = pop_two(mirror_list)
|
||||
mirror_list.append(make(sel, ops))
|
||||
elif mode == 0:
|
||||
ops = pop_two(select_list)
|
||||
select_list.append(make(sel, ops))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
ops = pop_two(b)
|
||||
b.append(make(sel, ops))
|
||||
elif btype == BODY_TYPE.index("Mirror"):
|
||||
start_mirror -= 1
|
||||
ops = [mirror_list.pop()]
|
||||
target = mirror_list if start_mirror > 0 else bucket(mode)
|
||||
target.append(make(sel, ops))
|
||||
elif btype == BODY_TYPE.index("Hole"):
|
||||
if start_mirror > 0:
|
||||
ops = [mirror_list.pop()]
|
||||
mirror_list.append(make(sel, ops))
|
||||
elif mode == 0:
|
||||
select_list.append(make(sel, []))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
bucket(mode).append(make(sel, []))
|
||||
elif int(sel[3]) == 0:
|
||||
ops = []
|
||||
if start_mirror > 0:
|
||||
ops.append(mirror_list.pop())
|
||||
mirror_list.append(make(sel, ops))
|
||||
elif mode == 0:
|
||||
ops.append(select_list.pop())
|
||||
select_list.append(make(sel, ops))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
ops.append(b.pop())
|
||||
b.append(make(sel, ops))
|
||||
else:
|
||||
if start_mirror > 0:
|
||||
mirror_list.append(make(sel, []))
|
||||
elif mode == 0:
|
||||
select_list.append(make(sel, []))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
bucket(mode).append(make(sel, []))
|
||||
elif stype == SELECT_TYPE.index("Sub_Face"):
|
||||
if btype in (BODY_TYPE.index("Chamfer"), BODY_TYPE.index("EdgeFillet")):
|
||||
if start_mirror > 0:
|
||||
ops = pop_two(mirror_list)
|
||||
mirror_list.append(make(sel, ops))
|
||||
elif mode == 0:
|
||||
ops = pop_two(select_list)
|
||||
select_list.append(make(sel, ops))
|
||||
else:
|
||||
b = bucket(mode)
|
||||
ops = pop_two(b)
|
||||
b.append(make(sel, ops))
|
||||
elif btype == BODY_TYPE.index("Shell"):
|
||||
if start_mirror > 0:
|
||||
ops = [mirror_list.pop()]
|
||||
mirror_list.append(make(sel, ops))
|
||||
flush_flags(mirror_list[-1])
|
||||
elif mode == 0:
|
||||
ops = [select_list.pop()]
|
||||
select_list.append(make(sel, ops))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
ops = [b.pop()]
|
||||
b.append(make(sel, ops))
|
||||
elif btype == BODY_TYPE.index("Mirror"):
|
||||
start_mirror -= 1
|
||||
ops = [mirror_list.pop()]
|
||||
target = mirror_list if start_mirror > 0 else bucket(mode)
|
||||
target.append(make(sel, ops))
|
||||
else:
|
||||
if start_mirror > 0:
|
||||
mirror_list.append(make(sel, []))
|
||||
elif mode == 0:
|
||||
select_list.append(make(sel, []))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
bucket(mode).append(make(sel, []))
|
||||
elif stype == SELECT_TYPE.index("Multiply_Face"):
|
||||
ops = []
|
||||
if start_mirror > 0:
|
||||
while mirror_list and mirror_list[-1].select_type == SELECT_TYPE.index('Sub_Face'):
|
||||
ops.append(mirror_list.pop())
|
||||
ops.reverse()
|
||||
mirror_list.append(make(sel, ops, body='None'))
|
||||
elif mode == 0:
|
||||
while select_list and select_list[-1].select_type == SELECT_TYPE.index('Sub_Face'):
|
||||
ops.append(select_list.pop())
|
||||
ops.reverse()
|
||||
select_list.append(make(sel, ops, body='None'))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
while b and b[-1].select_type == SELECT_TYPE.index('Sub_Face'):
|
||||
ops.append(b.pop())
|
||||
ops.reverse()
|
||||
b.append(make(sel, ops, body='None'))
|
||||
elif stype == SELECT_TYPE.index("Edge"):
|
||||
# Edge selects carry body_type None and bind the two preceding
|
||||
# face selects (the edge shared by / created from them).
|
||||
if start_mirror > 0:
|
||||
ops = pop_two(mirror_list)
|
||||
mirror_list.append(make(sel, ops, body='None'))
|
||||
elif mode == 0:
|
||||
ops = pop_two(select_list)
|
||||
select_list.append(make(sel, ops, body='None'))
|
||||
flush_flags(select_list[-1])
|
||||
else:
|
||||
b = bucket(mode)
|
||||
if btype == 2: # their mode-2 branch pops after append (kept as-is)
|
||||
b.append(make(sel, [], body='None'))
|
||||
ops = pop_two(b)
|
||||
else:
|
||||
ops = pop_two(b)
|
||||
b.append(make(sel, ops, body='None'))
|
||||
return select_list[0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# feature model
|
||||
|
||||
|
||||
@dataclass
|
||||
class SketchPlan:
|
||||
"""Decoded sketch: real 2D curves on the feature plane + plane frame."""
|
||||
plane_origin: np.ndarray
|
||||
plane_normal: np.ndarray
|
||||
plane_x_axis: np.ndarray
|
||||
plane_y_axis: np.ndarray
|
||||
profile: Profile # curves in real 2D coords (denormalized)
|
||||
profile_quantized: Profile # as-decoded quantized curves (audit reference)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExtrudeFeature:
|
||||
kind: str # 'Ext' | 'Pocket'
|
||||
operation: str # BOOLEAN_OPERATIONS value ('Pocket' → cut)
|
||||
sketch: SketchPlan
|
||||
extent_one: float
|
||||
extent_two: float
|
||||
extent_type1: str
|
||||
extent_type2: str
|
||||
select_list: List[Select] # UpTo targets when present
|
||||
|
||||
|
||||
@dataclass
|
||||
class RevolveFeature:
|
||||
kind: str # 'Rev' | 'Groove'
|
||||
operation: str
|
||||
sketch: SketchPlan
|
||||
angle_one: float # degrees, start angle from sketch plane (CATIA FirstAngle)
|
||||
angle_two: float # degrees, opposite side (CATIA SecondAngle)
|
||||
axis_select: Select
|
||||
|
||||
|
||||
@dataclass
|
||||
class FinishFeature:
|
||||
kind: str # 'Shell' | 'Chamfer' | 'Fillet'
|
||||
select_list: List[Select]
|
||||
params: Dict[str, float]
|
||||
|
||||
|
||||
@dataclass
|
||||
class HoleFeature:
|
||||
kind: str
|
||||
sketch: SketchPlan # plane under the hole; point_pos 2D on that plane
|
||||
point_pos: np.ndarray
|
||||
radius: float
|
||||
depth: float
|
||||
bottom_mode: str
|
||||
plane_ref: Select
|
||||
select_list: List[Select]
|
||||
|
||||
|
||||
@dataclass
|
||||
class UnsupportedFeature:
|
||||
kind: str # 'Draft' | 'Mirror'
|
||||
detail: str
|
||||
|
||||
|
||||
Feature = Any
|
||||
|
||||
|
||||
def _sketch_plan(plane6: np.ndarray, sket_pos: np.ndarray, sket_size: float,
|
||||
profile_q: Profile) -> SketchPlan:
|
||||
"""Assemble the real sketch frame.
|
||||
|
||||
``plane6`` carries (theta, phi, gamma) quantized + origin quantized — the
|
||||
CoordSystem origin IS sketch_pos (verified in Extrude.from_vector). Profile
|
||||
curves denormalize via (p - 128) * size / 95, the inverse of
|
||||
normalize(size=256) as used by the dataset's own CATIA rebuild.
|
||||
"""
|
||||
theta, phi, gamma = (_denorm_centered(float(v)) * math.pi for v in plane6[:3])
|
||||
origin = np.array([_denorm_centered(float(v)) for v in sket_pos])
|
||||
normal, x_axis = polar_parameterization_inverse(theta, phi, gamma)
|
||||
y_axis = np.cross(normal, x_axis)
|
||||
|
||||
real = _denormalize_profile(profile_q, _denorm_size(float(sket_size)))
|
||||
return SketchPlan(origin, normal, x_axis, y_axis, real, profile_q)
|
||||
|
||||
|
||||
def _denormalize_profile(profile_q: Profile, size: float) -> Profile:
|
||||
scale = size / DENORM_SCALE_DENOM
|
||||
offset = np.array([ARGS_N / 2.0, ARGS_N / 2.0])
|
||||
loops = []
|
||||
for loop in profile_q.loops:
|
||||
curves = []
|
||||
for c in loop.curves:
|
||||
c2 = _copy_curve(c)
|
||||
_curve_shift(c2, -offset)
|
||||
_curve_scale(c2, scale)
|
||||
curves.append(c2)
|
||||
loops.append(Loop(curves))
|
||||
return Profile(loops)
|
||||
|
||||
|
||||
def _copy_curve(c: Curve) -> Curve:
|
||||
if isinstance(c, Line):
|
||||
return Line(c.start_point.copy(), c.end_point.copy())
|
||||
if isinstance(c, Circle):
|
||||
return Circle(c.center.copy(), c.radius)
|
||||
if isinstance(c, Arc):
|
||||
return Arc(c.center.copy(), c.radius, c.start_arc, c.end_arc, c.mid_arc)
|
||||
return Spline([p.copy() for p in c.point_list])
|
||||
|
||||
|
||||
def _curve_shift(c: Curve, d: np.ndarray) -> None:
|
||||
if isinstance(c, Line):
|
||||
c.start_point = c.start_point + d
|
||||
c.end_point = c.end_point + d
|
||||
elif isinstance(c, Circle):
|
||||
c.center = c.center + d
|
||||
elif isinstance(c, Arc):
|
||||
c.center = c.center + d
|
||||
else:
|
||||
c.point_list = [p + d for p in c.point_list]
|
||||
|
||||
|
||||
def _curve_scale(c: Curve, s: float) -> None:
|
||||
if isinstance(c, Line):
|
||||
c.start_point = c.start_point * s
|
||||
c.end_point = c.end_point * s
|
||||
elif isinstance(c, (Circle, Arc)):
|
||||
c.center = c.center * s
|
||||
c.radius = c.radius * s
|
||||
else:
|
||||
c.point_list = [p * s for p in c.point_list]
|
||||
|
||||
|
||||
def _split_profile_rows(vec: np.ndarray) -> np.ndarray:
|
||||
"""Rows before the first Topo marker or the trailing feature command —
|
||||
mirrors their scan for TOPO_IDX / feature idx (Extrude.from_vector)."""
|
||||
body = vec[:-1] if vec.shape[0] else vec
|
||||
stops = np.where((body[:, 0] == TOPO_IDX) | (body[:, 0] == EOS_IDX))[0]
|
||||
cut = int(stops[0]) if len(stops) else body.shape[0]
|
||||
return body[:cut]
|
||||
|
||||
|
||||
def _parse_select_rows(vec: np.ndarray) -> List[Select]:
|
||||
"""Select blocks between profile rows and the trailing feature command —
|
||||
one Select tree per Topo group, mirroring their from_vector slicing."""
|
||||
commands = vec[:, 0]
|
||||
indices = np.where(commands == TOPO_IDX)[0].tolist()
|
||||
if not indices:
|
||||
return []
|
||||
groups = [vec[indices[i]:indices[i + 1]] for i in range(len(indices) - 1)]
|
||||
groups.append(vec[indices[-1]:])
|
||||
return [_to_select(g) for g in groups]
|
||||
|
||||
|
||||
def _plane_args(row: np.ndarray) -> Tuple[np.ndarray, np.ndarray, float]:
|
||||
ext_vec = row[1 + N_ARGS_SKETCH:1 + N_ARGS_SKETCH + N_ARGS_EXT]
|
||||
return ext_vec[:3], ext_vec[N_ARGS_PLANE:N_ARGS_PLANE + 3], float(ext_vec[N_ARGS_PLANE + N_ARGS_TRANS - 1])
|
||||
|
||||
|
||||
def _body_param(row: np.ndarray) -> np.ndarray:
|
||||
"""Trailing 7 body params of the feature row: ext1, ext2, type1, type2,
|
||||
-1, -1, operation (their ext_vec[N_ARGS_PLANE + N_ARGS_TRANS:])."""
|
||||
base = 1 + N_ARGS_SKETCH + N_ARGS_PLANE + N_ARGS_TRANS
|
||||
return row[base:base + N_ARGS_BODY_PARAM]
|
||||
|
||||
|
||||
def _finish_param(row: np.ndarray, start: int, count: int) -> np.ndarray:
|
||||
base = 1 + N_ARGS_SKETCH + N_ARGS_EXT
|
||||
return row[base + start:base + start + count]
|
||||
|
||||
|
||||
def _decode_ext_like(vec: np.ndarray, cmd_idx: int, is_numerical: bool) -> Feature:
|
||||
"""Ext and Pocket share the block layout [profile..., (Topo/Select...), cmd]."""
|
||||
kind = 'Ext' if cmd_idx == EXT_IDX else 'Pocket'
|
||||
profile_rows = _split_profile_rows(vec)
|
||||
profile_q = _profile_from_vector(np.concatenate([profile_rows, _eos_row()]))
|
||||
last = vec[-1]
|
||||
plane_ang, sket_pos_q, sket_size_q = _plane_args(last)
|
||||
param = _body_param(last)
|
||||
selects = _parse_select_rows(vec[:-1])
|
||||
if is_numerical:
|
||||
extent_one = _denorm_centered(float(param[0]))
|
||||
extent_two = _denorm_centered(float(param[1]))
|
||||
extent_type1 = EXTENT_TYPE[int(param[2])]
|
||||
extent_type2 = EXTENT_TYPE[int(param[3])]
|
||||
else:
|
||||
extent_one, extent_two = float(param[0]), float(param[1])
|
||||
extent_type1, extent_type2 = EXTENT_TYPE[int(param[2])], EXTENT_TYPE[int(param[3])]
|
||||
operation = BOOLEAN_OPERATIONS[int(param[6])] if kind == 'Ext' else 'CutFeatureOperation'
|
||||
sketch = _sketch_plan(plane_ang, sket_pos_q, sket_size_q, profile_q)
|
||||
return ExtrudeFeature(kind, operation, sketch, extent_one, extent_two,
|
||||
extent_type1, extent_type2, selects)
|
||||
|
||||
|
||||
def _decode_rev_like(vec: np.ndarray, cmd_idx: int, is_numerical: bool) -> Feature:
|
||||
"""Rev (Shaft) and Groove: [profile..., Topo/Select(axis), cmd]."""
|
||||
kind = 'Rev' if cmd_idx == REV_IDX else 'Groove'
|
||||
profile_rows = _split_profile_rows(vec)
|
||||
profile_q = _profile_from_vector(np.concatenate([profile_rows, _eos_row()]))
|
||||
last = vec[-1]
|
||||
plane_ang, sket_pos_q, sket_size_q = _plane_args(last)
|
||||
param = _body_param(last)
|
||||
axis_select = _to_select(np.array([vec[-2]]))
|
||||
if is_numerical:
|
||||
angle_one = float(param[4]) / (ARGS_N - 1) * 360.0
|
||||
angle_two = float(param[5]) / (ARGS_N - 1) * 360.0
|
||||
operation = BOOLEAN_OPERATIONS[int(param[6])] if kind == 'Rev' else 'CutFeatureOperation'
|
||||
else:
|
||||
angle_one, angle_two = float(param[4]), float(param[5])
|
||||
operation = BOOLEAN_OPERATIONS[int(param[6])]
|
||||
sketch = _sketch_plan(plane_ang, sket_pos_q, sket_size_q, profile_q)
|
||||
return RevolveFeature(kind, operation, sketch, angle_one, angle_two, axis_select)
|
||||
|
||||
|
||||
def _decode_finish(vec: np.ndarray, cmd_idx: int, is_numerical: bool) -> Feature:
|
||||
kind = {SHELL_IDX: 'Shell', CHAMFER_IDX: 'Chamfer', FILLET_IDX: 'Fillet'}[cmd_idx]
|
||||
last = vec[-1]
|
||||
selects = _parse_select_rows(vec[:-1])
|
||||
if kind == 'Shell':
|
||||
raw = _finish_param(last, 0, 2)
|
||||
params = {'thickness': _denorm_centered(float(raw[0])),
|
||||
'second_thickness': _denorm_centered(float(raw[1]))}
|
||||
elif kind == 'Chamfer':
|
||||
raw = _finish_param(last, 2, 2)
|
||||
params = {'length1': _denorm_centered(float(raw[0])),
|
||||
'angle_or_length2': _denorm_centered(float(raw[1]))}
|
||||
else:
|
||||
raw = _finish_param(last, 4, 1)
|
||||
params = {'radius': _denorm_centered(float(raw[0]))}
|
||||
return FinishFeature(kind, selects, params)
|
||||
|
||||
|
||||
def _decode_hole(vec: np.ndarray, is_numerical: bool) -> Feature:
|
||||
last = vec[-1]
|
||||
selects = _parse_select_rows(vec[:-1])
|
||||
plane_ref = selects[0] if selects else None
|
||||
select_list = selects[1:] if len(selects) > 1 else []
|
||||
point_q = np.array([float(last[1]), float(last[2])])
|
||||
plane_ang = last[1 + N_ARGS_SKETCH:1 + N_ARGS_SKETCH + 6]
|
||||
radius_q = float(_finish_param(last, 6, 1)[0])
|
||||
depth_q = float(_finish_param(last, 7, 1)[0])
|
||||
bottom_idx = int(_finish_param(last, 8, 1)[0])
|
||||
if is_numerical:
|
||||
point_pos = np.array([_denorm_centered(v) for v in point_q])
|
||||
radius = _denorm_centered(radius_q)
|
||||
depth = _denorm_centered(depth_q)
|
||||
bottom_mode = EXTENT_TYPE[bottom_idx]
|
||||
else:
|
||||
point_pos, radius, depth, bottom_mode = point_q, radius_q, depth_q, EXTENT_TYPE[bottom_idx]
|
||||
# Hole plane: (theta, phi, gamma, origin) quantized; origin at plane_vec[0:3]
|
||||
theta, phi, gamma = (_denorm_centered(float(v)) * math.pi for v in plane_ang[:3])
|
||||
origin = np.array([_denorm_centered(float(v)) for v in plane_ang[3:6]])
|
||||
normal, x_axis = polar_parameterization_inverse(theta, phi, gamma)
|
||||
sketch = SketchPlan(origin, normal, x_axis, np.cross(normal, x_axis),
|
||||
Profile([]), Profile([]))
|
||||
return HoleFeature('Hole', sketch, point_pos, radius, depth, bottom_mode, plane_ref, select_list)
|
||||
|
||||
|
||||
def _eos_row() -> np.ndarray:
|
||||
return np.array([EOS_IDX, *([-1] * N_ARGS)])[np.newaxis]
|
||||
|
||||
|
||||
def decode_vec(vec: np.ndarray, is_numerical: bool = True) -> List[Feature]:
|
||||
"""Decode a quantized command matrix (len, 1 + N_ARGS) into features."""
|
||||
vec = np.asarray(vec)[:, :1 + N_ARGS]
|
||||
commands = vec[:, 0]
|
||||
feature_cmds = (EXT_IDX, REV_IDX, SHELL_IDX, CHAMFER_IDX, FILLET_IDX,
|
||||
POCKET_IDX, DRAFT_IDX, MIRROR_IDX, GROOVE_IDX, HOLE_IDX)
|
||||
op_indices = [-1] + np.where(np.isin(commands, feature_cmds))[0].tolist()
|
||||
features: List[Feature] = []
|
||||
for i in range(len(op_indices) - 1):
|
||||
start, end = op_indices[i], op_indices[i + 1]
|
||||
block = vec[start + 1:end + 1]
|
||||
cmd = int(commands[end])
|
||||
if cmd in (EXT_IDX, POCKET_IDX):
|
||||
features.append(_decode_ext_like(block, cmd, is_numerical))
|
||||
elif cmd in (REV_IDX, GROOVE_IDX):
|
||||
features.append(_decode_rev_like(block, cmd, is_numerical))
|
||||
elif cmd in (SHELL_IDX, CHAMFER_IDX, FILLET_IDX):
|
||||
features.append(_decode_finish(block, cmd, is_numerical))
|
||||
elif cmd == HOLE_IDX:
|
||||
features.append(_decode_hole(block, is_numerical))
|
||||
elif cmd in (DRAFT_IDX, MIRROR_IDX):
|
||||
features.append(UnsupportedFeature('Draft' if cmd == DRAFT_IDX else 'Mirror', ''))
|
||||
return features
|
||||
|
||||
|
||||
def load_h5(path) -> List[Feature]:
|
||||
import h5py
|
||||
|
||||
with h5py.File(path, "r") as fp:
|
||||
vec = fp["vec"][:].astype(int)
|
||||
return decode_vec(vec, is_numerical=True)
|
||||
@@ -436,7 +436,7 @@ resolution-markers = [
|
||||
"python_full_version < '3.11'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/54/eb9bfc647b19f2009dd5c7f5ec51c4e6ca831725f1aea7a993034f483147/contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54", size = 13466130, upload-time = "2025-04-15T17:47:53.79Z" }
|
||||
wheels = [
|
||||
@@ -507,7 +507,7 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" }
|
||||
wheels = [
|
||||
@@ -755,7 +755,7 @@ name = "exceptiongroup"
|
||||
version = "1.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749, upload-time = "2025-05-10T17:42:51.123Z" }
|
||||
wheels = [
|
||||
@@ -907,6 +907,49 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h5py"
|
||||
version = "3.16.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/db/33/acd0ce6863b6c0d7735007df01815403f5589a21ff8c2e1ee2587a38f548/h5py-3.16.0.tar.gz", hash = "sha256:a0dbaad796840ccaa67a4c144a0d0c8080073c34c76d5a6941d6818678ef2738", size = 446526, upload-time = "2026-03-06T13:49:08.07Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/6b/231413e58a787a89b316bb0d1777da3c62257e4797e09afd8d17ad3549dc/h5py-3.16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e06f864bedb2c8e7c1358e6c73af48519e317457c444d6f3d332bb4e8fa6d7d9", size = 3724137, upload-time = "2026-03-06T13:47:35.242Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/74/f9/557ce3aad0fe8471fb5279bab0fc56ea473858a022c4ce8a0b8f303d64e9/h5py-3.16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ec86d4fffd87a0f4cb3d5796ceb5a50123a2a6d99b43e616e5504e66a953eca3", size = 3090112, upload-time = "2026-03-06T13:47:37.634Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/f5/e15b3d0dc8a18e56409a839e6468d6fb589bc5207c917399c2e0706eeb44/h5py-3.16.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:86385ea895508220b8a7e45efa428aeafaa586bd737c7af9ee04661d8d84a10d", size = 4844847, upload-time = "2026-03-06T13:47:39.811Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/92/a8851d936547efe30cc0ce5245feac01f3ec6171f7899bc3f775c72030b3/h5py-3.16.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:8975273c2c5921c25700193b408e28d6bdd0111c37468b2d4e25dcec4cd1d84d", size = 5065352, upload-time = "2026-03-06T13:47:41.489Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2b/ae/f2adc5d0ca9626db3277a3d87516e124cbc5d0eea0bd79bc085702d04f2c/h5py-3.16.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:1677ad48b703f44efc9ea0c3ab284527f81bc4f318386aaaebc5fede6bbae56f", size = 4839173, upload-time = "2026-03-06T13:47:43.586Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/64/0b/e0c8c69da1d8838da023a50cd3080eae5d475691f7636b35eff20bb6ef20/h5py-3.16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:7c4dd4cf5f0a4e36083f73172f6cfc25a5710789269547f132a20975bfe2434c", size = 5076216, upload-time = "2026-03-06T13:47:45.315Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/66/35/d88fd6718832133c885004c61ceeeb24dbd6397ef877dbed6b3a64d6a286/h5py-3.16.0-cp310-cp310-win_amd64.whl", hash = "sha256:bdef06507725b455fccba9c16529121a5e1fbf56aa375f7d9713d9e8ff42454d", size = 3183639, upload-time = "2026-03-06T13:47:47.041Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/95/a825894f3e45cbac7554c4e97314ce886b233a20033787eda755ca8fecc7/h5py-3.16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:719439d14b83f74eeb080e9650a6c7aa6d0d9ea0ca7f804347b05fac6fbf18af", size = 3721663, upload-time = "2026-03-06T13:47:49.599Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/3b/38ff88b347c3e346cda1d3fc1b65a7aa75d40632228d8b8a5d7b58508c24/h5py-3.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c3f0a0e136f2e95dd0b67146abb6668af4f1a69c81ef8651a2d316e8e01de447", size = 3087630, upload-time = "2026-03-06T13:47:51.249Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/98/a8/2594cef906aee761601eff842c7dc598bea2b394a3e1c00966832b8eeb7c/h5py-3.16.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:a6fbc5367d4046801f9b7db9191b31895f22f1c6df1f9987d667854cac493538", size = 4823472, upload-time = "2026-03-06T13:47:53.085Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/52/a0/c1f604538ff6db22a0690be2dc44ab59178e115f63c917794e529356ab23/h5py-3.16.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:fb1720028d99040792bb2fb31facb8da44a6f29df7697e0b84f0d79aff2e9bd3", size = 5027150, upload-time = "2026-03-06T13:47:55.043Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2e/fd/301739083c2fc4fd89950f9bcfce75d6e14b40b0ca3d40e48a8993d1722c/h5py-3.16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:314b6054fe0b1051c2b0cb2df5cbdab15622fb05e80f202e3b6a5eee0d6fe365", size = 4814544, upload-time = "2026-03-06T13:47:56.893Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4c/42/2193ed41ccee78baba8fcc0cff2c925b8b9ee3793305b23e1f22c20bf4c7/h5py-3.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ffbab2fedd6581f6aa31cf1639ca2cb86e02779de525667892ebf4cc9fd26434", size = 5034013, upload-time = "2026-03-06T13:47:59.01Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/20/e6c0ff62ca2ad1a396a34f4380bafccaaf8791ff8fccf3d995a1fc12d417/h5py-3.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:17d1f1630f92ad74494a9a7392ab25982ce2b469fc62da6074c0ce48366a2999", size = 3191673, upload-time = "2026-03-06T13:48:00.626Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/48/239cbe352ac4f2b8243a8e620fa1a2034635f633731493a7ff1ed71e8658/h5py-3.16.0-cp311-cp311-win_arm64.whl", hash = "sha256:85b9c49dd58dc44cf70af944784e2c2038b6f799665d0dcbbc812a26e0faa859", size = 2673834, upload-time = "2026-03-06T13:48:02.579Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/c0/5d4119dba94093bbafede500d3defd2f5eab7897732998c04b54021e530b/h5py-3.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c5313566f4643121a78503a473f0fb1e6dcc541d5115c44f05e037609c565c4d", size = 3685604, upload-time = "2026-03-06T13:48:04.198Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/42/c84efcc1d4caebafb1ecd8be4643f39c85c47a80fe254d92b8b43b1eadaf/h5py-3.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:42b012933a83e1a558c673176676a10ce2fd3759976a0fedee1e672d1e04fc9d", size = 3061940, upload-time = "2026-03-06T13:48:05.783Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/84/06281c82d4d1686fde1ac6b0f307c50918f1c0151062445ab3b6fa5a921d/h5py-3.16.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:ff24039e2573297787c3063df64b60aab0591980ac898329a08b0320e0cf2527", size = 5198852, upload-time = "2026-03-06T13:48:07.482Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/e9/1a19e42cd43cc1365e127db6aae85e1c671da1d9a5d746f4d34a50edb577/h5py-3.16.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:dfc21898ff025f1e8e67e194965a95a8d4754f452f83454538f98f8a3fcb207e", size = 5405250, upload-time = "2026-03-06T13:48:09.628Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/8e/9790c1655eabeb85b92b1ecab7d7e62a2069e53baefd58c98f0909c7a948/h5py-3.16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:698dd69291272642ffda44a0ecd6cd3bda5faf9621452d255f57ce91487b9794", size = 5190108, upload-time = "2026-03-06T13:48:11.26Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/51/d7/ab693274f1bd7e8c5f9fdd6c7003a88d59bedeaf8752716a55f532924fbb/h5py-3.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2b2c02b0a160faed5fb33f1ba8a264a37ee240b22e049ecc827345d0d9043074", size = 5419216, upload-time = "2026-03-06T13:48:13.322Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/c1/0976b235cf29ead553e22f2fb6385a8252b533715e00d0ae52ed7b900582/h5py-3.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:96b422019a1c8975c2d5dadcf61d4ba6f01c31f92bbde6e4649607885fe502d6", size = 3182868, upload-time = "2026-03-06T13:48:15.759Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/14/d9/866b7e570b39070f92d47b0ff1800f0f8239b6f9e45f02363d7112336c1f/h5py-3.16.0-cp312-cp312-win_arm64.whl", hash = "sha256:39c2838fb1e8d97bcf1755e60ad1f3dd76a7b2a475928dc321672752678b96db", size = 2653286, upload-time = "2026-03-06T13:48:17.279Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0f/9e/6142ebfda0cb6e9349c091eae73c2e01a770b7659255248d637bec54a88b/h5py-3.16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:370a845f432c2c9619db8eed334d1e610c6015796122b0e57aa46312c22617d9", size = 3671808, upload-time = "2026-03-06T13:48:19.737Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/65/5e088a45d0f43cd814bc5bec521c051d42005a472e804b1a36c48dada09b/h5py-3.16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:42108e93326c50c2810025aade9eac9d6827524cdccc7d4b75a546e5ab308edb", size = 3045837, upload-time = "2026-03-06T13:48:21.854Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/da/1e/6172269e18cc5a484e2913ced33339aad588e02ba407fafd00d369e22ef3/h5py-3.16.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:099f2525c9dcf28de366970a5fb34879aab20491589fa89ce2863a84218bb524", size = 5193860, upload-time = "2026-03-06T13:48:24.071Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/98/ef2b6fe2903e377cbe870c3b2800d62552f1e3dbe81ce49e1923c53d1c5c/h5py-3.16.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:9300ad32dea9dfc5171f94d5f6948e159ed93e4701280b0f508773b3f582f402", size = 5400417, upload-time = "2026-03-06T13:48:25.728Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/81/5b62d760039eed64348c98129d17061fdfc7839fc9c04eaaad6dee1004e4/h5py-3.16.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:171038f23bccddfc23f344cadabdfc9917ff554db6a0d417180d2747fe4c75a7", size = 5185214, upload-time = "2026-03-06T13:48:27.436Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/28/c4/532123bcd9080e250696779c927f2cb906c8bf3447df98f5ceb8dcded539/h5py-3.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e420b539fb6023a259a1b14d4c9f6df8cf50d7268f48e161169987a57b737ff", size = 5414598, upload-time = "2026-03-06T13:48:29.49Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c3/d9/a27997f84341fc0dfcdd1fe4179b6ba6c32a7aa880fdb8c514d4dad6fba3/h5py-3.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:18f2bbcd545e6991412253b98727374c356d67caa920e68dc79eab36bf5fedad", size = 3175509, upload-time = "2026-03-06T13:48:31.131Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a5/23/bb8647521d4fd770c30a76cfc6cb6a2f5495868904054e92f2394c5a78ff/h5py-3.16.0-cp313-cp313-win_arm64.whl", hash = "sha256:656f00e4d903199a1d58df06b711cf3ca632b874b4207b7dbec86185b5c8c7d4", size = 2647362, upload-time = "2026-03-06T13:48:33.411Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httpcore"
|
||||
version = "1.0.9"
|
||||
@@ -961,7 +1004,7 @@ name = "importlib-metadata"
|
||||
version = "8.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "zipp" },
|
||||
{ name = "zipp", marker = "python_full_version < '3.12'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/76/66/650a33bd90f786193e4de4b3ad86ea60b53c89b669a5c7be931fac31cdb0/importlib_metadata-8.7.0.tar.gz", hash = "sha256:d13b81ad223b890aa16c5471f2ac3056cf76c5f10f82d6f9292f0b415f389000", size = 56641, upload-time = "2025-04-27T15:29:01.736Z" }
|
||||
wheels = [
|
||||
@@ -2782,7 +2825,7 @@ resolution-markers = [
|
||||
"python_full_version < '3.11'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/37/6964b830433e654ec7485e45a00fc9a27cf868d622838f6b6d9c5ec0d532/scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf", size = 59419214, upload-time = "2025-05-08T16:13:05.955Z" }
|
||||
wheels = [
|
||||
@@ -2841,7 +2884,7 @@ resolution-markers = [
|
||||
"python_full_version == '3.11.*'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" }
|
||||
wheels = [
|
||||
@@ -2895,7 +2938,7 @@ resolution-markers = [
|
||||
"python_full_version >= '3.12'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" } },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" }
|
||||
wheels = [
|
||||
@@ -2989,6 +3032,9 @@ gmsh = [
|
||||
inspect = [
|
||||
{ name = "matplotlib" },
|
||||
]
|
||||
whucad = [
|
||||
{ name = "h5py" },
|
||||
]
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
@@ -3011,6 +3057,7 @@ requires-dist = [
|
||||
{ name = "ezdxf", specifier = ">=1.4.4" },
|
||||
{ name = "gmsh", marker = "extra == 'fem'", specifier = ">=4.15,<5" },
|
||||
{ name = "gmsh", marker = "extra == 'gmsh'", specifier = ">=4.15,<5" },
|
||||
{ name = "h5py", marker = "extra == 'whucad'", specifier = ">=3.8" },
|
||||
{ name = "isort", marker = "extra == 'dev'", specifier = ">=5.0" },
|
||||
{ name = "jsonschema", specifier = ">=4.25.1,<5.0.0" },
|
||||
{ name = "matplotlib", marker = "extra == 'inspect'", specifier = ">=3.7.0" },
|
||||
@@ -3026,7 +3073,7 @@ requires-dist = [
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0,<3" },
|
||||
{ name = "typing-extensions", specifier = ">=4.12,<5" },
|
||||
]
|
||||
provides-extras = ["dev", "editor", "inspect", "gmsh", "fem"]
|
||||
provides-extras = ["dev", "editor", "inspect", "whucad", "gmsh", "fem"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
|
||||
Reference in New Issue
Block a user