import os import torch import json import shutil def is_connected(graph): # 获取所有的顶点 nodes = list(graph.keys()) # 如果图中没有节点,则认为是连通的(空图被视为连通) if not nodes: return False # 初始化一个集合用于记录访问过的节点 visited = set() # 深度优先搜索 DFS def dfs(node): visited.add(node) for neighbor in graph[node]: if neighbor not in visited: dfs(neighbor) # 从第一个节点开始 DFS dfs(nodes[0]) # 检查是否所有节点都被访问过 return len(visited) == len(nodes) folder_path = './dataset/parts_' if not os.path.exists(folder_path): os.makedirs(folder_path) cad_classes = ['building', 'chair', 'fan', 'lamp', 'table', 'tools', 'vehicle'] for cad_class in cad_classes: folder_name = f'./dataset/assemblies/{cad_class}' file_list = os.listdir(folder_name) file_list = sorted(file_list, key=lambda x: int(x.split('_')[1])) for file_name in file_list: full_name = os.path.join(folder_name, file_name) parts_list = os.listdir(full_name) parts_list = [part for part in parts_list if part.startswith('part')] parts_list = sorted(parts_list, key=lambda x: int(x.split('_')[1].split('.')[0])) graph_path = f'{full_name}/processed/data.pt' if not os.path.exists(graph_path): with open("./filtered/filtered_assembly.txt", "a") as f: f.write(f"{full_name},图为空\n") print(f"{full_name}被过滤掉,图为空") # 删除文件夹及其内容 if os.path.exists(full_name): shutil.rmtree(full_name) print(f"{full_name} 文件夹已被删除") continue data, slices = torch.load(graph_path) num_nodes = data['x'].size()[0] if num_nodes > 15: with open("./filtered/filtered_assembly.txt", "a") as f: f.write(f"{full_name},零件数量超过15\n") print(f"{full_name}被过滤掉,零件数量超过15") # 删除文件夹及其内容 if os.path.exists(full_name): shutil.rmtree(full_name) print(f"{full_name} 文件夹已被删除") continue edges = data['edge_index'] if edges.size()[0] != 2: with open("./filtered/filtered_assembly.txt", "a") as f: f.write(f"{full_name},图为空\n") print(f"{full_name}被过滤掉,图为空") # 删除文件夹及其内容 if os.path.exists(full_name): shutil.rmtree(full_name) print(f"{full_name} 文件夹已被删除") continue graph = {i: [] for i in range(num_nodes)} for i in range(edges.size()[1]): u, v = edges[0][i].item(), edges[1][i].item() graph[u].append(v) if is_connected(graph): parts_all_list = os.listdir(folder_path) num_parts_all = len(parts_all_list) with open(f'{full_name}/original_graph.json', 'w') as f: json.dump(graph, f) new_graph = {} for i in range(len(parts_list)): renamed_file = os.path.join(full_name, f'parts_{i + num_parts_all + 809}.step') original_file = os.path.join(full_name, parts_list[i]) os.rename(original_file, renamed_file) new_file_path = os.path.join(folder_path, os.path.basename(renamed_file)) shutil.copy(renamed_file, new_file_path) new_graph[f'parts_{i + num_parts_all + 809}'] = [f'parts_{j + num_parts_all + 809}' for j in graph[i]] with open(f'{full_name}/new_graph.json', 'w') as f: json.dump(new_graph, f) else: with open("./filtered/filtered_assembly.txt", "a") as f: f.write(f"{full_name},装配体不连通\n") print(f"{full_name}被过滤掉,装配体不连通") # 删除文件夹及其内容 if os.path.exists(full_name): shutil.rmtree(full_name) print(f"{full_name} 文件夹已被删除")