summrs commited on
Commit
779056a
·
verified ·
1 Parent(s): 5d26531

import os
import subprocess

def install(package):
subprocess.check_call(["pip", "install", package])

# Install dependencies
install("numpy")
install("networkx")
install("matplotlib")
install("gradio")

# Now import the installed libraries
import math
import itertools
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import gradio as gr

# --- Topological Index Functions ---

def wiener_index(graph):
sp = dict(nx.all_pairs_shortest_path_length(graph))
total = 0
for u in sp:
for v in sp[u]:
if u < v:
total += sp[u][v]
return total

def compute_indices(graph, index_type):
if index_type == "Wiener Index":
return wiener_index(graph)
elif index_type == "Randić Index":
return sum(1 / math.sqrt(graph.degree(u) * graph.degree(v)) for u, v in graph.edges())
elif index_type == "Balaban Index":
n = graph.number_of_nodes()
m = graph.number_of_edges()
if m == 0 or n <= 1:
return 0
return (m / (n - 1)) * sum(1 / math.sqrt(graph.degree(u) * graph.degree(v)) for u, v in graph.edges())
elif index_type == "Zagreb Index M1":
return sum(d**2 for _, d in graph.degree())
elif index_type == "Zagreb Index M2":
return sum(graph.degree(u) * graph.degree(v) for u, v in graph.edges())
elif index_type == "Harary Index":
return sum(1 / nx.shortest_path_length(graph, u, v) for u, v in itertools.combinations(graph.nodes(), 2))
elif index_type == "Schultz Index":
return sum((graph.degree(u) + graph.degree(v)) * nx.shortest_path_length(graph, u, v) for u, v in graph.edges())
elif index_type == "Gutman Index":
return sum(graph.degree(u) * graph.degree(v) * nx.shortest_path_length(graph, u, v) for u, v in graph.edges())
elif index_type == "Estrada Index":
A = nx.adjacency_matrix(graph).todense()
eigenvalues = np.linalg.eigvals(A)
return sum(math.exp(ev) for ev in eigenvalues)
elif index_type == "Hosoya Index":
return graph.number_of_edges()
else:
return "Invalid Index Type"

# --- Graph Drawing Function ---

def draw_graph(graph, index_type, index_value):
plt.figure(figsize=(6, 6))

# Fixed layout for more consistent shapes
pos = nx.spring_layout(graph, seed=42)

# Draw only edges (no nodes, no labels)
nx.draw_networkx_edges(graph, pos, edge_color="gray", width=2)

plt.title(f"{index_type}: {round(index_value, 3)}", fontsize=14)
plt.axis('off')

filename = "graph.png"
plt.savefig(filename, bbox_inches='tight')
plt.close()
return filename

# --- Main Logic ---

def process_graph(node_count, edge_count, index_type, custom_edges):
G = nx.Graph()

if not custom_edges.strip():
G = nx.gnm_random_graph(int(node_count), int(edge_count))
else:
try:
edges = [tuple(map(int, e.strip().split("-"))) for e in custom_edges.split(",")]
all_nodes = set()
for u, v in edges:
all_nodes.update([u, v])
n = max(all_nodes) + 1
G.add_nodes_from(range(n))
G.add_edges_from(edges)
except Exception as e:
return f"Error in custom edges input: {e}", None

index_value = compute_indices(G, index_type)
graph_img = draw_graph(G, index_type, index_value)
return index_value, graph_img

# --- Gradio App ---

with gr.Blocks() as demo:
gr.Markdown("# 🧠 Topological Index Calculator with Graph Visualization")

with gr.Row():
node_count = gr.Number(label="Number of Nodes", value=5, minimum=1)
edge_count = gr.Number(label="Number of Edges", value=5, minimum=0)

index_type = gr.Dropdown(
choices=["Wiener Index", "Randić Index", "Balaban Index", "Zagreb Index M1", "Zagreb Index M2",
"Harary Index", "Schultz Index", "Gutman Index", "Estrada Index", "Hosoya Index"],
label="Select Topological Index"
)

custom_edges = gr.Textbox(
label="Custom Edges (e.g., 0-1,1-2,2-3)",
placeholder="Leave blank for random graph"
)

calc_button = gr.Button("Calculate & Visualize")
result_box = gr.Textbox(label="Computed Index Value", interactive=False)
graph_output = gr.Image(label="Graph Visualization", interactive=False)

calc_button.click(
fn=process_graph,
inputs=[node_count, edge_count, index_type, custom_edges],
outputs=[result_box, graph_output]
)

# --- Run the App ---

if __name__ == "__main__":
demo.launch()

Files changed (1) hide show
  1. app.py +24 -9
app.py CHANGED
@@ -4,18 +4,21 @@ import subprocess
4
  def install(package):
5
  subprocess.check_call(["pip", "install", package])
6
 
 
7
  install("numpy")
8
  install("networkx")
9
  install("matplotlib")
10
  install("gradio")
11
 
 
12
  import math
13
  import itertools
14
  import numpy as np
15
  import networkx as nx
16
  import matplotlib.pyplot as plt
