summrs commited on
Commit
fdfa161
·
verified ·
1 Parent(s): f908f04

import os
import subprocess

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

# Manually install each required library
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):
"""
Wiener Index: Sum of shortest path distances between all pairs of vertices.
"""
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":
# Randić Index = Σ[1/√(d(u)*d(v))] for every edge (u,v)
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":
# M1 = Σ[d(v)]² over all vertices
return sum(d**2 for _, d in graph.degree())

elif index_type == "Zagreb Index M2":
# M2 = Σ[d(u)*d(v)] for every edge (u,v)
return sum(graph.degree(u) * graph.degree(v) for u, v in graph.edges())

elif index_type == "Harary Index":
# H = Σ[1 / d(u,v)] for all distinct vertex pairs
return sum(1 / nx.shortest_path_length(graph, u, v)
for u, v in itertools.combinations(graph.nodes(), 2))

elif index_type == "Schultz Index":
# Schultz Index = Σ[(d(u)+d(v))*d(u,v)] over all edges (as a simplified version)
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":
# Gutman Index = Σ[d(u)*d(v)*d(u,v)] over all edges
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":
# Estrada Index = Σ(exp(λ)) over all eigenvalues of the adjacency matrix.
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":
# Hosoya Index counts the number of matchings in a graph.
# For simplicity, we use a dummy value: the number of edges.
return graph.number_of_edges()

else:
return "Invalid Index Type"

# --- Graph Visualization Function ---

def draw_graph(graph, index_type, index_value):
"""
Draws the graph using a spring layout.
Only the edges are drawn (removing the blue nodes with numbers).
The title shows the index type and computed value.
"""
plt.figure(figsize=(6, 6))
pos = nx.spring_layout(graph, seed=42)

# Draw only the edges
nx.draw_networkx_edges(graph, pos, edge_color="gray")

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

# Save the plot as an image and return its filename.
filename = "graph.png"
plt.savefig(filename)
plt.close()
return filename

# --- Main Processing Function ---

def process_graph(node_count, edge_count, index_type, custom_edges):
"""
Creates a graph either from random generation or from custom edge input.
Then computes the selected topological index and draws the graph.
"""
G = nx.Graph()
# If custom_edges is empty, generate a random graph with given node and edge counts.
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 = nx.Graph()
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 Interface Setup ---

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 +9 -11
app.py CHANGED
@@ -1,16 +1,16 @@
 
1
  import subprocess
2
 
3
  def install(package):
4
  subprocess.check_call(["pip", "install", package])
5
 
6
  # Manually install each required library
 
7
  install("networkx")
8
  install("matplotlib")
9
  install("gradio")
10
- install("numpy")
11
 
12
  # Now import the installed libraries
13
- import os
14
  import math
15
  import itertools
16
  import numpy as np
@@ -89,15 +89,17 @@ def compute_indices(graph, index_type):
89
  def draw_graph(graph, index_type, index_value):
90
  """
91
  Draws the graph using a spring layout.
 
92
  The title shows the index type and computed value.
93
  """
94
  plt.figure(figsize=(6, 6))
95
  pos = nx.spring_layout(graph, seed=42)
96
- # Node size based on degree (scaled)
97
- node_sizes = [300 + 100 * graph.degree(n) for n in graph.nodes()]
98
- nx.draw(graph, pos, with_labels=True, node_color="skyblue", edge_color="gray",
99
- node_size=node_sizes, font_size=10)
100
  plt.title(f"{index_type}: {round(index_value, 3)}", fontsize=14)
 
101
  # Save the plot as an image and return its filename.
102
  filename = "graph.png"
103
  plt.savefig(filename)
@@ -114,17 +116,13 @@ def process_graph(node_count, edge_count, index_type, custom_edges):
114
  G = nx.Graph()
115
  # If custom_edges is empty, generate a random graph with given node and edge counts.
116
  if not custom_edges.strip():
117
- # Generate a random graph with given number of nodes and edges.
118
  G = nx.gnm_random_graph(int(node_count), int(edge_count))
119
  else:
120
- # Expecting custom edges in the format: "0-1,1-2,2-3" (nodes as integers)
121
  try:
122
  edges = [tuple(map(int, e.strip().split("-"))) for e in custom_edges.split(",")]
123
- # Determine number of nodes from the maximum node in edges.
124
  all_nodes = set()
125
  for u, v in edges:
126
  all_nodes.update([u, v])
127
- # Ensure all nodes from 0 to max are present.
128
  n = max(all_nodes) + 1
129
  G = nx.Graph()
130
  G.add_nodes_from(range(n))
@@ -166,4 +164,4 @@ with gr.Blocks() as demo:
166
  # --- Run the App ---
167
 
168
  if __name__ == "__main__":
169
- demo.launch()
 
1
+ import os
2
  import subprocess
3
 
4
  def install(package):
5
  subprocess.check_call(["pip", "install", package])
6
 
7
  # Manually install each required library
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
 
89
  def draw_graph(graph, index_type, index_value):
90
  """
91
  Draws the graph using a spring layout.
92
+ Only the edges are drawn (removing the blue nodes with numbers).
93
  The title shows the index type and computed value.
94
  """
95
  plt.figure(figsize=(6, 6))
96
  pos = nx.spring_layout(graph, seed=42)
97
+
98
+ # Draw only the edges
99
+ nx.draw_networkx_edges(graph, pos, edge_color="gray")
100
+
101
  plt.title(f"{index_type}: {round(index_value, 3)}", fontsize=14)
102
+
103
  # Save the plot as an image and return its filename.
104
  filename = "graph.png"
105
  plt.savefig(filename)
 
116
  G = nx.Graph()
117
  # If custom_edges is empty, generate a random graph with given node and edge counts.
118
  if not custom_edges.strip():
 
119
  G = nx.gnm_random_graph(int(node_count), int(edge_count))
120
  else:
 
121
  try:
122
  edges = [tuple(map(int, e.strip().split("-"))) for e in custom_edges.split(",")]
 
123
  all_nodes = set()
124
  for u, v in edges:
125
  all_nodes.update([u, v])
 
126
  n = max(all_nodes) + 1
127
  G = nx.Graph()
128
  G.add_nodes_from(range(n))
 
164
  # --- Run the App ---
165
 
166
  if __name__ == "__main__":
167
+ demo.launch()