| 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.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))}
|
|
|
|
|
| tasks = [(i, j) for i in range(len(shapes)) for j in range(i+1, len(shapes))]
|
|
|
|
|
| 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)}")
|
| print(f"Feature shape per node: {[len(f) for f in node_features]}")
|
|
|
| x = torch.tensor(node_features, dtype=torch.float)
|
| print(f"Feature tensor shape: {x.shape}")
|
|
|
|
|
| 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 self.raw_file_names:
|
|
|
|
|
| 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)
|
|
|
| data = create_pyg_data(graph, shapes)
|
| data_list.append(data)
|
|
|
| data, slices = self.collate(data_list)
|
| torch.save((data, slices), self.processed_paths[0])
|
|
|
|
|
|
|
| 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))))
|
|
|
| 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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| |