summrs commited on
Commit
4db4eb5
·
verified ·
1 Parent(s): dc5e736

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import networkx as nx
5
+
6
+ # Helper Functions
7
+ def parse_graph_input(graph_input):
8
+ """Parse user input to create an adjacency list."""
9
+ try:
10
+ graph = eval(graph_input)
11
+ if isinstance(graph, dict):
12
+ return graph
13
+ except:
14
+ pass
15
+
16
+ try:
17
+ edges = eval(graph_input)
18
+ if not isinstance(edges, list):
19
+ raise ValueError("Invalid graph input. Please use an adjacency list or edge list.")
20
+
21
+ graph = {}
22
+ for u, v in edges:
23
+ graph.setdefault(u, []).append(v)
24
+ graph.setdefault(v, []).append(u)
25
+ return graph
26
+ except:
27
+ raise ValueError("Invalid graph input. Please use a valid adjacency list or edge list.")
28
+
29
+ def visualize_graph(graph):
30
+ """Generate a visualization of the graph using a circular layout."""
31
+ plt.figure()
32
+ nodes = list(graph.keys())
33
+ edges = [(u, v) for u in graph for v in graph[u]]
34
+
35
+ pos = nx.circular_layout(nx.Graph(edges))
36
+ nx.draw(
37
+ nx.Graph(edges),
38
+ pos,
39
+ with_labels=True,
40
+ node_color='lightblue',
41
+ edge_color='gray',
42
+ node_size=500,
43
+ font_size=10
44
+ )
45
+ return plt.gcf()
46
+
47
+ def spectral_isomorphism_test(graph1, graph2):
48
+ """Perform spectral isomorphism test with step-by-step explanation."""
49
+ adj_spectrum1 = sorted(np.linalg.eigvals(nx.adjacency_matrix(nx.Graph(graph1)).todense()).real)
50
+ adj_spectrum2 = sorted(np.linalg.eigvals(nx.adjacency_matrix(nx.Graph(graph2)).todense()).real)
51
+ lap_spectrum1 = sorted(np.linalg.eigvals(nx.laplacian_matrix(nx.Graph(graph1)).todense()).real)
52
+ lap_spectrum2 = sorted(np.linalg.eigvals(nx.laplacian_matrix(nx.Graph(graph2)).todense()).real)
53
+
54
+ adj_spectrum1 = [round(float(x), 2) for x in adj_spectrum1]
55
+ adj_spectrum2 = [round(float(x), 2) for x in adj_spectrum2]
56
+ lap_spectrum1 = [round(float(x), 2) for x in lap_spectrum1]
57
+ lap_spectrum2 = [round(float(x), 2) for x in lap_spectrum2]
58
+
59
+ output = (
60
+ f"### **Spectral Isomorphism Test Results**\n\n"
61
+ f"#### **Step 1: Node and Edge Counts**\n"
62
+ f"- **Graph 1**: Nodes: {len(graph1)}, Edges: {sum(len(neighbors) for neighbors in graph1.values()) // 2}\n"
63
+ f"- **Graph 2**: Nodes: {len(graph2)}, Edges: {sum(len(neighbors) for neighbors in graph2.values()) // 2}\n\n"
64
+ f"#### **Step 2: Adjacency Spectra**\n"
65
+ f"- Graph 1: {adj_spectrum1}\n"
66
+ f"- Graph 2: {adj_spectrum2}\n"
67
+ f"- Are the adjacency spectra approximately equal? {'✅ Yes' if np.allclose(adj_spectrum1, adj_spectrum2) else '❌ No'}\n\n"
68
+ f"#### **Step 3: Laplacian Spectra**\n"
69
+ f"- Graph 1: {lap_spectrum1}\n"
70
+ f"- Graph 2: {lap_spectrum2}\n"
71
+ f"- Are the Laplacian spectra approximately equal? {'✅ Yes' if np.allclose(lap_spectrum1, lap_spectrum2) else '❌ No'}\n\n"
72
+ f"#### **Final Result**\n"
73
+ f"- Outcome: {'✅ PASS' if np.allclose(adj_spectrum1, adj_spectrum2) and np.allclose(lap_spectrum1, lap_spectrum2) else '❌ FAIL'}\n"
74
+ f"- Conclusion: The graphs are {'isomorphic' if np.allclose(adj_spectrum1, adj_spectrum2) and np.allclose(lap_spectrum1, lap_spectrum2) else 'NOT isomorphic'}.\n"
75
+ )
76
+ return output
77
+
78
+ def process_inputs(graph1_input, graph2_input):
79
+ """Process user inputs and perform the spectral isomorphism test."""
80
+ graph1 = parse_graph_input(graph1_input)
81
+ graph2 = parse_graph_input(graph2_input)
82
+
83
+ result = spectral_isomorphism_test(graph1, graph2)
84
+
85
+ graph1_plot = visualize_graph(graph1)
86
+ graph2_plot = visualize_graph(graph2)
87
+
88
+ return graph1_plot, graph2_plot, result
89
+
90
+ # Gradio Interface
91
+ with gr.Blocks(title="Graph Theory Project") as demo:
92
+ gr.Markdown("# Graph Theory Project")
93
+ gr.Markdown("Analyze two graphs using spectral isomorphism tests!")
94
+
95
+ with gr.Row():
96
+ graph1_input = gr.Textbox(label="Graph 1 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")
97
+ graph2_input = gr.Textbox(label="Graph 2 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")
98
+
99
+ with gr.Row():
100
+ graph1_output = gr.Plot(label="Graph 1 Visualization")
101
+ graph2_output = gr.Plot(label="Graph 2 Visualization")
102
+
103
+ result_output = gr.Textbox(label="Results", lines=20)
104
+
105
+ submit_button = gr.Button("Run")
106
+ submit_button.click(process_inputs, inputs=[graph1_input, graph2_input], outputs=[graph1_output, graph2_output, result_output])
107
+
108
+ # Launch the app
109
+ demo.launch()