File size: 9,998 Bytes
38f979d
 
 
72f2a80
38f979d
f2eec95
8f75d16
f2eec95
72f2a80
 
98c04d6
8f75d16
98c04d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f75d16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2eec95
ff6ff0e
f2eec95
 
 
 
 
 
 
 
e4dd1a7
 
ff6ff0e
f2eec95
 
 
 
 
 
 
5a61687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72f2a80
 
 
35916b9
 
 
 
 
 
 
 
 
 
 
 
 
72f2a80
8f75d16
e95128d
67e7fee
e95128d
98c04d6
8f75d16
e95128d
 
98c04d6
e95128d
 
 
 
 
 
c8786b4
 
 
 
 
8f75d16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8786b4
 
 
 
 
f2eec95
 
 
 
 
 
e4dd1a7
f2eec95
e4dd1a7
 
 
 
 
 
 
 
 
 
 
 
f2eec95
 
50a227a
f2eec95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4dd1a7
f2eec95
 
 
 
5a61687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50a227a
5a61687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72f2a80
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import streamlit as st
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

# Sidebar for selecting an option
sidebar_option = st.sidebar.radio("Select an option", 
                                 ["Select an option", "Basic: Properties", 
                                  "Basic: Read and write graphs", "Basic: Simple graph", 
                                  "Basic: Simple graph Directed", "Drawing: Custom Node Position"])

# Function to display properties and graph for Basic: Properties
def display_graph_properties(G):
    # Initialize a list for path lengths
    pathlengths = []

    # Display the source-target shortest path lengths
    st.write("### Source vertex {target:length, }")
    for v in G.nodes():
        spl = dict(nx.single_source_shortest_path_length(G, v))
        st.write(f"Vertex {v}: {spl}")
        for p in spl:
            pathlengths.append(spl[p])

    # Calculate and display the average shortest path length
    avg_path_length = sum(pathlengths) / len(pathlengths)
    st.write(f"### Average shortest path length: {avg_path_length}")

    # Calculate and display the distribution of path lengths
    dist = {}
    for p in pathlengths:
        if p in dist:
            dist[p] += 1
        else:
            dist[p] = 1

    st.write("### Length #paths")
    for d in sorted(dist.keys()):
        st.write(f"Length {d}: {dist[d]} paths")

    # Display the graph metrics with a "Properties" heading
    st.write("### Properties")
    st.write(f"Radius: {nx.radius(G)}")
    st.write(f"Diameter: {nx.diameter(G)}")
    st.write(f"Eccentricity: {nx.eccentricity(G)}")
    st.write(f"Center: {nx.center(G)}")
    st.write(f"Periphery: {nx.periphery(G)}")
    st.write(f"Density: {nx.density(G)}")

    # Visualize the graph
    st.write("### Graph Visualization")
    pos = nx.spring_layout(G, seed=3068)  # Seed layout for reproducibility
    plt.figure(figsize=(8, 6))
    nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500, font_size=10, font_weight='bold')
    st.pyplot(plt)

# Function to display graph for Basic: Read and write graphs
def display_read_write_graph(G):
    # Print the adjacency list of the graph
    st.write("### Adjacency List:")
    for line in nx.generate_adjlist(G):
        st.write(line)
    
    # Write the graph's edge list to a file
    st.write("### Writing Edge List to 'grid.edgelist' file:")
    nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
    st.write("Edge list written to 'grid.edgelist'")

    # Read the graph from the edge list
    st.write("### Reading Edge List from 'grid.edgelist' file:")
    H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
    st.write("Edge list read into graph H")

    # Visualize the graph
    st.write("### Graph Visualization:")
    pos = nx.spring_layout(H, seed=200)  # Seed for reproducibility
    plt.figure(figsize=(8, 6))
    nx.draw(H, pos, with_labels=True, node_color='lightblue', node_size=500, font_size=10, font_weight='bold')
    st.pyplot(plt)

# Function to display Simple Graphs for Basic: Simple graph
def display_simple_graph(G, pos=None):
    options = {
        "font_size": 36,
        "node_size": 3000,
        "node_color": "white",
        "edgecolors": "black",
        "linewidths": 5,
        "width": 5,
    }
    
    # Draw the network
    nx.draw_networkx(G, pos, **options)

    # Set margins for the axes so that nodes aren't clipped
    ax = plt.gca()
    ax.margins(0.20)
    plt.axis("off")
    st.pyplot(plt)

# Function to display Simple Directed Graphs for Basic: Simple graph Directed
def display_simple_directed_graph(G, pos=None):
    options = {
        "node_size": 500,
        "node_color": "lightblue",
        "arrowsize": 20,
        "width": 2,
        "edge_color": "gray",
    }
    
    # Draw the directed graph with the given positions and options
    nx.draw_networkx(G, pos, **options)

    # Set margins for the axes so that nodes aren't clipped
    ax = plt.gca()
    ax.margins(0.20)
    plt.axis("off")
    st.pyplot(plt)

# Function to display Custom Node Position Graphs for Drawing: Custom Node Position
def display_custom_node_position():
    st.title("Drawing: Custom Node Position")
    
    # Default example graph (path graph with custom node position)
    G = nx.path_graph(20)
    center_node = 5
    edge_nodes = set(G) - {center_node}
    
    # Ensure the nodes around the circle are evenly distributed
    pos = nx.circular_layout(G.subgraph(edge_nodes))
    pos[center_node] = np.array([0, 0])  # Manually specify node position
    
    # Draw the graph
    nx.draw(G, pos, with_labels=True)
    st.pyplot(plt)

