Skip to content

Commit b6ba0e9

Browse files
authored
Add files via upload
1 parent e6839e6 commit b6ba0e9

File tree

1 file changed

+160
-145
lines changed

1 file changed

+160
-145
lines changed

graphs/VisualizeGraph.py

+160-145
Original file line numberDiff line numberDiff line change
@@ -1,179 +1,194 @@
11
import networkx as nx
22
import matplotlib.pyplot as plt
3-
# https://networkx.org/documentation/latest/tutorial.html
4-
# Link for tutorial
53

64

7-
8-
def visualize_graph_from_adjacency_matrix(adj_matrix):
9-
# Create an empty graph
10-
G = nx.Graph()
11-
12-
# Add nodes and edges from adjacency matrix
13-
for i in range(len(adj_matrix)):
14-
for j in range(i, len(adj_matrix)): # Iterate only over upper triangle for undirected graph
15-
if adj_matrix[i][j] > 0: # There's an edge between node i and j
16-
G.add_edge(i, j, weight=adj_matrix[i][j])
5+
# For tutorial of networkx visit https://networkx.org/documentation/latest/tutorial.html
176

18-
# Set up layout for the graph visualization
19-
pos = nx.spring_layout(G, seed=42) # Spring layout for better visualization
207

21-
# Plot the graph
22-
plt.figure(figsize=(8, 8))
23-
24-
# Draw the graph with node colors and edge colors
25-
nx.draw(G, pos, with_labels=True, node_color='skyblue', node_size=700, edge_color='gray', width=2)
268

27-
# Optionally draw edge labels if the graph is weighted
28-
edge_labels = nx.get_edge_attributes(G, 'weight')
29-
if edge_labels:
30-
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
31-
32-
# Display the graph
33-
plt.title("Graph Visualization from Adjacency Matrix", size=15)
34-
plt.axis('off')
35-
plt.show()
9+
def undirected_visualize_from_adjmat(adjmat):
10+
size = len(adjmat)
3611

37-
38-
def visualize(n):
12+
# Create a graph object
3913
G = nx.Graph()
4014

41-
# Add edges where i is divisible by j
42-
for i in range(1, n + 1):
43-
for j in range(1, n + 1):
44-
if i % j == 0 and i != j:
45-
G.add_edge(i, j, weight=1)
15+
for i in range(size):
16+
for j in range(size):
17+
if adjmat[i][j] != 0:
18+
# Add edge to the graph object
19+
G.add_edge(i, j, weight=adjmat[i][j])
20+
4621

47-
# Set up layout for better spacing between nodes
48-
pos = nx.spring_layout(G, seed=42)
22+
# Specify the layout of graph
23+
pos = nx.spring_layout(G)
4924

50-
# Create a figure
5125
plt.figure(figsize=(10, 10))
5226

53-
# Customize node colors with a color map
54-
node_colors = range(1, n + 1)
55-
cmap = plt.cm.viridis # Use a color map (e.g., 'viridis', 'plasma')
56-
57-
# Draw nodes with color mapping, size scaling
58-
nx.draw_networkx_nodes(G, pos, node_color=node_colors, cmap=cmap, node_size=800)
59-
60-
# Draw edges with custom width and transparency
61-
nx.draw_networkx_edges(G, pos, width=2.5, edge_color="slategrey")
62-
63-
# Add labels to nodes with larger font size
64-
nx.draw_networkx_labels(G, pos, font_size=14, font_color="white", font_weight="bold")
27+
# Draw the vertices
28+
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='skyblue', alpha=0.9)
29+
30+
# Draw the edges
31+
nx.draw_networkx_edges(G, pos, width=2, alpha=0.5, edge_color='gray')
32+
33+
# Draw the Vertices Labels
34+
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black', font_family='sans-serif')
6535

66-
# Optionally draw edge labels (for weighted edges if applicable)
36+
# Draw the weights of edges
6737
edge_labels = nx.get_edge_attributes(G, 'weight')
68-
if edge_labels:
69-
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
70-
71-
# Add a title with larger font
72-
plt.title(f"Divisibility Graph Visualization (n = {n})", size=20, color="darkblue", pad=20)
73-
74-
# Turn off the axis
75-
plt.axis("off")
38+
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='black', font_size=10)
7639

