from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.BRepExtrema import BRepExtrema_DistShapeShape from OCC.Core.TopoDS import TopoDS_Shape from OCC.Core.BRep import BRep_Tool from OCC.Core.TopAbs import TopAbs_FACE from OCC.Core.TopExp import TopExp_Explorer import numpy as np from StepParser import StepParser from OCC.Core.TopAbs import TopAbs_COMPOUND, TopAbs_SOLID, TopAbs_SHELL from OCC.Core.TopExp import TopExp_Explorer import torch from torch_geometric.data import Data from OCC.Core.BRepBndLib import brepbndlib from OCC.Core.Bnd import Bnd_Box from torch_geometric.data import InMemoryDataset from OCC.Display.SimpleGui import init_display from OCC.Core.TopAbs import (TopAbs_COMPOUND, TopAbs_SOLID, TopAbs_SHELL, TopAbs_FACE, TopAbs_WIRE, TopAbs_EDGE, TopAbs_VERTEX) from OCC.Core.TopLoc import TopLoc_Location # from OCC.Core.TopoDS import topods_Compound, topods_Face from OCC.Core.Quantity import Quantity_Color, Quantity_NOC_WHITE from collections import Counter from tqdm import tqdm from OCC.Core.Bnd import Bnd_Box from OCC.Core.BRepBndLib import brepbndlib from concurrent.futures import ThreadPoolExecutor, as_completed from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs from OCC.Core.IFSelect import IFSelect_RetDone import os import shutil import json def export_graph_shapes(shapes, save_dir): os.makedirs(save_dir, exist_ok=True) for i, shape in enumerate(shapes): export_shape_to_step(shape, os.path.join(save_dir, f"part_{i}.step")) def export_shape_to_step(shape, save_path): writer = STEPControl_Writer() writer.Transfer(shape, STEPControl_AsIs) status = writer.Write(save_path) if status != IFSelect_RetDone: print(f"Export failed for {save_path}") else: print(f"Exported: {save_path}") def bbox_distance(shape1, shape2): bbox1 = Bnd_Box() bbox2 = Bnd_Box() brepbndlib.Add(shape1, bbox1) brepbndlib.Add(shape2, bbox2) return bbox1.Distance(bbox2) # 返回的是平方距离 def detect_adjacency(shape1, shape2, tolerance=1, bbox_tol=2): """检测两个实体是否相邻(使用几何距离法)""" if bbox_distance(shape1, shape2) > bbox_tol : return False # 包围盒距离远,直接判定不相邻 if shape1.IsNull() or shape2.IsNull(): raise RuntimeError(f"shape1 or shape2 is null") extrema = BRepExtrema_DistShapeShape(shape1, shape2) extrema.Perform() return extrema.Value() < tolerance def build_adjacency_graph(shapes): graph = {i: [] for i in range(len(shapes))} for i in tqdm(range(len(shapes))): for j in range(i + 1, len(shapes)): if detect_adjacency(shapes[i], shapes[j]): graph[i].append(j) graph[j].append(i) print(f"Graph structure: {graph}") # 检查邻接关系 return graph def build_adjacency_graph_parallel(shapes, bbox_tol=2, tolerance=1, num_workers=2): """多线程+进度条+预筛选 构建邻接图""" graph = {i: [] for i in range(len(shapes))} # 准备所有 shape 对 tasks = [(i, j) for i in range(len(shapes)) for j in range(i+1, len(shapes))] # 多线程 + tqdm with ThreadPoolExecutor(max_workers=num_workers) as executor: futures = {executor.submit(detect_adjacency, shapes[i], shapes[j], tolerance, bbox_tol): (i, j) for i, j in tasks} for future in tqdm(as_completed(futures), total=len(futures), desc="Inner loop", position=1): i, j = futures[future] if future.result(): graph[i].append(j) graph[j].append(i) return graph def extract_features(shape): features = [] # 包围盒 bbox = Bnd_Box() brepbndlib.Add(shape, bbox) min_corner = bbox.CornerMin() max_corner = bbox.CornerMax() features += [min_corner.X(), min_corner.Y(), min_corner.Z()] features += [max_corner.X(), max_corner.Y(), max_corner.Z()] # 体积计算(使用新方法) from OCC.Core.GProp import GProp_GProps from OCC.Core.BRepGProp import brepgprop try: props = GProp_GProps() brepgprop.VolumeProperties(shape, props) # 静态方法调用 features.append(props.Mass()) except: features.append(0.0) # 表面积计算(使用新方法) try: props = GProp_GProps() brepgprop.SurfaceProperties(shape, props) # 静态方法调用 features.append(props.Mass()) except: features.append(0.0) return features def create_pyg_data(graph, shapes): """创建PyG图数据""" # 节点特征 node_features = [extract_features(shape) for shape in shapes] print(f"Number of nodes: {len(node_features)}") # 应为 8 print(f"Feature shape per node: {[len(f) for f in node_features]}") # 每个应为 8 x = torch.tensor(node_features, dtype=torch.float) print(f"Feature tensor shape: {x.shape}") # 应为 torch.Size([8, 8]) # 边索引 edge_index = [] for src, dst_list in graph.items(): for dst in dst_list: edge_index.append([src, dst]) edge_index = torch.tensor(edge_index, dtype=torch.long).t().contiguous() return Data(x=x, edge_index=edge_index) class STEPDataset(InMemoryDataset): def __init__(self, root, step_files, transform=None): self.step_files = step_files super().__init__(root, transform) self.data, self.slices = torch.load(self.processed_paths[0], weights_only=False) @property def raw_file_names(self): return self.step_files @property def processed_file_names(self): return ['data.pt'] def process(self): data_list = [] #for file_path in tqdm(self.raw_file_names, desc="Processing files", ncols=100, unit="file"): for file_path in self.raw_file_names: # 解析STEP文件 shapes = StepParser.parse_step_file(file_path) # 构建邻接图 print("零件数量为:", len(shapes)) if len(shapes) < 2 or len(shapes) > 15: raise Exception graph = build_adjacency_graph_parallel(shapes) print(graph) # 创建PyG数据 data = create_pyg_data(graph, shapes) data_list.append(data) # 保存数据集 data, slices = self.collate(data_list) torch.save((data, slices), self.processed_paths[0]) # if __name__ == "__main__": # 示例用法 folder_name = r"F:\1_study\project\CADRec\dataset_final\table" file_list = os.listdir(folder_name) file_list = sorted(os.listdir(folder_name), key=lambda x: int(''.join(filter(str.isdigit, x)))) # k = 430 for i in tqdm(range(len(file_list)), desc="Outer loop", position=0): full_path = os.path.join(folder_name, file_list[i]) try: dataset = STEPDataset( root=f'./dataset/assemblies/table/assembly_{i}', step_files=[full_path] ) shapes = StepParser.parse_step_file(full_path) except RuntimeError as e: with open("failed_step_files_assemblies.txt", "a") as f: f.write(f"Error processing {full_path}: {e}. Skipping this file.\n") print(f"Error processing {full_path}: {e}. Skipping this file.") except Exception as e: with open("failed_step_files_assemblies.txt", "a") as f: f.write(f"Error processing {full_path}: {e}. Skipping this file.\n") print(f"Error processing {full_path}: {e}. Skipping this file.") continue export_graph_shapes(shapes, f"./dataset/assemblies/table/assembly_{i}") shutil.copy(full_path, f"./dataset/assemblies/table/assembly_{i}") # 访问第一个图 data = dataset[0] print(f"Nodes: {data.num_nodes}") print(f"Edges: {data.num_edges}") print(f"Features: {data.x.shape}") # 使用示例 # if __name__ == "__main__": # # 解析文件 # shapes = StepParser.parse_step_file( r"F:\1_study\project\CADRec\dataset\dataset_builder\dataset\a1.0.0_00\7778_3a9748b3\assembly.step" ) # # # 启动交互查看器 # StepParser.interactive_viewer(shapes)