-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
68 lines (61 loc) · 2.26 KB
/
Copy pathapp.py
File metadata and controls
68 lines (61 loc) · 2.26 KB
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
import matplotlib.pyplot as plt
import networkx as nx
import json
class Graph:
def __init__(self):
self.nodes = set()
self.edges = {}
def add_node(self, name):
self.nodes.add(name)
if name not in self.edges:
self.edges[name] = {}
def add_edge(self, node1, node2, edge_name=""):
self.add_node(node1)
self.add_node(node2)
self.edges[node1][node2] = edge_name
self.edges[node2][node1] = edge_name
def color_graph(self):
color_assignment = {}
for node in sorted(self.nodes):
neighbor_colors = {color_assignment.get(neigh) for neigh in self.edges[node] if neigh in color_assignment}
color = 0
while color in neighbor_colors:
color += 1
color_assignment[node] = color
num_colors = max(color_assignment.values()) + 1 if color_assignment else 0
return color_assignment, num_colors
def visualize(self, coloring=None):
G = nx.Graph()
for node in self.nodes:
G.add_node(node)
for node, neighbors in self.edges.items():
for neighbor, edge_name in neighbors.items():
if (neighbor, node) not in G.edges:
G.add_edge(node, neighbor, label=edge_name)
pos = nx.spring_layout(G)
if coloring:
colors = [coloring[node] for node in G.nodes()]
else:
colors = "lightblue"
nx.draw(G, pos, with_labels=True, node_color=colors, cmap=plt.cm.Set3, node_size=800)
edge_labels = nx.get_edge_attributes(G, 'label')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='red')
plt.show()
def load_graph_from_json(filepath):
with open(filepath, "r") as f:
data = json.load(f)
g = Graph()
for node in data.get("nodes", []):
g.add_node(node)
for edge in data.get("edges", []):
node1 = edge["from"]
node2 = edge["to"]
name = edge.get("name", "")
g.add_edge(node1, node2, name)
return g
if __name__ == "__main__":
g = load_graph_from_json("graph.json")
coloring, num_colors = g.color_graph()
print("Coloring:", coloring)
print("Number of colors used:", num_colors)
g.visualize(coloring)