77-
# Display the graph
40+
plt.title("Undirected Graph Visualization", size=15)
41+
plt.axis('off')
7842
plt.show()
7943

8044

81-
def condition(G,n):
82-
# Dynamically add edges where i is divisible by j, skip j=1 for clarity
83-
for i in range(1, n + 1):
84-
for j in range(2, n + 1): # Skip j=1 to avoid self-loop-like behavior
85-
if i % j == 0 and i != j:
86-
G.add_edge(j, i, weight=1) # Directed edge from j to i
87-
88-
def visualize_dag(n):
89-
G = nx.DiGraph() # Create a directed graph (DAG)
90-
91-
condition(G,n)
92-
93-
# Calculate the actual nodes included in the graph
94-
node_list = list(G.nodes())
9545

96-
# Set up layout for better spacing between nodes
97-
pos = nx.spring_layout(G, seed=42)
98-
# pos = nx.circular_layout(G)
99-
# pos = nx.shell_layout(G)
100-
# pos = nx.random_layout(G)
101-
# pos = nx.kamada_kawai_layout(G)
102-
# pos = nx.planar_layout(G)
103-
# pos = nx.spectral_layout(G,seed = 42)
104-
# pos = nx.spiral_layout(G,seed = 42)
105-
# pos = nx.multipartite_layout(G,seed = 42)
10646

47+
def directed_visualize_from_adjmat(adjmat):
48+
size = len(adjmat)
10749

50+
# Create a Digraph object
51+
G = nx.DiGraph()
10852

53+
for i in range(size):
54+
for j in range(size):
55+
if adjmat[i][j] != 0:
56+
# Add edges to the graph object
57+
G.add_edge(i, j, weight=adjmat[i][j])
10958

59+
# Specify the layout to use while plotting the graph
60+
pos = nx.spring_layout(G)
11061

111-
# Create a figure
11262
plt.figure(figsize=(10, 10))
11363

114-
# Customize node colors with a color map
115-
node_colors = range(len(node_list)) # Range over dynamically created nodes
116-
cmap = plt.cm.viridis # Use a color map (e.g., 'viridis', 'plasma')
117-
118-
# Draw nodes with color mapping, size scaling
119-
nx.draw_networkx_nodes(G, pos, node_color=node_colors, cmap=cmap, node_size=800)
120-
121-
# Draw edges with arrows, custom width, and transparency
122-
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), width=2.5, edge_color="slategrey", arrows=True, arrowstyle='->', arrowsize=20)
123-
124-
# Add labels to nodes with larger font size
125-
nx.draw_networkx_labels(G, pos, font_size=14, font_color="white", font_weight="bold")
64+
# Draw the vertices
65+
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='skyblue', alpha=0.9)
66+
67+
# Draw the labels for vertices
68+
nx.draw_networkx_edges(G, pos,arrowstyle='-|>', arrowsize=30, width=2, alpha=0.5, edge_color='gray')
69+
70+
# Draw the weights
71+
nx.draw_networkx_labels(G, pos, font_size=12, font_color='black', font_family='sans-serif')
12672

127-
# Optionally draw edge labels (for weighted edges if applicable)
73+
# Draw the weights
12874
edge_labels = nx.get_edge_attributes(G, 'weight')
129-
if edge_labels:
130-
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
75+
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color='black', font_size=10)
13176

132-
# Add a title with larger font
133-
plt.title(f"DAG Visualization with Dynamic Nodes (n = {n})", size=20, color="darkblue", pad=20)
134-
135-
# Turn off the axis
136-
plt.axis("off")
137-
138-
# Display the graph
77+
plt.title("Directed Graph Visualization", size=15)
78+
plt.axis('off')
13979
plt.show()
14080

141-
# Visualize the DAG for a given n
142-
# visualize_dag(12)
143-
144-
145-
146-
147-
148-
149-
150-
151-
152-
153-
154-
155-
# Example adjacency matrix (unweighted graph)
156-
adj_matrix = [
157-
[0, 1, 0, 0, 1],
158-
[1, 0, 1, 1, 1],
159-
[0, 1, 0, 1, 0],
160-
[0, 1, 1, 0, 1],
161-
[1, 1, 0, 1, 0]
162-
]
163-
164-
# Visualize the graph
165-
# visualize_graph_from_adjacency_matrix(adj_matrix)
166-
167-
168-
169-
# Visualize the graph for a given n
170-
# visualize(12)
171-
172-
173-
174-
# Visualize the DAG for a given n
175-
visualize_dag(15)
176-
177-
178-
17981

