shukdevdatta123 commited on
Commit
ad4e1f3
·
verified ·
1 Parent(s): aa3d7ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -39
app.py CHANGED
@@ -25,31 +25,36 @@ sidebar_option = st.sidebar.radio("Select an option",
25
  "Graph: DAG - Topological Layout", "Graph: Erdos Renyi", "Graph: Karate Club", "Graph: Minimum Spanning Tree",
26
  "Graph: Triads", "Algorithms: Cycle Detection", "Algorithms: Greedy Coloring", "Algorithms: Find Shortest Path"])
27
 
28
- def plot_shortest_path(graph, start_node, end_node):
29
- # Find the shortest path from start_node to end_node
30
- path = nx.shortest_path(graph, start_node, end_node, weight="weight")
31
- st.write("Shortest Path:", path)
 
32
 
33
- # Create a list of edges in the shortest path
34
- path_edges = list(zip(path, path[1:]))
35
 
36
- # Create a list of all edges, and assign colors based on whether they are in the shortest path or not
37
- edge_colors = [
38
- "red" if edge in path_edges or tuple(reversed(edge)) in path_edges else "black"
39
- for edge in graph.edges()
40
- ]
41
 
42
- # Visualize the graph
43
- pos = nx.spring_layout(graph)
44
- nx.draw_networkx_nodes(graph, pos)
45
- nx.draw_networkx_edges(graph, pos, edge_color=edge_colors)
46
- nx.draw_networkx_labels(graph, pos)
47
- nx.draw_networkx_edge_labels(
48
- graph, pos, edge_labels={(u, v): d["weight"] for u, v, d in graph.edges(data=True)}
49
- )
 
 
50
 
51
- plt.title(f"Shortest Path from {start_node} to {end_node}")
52
- st.pyplot(plt)
 
 
53
 
54
  def algorithms_shortest_path():
55
  st.title("Algorithms: Find Shortest Path")
@@ -62,7 +67,7 @@ def algorithms_shortest_path():
62
  )
63
 
64
  if graph_mode == "Default Example":
65
- # Create a predefined graph with nodes and weighted edges
66
  G = nx.Graph()
67
  G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
68
  G.add_edge("A", "B", weight=4)
@@ -80,20 +85,17 @@ def algorithms_shortest_path():
80
  G.add_edge("G", "I", weight=6)
81
  G.add_edge("H", "I", weight=7)
82
 
83
- # Set default start and end nodes
84
- start_node = "A"
85
- end_node = "E"
86
- st.write(f"Finding the shortest path from {start_node} to {end_node}")
87
- plot_shortest_path(G, start_node, end_node)
88
 
89
  elif graph_mode == "Create Your Own":
90
  st.write("### Create Your Own Graph")
91
 
92
- # Input for nodes
93
- nodes_input = st.text_area("Enter nodes (e.g., A, B, C, D, E, F, G, H):")
94
- edges_input = st.text_area("Enter edges with weights (e.g., (A, B, 4), (B, C, 8)):").strip()
95
-
96
- # Input for start and end nodes
97
  start_node = st.text_input("Enter start node (e.g., A):")
98
  end_node = st.text_input("Enter end node (e.g., E):")
99
 
@@ -103,20 +105,24 @@ def algorithms_shortest_path():
103
  # Parse the input for nodes and edges
104
  nodes = nodes_input.split(",")
105
  edges = [
106
- tuple(edge.strip()[1:-1].split(",") + [edge.strip().split(",")[-1]])
107
- for edge in edges_input.split("),")
108
- ]
109
- edges = [
110
- (edge[0], edge[1], int(edge[2])) for edge in edges if len(edge) == 3
111
  ]
 
112
 
113
- # Create the graph and add nodes and edges
114
  G = nx.Graph()
115
  G.add_nodes_from(nodes)
116
  G.add_weighted_edges_from(edges)
117
 
 
118
  st.write("Custom Graph:", G.edges())
119
- plot_shortest_path(G, start_node, end_node)
 
 
 
 
 
120
 
121
  except Exception as e:
