File size: 9,602 Bytes
38f979d
 
 
e39c5f4
38f979d
f2eec95
8f75d16
f2eec95
72f2a80
e39c5f4
 
98c04d6
8038dda
c6e0851
 
 
 
 
 
 
e39c5f4
 
 
 
 
c6e0851
e39c5f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8038dda
 
e39c5f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e0851
e39c5f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6e0851
e39c5f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c04d6
 
 
 
 
 
 
 
 
 
 
 
 
 
e39c5f4
 
 
 
 
98c04d6
 
 
 
 
 
 
 
 
 
 
 
 
e39c5f4
 
 
 
f2eec95
e39c5f4
 
 
 
 
 
 
 
 
 
 
 
 
f2eec95
 
e39c5f4
 
 
 
 
5a61687
e39c5f4
 
 
 
5a61687
 
72f2a80
 
e39c5f4
 
 
 
e95128d
 
e39c5f4
 
 
8f75d16
e39c5f4
f2eec95
e39c5f4
5a61687
e39c5f4
72f2a80
 
e39c5f4
 
 
 
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
import streamlit as st
import matplotlib.pyplot as plt
import networkx as nx
import bz2

# 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", 
                                  "Drawing: Chess Masters"])

# Helper function to draw and display graph
def draw_graph(G, pos=None, title="Graph Visualization", edgewidth=None, nodesize=None):
    if edgewidth is None:
        edgewidth = [1] * len(G.edges())  # Default edge width if not provided

    if nodesize is None:
        nodesize = [300] * len(G.nodes())  # Default node size if not provided

    plt.figure(figsize=(12, 12))
    nx.draw_networkx_edges(G, pos, alpha=0.3, width=edgewidth, edge_color="m")
    nx.draw_networkx_nodes(G, pos, node_size=nodesize, node_color="#210070", alpha=0.9)
    label_options = {"ec": "k", "fc": "white", "alpha": 0.7}
    nx.draw_networkx_labels(G, pos, font_size=14, bbox=label_options)

    # Title/legend
    font = {"fontname": "Helvetica", "color": "k", "fontweight": "bold", "fontsize": 14}
    ax = plt.gca()
    ax.set_title(title, font)
    ax.text(
        0.80,
        0.10,
        "edge width = # games played",
        horizontalalignment="center",
        transform=ax.transAxes,
        fontdict=font,
    )
    ax.text(
        0.80,
        0.06,
        "node size = # games won",
        horizontalalignment="center",
        transform=ax.transAxes,
        fontdict=font,
    )

    # Resize figure for label readability
    ax.margins(0.1, 0.05)
    plt.axis("off")
    st.pyplot(plt)


def chess_pgn_graph(pgn_file="chess_masters_WCC.pgn.bz2"):
    """Read chess games in pgn format in pgn_file.
    
    Filenames ending in .bz2 will be uncompressed.
    
    Return the MultiDiGraph of players connected by a chess game.
    Edges contain game data in a dict.
    """
    G = nx.MultiDiGraph()
    game = {}
    with bz2.BZ2File(pgn_file) as datafile:
        lines = [line.decode().rstrip("\r\n") for line in datafile]
    for line in lines:
        if line.startswith("["):
            tag, value = line[1:-1].split(" ", 1)
            game[str(tag)] = value.strip('"')
        else:
            if game:
                white = game.pop("White")
                black = game.pop("Black")
                G.add_edge(white, black, **game)
                game = {}
    return G


