-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
834 lines (723 loc) · 36.2 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
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
"""
3D-Scere app.
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_cytoscape as cyto
import dash_table
from dash.dependencies import Input, Output, State
import networkx as nx
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import lib.tools as tools
import lib.visualization_2D as vis2D
import lib.visualization_3D as vis3D
########################
############APP_INITIALIZATION############
########################
NAME = "3D-Scere"
FONTAWESOME = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
LITERA = "https://cdn.jsdelivr.net/npm/bootswatch@4.5.2/dist/litera/bootstrap.min.css"
GO_terms = pd.read_csv("./static/GO_terms.csv")
GO_terms_options = [{"label": GO, "value": GO} for GO in GO_terms["GO_terms"]]
plotly_segments = pd.read_csv("./static/plotly_segments.csv")
edges_list = pd.read_parquet("./static/3D_distances.parquet.gzip", engine="pyarrow")
demo_1 = pd.read_csv("./example_data/gene_list_example_UPC2_38_targets.csv")
demo_2 = pd.read_csv("./example_data/quantitative_variables_example.csv")
# Get all features for all gene
SQL_QUERY = \
"""SELECT Primary_SGDID, Standard_gene_name, Chromosome, Feature_name, Strand, Stop_coordinate, Start_coordinate, Description
FROM SGD_features
"""
all_feature_name = tools.get_locus_info("./static/SCERE.db", SQL_QUERY)
#3D distance histogram constants
BIN_NUMBER = 50
all_x = list(edges_list["3D_distances"])
H2, X = np.histogram(all_x, bins=BIN_NUMBER, range=(0, 200))
H2 = H2/len(all_x)
F2 = np.cumsum(H2)/sum(H2)
basic_stylesheet = [{"selector": "node", "style": {"background-color": "#BFD7B5"}},
{"selector": "node", "style": {"label": "data(label)"}}]
colors = ["darkred", "red", "darkorange", "orange", "gold", "green",
"mediumseagreen", "turquoise", "deepskyblue", "dodgerblue",
"blueviolet", "purple", "magenta", "deeppink", "crimson", "black"]
app = dash.Dash(name=NAME, assets_folder="./assets", external_stylesheets=[dbc.themes.LUX, LITERA])
app.title = NAME
app.config.suppress_callback_exceptions = True
server = app.server
########################
############DASHBOARD_LAYOUT############
########################
############APP_HEADER############
header = html.Div(
[dbc.Row(
[
html.Img(src="./static/yeast_icon.png", height="70px"),
html.H1("3D-Scere", style={"padding-left": "2%", "padding-top": "1%"})
])
],
style = {"padding-down": "4%", "padding-top": "2%"})
summary = html.Details([html.Summary([html.H3("Introduction")]),
html.Div("""3D-Scere is an open-source online tool for interactive visualization and exploration.
This tool allows the visualization of any list of genes in the context of the 3D model of S. cerevisiae genome.
Further information can easily be added like functional annotations (GO terms) or gene expression measurements.
Qualitative or quantitative functional properties are thus highlighted in the large-scale 3D context of the genome
with only a few mouse clicks.""")
], open = True)
############APP_INPUTS_COMPONENTS############
input_tab1 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("csv file upload", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Upload a one column .csv file with YORF")]),
dcc.Upload(id="upload_data_tab1", children=html.Div(
["Drag and Drop or ",
html.A("Select Files")
]),
style={"height": "60px",
"lineHeight": "60px",
"borderWidth": "1px",
"borderStyle": "dashed",
"borderRadius": "5px",
"textAlign": "center",
"margin": "10px"},
multiple=True),
dcc.Loading(children=[html.Div(id="output_data_upload_tab1")]),
]),
dbc.Col(
[dbc.Row(style={"height" : 63}),
dbc.Button("Load demo data", id="demo_tab1", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"})
])
]),
dbc.Row(style={"height" : 35}),
dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("GO terms", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Choose a GO term to tag")]),
dcc.Dropdown(
id="GoTerm-dropdown",
options=GO_terms_options,
placeholder="select a GO term"),
]),
dbc.Col(
[
dbc.Row([html.H3("Color", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Choose the tagging color of the GO term")]),
dcc.Dropdown(
id="color-dropdown",
options=[
{"label": "Red", "value": "red"},
{"label": "Green", "value": "green"},
{"label": "Yellow", "value": "yellow"}],
placeholder="select a color"),
]),
]),
dbc.Row(style={"height" : 25}),
dbc.Row(
[
dbc.Button("Submit", id="Submit_tab1", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"})
],
justify="end"
)
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
input_tab2 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("csv file upload", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Upload a .csv file with YORF in the first column")]),
dcc.Upload(id="upload_data_tab2", children=html.Div(
["Drag and Drop or ",
html.A("Select Files")
]),
style={"height": "60px",
"lineHeight": "60px",
"borderWidth": "1px",
"borderStyle": "dashed",
"borderRadius": "5px",
"textAlign": "center",
"margin": "10px"},
multiple=True),
dbc.Button("Load demo data", id="demo_tab2", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"}),
dcc.Loading(children=[html.Div(id="output_data_upload_tab2")]),
]),
dbc.Col(
[
dbc.Row([html.H3("Color scale", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Color scales can be diverging or linear")]),
dcc.Dropdown(
id="color_scale_dropdown",
options=[
{"label": "rainbow (diverging scale)", "value": "Rainbow"},
{"label": "picnic (diverging scale)", "value": "Picnic"},
{"label": "viridis", "value": "Viridis"},
{"label": "plasma", "value": "Plasma"},
{"label": "thermal", "value": "thermal"}],
placeholder="select a color scale"),
])
]),
dbc.Row(style={"height" : 25}),
dbc.Row(
[
dbc.Button("Submit", id="Submit_tab2", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"})
],
justify="end"
)
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
input_tab3 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("csv file upload", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Upload a one column .csv file with YORF")]),
dcc.Upload(id="upload_data_tab3", children=html.Div(
["Drag and Drop or ",
html.A("Select Files")
]),
style={"height": "60px",
"lineHeight": "60px",
"borderWidth": "1px",
"borderStyle": "dashed",
"borderRadius": "5px",
"textAlign": "center",
"margin": "10px"},
multiple=True),
dcc.Loading(children=[html.Div(id="output_data_upload_tab3")]),
]),
dbc.Col(
[dbc.Row(style={"height" : 63}),
dbc.Button("Load demo data", id="demo_tab3", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"})
]),
]),
dbc.Row(style={"height" : 25}),
dbc.Row(
[
dbc.Button("Submit", id="Submit_tab3", outline=True, color="primary", className="mr-1", style={"vertical-align": "middle"})
],
justify="end"
)
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
slider_tab3 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("3D distances treshold", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Select a threshold under which 3D distances are used to construct the network")]),
dcc.Slider(id="treshold_slider",
min=0,
max=10,
step=1,
value=5),
html.Div(id='output_min_slider'),
html.Div(id='output_max_slider'),
html.Div(id='output_value_slider')
]),
dbc.Col(
[
]),
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
############APP_VISUALIZATIONS_COMPONENTS############
visualization_tab1 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("2D visualization", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="Scaled linear representation of the S. cerevisiae genome, each chromosome is represented as two stands : - above +")]),
dcc.Loading(children=[dcc.Graph(id="2D_representation")]),
])
]),
dbc.Row(
[
dbc.Col(
[
html.H3("Target's repartition on chromosomes"),
dcc.Loading(children=[dcc.Graph(id="Chromosomes_repartition")]),
])
]),
dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("3D visualizations", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="3D representations of the S cerevisiae genome, the size of loci on chromosomes are not to scale")]),
dcc.Loading(children=[dcc.Graph(id="3D_representation")]),
])
]),
dbc.Row(
[
dbc.Col(
[
dcc.Loading(children=[dcc.Graph(id="3D_representation_chrom")]),
])
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
visualization_tab2 = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("3D visualization", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="3D representation of the S cerevisiae genome, the size of loci on chromosomes are not to scale")]),
dcc.Loading(children=[dcc.Graph(id="3D_representation_tab2")]),
])
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
visualization_tab3_hist = html.Div(
[ dbc.Row(
[
dbc.Col(
[
dbc.Row([html.H3("3D distances histogram", style={"padding-right" : "2%", "padding-left" : "2%"}),
html.Abbr("\u003f\u20dd", title="The treshold is dynamically represented by the dashed black line. CDF = cumulative distribution function")]),
dbc.Row(style={"height" : 10}),
dcc.Loading(children=[html.Img(id="hist", src="")])
]),
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
visualization_tab3_network = html.Div(
[ dbc.Row(
[
dbc.Col(
[
html.H3("Network visualization"),
dcc.Loading(children=[cyto.Cytoscape(id="network",
stylesheet=basic_stylesheet,
elements=[],
style={"width": "100%", "height": "400px"},
layout={"name": "random"})])
])
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
visualization_tab3_metrics = html.Div(
[ dbc.Row(
[
dbc.Col(
[
html.H3("Degrees distribution"),
html.Div(id="output_edges_number_tab3"),
html.Div(id="output_nodes_number_tab3"),
dcc.Loading(children=[dcc.Graph(id="Degrees_hist")])
])
])
],
className="shadow p-3 mb-5 bg-body rounded", style={"padding-top" : "1%"})
############APP_LAYOUT############
app.layout = dbc.Container(
[ header,
dbc.Row(style={"height" : 25}),
summary,
dbc.Row(style={"height" : 25}),
dcc.Tabs([
dcc.Tab(label="GO term projection", children=[
dbc.Row(style={"height" : 45}),
html.Div("""The projected list of genes can be colored uniformly or according to a selected Gene Ontology (GO) term.
Upload the genes list as a one column .csv file containing YORF, then click the submit button.
Optionally, select a GO term and a color before submitting to color associated genes in the list."""),
dbc.Row(style={"height" : 45}),
input_tab1,
visualization_tab1
]),
dcc.Tab(label="Quantitative variable projection", children=[
dbc.Row(style={"height" : 45}),
html.Div("""The projected list of genes can be colored according to a given quantitative variable.
Upload the genes list as a .csv file, with YORF in the first column. Then select the column corresponding to the quantitative variable and a color scale before
clicking on submit."""),
dbc.Row(style={"height" : 45}),
input_tab2,
visualization_tab2
]),
dcc.Tab(label="3D distances histogram and network", children=[
dbc.Row(style={"height" : 45}),
html.Div("""All the 3D distances between genes in the list are summarized into a histogram and a network.
Upload the genes list as a one column .csv file containing YORF, then click the submit button.
The slider determines the threshold under which 3D distances are used to construct the network."""),
dbc.Row(style={"height" : 45}),
input_tab3,
visualization_tab3_hist,
slider_tab3,
visualization_tab3_network,
visualization_tab3_metrics
]),
])
])
########################
############CALLBACKS############
########################
############TAB1_UPLOAD############
@app.callback(Output("output_data_upload_tab1", "children"),
Input("demo_tab1", "n_clicks"),
Input("upload_data_tab1", "contents"),
State("upload_data_tab1", "filename"))
def update_output(n_clicks, list_of_contents, list_of_names):
ctx = dash.callback_context
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "demo_tab1":
children = dash_table.DataTable(id="datatable_tab1",
data=demo_1.to_dict('records'),
columns=[{'name': i, 'id': i, "selectable": True} for i in demo_1.columns],
page_size=10,
column_selectable="multi",
selected_columns=[demo_1.columns[0]],
style_cell={'textAlign': 'left'},
style_data_conditional=[{'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'}],
style_header={'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'})
else:
if list_of_contents is not None:
children=[tools.parse_contents(c, n, "datatable_tab1") for c, n in zip(list_of_contents, list_of_names)]
return children
############TAB1_UPLOAD_STYLE############
@app.callback(
Output("datatable_tab1", "style_data_conditional"),
Input("datatable_tab1", "selected_columns"))
def update_styles_tab1(selected_columns):
return [{
"if": { "column_id": i },
"background_color": "#D2F3FF"
} for i in selected_columns]
############TAB1_2D_GRAPH############
@app.callback(Output("2D_representation", "figure"),
Input("Submit_tab1", "n_clicks"),
State("GoTerm-dropdown", "value"),
State("color-dropdown", "value"),
State("datatable_tab1", "derived_virtual_data"),
State("datatable_tab1", "selected_columns"))
def update_2D_graphs_tab1(n_clicks, GoTerm, color, data, column):
sql_query_gobal = \
"""SELECT Primary_SGDID, count(SGDID), Feature_name, Start_coordinate, Stop_coordinate, Chromosome, Strand, GO_slim_term
FROM SGD_features, go_slim_mapping
WHERE SGDID == Primary_SGDID
GROUP BY SGDID
ORDER BY Start_coordinate
"""
sql_query_specific = \
"""SELECT Primary_SGDID, count(SGDID), Feature_name, Start_coordinate, Stop_coordinate, Chromosome, Strand, GO_slim_term
FROM SGD_features, go_slim_mapping
WHERE SGDID == Primary_SGDID
AND (GO_slim_term == """ + "'" + str(GoTerm) + "'" + """)
GROUP BY SGDID
ORDER BY Start_coordinate
"""
all_loci = tools.get_locus_info("./static/SCERE.db", sql_query_gobal)
selected_loci = tools.get_locus_info("./static/SCERE.db", sql_query_specific)
loci = pd.concat([all_loci, selected_loci]).drop_duplicates(subset=["Primary_SGDID"], keep="last")
if column != []:
unfiltered_data = pd.DataFrame(data)
filtered_data = unfiltered_data[str(column[0])]
loci = loci.assign(FT_target=loci.Feature_name.isin(filtered_data))
loci.loc[loci.FT_target == True, "colors_parameters"]="Targets"
loci.loc[(loci.GO_slim_term == str(GoTerm)) & (loci.FT_target == True), "colors_parameters"]=str(GoTerm)
loci = vis2D.format_coordinates(loci, 6)
fig = vis2D.genome_drawing(loci, "colors_parameters", [str(GoTerm), "Targets"], [str(color), "Black"])
else :
loci = vis2D.format_coordinates(loci, 6)
fig = vis2D.genome_drawing(loci, "GO_slim_term", [str(GoTerm)], [str(color)])
return fig
############TAB1_CHROMOSOME_REPARTITION############
@app.callback(Output("Chromosomes_repartition", "figure"),
Input("Submit_tab1", "n_clicks"),
State("datatable_tab1", "derived_virtual_data"),
State("datatable_tab1", "selected_columns"))
def update_chrom_repartition_tab1(n_clicks, data, column):
sql_query_2 = \
"""SELECT Primary_SGDID, Feature_name, Start_coordinate, Stop_coordinate, Chromosome, Strand
FROM SGD_features
ORDER BY Start_coordinate
"""
if column != []:
unfiltered_data = pd.DataFrame(data)
filtered_data = unfiltered_data[str(column[0])]
loci = tools.get_locus_info("./static/SCERE.db", sql_query_2)
loci = loci.assign(FT_target=loci.Feature_name.isin(filtered_data))
loci = loci[loci.FT_target == True].drop(["FT_target"], axis=1)
loci.rename(columns = {'Chromosome':'chromosomes'}, inplace = True)
fig = px.histogram(loci, x="chromosomes", nbins=30, range_x=[0, 17], color_discrete_sequence=["#5767FF"])
fig.update_layout(plot_bgcolor="white",
bargap = 0.01,
xaxis_showgrid=False,
yaxis_showgrid=False,
showlegend=True)
fig.update_xaxes(dtick = 1)
fig.update_traces(marker={"opacity": 0.7})
return fig
############TAB1_3D_GRAPH_FEATURE############
@app.callback(Output("3D_representation", "figure"),
Input("Submit_tab1", "n_clicks"),
State("GoTerm-dropdown", "value"),
State("color-dropdown", "value"),
State("datatable_tab1", "derived_virtual_data"),
State("datatable_tab1", "selected_columns"))
def update_3D_graph_tab1(n_clicks, GoTerm, color, data, column):
sql_query_gobal = \
"""SELECT Primary_SGDID, count(SGDID), Feature_name, Start_coordinate, Stop_coordinate, Chromosome, Strand, GO_slim_term
FROM SGD_features, go_slim_mapping
WHERE SGDID == Primary_SGDID
GROUP BY SGDID
ORDER BY Start_coordinate
"""
sql_query_3 = \
"""SELECT Primary_SGDID, Feature_name, Start_coordinate, Stop_coordinate, Chromosome, Strand, GO_slim_term
FROM SGD_features, go_slim_mapping
WHERE SGDID == Primary_SGDID
AND (GO_slim_term == """ + "'" + str(GoTerm) + "'" + """)
GROUP BY SGDID
ORDER BY Start_coordinate
"""
all_loci = tools.get_locus_info("./static/SCERE.db", sql_query_gobal)
selected_loci = tools.get_locus_info("./static/SCERE.db", sql_query_3)
if column != []:
unfiltered_data = pd.DataFrame(data)
filtered_data = unfiltered_data[str(column[0])]
loci = all_loci.assign(FT_target=all_loci.Feature_name.isin(filtered_data))
loci = loci.assign(GoTerm=loci.Primary_SGDID.isin(selected_loci.Primary_SGDID))
loci.loc[loci.FT_target == True, "colors_parameters"]="Targets"
loci.loc[(loci.GoTerm == True) & (loci.FT_target == True), "colors_parameters"]=str(GoTerm)
loci_segments = plotly_segments.merge(loci, on="Primary_SGDID", how="left", copy=False)
loci_segments.index = range(1, len(loci_segments) + 1)
loci_segments = vis3D.get_color_discreet_3D(loci_segments, "colors_parameters", [str(GoTerm), "Targets"], [str(color), "blue"])
fig = vis3D.genome_drawing(loci_segments)
else :
selected_loci_segments = plotly_segments.merge(selected_loci, on="Primary_SGDID", how="left", copy=False)
selected_loci_segments.index = range(1, len(selected_loci_segments) + 1)
selected_loci_segments = vis3D.get_color_discreet_3D(selected_loci_segments, "GO_slim_term", [str(GoTerm)], [str(color)])
fig = vis3D.genome_drawing(selected_loci_segments)
return fig
############TAB1_3D_GRAPH_CHROMOSOMES############
@app.callback(Output("3D_representation_chrom", "figure"),
Input("Submit_tab1", "n_clicks"))
def update_3D_graph_chrom_tab1(n_clicks):
sql_query_4 = \
"""SELECT Primary_SGDID, Start_coordinate, Stop_coordinate, Chromosome, Strand
FROM SGD_features
ORDER BY Start_coordinate
"""
selected_loci = tools.get_locus_info("./static/SCERE.db", sql_query_4)
selected_loci_segments = plotly_segments.merge(selected_loci, on="Primary_SGDID", how="left", copy=False)
selected_loci_segments.index = range(1, len(selected_loci_segments) + 1)
selected_loci_segments = vis3D.get_color_discreet_3D(selected_loci_segments, "Chromosome", list(range(1, 17)), colors)
fig = go.Figure(data=[go.Scatter3d(x = selected_loci_segments.x,
y = selected_loci_segments.y,
z = selected_loci_segments.z,
mode = "lines",
name = "",
line = {"color": selected_loci_segments["legend"],
"width": 12},
customdata = selected_loci_segments["Chromosome"],
hovertemplate = ("<b>Chromosome :</b> %{customdata} <br>"),
hoverlabel = dict(bgcolor = "white", font_size = 16))])
fig.update_layout(scene=dict(xaxis = dict(showgrid = False, backgroundcolor = "white"),
yaxis = dict(showgrid = False, backgroundcolor = "white"),
zaxis = dict(showgrid = False, backgroundcolor = "white")))
fig.update_layout(height=800)
return fig
############TAB2_UPLOAD############
@app.callback(Output("output_data_upload_tab2", "children"),
Input("demo_tab2", "n_clicks"),
Input("upload_data_tab2", "contents"),
State("upload_data_tab2", "filename"))
def update_output_tab2(n_clicks, list_of_contents, list_of_names):
ctx = dash.callback_context
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "demo_tab2":
children = dash_table.DataTable(id="datatable",
data=demo_2.to_dict('records'),
columns=[{'name': i, 'id': i, "selectable": True} for i in demo_2.columns],
page_size=10,
column_selectable="multi",
selected_columns=[demo_2.columns[0], demo_2.columns[1]],
style_cell={'textAlign': 'left'},
style_data_conditional=[{'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'}],
style_header={'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'})
else:
if list_of_contents is not None:
children=[tools.parse_contents(c, n, "datatable") for c, n in zip(list_of_contents, list_of_names)]
return children
############TAB2_COLUMN_SELECTION_UPLOAD############
@app.callback(
Output("datatable", "style_data_conditional"),
Input("datatable", "selected_columns"))
def update_styles_tab2(selected_columns):
return [{
"if": { "column_id": i },
"background_color": "#D2F3FF"
} for i in selected_columns]
############TAB2_3D_GRAPH############
@app.callback(Output("3D_representation_tab2", "figure"),
Input("Submit_tab2", "n_clicks"),
State("datatable", "derived_virtual_data"),
State("datatable", "selected_columns"),
State("color_scale_dropdown", "value"))
def update_3D_graphs_tab2(n_clicks, input1, input2, input3):
unfiltered_data = pd.DataFrame(input1)
filtered_data = unfiltered_data[[str(input2[0]), str(input2[1])]]
sql_query_5 = \
"""SELECT Primary_SGDID, Start_coordinate, Stop_coordinate, Chromosome, Feature_name, Strand
FROM gene_literature, SGD_features
WHERE SGDID == Primary_SGDID
GROUP BY SGDID
ORDER BY Start_coordinate
"""
whole_genome = tools.get_locus_info("./static/SCERE.db", sql_query_5)
whole_genome_segments = plotly_segments.merge(whole_genome, on="Primary_SGDID", how="left", copy=False)
whole_genome_segments.index = range(1, len(whole_genome_segments) + 1)
whole_genome_segments = whole_genome_segments.merge(filtered_data, left_on="Feature_name", right_on="YORF", how="left", copy=False)
whole_genome_segments.iloc[: , -1].fillna("whitesmoke", inplace=True)
fig = go.Figure(data=[go.Scatter3d(x=whole_genome_segments.x,
y=whole_genome_segments.y,
z=whole_genome_segments.z,
mode="lines",
name="",
line={"color": whole_genome_segments.iloc[: , -1],
"colorscale": input3,
"showscale": True,
"width": 12},
customdata=whole_genome_segments.Feature_name,
hovertemplate=("<b>YORF :</b> %{customdata} <br>"),
hoverlabel=dict(bgcolor="white", font_size=16))])
fig.update_layout(scene=dict(xaxis=dict(showgrid=False, backgroundcolor="white"),
yaxis=dict(showgrid=False, backgroundcolor="white"),
zaxis=dict(showgrid=False, backgroundcolor="white")))
fig.update_layout(height=800)
return fig
############TAB3_UPLOAD############
@app.callback(Output("output_data_upload_tab3", "children"),
Input("demo_tab3", "n_clicks"),
Input("upload_data_tab3", "contents"),
State("upload_data_tab3", "filename"))
def update_output_tab3(n_clicks, list_of_contents, list_of_names):
ctx = dash.callback_context
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "demo_tab3":
children = dash_table.DataTable(id="datatable_tab3",
data=demo_1.to_dict('records'),
columns=[{'name': i, 'id': i, "selectable": True} for i in demo_1.columns],
page_size=10,
column_selectable="multi",
selected_columns=[demo_1.columns[0]],
style_cell={'textAlign': 'left'},
style_data_conditional=[{'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'}],
style_header={'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'})
else:
if list_of_contents is not None:
children=[tools.parse_contents(c, n, "datatable_tab3") for c, n in zip(list_of_contents, list_of_names)]
return children
############TAB3_UPLOAD_STYLE############
@app.callback(
Output("datatable_tab3", "style_data_conditional"),
Input("datatable_tab3", "selected_columns"))
def update_styles_tab3(selected_columns):
return [{
"if": { "column_id": i },
"background_color": "#D2F3FF"
} for i in selected_columns]
############TAB3_SLIDER_AND_NETWORK############
@app.callback(Output("network", "elements"),
Output("treshold_slider", "min"),
Output("treshold_slider", "max"),
Output("output_min_slider", "children"),
Output("output_max_slider", "children"),
Input("Submit_tab3", "n_clicks"),
State("datatable_tab3", "derived_virtual_data"))
def update_network(n_clicks, input1):
genes_list = pd.DataFrame(input1)
sql_query_6 = \
"""SELECT Primary_SGDID, Chromosome, Feature_name, Strand, Stop_coordinate, Start_coordinate
FROM SGD_features
"""
Feature_name = tools.get_locus_info("./static/SCERE.db", sql_query_6)
Feature_name = Feature_name.merge(genes_list, left_on="Feature_name", right_on=genes_list.columns[0])
nodes = [{"data": {"id": Primary_SGDID, "label": Feature_name}}
for Primary_SGDID, Feature_name in zip(Feature_name["Primary_SGDID"], Feature_name["Feature_name"])
]
edges_list_select = tools.get_edges_list(genes_list, edges_list, all_feature_name)
edges = [{"data": {"source": source, "target": target, "weight": float(weight)}}
for source, target, weight in zip(edges_list_select["Primary_SGDID_bis"], edges_list_select["Primary_SGDID"], edges_list_select["3D_distances"])
]
elements = nodes + edges
slider_max = max(edges_list_select["3D_distances"])
slider_min = min(edges_list_select["3D_distances"])
return elements, slider_min, slider_max, "min {}".format(round(slider_min)), "max {}".format(round(slider_max))
############TAB3_SLIDER_OUTPUT############
@app.callback(Output("output_value_slider", "children"),
Input("treshold_slider", "value"))
def update_slider_output(value):
return "3D distances in network are inferior to {}".format(value)
############TAB3_HIST############
@app.callback(Output("hist", component_property="src"),
Input("Submit_tab3", "n_clicks"),
Input("treshold_slider", "value"),
State("datatable_tab3", "derived_virtual_data"))
def update_hist(n_clicks, input1, input2):
genes_list = pd.DataFrame(input2)
fig = tools.distri(genes_list, edges_list, all_feature_name, H2, F2, BIN_NUMBER, input1)
out_url = tools.fig_to_uri(fig)
return out_url
############TAB3_NETWORK_TRESHOLD############
@app.callback(Output("network", "stylesheet"),
Input("treshold_slider", "value"))
def update_stylesheet_(treshold):
new_styles = [{"selector": "[weight >" + str(treshold) + "]", "style": {"opacity": 0}}]
stylesheet = basic_stylesheet + new_styles
return stylesheet
############TAB3_NETWORK_METRICS############
@app.callback(Output("output_nodes_number_tab3", "children"),
Input("treshold_slider", "value"),
Input("network", "elements"))
def update_metrics_1(treshold, elements):
subgraph_edges = pd.DataFrame(elements)
subgraph_edges = pd.json_normalize(subgraph_edges["data"])
subgraph_edges = subgraph_edges[subgraph_edges["weight"] < treshold]
G = nx.from_pandas_edgelist(subgraph_edges, source="source", target="target")
return "number of connected nodes : " + str(G.number_of_nodes())
@app.callback(Output("output_edges_number_tab3", "children"),
Input("treshold_slider", "value"),
Input("network", "elements"))
def update_metrics_2(treshold, elements):
subgraph_edges = pd.DataFrame(elements)
subgraph_edges = pd.json_normalize(subgraph_edges["data"])
subgraph_edges = subgraph_edges[subgraph_edges["weight"] < treshold]
G = nx.from_pandas_edgelist(subgraph_edges, source="source", target="target")
return "number of edges : " + str(G.number_of_edges())
@app.callback(Output("Degrees_hist", "figure"),
Input("treshold_slider", "value"),
Input("network", "elements"))
def update_metrics_3(treshold, elements):
subgraph_edges = pd.DataFrame(elements)
subgraph_edges = pd.json_normalize(subgraph_edges["data"])
subgraph_edges = subgraph_edges[subgraph_edges["weight"] < treshold]
G = nx.from_pandas_edgelist(subgraph_edges, source="source", target="target")
degrees = [val for (node, val) in G.degree()]
fig = px.histogram(degrees, nbins=70, color_discrete_sequence=["#A0E8AF"], labels={"value": "degrees"})
fig.update_layout(plot_bgcolor="white",
xaxis_showgrid=False,
yaxis_showgrid=False,
showlegend=False)
return fig
if __name__ == "__main__":
app.run_server(debug=False)