File size: 3,576 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 | import networkx as nx
import itertools
import os
import json
from tqdm import tqdm
import random
def build_graph(graph_dict):
G = nx.Graph()
for node, neighbors in graph_dict.items():
for neighbor in neighbors:
G.add_edge(node, neighbor)
return G
# 图转字典形式
def graph_to_dict(G):
return {node: sorted(list(G.neighbors(node))) for node in sorted(G.nodes)}
# 生成连通子图(带去重 + 可恢复节点)
def find_connected_subgraphs(G):
results = []
seen = set() # 用于去重
nodes = list(G.nodes)
max_remove = len(nodes) - 1
for k in range(1, max_remove + 1):
for to_remove in itertools.combinations(nodes, k):
G_copy = G.copy()
G_copy.remove_nodes_from(to_remove)
if not nx.is_connected(G_copy):
continue
# 生成唯一 key(节点+边)用于去重
key = (
frozenset(G_copy.nodes),
frozenset((min(a, b), max(a, b)) for a, b in G_copy.edges)
)
if key in seen:
continue
seen.add(key)
# 找出可以恢复的节点
restorable = []
for node in to_remove:
temp_G = G_copy.copy()
temp_G.add_node(node)
for neighbor in graph_dict.get(node, []):
if neighbor in temp_G.nodes:
temp_G.add_edge(node, neighbor)
if nx.is_connected(temp_G):
restorable.append(node)
results.append({
"deleted_nodes": list(to_remove),
"restorable_nodes": restorable,
"graph_dict": graph_to_dict(G_copy)
})
return results
# 执行
cad_classes = ['building', 'chair', 'fan', 'lamp', 'table', 'tools', 'vehicle']
for cad_class in cad_classes:
folder_name = f"./dataset/assemblies_15/{cad_class}"
file_list = os.listdir(folder_name)
file_list = sorted(file_list, key=lambda x: int(x.split('_')[1]))
folder_path = './dataset/parts_15'
parts_list = os.listdir(folder_path)
for file_name in tqdm(file_list):
graph_path = os.path.join(folder_name, file_name)
step_list = os.listdir(graph_path)
if 'new_graph.json' not in step_list:
continue
with open(f'{graph_path}/new_graph.json', 'r') as f:
graph_dict = json.load(f)
negative_parts_list = [part for part in parts_list if part not in graph_dict]
G = build_graph(graph_dict)
results = find_connected_subgraphs(G)
with open(f'{graph_path}/train_examples.json', 'r') as f:
train_examples = json.load(f)
partial_assemblies = []
for train_example in train_examples:
partial_assemblies.append(train_example["partial assembly"])
# 输出结果
examples = []
for result in results:
for restorable_node in result['restorable_nodes']:
negative_parts = random.sample(negative_parts_list, 1)
if result['graph_dict'] not in partial_assemblies:
example = {"partial assembly": result['graph_dict'], "label": restorable_node, 'negative': [negative_part.split('.')[0] for negative_part in negative_parts]}
examples.append(example)
with open(f'{graph_path}/test_examples.json', 'w') as f:
json.dump(examples, f, indent=4) |