122
  st.error(f"Error creating the graph: {e}")
 
25
  "Graph: DAG - Topological Layout", "Graph: Erdos Renyi", "Graph: Karate Club", "Graph: Minimum Spanning Tree",
26
  "Graph: Triads", "Algorithms: Cycle Detection", "Algorithms: Greedy Coloring", "Algorithms: Find Shortest Path"])
27
 
28
+ def plot_shortest_path(graph, start, end):
29
+ try:
30
+ # Find the shortest path from start to end node
31
+ path = nx.shortest_path(graph, source=start, target=end, weight='weight')
32
+ st.write(f"Shortest path from {start} to {end}:", path)
33
 
34
+ # Create a list of edges in the shortest path
35
+ path_edges = list(zip(path, path[1:]))
36
 
37
+ # Create a list of all edges, and assign colors based on whether they are in the shortest path or not
38
+ edge_colors = [
39
+ "red" if edge in path_edges or tuple(reversed(edge)) in path_edges else "black"
40
+ for edge in graph.edges()
41
+ ]
42
 
43
+ # Visualize the graph
44
+ pos = nx.spring_layout(graph)
45
+ nx.draw_networkx_nodes(graph, pos)
46
+ nx.draw_networkx_edges(graph, pos, edge_color=edge_colors)
47
+ nx.draw_networkx_labels(graph, pos)
48
+ nx.draw_networkx_edge_labels(
49
+ graph, pos, edge_labels={(u, v): d["weight"] for u, v, d in graph.edges(data=True)}
50
+ )
51
+ plt.title(f"Shortest Path from {start} to {end}")
52
+ st.pyplot(plt)
53
 
54
+ except nx.NetworkXNoPath:
55
+ st.error(f"No path found between {start} and {end}.")
56
+ except nx.NodeNotFound as e:
57
+ st.error(f"Error: {str(e)}")
58
 
59
  def algorithms_shortest_path():
60
  st.title("Algorithms: Find Shortest Path")
 
67
  )
68
 
69
  if graph_mode == "Default Example":
70
+ # Create a predefined graph for the shortest path example
71
  G = nx.Graph()
72
  G.add_nodes_from(["A", "B", "C", "D", "E", "F", "G", "H"])
73
  G.add_edge("A", "B", weight=4)
 
85
  G.add_edge("G", "I", weight=6)
86
  G.add_edge("H", "I", weight=7)
87
 
88
+ # Set start and end nodes
89
+ start = "A"
90
+ end = "E"
91
+ plot_shortest_path(G, start, end)
 
92
 
93
  elif graph_mode == "Create Your Own":
94
  st.write("### Create Your Own Graph")
95
 
96
+ # Input for creating a custom graph
97
+ nodes_input = st.text_area("Enter nodes (e.g., A, B, C, D):")
98
+ edges_input = st.text_area("Enter edges with weights (e.g., A,B,4, B,C,7):").strip()
 
 
99
  start_node = st.text_input("Enter start node (e.g., A):")
100
  end_node = st.text_input("Enter end node (e.g., E):")
101
 
 
105
  # Parse the input for nodes and edges
106
  nodes = nodes_input.split(",")
107
  edges = [
108
+ tuple(edge.split(","))
109
+ for edge in edges_input.split("\n") if edge.strip()
 
 
 
110
  ]
111
+ edges = [(u, v, int(weight)) for u, v, weight in edges] # Parse weights as integers
112
 
113
+ # Create graph
114
  G = nx.Graph()
115
  G.add_nodes_from(nodes)
116
  G.add_weighted_edges_from(edges)
117
 
118
+ # Show custom graph edges
119
  st.write("Custom Graph:", G.edges())
120
+
121
+ # Check if start and end nodes are valid
122
+ if start_node not in G.nodes or end_node not in G.nodes:
123
+ st.error("Start or End node is not in the graph!")
124
+ else:
125
+ plot_shortest_path(G, start_node, end_node)
126
 
127
  except Exception as e:
128
  st.error(f"Error creating the graph: {e}")