17
  import gradio as gr
18
- from io import BytesIO
 
19
 
20
  def wiener_index(graph):
21
  sp = dict(nx.all_pairs_shortest_path_length(graph))
@@ -56,22 +59,30 @@ def compute_indices(graph, index_type):
56
  else:
57
  return "Invalid Index Type"
58
 
 
 
59
  def draw_graph(graph, index_type, index_value):
60
  plt.figure(figsize=(6, 6))
 
 
61
  pos = nx.spring_layout(graph, seed=42)
 
 
62
  nx.draw_networkx_edges(graph, pos, edge_color="gray", width=2)
 
63
  plt.title(f"{index_type}: {round(index_value, 3)}", fontsize=14)
64
  plt.axis('off')
65
 
66
- # Save directly to memory buffer, no disk usage!
67
- buf = BytesIO()
68
- plt.savefig(buf, format='png', bbox_inches='tight')
69
  plt.close()
70
- buf.seek(0)
71
- return buf
 
72
 
73
  def process_graph(node_count, edge_count, index_type, custom_edges):
74
  G = nx.Graph()
 
75
  if not custom_edges.strip():
76
  G = nx.gnm_random_graph(int(node_count), int(edge_count))
77
  else:
@@ -90,15 +101,17 @@ def process_graph(node_count, edge_count, index_type, custom_edges):
90
  graph_img = draw_graph(G, index_type, index_value)
91
  return index_value, graph_img
92
 
 
 
93
  with gr.Blocks() as demo:
94
  gr.Markdown("# 🧠 Topological Index Calculator with Graph Visualization")
95
-
96
  with gr.Row():
97
  node_count = gr.Number(label="Number of Nodes", value=5, minimum=1)
98
  edge_count = gr.Number(label="Number of Edges", value=5, minimum=0)
99
 
100
  index_type = gr.Dropdown(
101
- choices=["Wiener Index", "Randić Index", "Balaban Index", "Zagreb Index M1", "Zagreb Index M2",
102
  "Harary Index", "Schultz Index", "Gutman Index", "Estrada Index", "Hosoya Index"],
103
  label="Select Topological Index"
104
  )
@@ -118,5 +131,7 @@ with gr.Blocks() as demo:
118
  outputs=[result_box, graph_output]
119
  )
120
 
 
 
121
  if __name__ == "__main__":
122
- demo.launch()
 
4
  def install(package):
5
  subprocess.check_call(["pip", "install", package])
6
 
7
+ # Install dependencies
8
  install("numpy")
9
  install("networkx")
10
  install("matplotlib")
11
  install("gradio")
12
 
13
+ # Now import the installed libraries
14
  import math
15
  import itertools
16
  import numpy as np
17
  import networkx as nx
18
  import matplotlib.pyplot as plt
19
  import gradio as gr
20
+
21
+ # --- Topological Index Functions ---
22
 
23
  def wiener_index(graph):
24
  sp = dict(nx.all_pairs_shortest_path_length(graph))
 
59
  else:
60
  return "Invalid Index Type"
61
 
62
+ # --- Graph Drawing Function ---
63
+
64
  def draw_graph(graph, index_type, index_value):
65
  plt.figure(figsize=(6, 6))
66
+
67
+ # Fixed layout for more consistent shapes
68
  pos = nx.spring_layout(graph, seed=42)
69
+
70
+ # Draw only edges (no nodes, no labels)
71
  nx.draw_networkx_edges(graph, pos, edge_color="gray", width=2)
72
+
73
  plt.title(f"{index_type}: {round(index_value, 3)}", fontsize=14)
74
  plt.axis('off')
75
 
76
+ filename = "graph.png"
77
+ plt.savefig(filename, bbox_inches='tight')
 
78
  plt.close()
79
+ return filename
80
+
81
+ # --- Main Logic ---
82
 
83
  def process_graph(node_count, edge_count, index_type, custom_edges):
84
  G = nx.Graph()
85
+
86
  if not custom_edges.strip():
87
  G = nx.gnm_random_graph(int(node_count), int(edge_count))
88
  else:
 
101
  graph_img = draw_graph(G, index_type, index_value)
102
  return index_value, graph_img
103
 
104
+ # --- Gradio App ---
105
+
106
  with gr.Blocks() as demo:
107
  gr.Markdown("# 🧠 Topological Index Calculator with Graph Visualization")
108
+
109
  with gr.Row():
110
  node_count = gr.Number(label="Number of Nodes", value=5, minimum=1)
111
  edge_count = gr.Number(label="Number of Edges", value=5, minimum=0)
112
 
113
  index_type = gr.Dropdown(
114
+ choices=["Wiener Index", "Randić Index", "Balaban Index", "Zagreb Index M1", "Zagreb Index M2",
115
  "Harary Index", "Schultz Index", "Gutman Index", "Estrada Index", "Hosoya Index"],
116
  label="Select Topological Index"
117
  )
 
131
  outputs=[result_box, graph_output]
132
  )
133
 
134
+ # --- Run the App ---
135
+
136
  if __name__ == "__main__":
137
+ demo.launch()