| 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 = (
|
| 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) |