# Display Basic: Properties if selected
if sidebar_option == "Basic: Properties":
    st.title("Basic: Properties")
    option = st.radio("Choose a graph type:", ("Default Example", "Create your own"))

    # Default example: 5x5 grid graph
    if option == "Default Example":
        G = nx.lollipop_graph(4, 6)
        display_graph_properties(G)

    # Create your own graph
    elif option == "Create your own":
        num_nodes = st.number_input("Number of nodes:", min_value=2, max_value=50, value=5)
        num_edges = st.number_input("Number of edges per group (for lollipop graph):", min_value=1, max_value=10, value=3)

        # Button to generate the graph
        if st.button("Generate"):
            if num_nodes >= 2 and num_edges >= 1:
                G_custom = nx.lollipop_graph(num_nodes, num_edges)
                display_graph_properties(G_custom)

# Display Basic: Read and write graphs if selected
elif sidebar_option == "Basic: Read and write graphs":
    st.title("Basic: Read and write graphs")
    option = st.radio("Choose a graph type:", ("Default Example", "Create your own"))

    # Default example: 5x5 grid graph
    if option == "Default Example":
        G = nx.grid_2d_graph(5, 5)  # 5x5 grid
        display_read_write_graph(G)

    # Create your own graph
    elif option == "Create your own":
        rows = st.number_input("Number of rows:", min_value=2, max_value=20, value=5)
        cols = st.number_input("Number of columns:", min_value=2, max_value=20, value=5)

        # Button to generate the graph
        if st.button("Generate"):
            if rows >= 2 and cols >= 2:
                G_custom = nx.grid_2d_graph(rows, cols)
                display_read_write_graph(G_custom)

# Display Basic: Simple Graph if selected
elif sidebar_option == "Basic: Simple graph":
    st.title("Basic: Simple graph")
    option = st.radio("Choose a graph type:", ("Default Example", "Create your own"))

    # Default example: simple undirected graph
    if option == "Default Example":
        G = nx.Graph()
        G.add_edge(1, 2)
        G.add_edge(1, 3)
        G.add_edge(1, 5)
        G.add_edge(2, 3)
        G.add_edge(3, 4)
        G.add_edge(4, 5)

        # explicitly set positions for visualization
        pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}
        display_simple_graph(G, pos)

    # Create your own graph
    elif option == "Create your own":
        # num_nodes = st.number_input("Number of nodes:", min_value=2, max_value=20, value=5)
        edges = []
        
        # Let the user define edges
        st.write("Enter the edges (as pairs of nodes) separated by commas. For example, 1,2 or 3,4.")
        edge_input = st.text_area("Edges:", value="1,2\n1,3\n2,3")
        
        # Parse the edges
        if edge_input:
            edge_list = edge_input.split("\n")
            for edge in edge_list:
                u, v = map(int, edge.split(","))
                edges.append((u, v))

        # Button to generate the graph
        if st.button("Generate"):
            G_custom = nx.Graph()
            G_custom.add_edges_from(edges)
            
            # Set a basic layout (spring layout as default)
            pos = nx.spring_layout(G_custom, seed=42)
            display_simple_graph(G_custom, pos)

# Display Basic: Simple Directed Graph if selected
elif sidebar_option == "Basic: Simple graph Directed":
    st.title("Basic: Simple graph Directed")
    option = st.radio("Choose a graph type:", ("Default Example", "Create your own"))

    # Default example: simple directed graph
    if option == "Default Example":
        G = nx.DiGraph([(0, 3), (1, 3), (2, 4), (3, 5), (3, 6), (4, 6), (5, 6)])

        # Group nodes by column
        left_nodes = [0, 1, 2]
        middle_nodes = [3, 4]
        right_nodes = [5, 6]

        # Set the position according to column (x-coord)
        pos = {n: (0, i) for i, n in enumerate(left_nodes)}
        pos.update({n: (1, i + 0.5) for i, n in enumerate(middle_nodes)})
        pos.update({n: (2, i + 0.5) for i, n in enumerate(right_nodes)})

        # Draw the directed graph
        display_simple_directed_graph(G, pos)

    # Create your own directed graph
    elif option == "Create your own":
        # num_nodes = st.number_input("Number of nodes:", min_value=2, max_value=20, value=5)
        edges = []
        
        # Let the user define directed edges
        st.write("Enter the directed edges (as pairs of nodes) separated by commas. For example, 1,2 or 3,4.")
        edge_input = st.text_area("Edges:", value="1,2\n1,3\n2,3")
        
        # Parse the edges
        if edge_input:
            edge_list = edge_input.split("\n")
            for edge in edge_list:
                u, v = map(int, edge.split(","))
                edges.append((u, v))

        # Button to generate the directed graph
        if st.button("Generate"):
            G_custom = nx.DiGraph()
            G_custom.add_edges_from(edges)
            
            # Set a basic layout (spring layout as default)
            pos = nx.spring_layout(G_custom, seed=42)
            display_simple_directed_graph(G_custom, pos)

# Display Drawing: Custom Node Position if selected
elif sidebar_option == "Drawing: Custom Node Position":
    display_custom_node_position()