-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
696 lines (644 loc) · 22.8 KB
/
app.py
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
import itertools as it
import sys
from tempfile import NamedTemporaryFile
import io
import base64
import numpy as np
import pandas as pd
import dash
from dash.dependencies import Output, Input, State
from dash import dcc, html, ALL
from dash.exceptions import PreventUpdate
import dash_bio as dashbio
import dash_bootstrap_components as dbc
import dash_cytoscape as cyto
# Load extra layouts
cyto.load_extra_layouts()
import networkx as nx
import plotly.graph_objects as go
import plotly.express as px
import seaborn as sns
from matplotlib.figure import Figure
from components import *
from utils import *
from layouts.landing_page_layout import landing_page_layout
from layouts.heatmap_layout import make_heatmap_layout
from layouts.network_layout import make_network_layout
if __name__ == "__main__":
FONT_AWESOME = "https://use.fontawesome.com/releases/v5.7.2/css/all.css"
external_stylesheets = [
FONT_AWESOME,
dbc.themes.JOURNAL,
]
app = dash.Dash(
__name__,
external_stylesheets=external_stylesheets,
suppress_callback_exceptions=False,
)
server = app.server
colorscales = px.colors.named_colorscales()
try:
assert len(sys.argv) == 2
except:
raise ValueError(
"app.py accepts exactly one argument. Please use the included sample sheet maker to create the required file."
)
# get the files
print("Parsing sample sheet. . .")
metas, dms, pa, tree = initialize_data(sys.argv[1])
# make the network
print("Initializing network. . . ")
G = make_graph(metas, dms)
node_items = [{"label": node, "value": node} for node in G.nodes]
print("Done. Configuring dashboard. . .")
dm_metric_options = []
for i, tup in enumerate(dms):
dm_metric_options.append({"label": tup[0], "value": tup[0]})
# dms is a list of tuples
dm_dict = {attr: frame for attr, frame in dms}
# metas is either list of tuples or empty list
meta_dict = {attr: frame for attr, frame in metas}
default_stylesheet = [
{
"selector": "edge",
"style": {
#'width': 'mapData(lr, 50, 200, 0.75, 5)',
"opacity": 0.4,
},
},
{
"selector": "node",
"style": {
#'color': '#317b75',
"background-color": "#317b75",
"content": "data(label)",
},
},
{
"selector": ".focal",
"style": {
#'color': '#E65340',
"background-color": "#E65340",
"content": "data(label)",
},
},
{
"selector": ".other",
"style": {
#'color': '#317b75',
"background-color": "#317b75",
"content": "data(label)",
},
},
]
################################################################################
### Page Layouts ###
################################################################################
### Entry Point. Also Serves as data dump for sharing between apps ###
app.layout = html.Div(
[
dcc.Location(id="url", refresh=False),
# Stores for data persistence.
dcc.Store(id="node-data-store"),
make_navbar(active=0),
html.Div(id="page-content"),
]
)
### Heat Map Viewer Layout ###
page1_layout = make_heatmap_layout(dm_metric_options, colorscales)
### Network viz layout ###
page2_layout = make_network_layout(
node_items, list(dm_dict.keys()), default_stylesheet
)
page3_layout = dbc.Container(
fluid=True,
children=[
dbc.Row(
id="historgram-display",
children=[
dbc.Col(
[
dcc.Loading(
#html.Img(id="clustergram-graph"),
dcc.Graph(id='clustergram-graph', style={'width': '90vh', 'height': '90vh'}),
),
dbc.Row(
[],
),
]
),
],
),
],
)
################################################################################
### Heatmap Callbacks ###
################################################################################
@app.callback(
Output("slider-container", "children"), [Input("dataset-select", "value")]
)
def update_colorscale_slider(metric):
df = dm_dict[metric]
maxval = np.nanmax(df.values)
minval = np.nanmin(df.values)
slider = dcc.RangeSlider(
min=minval,
max=maxval,
step=(maxval - minval) / 100,
marks={
minval: {"label": "{:.2f}".format(minval)},
maxval: {
"label": "{:.2f}".format(maxval),
},
},
value=[minval, maxval],
tooltip={"placement": "bottom", "always_visible": False},
id={"role": "slider", "index": 0},
)
#print(minval, maxval)
return slider
@app.callback(
Output({"role": "slider", "index": ALL}, "value"),
[
Input("minus-button", "n_clicks"),
Input("plus-button", "n_clicks"),
State({"role": "slider", "index": ALL}, "value"),
],
)
def update_marks(minus, plus, sliderstate):
ctx = dash.callback_context
slidervals = sliderstate[0]
minval = slidervals[0]
maxval = slidervals[-1]
n_vals = len(slidervals)
if not ctx.triggered:
button_id = "noclick"
else:
button_id = ctx.triggered[0]["prop_id"].split(".")[0]
if button_id == "noclick":
return dash.no_update
elif button_id == "minus-button":
if n_vals <= 2:
return dash.no_update
vals = list(np.linspace(minval, maxval, n_vals - 1))
return [vals]
else:
vals = list(np.linspace(minval, maxval, n_vals + 1))
return [vals]
@app.callback(
Output("heatmap-graph", "figure"),
[
Input("heatmap-button", "n_clicks"),
State("dataset-select", "value"),
State("colorscale", "value"),
State("plot-mode-radio", "value"),
State({"role": "slider", "index": ALL}, "value"),
],
)
def plot(click, dataset, scale, mode, slidervals):
fig = go.Figure()
# empty initially
feature_df = dm_dict[dataset]
meta_df = None
if dataset in meta_dict.keys():
meta_df = meta_dict[dataset]
if len(slidervals) == 0:
slidervals = [np.nanmin(feature_df.values), np.nanmax(feature_df.values)]
else:
slidervals = slidervals[0]
slidervals = sorted(slidervals)
if mode == 2:
colorscale = []
colors = get_color(scale, np.linspace(0, 1, len(slidervals) - 1))
minval = min(slidervals)
maxval = max(slidervals)
normed_vals = [(x - minval) / (maxval - minval) for x in slidervals]
for i, _ in enumerate(normed_vals[:-1]):
colorscale.append([normed_vals[i], colors[i]])
colorscale.append([normed_vals[i + 1], colors[i]])
else:
colorscale = scale
ava_hm = go.Heatmap(
x=feature_df.columns,
y=feature_df.index,
z=feature_df,
colorscale=colorscale,
zmin=slidervals[0],
zmax=slidervals[-1],
# colorbar=colorbar,
)
if type(meta_df) != type(None):
meta_hm = go.Heatmap(
x=meta_df.columns,
y=meta_df.index,
z=meta_df,
colorscale=colorscale,
zmin=slidervals[0],
zmax=slidervals[-1],
showscale=False,
)
f1 = go.Figure(meta_hm)
for data in f1.data:
fig.add_trace(data)
f2 = go.Figure(ava_hm)
for i in range(len(f2["data"])):
f2["data"][i]["xaxis"] = "x2"
for data in f2.data:
fig.add_trace(data)
fig.update_layout({"height": 800})
fig.update_layout(
xaxis={
"domain": [0.0, 0.20],
"mirror": False,
"showgrid": False,
"showline": False,
"zeroline": False,
#'ticks':"",
#'showticklabels': False
}
)
# Edit xaxis2
fig.update_layout(
xaxis2={
"domain": [0.25, 1.0],
"mirror": False,
"showgrid": False,
"showline": False,
"zeroline": False,
#'showticklabels': False,
#'ticks':""
}
)
else:
f = go.Figure(ava_hm)
for data in f.data:
fig.add_trace(data)
fig.update_layout({"height": 800})
fig.update_layout(
xaxis={
"mirror": False,
"showgrid": False,
"showline": False,
"zeroline": False,
"tickmode": "array",
"ticktext": feature_df.columns.str.slice(-8).tolist(),
}
)
return fig
################################################################################
### Network Visualization Callbacks ###
################################################################################
@app.callback(
Output("network-plot", "layout"), Input("network-callbacks-1", "value")
)
def update_layout(layout):
return {"name": layout, "animate": True}
@app.callback(
Output("download-network", "data"),
[
Input("download-network-button", "n_clicks"),
State("node-dropdown", "value"),
State("degree", "value"),
State({"role": "threshold", "index": ALL}, "value"),
State({"role": "bounds-select", "index": ALL}, "value"),
],
)
def download_network(click, nodes, degree, thresholds, bounds):
n_nodes = 0
n_edges = 0
attributes = list(dm_dict.keys())
H = None
if len(nodes) == 0:
elements = []
else:
H = filter_graph(G, nodes, degree, attributes, thresholds, bounds)
if H:
nfile = NamedTemporaryFile("w")
# nfile.name = 'tmp/network.graphml' TODO how can i change the name of this file?
nx.readwrite.graphml.write_graphml(H, nfile.name)
return dcc.send_file(nfile.name)
return dash.no_update
@app.callback(
Output("node-data-store", "data"),
[
Input("interactive-button", "n_clicks"),
State("node-dropdown", "value"),
State("degree", "value"),
State({"role": "threshold", "index": ALL}, "value"),
State({"role": "bounds-select", "index": ALL}, "value"),
],
)
def update_elements(click, nodes, degree, thresholds, bounds):
print("UPDATE ELEMENTS INVOKED")
n_nodes = 0
n_edges = 0
attributes = list(dm_dict.keys())
if len(nodes) == 0:
nodes = [i["value"] for i in node_items]
# else:
H = filter_graph(G, nodes, degree, attributes, thresholds, bounds)
connected = list(H.nodes)
# Graph basics
elements = nx_to_dash(H, nodes)
n_nodes = len(H.nodes)
n_edges = len(H.edges)
# end else
summary_data = {
"nodes": nodes,
'connected_nodes': connected,
"degree": degree,
"attributes": [],
"n_nodes": n_nodes,
"n_edges": n_edges,
}
for attr, thresh in zip(attributes, thresholds):
summary_data["attributes"].append({"attribute": attr, "threshold": thresh})
#print(summary_data)
return {"elements": elements, "summary_data": summary_data}
@app.callback(
Output("network-plot", "elements"),
[Input("node-data-store", "modified_timestamp"),
State("node-data-store", "data")],
)
def update_network_plot(ts, data):
if ts is None:
raise PreventUpdate
return data["elements"]
@app.callback(
Output("node-selected", "children"),
[Input("node-data-store", "modified_timestamp"),
State("node-data-store", "data")],
)
def update_node_summary(ts, data):
if ts is None:
raise PreventUpdate
summary_data = [
dbc.ListGroupItem("Focal Node: {}".format(data["summary_data"]["nodes"])),
dbc.ListGroupItem("Degree: {}".format(data["summary_data"]["degree"])),
]
for attribute_record in data["summary_data"]["attributes"]:
summary_data.append(
dbc.ListGroupItem(
"{0} threshold: {1}".format(
attribute_record["attribute"], attribute_record["threshold"]
)
),
)
summary_data += [
dbc.ListGroupItem("n Nodes: {}".format(data["summary_data"]["n_nodes"])),
dbc.ListGroupItem("n Edges: {}".format(data["summary_data"]["n_edges"])),
]
# summary = html.P("Focal Node: {0}\nDegree: {1}<br>LR Threshold: {2}<br>P Threshold: {3}<br>Nodes in selection: {4}<br>Edges in selection: {5}".format(node, degree, lr_threshold, p_threshold,n_nodes, n_edges))
summary = dbc.ListGroup(
summary_data,
)
return summary
@app.callback(
Output("network-plot", "stylesheet"), [Input("network-plot", "tapNode")],
)
def highlight_edges(node):
if not node:
return default_stylesheet
stylesheet = [
{
"selector": "edge",
"style": {
"opacity": 0.4,
#'width': 'mapData(lr, 50, 200, 0.75, 5)',
},
},
{
"selector": "node",
"style": {
#'color': '#317b75',
"background-color": "#317b75",
"content": "data(label)",
"width": "mapData(degree, 1, 100, 25, 200)",
},
},
{
"selector": ".focal",
"style": {
#'color': '#E65340',
"background-color": "#E65340",
"content": "data(label)",
},
},
{
"selector": ".other",
"style": {
#'color': '#317b75',
"background-color": "#317b75",
"content": "data(label)",
},
},
{
"selector": 'node[id = "{}"]'.format(node["data"]["id"]),
"style": {
"background-color": "#B10DC9",
"border-color": "purple",
"border-width": 2,
"border-opacity": 1,
"opacity": 1,
"label": "data(label)",
"color": "#B10DC9",
"text-opacity": 1,
"font-size": 12,
"z-index": 9999,
},
},
]
for edge in node["edgesData"]:
stylesheet.append(
{
"selector": 'node[id= "{}"]'.format(edge["target"]),
"style": {
"background-color": "blue",
"opacity": 0.9,
},
}
)
stylesheet.append(
{
"selector": 'node[id= "{}"]'.format(edge["source"]),
"style": {
"background-color": "blue",
"opacity": 0.9,
},
}
)
stylesheet.append(
{
"selector": 'edge[id= "{}"]'.format(edge["id"]),
"style": {"line-color": "green", "opacity": 0.9, "z-index": 5000},
}
)
return stylesheet
################################################################################
### Dendrogram Callbacks ###
################################################################################
@app.callback(
Output('clustergram-graph', 'figure'),
[Input("node-data-store", "modified_timestamp"),
State("node-data-store", "data")],
)
def create_clustergram(ts, data):
if not ts or isinstance(pa, type(None)) or isinstance(tree, type(None)): #TODO plot the P/A if there's no tree
raise PreventUpdate
# subset_pa = pa[data['summary_data']['nodes']]
# fig = Figure()
# ax = fig.subplots()
# clustergram_kwargs = {
# 'data': subset_pa,
# 'row_linkage': tree,
# 'cbar_pos' : None,
# 'cmap' : sns.color_palette(['#f5f5f5', '#021657']),
# 'method' : 'complete',
# 'xticklabels':1,
# 'yticklabels': False,
# 'ax': ax,
# }
# if not isinstance(metas, type(None)):
# #process the metadata and add a row_colors arg
# pass
# #g = sns.clustermap(**clustergram_kwargs)
# #create a bytes buffer, put the plot into bytes
# # The buffer will populate an <img> HTML tag
# ax.plot([1,2])
# buf = io.BytesIO()
# fig.savefig(buf, format='png')
# data = base64.b64encode(buf.getbuffer()).decode('utf8')
# buf.close()
# return "data:image/png;base64.{}".format(data)
subset_pa = pa[data['summary_data']['connected_nodes']]
def phylo_linkage(y, method='single', metric='euclidean', optimal_ordering=False):
"""
A hack to allow us to use Clustergram. Linkage is precomputed
"""
return tree
print("========")
print(f"Treeshape: {tree.shape}")
print(f"Subset PA shape: {subset_pa.shape}")
print(f"PA shape: {pa.shape}")
print("========")
clustergram = dashbio.Clustergram(
data = subset_pa.values,
row_labels = list(subset_pa.index),
column_labels = list(subset_pa.columns.values),
link_fun = phylo_linkage,
cluster='row',
hidden_labels='row',
height=900,
width=1100,
color_map= [
[0.0, '#FFFFFF'],
[1.0, '#EF553B']
]
)
return clustergram
"""
@app.callback(
Output('histogram-graph', 'figure'),
[Input('histogram-button', 'n_clicks'),
State('histogram-metric-select', 'value'),
State('histogram-y-select', 'value')]
)
def show_histogram(click, metric_sel, y_sel):
metric_map = {
'1': ('lr', 'p'),
'2': ('p', 'lr')
}
y_map = {
'1': 'node_degree',
'2': 'n_nodes',
'3': 'n_edges'
}
dynamic_metric, static_metric = metric_map[str(metric_sel)]
y = y_map[str(y_sel)]
lte = lambda x,y: x<=y
gte = lambda x,y: x>=y
if dynamic_metric == 'lr':
search = [25, 50, 100, 150]
dfun = gte
sfun = lte
else:
search = [0.05, 1e-5, 1e-9, 1e-12]
dfun = lte
sfun = gte
if static_metric == 'p':
static_threshold = 0.05
else:
static_threshold = 50
records = []
node_list = []
for node in G.nodes:
node_list.append((node, {**G.nodes[node]}))
for dynamic_threshold in search:
F= nx.Graph()
F.add_nodes_from(node_list)
edges = []
for u,v,e in G.edges(data=True):
if dfun(e[dynamic_metric], dynamic_threshold) and sfun(e[static_metric], static_threshold):
#if e['lr'] >= lr_threshold and e['p'] <= p_threshold:
edges.append((u,v, e))
F.add_edges_from(edges)
graph_degree = F.degree()
for i, node in enumerate(F.nodes):
Sub = F.subgraph(neighborhood(F, node, 2))
n_nodes = len(Sub.nodes)
n_edges = len(Sub.edges)
records.append({'node': node,
'node_degree': graph_degree[node],
'n_nodes': n_nodes,
'n_edges': n_edges,
dynamic_metric: dynamic_threshold,
static_metric: static_threshold,})
rdf = pd.DataFrame.from_records(records)
plot = px.histogram(rdf, x='node', y=y, facet_col=dynamic_metric)
plot.update_layout({'height':800})
return plot
"""
################################################################################
### Page Navigation callbacks ###
################################################################################
@app.callback(
[
Output("page-content", "children"),
Output("page-1-nav", "className"),
Output("page-2-nav", "className"),
Output("page-3-nav", "className"),
],
[
Input("url", "pathname"),
],
)
def display_page(pathname):
if pathname == "/page-1":
return (
page1_layout,
"active",
"",
"",
)
elif pathname == "/page-2":
return (
page2_layout,
"",
"active",
"",
)
elif pathname == "/page-3":
return (
page3_layout,
"",
"",
"active",
)
else:
return (
landing_page_layout,
"",
"",
"",
)
app.run_server(debug=True, dev_tools_ui=True)