82+
def visualize_from_adjmat(adjmat,isdirected):
83+
if isdirected:
84+
directed_visualize_from_adjmat(adjmat)
85+
else:
86+
undirected_visualize_from_adjmat(adjmat)
87+
88+
89+
90+
91+
def edges_to_adjacency_matrix(vertex_count, edge_count, is_directed):
92+
'''
93+
Takes input in form of edges and convert it to adjacency matrix.
94+
'''
95+
96+
adjacency_matrix = [[0] * vertex_count for _ in range(vertex_count)]
97+
for _ in range(edge_count):
98+
u, v, weight = map(int, input().split())
99+
adjacency_matrix[u][v] = weight
100+
if not is_directed:
101+
adjacency_matrix[v][u] = weight
102+
return adjacency_matrix
103+
104+
def matinput(vertex_count, edge_count, is_directed):
105+
'''
106+
Takes input in form of adjacency matrix and convert it to adjacency matrix.
107+
'''
108+
109+
adjacency_matrix = []
110+
print("Enter the adjacency matrix row by row:")
111+
for _ in range(vertex_count):
112+
row = list(map(int, input().split()))
113+
adjacency_matrix.append(row)
114+
return adjacency_matrix
115+
116+
def list_to_adjacency_matrix(vertex_count, edge_count, is_directed):
117+
'''
118+
Takes input in form of adjacency list and convert it to adjacency matrix.
119+
'''
120+
121+
adjacency_matrix = [[0] * vertex_count for _ in range(vertex_count)]
122+
print("Enter the adjacency list:")
123+
for u in range(vertex_count):
124+
print("Neighbours of ",u,end=": ")
125+
neighbours = input().split()
126+
for neigh in neighbours:
127+
v,weight = map(int,neigh.split(','))
128+
adjacency_matrix[u][v] = weight
129+
if not is_directed:
130+
adjacency_matrix[v][u] = weight
131+
return adjacency_matrix
132+
133+
134+
def main():
135+
vertex_count = int(input("Enter the number of vertices: "))
136+
edge_count = int(input("Enter the number of edges: "))
137+
is_directed = int(input("Is the graph Directed?? 1 or 0 :"))
138+
139+
print("Enter the type of input:")
140+
print("1: Edge List")
141+
print("2: Adjacency Matrix")
142+
print("3: Adjacency List")
143+
input_type = int(input())
144+
145+
if input_type == 1:
146+
print("The expected input is of the form u v w where w is the weight.")
147+
adjacency_matrix = edges_to_adjacency_matrix(vertex_count, edge_count, is_directed)
148+
elif input_type == 2:
149+
print("Expected input is of the form V columns and V rows with the weights of the edges.")
150+
adjacency_matrix = matinput(vertex_count, edge_count, is_directed)
151+
elif input_type == 3:
152+
print("Expected input is of the form for neighbour vertex v,w")
153+
adjacency_matrix = list_to_adjacency_matrix(vertex_count, edge_count, is_directed)
154+
else:
155+
print("Enter valid input.")
156+
return
157+
158+
visualize_from_adjmat(adjacency_matrix, is_directed)
159+
160+
if __name__ == "__main__":
161+
main()
162+
163+
164+
165+
'''
166+
Example Inputs:
167+
168+
1) Edge List:
169+
170+
The expected input is of the form u v w where w is the weight.
171+
0 1 1
172+
0 2 1
173+
0 3 1
174+
3 1 1
175+
3 2 1
176+
177+
2) Adj Mat:
178+
179+
Expected input is of the form V columns and V rows with the weights of the edges.
180+
Enter the adjacency matrix row by row:
181+
0 1 1 1
182+
1 0 0 1
183+
1 0 0 1
184+
1 1 1 0
185+
186+
3) Adj List:
187+
Expected input is of the form for neighbour vertex v,w
188+
Enter the adjacency list:
189+
Neighbours of 0: 1,2 2,3 3,-3
190+
Neighbours of 1: 2,3
191+
Neighbours of 2: 3,-3
192+
Neighbours of 3:
193+
194+
'''

0 commit comments

Comments
 (0)