File size: 8,403 Bytes
f7d3a87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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)