-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
764 lines (681 loc) · 24.1 KB
/
main.py
File metadata and controls
764 lines (681 loc) · 24.1 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
from typing import Union
import dash
from dash import dcc
from dash import html
import plotly.graph_objects as go
from dash.dependencies import Input, Output
import networkx as nx
import csv
import pandas as pd
from dash import dash_table
import dash_bootstrap_components as dbc
import scholar_network
import pickle
from utils import graphing, utils
from dotenv import load_dotenv
import os
load_dotenv()
def load_scholar_names_from_file() -> list[str]:
"""Loads scholars from file.
Returns:
list[str]: A list of scholar names.
"""
with open("data/COPscholars.csv", "r") as f:
csvreader = csv.DictReader(f)
authors = []
for row in csvreader:
authors.append(row.get("Name"))
return authors
def load_ipop_scholar_names_from_file() -> list[str]:
"""Loads, specifically, IPOP scholars from file.
Returns:
list[str]: List of IPOP scholar names.
"""
with open("data/IPOP-Scholars.csv", "r") as f:
csvreader = csv.DictReader(f)
authors = []
for row in csvreader:
authors.append(row.get("Name"))
return authors
def load_sure_scholar_names_from_file() -> list[str]:
"""Loads, specifically, SURE scholars from file.
Returns:
list[str]: List of SURE scholar names.
"""
with open("data/SUREscholars.csv", "r") as f:
csvreader = csv.DictReader(f)
authors = []
for row in csvreader:
authors.append(
row.get("First", "").strip() + " " + row.get("Last", "").strip()
)
return authors
def create_cop_network_graph_figure():
"""Creates entire network graph.
This function calls our utility and graphing functions
to generate the entire network once on page load.
Returns:
[go.Figure]: plotly figure representing drawn network.
"""
graph, positions = utils.load_graph_from_files()
node_trace, edge_trace = graphing.build_network(graph, positions)
fig = graphing.draw_network(node_trace, edge_trace, title="COP Network Graph")
return fig
def create_ipop_network_graph_figure():
"""Creates entire network graph for IPOP scholars only.
This function calls our utility and graphing functions
to generate the entire network once on page load.
Returns:
[go.Figure]: plotly figure representing drawn network.
"""
graph, positions = utils.load_ipop_graph_from_files()
node_trace, edge_trace = graphing.build_network(graph, positions)
fig = graphing.draw_network(node_trace, edge_trace, title="IPOP Network Graph")
return fig
def create_sure_graph_figure():
"""Creates entire network graph for POC scholars only.
This function calls our utility and graphing functions
to generate the entire network once on page load.
Returns:
[go.Figure]: plotly figure representing drawn network.
"""
with open("data/sure-graph.pkl", "rb") as f:
graph = pickle.load(f)
with open("data/sure-pos.pkl", "rb") as f:
positions = pickle.load(f)
node_trace, edge_trace = graphing.build_network(graph, positions)
fig = graphing.draw_network(node_trace, edge_trace, title="SURE Network Graph")
return fig
def parse_name(name: str) -> str:
"""Extracts first and last parts of a name.
This could be first and last name or any variation.
Args:
name (str): String name to be parsed
Returns:
str: Extracted 2-part name.
"""
parts = name.split()
parsed = f"{parts[0][0]} {parts[-1]}".title()
if parsed == "J Mcginty":
return "J McGinty"
return parsed
def pair_graph(name1: str, name2: str) -> go.Figure:
"""Draws a graph, given two scholars to filter the network on.
Args:
author1 (str): first scholar name to filter on
author2 (str): second scholar name to filter on
Returns:
go.Figure: drawn network graph
"""
a1 = parse_name(name1) if name1 else None
a2 = parse_name(name2) if name2 else None
graph = scholar_network.build_graph(a1, a2)
print(name1, "--0-", name2)
print(graph.node_pairs())
# ! time consuming, re-looping over nodes
# ! also, try to just filter the pickled graph instead of recreating a new one
G = nx.Graph()
print(name1, "--1-", name2)
G.add_edges_from(graph.node_pairs())
print(name1, "--2-", name2)
positions = nx.spring_layout(G)
print(name1, "--3-", name2)
node_trace, edge_trace = graphing.build_network(G, positions, a1, a2)
fig = graphing.draw_network(
node_trace,
edge_trace,
title=f"{name1.title() if name1 else '...'} x {name2.title() if name2 else '...'} Network Graph",
)
return fig
def pair_graph_sure(name1: str, name2: str) -> go.Figure:
"""Draws a graph, given two scholars to filter the network on.
Args:
author1 (str): first scholar name to filter on
author2 (str): second scholar name to filter on
Returns:
go.Figure: drawn network graph
"""
a1 = parse_name(name1) if name1 else None
a2 = parse_name(name2) if name2 else None
graph = scholar_network.build_graph(a1, a2, fpath="data/scraped_sure.json")
print(a1, "--0-", a2)
# ! time consuming, re-looping over nodes
# ! also, try to just filter the pickled graph instead of recreating a new one
G = nx.Graph()
print(a1, "--1-", a2)
G.add_edges_from(graph.node_pairs())
print(a1, "--2-", a2)
positions = nx.spring_layout(G)
print(a1, "--3-", a2)
node_trace, edge_trace = graphing.build_network(G, positions, a1, a2)
fig = graphing.draw_network(
node_trace,
edge_trace,
title=f"{name1.title() if name1 else '...'} x {name2.title() if name2 else '...'} Network Graph",
)
print(a1, "--4-", a2)
return fig
def make_datatable(df: pd.DataFrame) -> dash_table.DataTable:
"""Creates a datatable of all scholars."""
table = dash_table.DataTable(
id="datatable",
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("records"),
style_cell={"textAlign": "left"},
style_header={"backgroundColor": "rgb(3, 60, 115)", "color": "white"},
filter_action="native",
sort_action="native",
sort_mode="single",
page_size=20,
)
return table
# dash globals
theme = "https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/sketchy/bootstrap.min.css"
app = dash.Dash(
__name__,
title="COP Scholar Network Dashboard",
external_stylesheets=[dbc.themes.CERULEAN],
)
server = app.server
app.config["suppress_callback_exceptions"] = True
# call these once here, in global state, at application startup, then reuse
scholar_names = load_scholar_names_from_file()
ipop_names = load_ipop_scholar_names_from_file()
all_names = set(scholar_names) | set(ipop_names)
sure_names = load_sure_scholar_names_from_file()
sure_graph = create_sure_graph_figure()
cop_network_graph = create_cop_network_graph_figure()
ipop_network_graph = create_ipop_network_graph_figure()
counts_df = pd.read_csv("data/coauthor_counts.csv")
table = make_datatable(counts_df)
# tab for entire COP
tab1 = dbc.Container(
[
dbc.Row(
[
dbc.Col(
[
html.H2("Description:", className="text-center text-info"),
html.Hr(),
html.P(
[
"This network graph shows authors and their direct coauthors. "
"When an author is selected you are able to see the author's entire network graph. "
"When you select two authors, you are able to see their combined network(s) and any "
"shared connections they may have. Note that only full graphs for the selected authors "
"are shown, and any other authors are only showcasing a sub-graph or sub-network of their "
"entire network. To see their entire network, selected them from the dropdown. If they "
"are not in the dropdown, then you can request to add them, although at this time only "
"COP scholars are included. There are: ",
html.Span(
f"{len(scholar_names)} COP ",
className="strong text-primary",
),
"scholars/authors available to choose from.",
]
),
],
width=9,
)
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Col(
[
html.Label("Author 1 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown1",
options=[],
value="",
),
],
width=4,
),
dbc.Col(
[
html.Label("Author 2 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown2",
options=[],
value="",
),
],
width=4,
),
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Card(
dbc.Spinner(
dcc.Graph(id="network-graph"),
type="grow",
color="primary",
size="lg",
),
className="p-3 m-3",
body=True,
)
],
className="px-5",
justify="center",
align="center",
),
],
fluid=True,
)
# tab for IPOP only
tab2 = dbc.Container(
[
dbc.Row(
[
dbc.Col(
[
html.H2("Description:", className="text-center text-info"),
html.Hr(),
html.P(
[
"This network graph shows authors and their direct coauthors. "
"When an author is selected you are able to see the author's entire network graph. "
"When you select two authors, you are able to see their combined network(s) and any "
"shared connections they may have. Note that only full graphs for the selected authors "
"are shown, and any other authors are only showcasing a sub-graph or sub-network of their "
"entire network. To see their entire network, selected them from the dropdown. If they "
"are not in the dropdown, then you can request to add them, although at this time only "
"COP scholars are included. There are: ",
html.Span(
f"{len(ipop_names)} IPOP ",
className="strong text-primary",
),
"scholars/authors available to choose from.",
]
),
],
width=9,
)
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Col(
[
html.Label("Author 1 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown3",
options=[],
value="",
),
],
width=4,
),
dbc.Col(
[
html.Label("Author 2 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown4",
options=[],
value="",
),
],
width=4,
),
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Card(
dbc.Spinner(
dcc.Graph(figure=ipop_network_graph, id="ipop-graph"),
type="grow",
color="primary",
size="lg",
),
className="p-3 m-3",
body=True,
)
],
className="px-5",
justify="center",
align="center",
),
],
fluid=True,
)
# tab for SURE conference only
tab3 = dbc.Container(
[
dbc.Row(
[
dbc.Col(
[
html.Img(
src="/assets/sure_logo.PNG",
style={
"display": "block",
"margin-left": "auto",
"margin-right": "auto",
"width": "30%",
},
className="text-center",
),
html.P(
[
"There are: ",
html.Span(
f"{len(sure_names)} SURE ",
className="strong text-primary",
),
"scholars/authors available to choose from.",
]
),
],
width=9,
)
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Col(
[
html.Label("Author 1 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown5",
options=[],
value="",
),
],
width=4,
),
dbc.Col(
[
html.Label("Author 2 Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown6",
options=[],
value="",
),
],
width=4,
),
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Card(
dbc.Spinner(
dcc.Graph(figure=sure_graph, id="poc-graph"),
type="grow",
color="primary",
size="lg",
),
className="p-3 m-3",
body=True,
)
],
className="px-5",
justify="center",
align="center",
),
],
fluid=True,
)
# tabe 4 for datatabel
tab4 = dbc.Container(
[
dbc.Row(
[
dbc.Col(
[
html.H2("Description:", className="text-center text-info"),
html.Hr(),
html.P(
[
"This page showcases UK COP authors and their co-authors. "
"Use the dropdown to select an author and see their co-author specifically. "
]
),
],
width=9,
)
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Col(
[
html.Label("Author Select:", className="text-info"),
dcc.Dropdown(
id="author-dropdown4",
options=[
{"label": person, "value": person}
for person in sorted(scholar_names)
],
value="",
),
],
width=6,
),
],
justify="center",
align="center",
),
dbc.Row(
[
dbc.Card(
children=table,
className="p-3 m-3",
id="table-card",
body=True,
)
],
className="px-5",
justify="center",
align="center",
),
],
fluid=True,
)
# content for main card area
main_content = dbc.Card(
[
dbc.CardHeader(
dbc.Tabs(
[
dbc.Tab(label="COP", tab_id="tab-1", tabClassName="mx-auto"),
dbc.Tab(label="IPOP", tab_id="tab-2", tabClassName="mx-auto"),
dbc.Tab(label="SURE", tab_id="tab-3", tabClassName="mx-auto"),
dbc.Tab(label="Data Table", tab_id="tab-4", tabClassName="mx-auto"),
],
id="card-tabs",
active_tab="tab-1",
)
),
dbc.CardBody(id="main_content_body"),
]
)
# layout for entire application
app.layout = dbc.Container(
[
dbc.Row(
[
dbc.Col(
[
html.Img(
src="/assets/IPOP-logo.png",
style={"width": "100px"},
)
],
align="center",
width=2,
),
dbc.Col(
[
html.H1(
children="UK COP Scholarship Network",
className="text-info",
style={"text-align": "center"},
)
],
width=4,
),
dbc.Col(
[
html.Img(
src="/assets/UK-COP-logo.jpg",
style={"width": "250px", "height": "200px"},
)
],
align="center",
width=2,
),
],
justify="center",
align="center",
),
main_content,
],
fluid=True,
)
@app.callback(
Output(component_id="table-card", component_property="children"),
Input(component_id="author-dropdown4", component_property="value"),
)
def update_options_table(input_value: str) -> dash_table.DataTable:
"""Dynamically adjust datatable to selected author."""
if input_value:
first, last = input_value.split(" ")
return make_datatable(counts_df[counts_df["Author 1"] == f"{first[0]} {last}"])
return make_datatable(df=counts_df)
@app.callback(
Output(component_id="author-dropdown2", component_property="options"),
Input(component_id="author-dropdown1", component_property="value"),
)
def update_options1(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(scholar_names)
if person != input_value
]
@app.callback(
Output(component_id="author-dropdown1", component_property="options"),
Input(component_id="author-dropdown2", component_property="value"),
)
def update_options2(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(scholar_names)
if person != input_value
]
@app.callback(
Output(component_id="author-dropdown4", component_property="options"),
Input(component_id="author-dropdown3", component_property="value"),
)
def update_options3(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(ipop_names)
if person != input_value
]
@app.callback(
Output(component_id="author-dropdown3", component_property="options"),
Input(component_id="author-dropdown4", component_property="value"),
)
def update_options4(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(ipop_names)
if person != input_value
]
@app.callback(
Output(component_id="author-dropdown6", component_property="options"),
Input(component_id="author-dropdown5", component_property="value"),
)
def update_options5(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(sure_names)
if person != input_value
]
@app.callback(
Output(component_id="author-dropdown5", component_property="options"),
Input(component_id="author-dropdown6", component_property="value"),
)
def update_options6(input_value: str) -> list[dict[str, str]]:
"""Dynamically adjust dropdown options to not include selected."""
return [
{"label": person, "value": person}
for person in sorted(sure_names)
if person != input_value
]
@app.callback(
Output("network-graph", "figure"),
[
Input(component_id="author-dropdown1", component_property="value"),
Input(component_id="author-dropdown2", component_property="value"),
],
)
def draw_cop_graph(author1: Union[str, None], author2: Union[str, None]) -> go.Figure:
"""Generate new visualization given author filters or load default."""
if author1 or author2:
return pair_graph(author1, author2)
return cop_network_graph
@app.callback(
Output("ipop-graph", "figure"),
[
Input(component_id="author-dropdown3", component_property="value"),
Input(component_id="author-dropdown4", component_property="value"),
],
)
def draw_ipop_graph(author1: Union[str, None], author2: Union[str, None]) -> go.Figure:
"""Generate new visualization given author filters or load default."""
if author1 or author2:
return pair_graph(author1, author2)
return ipop_network_graph
@app.callback(
Output("poc-graph", "figure"),
[
Input(component_id="author-dropdown5", component_property="value"),
Input(component_id="author-dropdown6", component_property="value"),
],
)
def draw_poc_graph(author1: Union[str, None], author2: Union[str, None]) -> go.Figure:
"""Generate new visualization given author filters or load default."""
if author1 or author2:
return pair_graph_sure(author1, author2)
return sure_graph
@app.callback(
Output("main_content_body", "children"), [Input("card-tabs", "active_tab")]
)
def tab_content(active_tab):
"""Control tab navigation."""
if active_tab == "tab-2":
return tab2
elif active_tab == "tab-3":
return tab3
elif active_tab == "tab-4":
return tab4
else:
return tab1
# run main application
if __name__ == "__main__":
app.run_server(debug=os.getenv("DEBUG", False))