| """ |
| Utility helpers for loading BRep extractor-processed STEP data as PyG graphs. |
| """ |
| from __future__ import annotations |
|
|
| from collections import defaultdict |
| from pathlib import Path |
| import re |
| from typing import Dict, Iterable, List, Tuple |
|
|
| import numpy as np |
| import torch |
| from torch_geometric.data import HeteroData |
|
|
| |
| DEFAULT_LABELS: Dict[str, int] = {"pipe": 0, "elbow": 1, "tjoint": 2, "random": 3} |
| LABELS: Dict[str, int] = DEFAULT_LABELS.copy() |
| STEP_EXTS = ("*.step", "*.stp", "*.STEP", "*.STP") |
|
|
|
|
| def _class_sort_key(class_name: str) -> Tuple[int, int, str]: |
| """ |
| Sort class names numerically when they have prefixes like `0_random`, |
| then lexicographically for the remaining part. |
| """ |
| match = re.match(r"^\s*(\d+)(?:[_\-\s]+(.*))?$", class_name) |
| if match: |
| suffix = (match.group(2) or "").strip().lower() |
| return (0, int(match.group(1)), suffix) |
| return (1, 10**9, class_name.lower()) |
|
|
|
|
| def _iter_step_files(step_root: Path) -> List[Path]: |
| files_set = set() |
| for pattern in STEP_EXTS: |
| for step_file in step_root.glob(pattern): |
| files_set.add(step_file.resolve()) |
| for step_file in step_root.glob(f"**/{pattern}"): |
| files_set.add(step_file.resolve()) |
| return sorted(files_set) |
|
|
|
|
| def discover_step_classes(step_root: Path) -> List[str]: |
| """ |
| Discover class names from top-level folders under `step_root` that contain |
| STEP files. |
| """ |
| step_root = Path(step_root) |
| if not step_root.exists(): |
| raise FileNotFoundError(f"STEP root does not exist: {step_root}") |
|
|
| class_names = set() |
| for step_file in _iter_step_files(step_root): |
| rel = step_file.relative_to(step_root) |
| if len(rel.parts) < 2: |
| |
| continue |
| class_names.add(rel.parts[0]) |
|
|
| if not class_names: |
| raise RuntimeError(f"No STEP class folders found under {step_root}") |
| return sorted(class_names, key=_class_sort_key) |
|
|
|
|
| def build_class_labels(step_root: Path) -> Dict[str, int]: |
| """ |
| Build a deterministic {class_name -> class_id} mapping from step_root. |
| """ |
| classes = discover_step_classes(step_root) |
| return {name: idx for idx, name in enumerate(classes)} |
|
|
|
|
| def build_label_metadata( |
| step_root: Path, |
| labels: Dict[str, int] | None = None, |
| ) -> Tuple[Dict[str, int], Dict[str, int], Dict[str, Tuple[str, ...]]]: |
| """ |
| Build label metadata from STEP folder structure. |
| |
| Returns: |
| - labels: {class_name: class_id} |
| - stem_to_label: {npz_stem: class_id} |
| - collisions: {stem: (class_name_a, class_name_b, ...)} for stems that |
| appear in more than one class folder. The chosen label follows the same |
| overwrite behavior as extractor output naming (`<stem>.npz`). |
| """ |
| step_root = Path(step_root) |
| if labels is None: |
| labels = build_class_labels(step_root) |
| if not labels: |
| raise RuntimeError("No labels were provided/discovered for STEP classes.") |
|
|
| stem_to_label: Dict[str, int] = {} |
| stem_to_class: Dict[str, str] = {} |
| collisions = defaultdict(set) |
|
|
| for step_file in _iter_step_files(step_root): |
| rel = step_file.relative_to(step_root) |
| if len(rel.parts) < 2: |
| continue |
| class_name = rel.parts[0] |
| if class_name not in labels: |
| continue |
|
|
| stem = step_file.stem |
| prev_class = stem_to_class.get(stem) |
| if prev_class is not None and prev_class != class_name: |
| collisions[stem].update((prev_class, class_name)) |
|
|
| stem_to_class[stem] = class_name |
| stem_to_label[stem] = int(labels[class_name]) |
|
|
| if not stem_to_label: |
| raise RuntimeError( |
| f"No STEP files found under {step_root} for classes: {tuple(labels)}" |
| ) |
|
|
| collision_out = { |
| stem: tuple(sorted(classes, key=_class_sort_key)) |
| for stem, classes in collisions.items() |
| } |
| return labels, stem_to_label, collision_out |
|
|
|
|
| def build_label_map(step_root: Path, labels: Dict[str, int] | None = None) -> Dict[str, int]: |
| """ |
| Build a mapping from STEP file stem to integer label. |
| """ |
| _, stem_to_label, _ = build_label_metadata(step_root, labels) |
| return stem_to_label |
|
|
|
|
| def _flatten(arr: np.ndarray) -> np.ndarray: |
| return np.asarray(arr, dtype=np.float32).reshape(arr.shape[0], -1) |
|
|
|
|
| def _coedge_grid_stats(coedge_grids: np.ndarray) -> np.ndarray: |
| """ |
| Summarize coedge point grids into compact, less position-sensitive stats. |
| Input shape is expected as [N, C, U] (typically C=12). |
| |
| Returns [N, 28]: |
| - channel mean (C=12) |
| - channel std (C=12) |
| - xyz path length, xyz chord length, tortuosity, xyz bbox diag (4) |
| """ |
| grids = np.asarray(coedge_grids, dtype=np.float32) |
| if grids.ndim != 3: |
| raise RuntimeError(f"Expected coedge grids with ndim=3, got shape {grids.shape}") |
| n, c, u = grids.shape |
|
|
| mean_c = grids.mean(axis=2) |
| std_c = grids.std(axis=2) |
|
|
| if c >= 3 and u >= 2: |
| xyz = grids[:, 0:3, :].transpose(0, 2, 1) |
| dif = xyz[:, 1:, :] - xyz[:, :-1, :] |
| seg_len = np.linalg.norm(dif, axis=2) |
| path_len = seg_len.sum(axis=1) |
| chord = np.linalg.norm(xyz[:, -1, :] - xyz[:, 0, :], axis=1) |
| bbox_diag = np.linalg.norm(xyz.max(axis=1) - xyz.min(axis=1), axis=1) |
| tort = path_len / (chord + 1e-6) |
| else: |
| path_len = np.zeros(n, dtype=np.float32) |
| chord = np.zeros(n, dtype=np.float32) |
| tort = np.ones(n, dtype=np.float32) |
| bbox_diag = np.zeros(n, dtype=np.float32) |
|
|
| shape_stats = np.stack([path_len, chord, tort, bbox_diag], axis=1).astype(np.float32) |
| return np.concatenate([mean_c, std_c, shape_stats], axis=1).astype(np.float32) |
|
|
|
|
| def _face_grid_stats(face_grids: np.ndarray) -> np.ndarray: |
| """ |
| Summarize face point grids into compact stats per face. |
| Returns [F, 10]: xyz_mean (3), xyz_std (3), nrm_mean (3), mask_frac (1). |
| """ |
| face_grids = np.asarray(face_grids, dtype=np.float32) |
| f = face_grids.shape[0] |
| xyz = face_grids[:, 0:3, :, :].reshape(f, 3, -1) |
| nrm = face_grids[:, 3:6, :, :].reshape(f, 3, -1) |
| msk = face_grids[:, 6, :, :].reshape(f, -1) |
|
|
| mask = (msk > 0.5).astype(np.float32) |
| mask_frac = mask.mean(axis=1, keepdims=True) |
| w = mask / (mask.sum(axis=1, keepdims=True) + 1e-6) |
|
|
| xyz_mean = (xyz * w[:, None, :]).sum(axis=2) |
| xyz_var = (w[:, None, :] * (xyz - xyz_mean[:, :, None]) ** 2).sum(axis=2) |
| xyz_std = np.sqrt(np.maximum(xyz_var, 1e-12)) |
| nrm_mean = (nrm * w[:, None, :]).sum(axis=2) |
| return np.concatenate([xyz_mean, xyz_std, nrm_mean, mask_frac], axis=1) |
|
|
|
|
| def _build_face_neighbors( |
| coedge_face: np.ndarray, |
| coedge_edge: np.ndarray, |
| num_faces: int, |
| ) -> List[set[int]]: |
| """ |
| Build face-face adjacency from shared model edges. |
| """ |
| neighbors: List[set[int]] = [set() for _ in range(max(0, int(num_faces)))] |
| if num_faces <= 0 or coedge_face.size == 0 or coedge_edge.size == 0: |
| return neighbors |
|
|
| edge_to_faces: Dict[int, set[int]] = defaultdict(set) |
| for face_id, edge_id in zip(coedge_face.tolist(), coedge_edge.tolist()): |
| if face_id < 0 or face_id >= num_faces or edge_id < 0: |
| continue |
| edge_to_faces[int(edge_id)].add(int(face_id)) |
|
|
| for attached_faces in edge_to_faces.values(): |
| if len(attached_faces) < 2: |
| continue |
| face_list = list(attached_faces) |
| for src in face_list: |
| for dst in face_list: |
| if src != dst: |
| neighbors[src].add(dst) |
| return neighbors |
|
|
|
|
| def _derive_torus_like_features( |
| face_feats: np.ndarray, |
| coedge_face: np.ndarray, |
| coedge_edge: np.ndarray, |
| ) -> Tuple[np.ndarray, np.ndarray]: |
| """ |
| Derive robust torus-like signals from primitive flags + face adjacency. |
| |
| Returns: |
| - face_ctx [F, 3]: bspline_core_flag, torus_like_flag, cyl_neighbor_count_norm |
| - global_ctx [3]: torus_like_face_fraction, torus_like_area_fraction, bspline_core_fraction |
| """ |
| num_faces = int(face_feats.shape[0]) |
| if num_faces == 0: |
| return np.zeros((0, 3), dtype=np.float32), np.zeros(3, dtype=np.float32) |
|
|
| feat_dim = int(face_feats.shape[1]) if face_feats.ndim == 2 else 0 |
| if feat_dim > 5: |
| area = np.clip(np.asarray(face_feats[:, 5], dtype=np.float32), 0.0, None) |
| else: |
| area = np.ones((num_faces,), dtype=np.float32) |
| area_sum = float(area.sum()) |
| if area_sum <= 1e-8: |
| area_frac = np.full((num_faces,), 1.0 / max(1, num_faces), dtype=np.float32) |
| else: |
| area_frac = area / (area_sum + 1e-8) |
|
|
| cylinder_mask = face_feats[:, 1] > 0.5 if feat_dim > 1 else np.zeros((num_faces,), dtype=bool) |
| torus_mask = face_feats[:, 4] > 0.5 if feat_dim > 4 else np.zeros((num_faces,), dtype=bool) |
| nurbs_mask = face_feats[:, 6] > 0.5 if feat_dim > 6 else np.zeros((num_faces,), dtype=bool) |
|
|
| neighbors = _build_face_neighbors(coedge_face, coedge_edge, num_faces) |
| cyl_neighbor_count = np.zeros((num_faces,), dtype=np.float32) |
| for i, nbrs in enumerate(neighbors): |
| if nbrs: |
| cyl_neighbor_count[i] = float(sum(1 for n in nbrs if cylinder_mask[n])) |
|
|
| cyl_neighbor_den = max(1.0, float(cyl_neighbor_count.max())) |
| cyl_neighbor_count_norm = (cyl_neighbor_count / cyl_neighbor_den).astype(np.float32) |
|
|
| |
| bspline_core_mask = nurbs_mask & (area_frac >= 0.03) & (cyl_neighbor_count >= 1.0) |
| torus_like_mask = torus_mask | bspline_core_mask |
|
|
| face_ctx = np.stack( |
| [ |
| bspline_core_mask.astype(np.float32), |
| torus_like_mask.astype(np.float32), |
| cyl_neighbor_count_norm, |
| ], |
| axis=1, |
| ).astype(np.float32) |
| global_ctx = np.array( |
| [ |
| float(np.mean(torus_like_mask)), |
| float(np.sum(area_frac[torus_like_mask])), |
| float(np.mean(bspline_core_mask)), |
| ], |
| dtype=np.float32, |
| ) |
| return face_ctx, global_ctx |
|
|
|
|
| def compute_global_geom_features(data) -> np.ndarray: |
| """ |
| Compute compact global geometry descriptors from face/coedge point samples. |
| Returns [5] float32: pca_ev_ratio_1/2/3, line_fit_rmse, plane_fit_rmse. |
| """ |
| points = [] |
| face_grids = np.asarray(data["face_point_grids"], dtype=np.float32) |
| if face_grids.size: |
| xyz = face_grids[:, 0:3, :, :].transpose(0, 2, 3, 1).reshape(-1, 3) |
| mask = face_grids[:, 6, :, :].reshape(-1) > 0.5 |
| if mask.any(): |
| points.append(xyz[mask]) |
|
|
| coedge_grids = np.asarray(data["coedge_point_grids"], dtype=np.float32) |
| if coedge_grids.size: |
| co_xyz = coedge_grids[:, 0:3, :].transpose(0, 2, 1).reshape(-1, 3) |
| points.append(co_xyz) |
|
|
| if not points: |
| return np.zeros(5, dtype=np.float32) |
|
|
| pts = np.concatenate(points, axis=0) |
| if pts.shape[0] < 3: |
| return np.zeros(5, dtype=np.float32) |
| pts = pts[np.isfinite(pts).all(axis=1)] |
| if pts.shape[0] < 3: |
| return np.zeros(5, dtype=np.float32) |
|
|
| mean = pts.mean(axis=0, keepdims=True) |
| centered = pts - mean |
| scale = np.sqrt(np.mean(np.sum(centered ** 2, axis=1))) |
| centered = centered / (scale + 1e-6) |
| cov = (centered.T @ centered) / max(1, centered.shape[0]) |
| if not np.isfinite(cov).all(): |
| return np.zeros(5, dtype=np.float32) |
|
|
| ev = np.linalg.eigvalsh(cov) |
| ev = np.sort(ev)[::-1] |
| ev = np.maximum(ev, 0.0) |
| total = ev.sum() |
| if not np.isfinite(total) or total <= 0.0: |
| return np.zeros(5, dtype=np.float32) |
|
|
| ratios = ev / total |
| line_rmse = np.sqrt(max(ev[1] + ev[2], 0.0)) |
| plane_rmse = np.sqrt(max(ev[2], 0.0)) |
| feats = np.array( |
| [ratios[0], ratios[1], ratios[2], line_rmse, plane_rmse], |
| dtype=np.float32, |
| ) |
| if not np.isfinite(feats).all(): |
| return np.zeros(5, dtype=np.float32) |
| return feats |
|
|
| def load_coedge_arrays(npz_path: Path) -> Dict[str, np.ndarray]: |
| """ |
| Load node features and adjacency indices from a BRep extractor npz. |
| Returns a dict with coedge/face/edge/global features and topology arrays. |
| """ |
| with np.load(npz_path) as data: |
| coedge_feats = _flatten(data["coedge_features"]) |
| scale = np.asarray(data["coedge_scale_factors"], dtype=np.float32)[:, None] |
| reverse = np.asarray(data["coedge_reverse_flags"], dtype=np.float32)[:, None] |
| point_grids = _coedge_grid_stats(data["coedge_point_grids"]) |
| lcs = _flatten(data["coedge_lcs"]) |
|
|
| face_idx = np.asarray(data["face"], dtype=np.int64) |
| edge_idx = np.asarray(data["edge"], dtype=np.int64) |
| face_feats = np.asarray(data["face_features"], dtype=np.float32) |
| edge_feats = np.asarray(data["edge_features"], dtype=np.float32) |
|
|
| face_grids = np.asarray(data["face_point_grids"], dtype=np.float32) |
| face_grid_stats = _face_grid_stats(face_grids) |
| face_ctx, global_ctx = _derive_torus_like_features(face_feats, face_idx, edge_idx) |
|
|
| coedge_x = np.concatenate( |
| [coedge_feats, scale, reverse, point_grids, lcs], axis=1 |
| ) |
| face_x = np.concatenate([face_feats, face_ctx, face_grid_stats], axis=1) |
| edge_x = edge_feats |
| next_index = np.asarray(data["next"], dtype=np.int64) |
| mate_index = np.asarray(data["mate"], dtype=np.int64) |
| global_legacy = compute_global_geom_features(data) |
| |
| global_features = np.concatenate([global_legacy, global_ctx], axis=0).astype(np.float32) |
|
|
| return { |
| "coedge_x": coedge_x, |
| "face_x": face_x, |
| "edge_x": edge_x, |
| "next": next_index, |
| "mate": mate_index, |
| "coedge_face": face_idx, |
| "coedge_edge": edge_idx, |
| "global_x": global_features, |
| } |
|
|
|
|
| def make_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor: |
| """ |
| Build a 2 x E tensor of edge indices (with both directions, deduplicated). |
| """ |
| pairs = np.stack([source, target], axis=1) |
| flipped = pairs[:, ::-1] |
| all_pairs = np.concatenate([pairs, flipped], axis=0) |
| all_pairs = np.unique(all_pairs, axis=0) |
| return torch.tensor(all_pairs.T, dtype=torch.long) |
|
|
| def make_directed_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor: |
| """ |
| Build a 2 x E tensor of directed edge indices (no deduplication). |
| """ |
| return torch.tensor(np.stack([source, target], axis=0), dtype=torch.long) |
|
|
| def make_bipartite_edge_index(source: np.ndarray, target: np.ndarray) -> torch.Tensor: |
| """ |
| Build a 2 x E tensor of directed bipartite edge indices (deduplicated). |
| """ |
| pairs = np.stack([source, target], axis=1) |
| pairs = np.unique(pairs, axis=0) |
| return torch.tensor(pairs.T, dtype=torch.long) |
|
|
| def make_heterodata( |
| coedge_x: np.ndarray, |
| face_x: np.ndarray, |
| edge_x: np.ndarray, |
| next_index: np.ndarray, |
| mate_index: np.ndarray, |
| coedge_face: np.ndarray, |
| coedge_edge: np.ndarray, |
| global_features: np.ndarray, |
| label: int | None, |
| norm_stats: Dict[str, Dict[str, np.ndarray | torch.Tensor]] | None = None, |
| ) -> HeteroData: |
| """ |
| Create a PyG HeteroData graph for the coedge features/relations. |
| When mean/std are provided the features are normalised element-wise. |
| """ |
| def _normalize(x_arr: np.ndarray, stats: Dict[str, np.ndarray | torch.Tensor] | None) -> torch.Tensor: |
| x_t = torch.tensor(x_arr, dtype=torch.float32) |
| if stats is None: |
| return x_t |
| mean = stats.get("mean") |
| std = stats.get("std") |
| if mean is None or std is None: |
| return x_t |
| mean_t = torch.as_tensor(mean, dtype=torch.float32) |
| std_t = torch.as_tensor(std, dtype=torch.float32) |
| return (x_t - mean_t) / std_t |
|
|
| coedge_stats = norm_stats.get("coedge") if norm_stats else None |
| face_stats = norm_stats.get("face") if norm_stats else None |
| edge_stats = norm_stats.get("edge") if norm_stats else None |
|
|
| x_coedge = _normalize(coedge_x, coedge_stats) |
| x_face = _normalize(face_x, face_stats) |
| x_edge = _normalize(edge_x, edge_stats) |
|
|
| idx = np.arange(coedge_x.shape[0], dtype=np.int64) |
| edge_next = make_directed_edge_index(idx, next_index) |
| edge_prev = make_directed_edge_index(next_index, idx) |
| edge_mate = make_edge_index(idx, mate_index) |
| edge_coedge_face = make_directed_edge_index(idx, coedge_face) |
| edge_face_coedge = make_directed_edge_index(coedge_face, idx) |
| edge_coedge_edge = make_directed_edge_index(idx, coedge_edge) |
| edge_edge_coedge = make_directed_edge_index(coedge_edge, idx) |
| edge_face_edge = make_bipartite_edge_index(coedge_face, coedge_edge) |
| edge_edge_face = make_bipartite_edge_index(coedge_edge, coedge_face) |
|
|
| data = HeteroData() |
| data["coedge"].x = x_coedge |
| data["face"].x = x_face |
| data["edge"].x = x_edge |
| data["global"].x = torch.tensor(global_features, dtype=torch.float32).view(1, -1) |
| data["coedge", "next", "coedge"].edge_index = edge_next |
| data["coedge", "prev", "coedge"].edge_index = edge_prev |
| data["coedge", "mate", "coedge"].edge_index = edge_mate |
| data["coedge", "to_face", "face"].edge_index = edge_coedge_face |
| data["face", "to_coedge", "coedge"].edge_index = edge_face_coedge |
| data["coedge", "to_edge", "edge"].edge_index = edge_coedge_edge |
| data["edge", "to_coedge", "coedge"].edge_index = edge_edge_coedge |
| data["face", "to_edge", "edge"].edge_index = edge_face_edge |
| data["edge", "to_face", "face"].edge_index = edge_edge_face |
| if label is not None: |
| data.y = torch.tensor([int(label)], dtype=torch.long) |
| return data |
|
|
|
|
| def compute_feature_stats(npz_paths: Iterable[Path]) -> Dict[str, np.ndarray]: |
| """ |
| Compute mean and std (per feature dimension) across all node features in the dataset. |
| """ |
| totals = {"coedge": 0, "face": 0, "edge": 0} |
| sum_vec: Dict[str, np.ndarray | None] = {"coedge": None, "face": None, "edge": None} |
| sum_sq: Dict[str, np.ndarray | None] = {"coedge": None, "face": None, "edge": None} |
|
|
| for path in npz_paths: |
| graph = load_coedge_arrays(path) |
| for key, x in (("coedge", graph["coedge_x"]), ("face", graph["face_x"]), ("edge", graph["edge_x"])): |
| if sum_vec[key] is None: |
| sum_vec[key] = np.zeros(x.shape[1], dtype=np.float64) |
| sum_sq[key] = np.zeros(x.shape[1], dtype=np.float64) |
| sum_vec[key] += x.sum(axis=0) |
| sum_sq[key] += (x * x).sum(axis=0) |
| totals[key] += x.shape[0] |
|
|
| out = {} |
| for key in ("coedge", "face", "edge"): |
| if sum_vec[key] is None or totals[key] == 0: |
| raise RuntimeError(f"Cannot compute feature stats: no {key} features observed.") |
| mean = sum_vec[key] / totals[key] |
| var = sum_sq[key] / totals[key] - mean * mean |
| var = np.maximum(var, 1e-12) |
| std = np.sqrt(var) |
| out[key] = {"mean": mean.astype(np.float32), "std": std.astype(np.float32)} |
| return out |
|
|