# Draw Chess Masters Graph (the main section)
def display_chess_masters_graph():
    st.title("Drawing: Chess Masters")

    option = st.radio("Choose a graph type:", ("Default Example", "Create your own"))

    if option == "Default Example":
        G = chess_pgn_graph("chess_masters_WCC.pgn.bz2")

        # identify connected components of the undirected version
        H = G.to_undirected()
        Gcc = [H.subgraph(c) for c in nx.connected_components(H)]
        if len(Gcc) > 1:
            st.write(f"Note the disconnected component consisting of:\n{Gcc[1].nodes()}")

        # find all games with B97 opening (as described in ECO)
        openings = {game_info["ECO"] for (white, black, game_info) in G.edges(data=True)}
        st.write(f"\nFrom a total of {len(openings)} different openings,")
        st.write("the following games used the Sicilian opening")
        st.write('with the Najdorff 7...Qb6 "Poisoned Pawn" variation.\n')

        for white, black, game_info in G.edges(data=True):
            if game_info["ECO"] == "B97":
                summary = f"{white} vs {black}\n"
                for k, v in game_info.items():
                    summary += f"   {k}: {v}\n"
                summary += "\n"
                st.write(summary)

        # Create undirected graph H without multi-edges
        H = nx.Graph(G)

        # Edge width is proportional to number of games played
        edgewidth = [len(G.get_edge_data(u, v)) for u, v in H.edges()]

        # Node size is proportional to number of games won
        wins = dict.fromkeys(G.nodes(), 0.0)
        for u, v, d in G.edges(data=True):
            r = d["Result"].split("-")
            if r[0] == "1":
                wins[u] += 1.0
            elif r[0] == "1/2":
                wins[u] += 0.5
                wins[v] += 0.5
            else:
                wins[v] += 1.0
        nodesize = [wins[v] * 50 for v in H]

        # Generate layout for visualization
        pos = nx.kamada_kawai_layout(H)

        # Manually tweak some positions to avoid label overlap
        pos["Reshevsky, Samuel H"] += (0.05, -0.10)
        pos["Botvinnik, Mikhail M"] += (0.03, -0.06)
        pos["Smyslov, Vassily V"] += (0.05, -0.03)

        # Draw the graph
        draw_graph(H, pos, title="World Chess Championship Games: 1886 - 1985", edgewidth=edgewidth, nodesize=nodesize)

    elif option == "Create your own":
        uploaded_file = st.file_uploader("Upload your own PGN file", type="pgn")
        if uploaded_file is not None:
            G_custom = chess_pgn_graph(uploaded_file)
            # Identify connected components and draw the graph for the uploaded data
            H_custom = G_custom.to_undirected()
            edgewidth = [len(G_custom.get_edge_data(u, v)) for u, v in H_custom.edges()]
            wins = dict.fromkeys(G_custom.nodes(), 0.0)
            for u, v, d in G_custom.edges(data=True):
                r = d["Result"].split("-")
                if r[0] == "1":
                    wins[u] += 1.0
                elif r[0] == "1/2":
                    wins[u] += 0.5
                    wins[v] += 0.5
                else:
                    wins[v] += 1.0
            nodesize = [wins[v] * 50 for v in H_custom]
            pos_custom = nx.kamada_kawai_layout(H_custom)
            draw_graph(H_custom, pos_custom, title="Custom Chess Game Graph", edgewidth=edgewidth, nodesize=nodesize)

# Display other sections
def display_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)

    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)

        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)

def display_graph_properties(G):
    pathlengths = []
    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])

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

    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")

    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)}")

    st.write("### Graph Visualization")
    pos = nx.spring_layout(G, seed=3068)
    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)

# Display other sections
def display_read_write_graph():
    st.title("Basic: Read and write graphs")
    G = nx.karate_club_graph()

    # Write the graph
    nx.write_gml(G, "karate_club.gml")
    st.write("Graph written to 'karate_club.gml'.")

    # Read the graph back
    G_new = nx.read_gml("karate_club.gml")
    st.write("Graph read back from 'karate_club.gml'.")
    nx.draw(G_new, with_labels=True)
    st.pyplot(plt)

def display_simple_graph():
    st.title("Basic: Simple graph")
    G = nx.complete_graph(5)
    nx.draw(G, with_labels=True)
    st.pyplot(plt)

def display_simple_directed_graph():
    st.title("Basic: Simple graph Directed")
    G = nx.complete_graph(5, nx.DiGraph())
    nx.draw(G, with_labels=True)
    st.pyplot(plt)

def display_custom_node_position():
    st.title("Drawing: Custom Node Position")
    pos = {"A": (1, 2), "B": (2, 3), "C": (3, 1)}
    G = nx.Graph(pos)
    nx.draw(G, pos=pos, with_labels=True)
    st.pyplot(plt)


# Call the appropriate function based on sidebar selection
if sidebar_option == "Basic: Properties":
    display_basic_properties()
elif sidebar_option == "Basic: Read and write graphs":
    display_read_write_graph()
elif sidebar_option == "Basic: Simple graph":
    display_simple_graph()
elif sidebar_option == "Basic: Simple graph Directed":
    display_simple_directed_graph()
elif sidebar_option == "Drawing: Custom Node Position":
    display_custom_node_position()
elif sidebar_option == "Drawing: Chess Masters":
    display_chess_masters_graph()
else:
    st.write("Please select a valid option from the sidebar.")