File size: 4,984 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
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 split_graph(graph):
    # 确保图是连通的
    if nx.is_connected(graph):
        # 获取所有节点和需要的节点数
        nodes = list(graph.nodes())
        total_nodes = len(nodes)
        half_size = total_nodes // 2

        # 生成所有可能的节点组合,遍历分割不同的节点数量
        for size in range(1, half_size+1):
            all_combinations = itertools.combinations(nodes, half_size+1-size)

            # 遍历所有组合,检查是否可以分割成两个连通的子图
            for combination in all_combinations:
                part1 = set(combination)
                part2 = set(nodes) - part1

                # 获取子图
                subgraph1 = graph.subgraph(part1).copy()
                subgraph2 = graph.subgraph(part2).copy()

                # 检查子图是否连通
                if nx.is_connected(subgraph1) and nx.is_connected(subgraph2):
                    return subgraph1, subgraph2

        # 如果没有找到符合条件的组合,抛出异常
        raise ValueError("Unable to split graph into two connected subgraphs.")

    else:
        raise ValueError("Graph is not connected!")


# 生成连通子图(带去重 + 可恢复节点)
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
i = 0
# 执行
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)
        subgraph1, subgraph2 = split_graph(G)
        results_1 = find_connected_subgraphs(subgraph1)
        results_2 = find_connected_subgraphs(subgraph2)
        i = i + 1
        # 输出结果
        examples = []
        for result in results_1:
            for restorable_node in result['restorable_nodes']:
                negative_parts = random.sample(negative_parts_list, 1)
                example = {"partial assembly": result['graph_dict'], "label": restorable_node, 'negative': [negative_part.split('.')[0] for negative_part in negative_parts]}
                examples.append(example)
        for result in results_2:
            for restorable_node in result['restorable_nodes']:
                negative_parts = random.sample(negative_parts_list, 1)
                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}/train_examples.json', 'w') as f:
            json.dump(examples, f, indent=4)