-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
1967 lines (1826 loc) · 69 KB
/
application.py
File metadata and controls
1967 lines (1826 loc) · 69 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
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from dash.dash import no_update
from flask import Flask
from os.path import exists, join, dirname, abspath
from os import makedirs, mkdir
from dash_bootstrap_components.themes import COSMO
from flask import send_from_directory
from dash import Dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from base64 import decodebytes
from zipfile import ZipFile
from os import remove, walk, listdir, sep
from nilearn.masking import apply_mask, compute_background_mask
from nilearn.image import resample_to_img
from nibabel import load as niload
from scipy.stats import pearsonr, spearmanr
from numpy import squeeze, array
from wordcloud import WordCloud
from sklearn.preprocessing import MinMaxScaler
from matplotlib.cm import plasma_r
from matplotlib.colors import to_hex
from shutil import rmtree
from plotly.io import read_json
from plotly.graph_objects import Scatter, Scatter3d, Figure
from plotly.colors import qualitative
import plotly_express as px
import pandas as pd
from sklearn import preprocessing
import csv
import numpy as np
red_button_style = {"color": "primary"}
UPLOAD_DIRECTORY = "Downloads"
if not exists(UPLOAD_DIRECTORY):
makedirs(UPLOAD_DIRECTORY)
server = Flask(__name__)
app = Dash(
server=server,
external_stylesheets=[COSMO],
suppress_callback_exceptions=True,
include_assets_files=False,
title="Gradient Explorer",
update_title="Processing...",
)
app._favicon = "favicon.ico"
application = app.server
@server.before_first_request
def before_first_request():
"""
Executed before the first request is handled by the server.
Creates an "assets" directory if it does not exist.
Removes all ".png" files from the "assets" directory.
Args:
self: The instance of the server.
Returns:
None
"""
if exists("assets") == False:
mkdir("assets")
dir_name = "assets"
test = listdir(dir_name)
for item in test:
if item.endswith(".png"):
remove(join(dir_name, item))
@server.route("/download/<path:path>")
def download(path):
"""Serve a file from the upload directory."""
return send_from_directory(UPLOAD_DIRECTORY, path, as_attachment=True)
# Define styles for dcc.Upload
upload_style = {
"width": "100%",
"height": "60px",
"lineHeight": "60px",
"borderWidth": "1px",
"borderStyle": "dashed",
"borderRadius": "5px",
"textAlign": "center",
"margin": "10px",
}
# Create dcc.Store components with a loop
store_ids = [
"session", "session2", "session3", "session4", "geng", "store1", "cl",
"iszipped", "showbar1", "showbar2", "showbar3", "showbar4", "spare"
]
stores = [dcc.Store(id=store_id, storage_type="session") for store_id in store_ids]
# Create dbc.Tab components with a list comprehension
tab_labels = [
"50-Topic Dataset", "100-Topic Dataset", "200-Topic Dataset",
"400-Topic Dataset", "Full Term Dataset"
]
tabs = [dbc.Tab(label=label, tab_id=label) for label in tab_labels]
app.layout = dbc.Container(
[
dbc.Spinner(
[
html.Div([""], id="loading-output4"),
html.Div([""], id="loading-output3"),
],
fullscreen=True,
),
html.H1("Gradient Explorer"),
html.H5(
dcc.Markdown(
"""
Upload an fMRI file or .zip archive containing fMRI files in a nibabel-compatible format and wait for the file(s) to be processed. When the processing is done, click the blue button below. Uploading single files will also generate wordclouds of the top 10 closest terms/topics. If you have any questions please email me at <goodallhalliwell.i@queensu.ca>.
"""
)
),
dcc.Upload(
id="upload-data",
style=upload_style,
multiple=True,
children=dbc.Spinner(
html.Div(
["Click or drag a file here to upload it."],
id="loading-output",
)
),
),
*stores, # Unpack the list of dcc.Store components
html.Hr(),
dbc.Button(
color="primary",
block=True,
id="button",
className="mb-3",
disabled=True,
children=dbc.Spinner(
html.Div(
["Place scan into gradient space"],
id="loading-output2",
)
),
),
dbc.Tabs(
tabs, # Use the list comprehension for tabs
id="tabs",
active_tab="50-Topic Dataset",
),
html.Div(
id="tab-content",
className="p-4",
),
],
style={"max-width": "95vw", "width": "80vw"},
)
@app.callback(
Output("loading-output4", "children"),
Output("tab-content", "children"),
Input("tabs", "active_tab"),
[
Input("store1", "data"),
],
Input("geng", "data"),
Input("cl", "data"),
Input("showbar1", "data"),
Input("showbar2", "data"),
Input("showbar3", "data"),
Input("showbar4", "data"),
)
def render_tab_content(
active_tab, data1, displayoptions, cldata, g1state, g2state, g3state, g4state
):
"""
Renders the content of a tab based on the active tab and input data.
Args:
active_tab (str): The active tab.
data1 (Any): The input data.
displayoptions (Any): The display options.
cldata (Any): The CL data.
g1state (Any): The G1 state.
g2state (Any): The G2 state.
g3state (Any): The G3 state.
g4state (Any): The G4 state.
Returns:
Tuple[str, str]: A tuple containing the loading output and the tab content.
Examples:
>>> render_tab_content("tab1", data1, displayoptions, cldata, g1state, g2state, g3state, g4state)
("", dbc.Row([...]))
"""
def create_graph():
"""
Creates a graph with specified properties.
Returns:
dcc.Graph: The created graph.
Examples:
>>> create_graph()
dcc.Graph(...)
"""
return dcc.Graph(
figure=px.bar(
title="Click on a point",
orientation="h",
color_continuous_scale="plasma_r",
height=900,
).update_layout(
title_x=0.5,
autosize=True,
xaxis=dict(showgrid=False, zeroline=False, visible=False),
yaxis=dict(showgrid=False, zeroline=False, visible=False),
)
)
def create_row(data_element, graph_id, display_state):
"""
Creates a row with data element and graph based on the provided parameters.
Args:
data_element (Any): The data element.
graph_id (str): The ID of the graph.
display_state (Any): The display state.
Returns:
dbc.Row: The created row.
Examples:
>>> create_row(data_element, "graph1", display_state)
dbc.Row([...])
"""
return dbc.Row(
[
dbc.Col(html.Div([data_element])),
dbc.Col(
html.Div(
[create_graph()],
id=graph_id,
style={"display": checkif2(displayoptions=display_state)},
),
width=3,
),
]
)
if active_tab and data1 is not None:
image_div = html.Div(
[html.Img(id="element-to-hide", src=cldata, style={"textAlign": "center"})],
style={"display": checkif(displayoptions), "textAlign": "center"},
)
rows = [create_row(data1[i], f"1graph{i+1}", g1state) for i in range(4)]
return (
f"",
dbc.Row(
[
dbc.Col(
[
image_div,
*rows
],
align="center",
),
],
),
)
return f"", "No tab selected"
def checkif(displayoptions):
"""
Checks the value of displayoptions and returns a corresponding display state.
Args:
displayoptions (int): The value of displayoptions.
Returns:
str: The display state based on the value of displayoptions.
Examples:
>>> checkif(0)
"none"
>>> checkif(1)
"block"
"""
if displayoptions == 0:
return "none"
elif displayoptions == 1:
return "block"
def checkif2(displayoptions=None):
"""
Checks the value of displayoptions and returns a corresponding display state.
Args:
displayoptions (int, optional): The value of displayoptions. Defaults to None.
Returns:
str: The display state based on the value of displayoptions.
Examples:
>>> checkif2(0)
"none"
>>> checkif2(1)
"block"
>>> checkif2()
"none"
"""
if displayoptions == 0 or None:
visible = "none"
return visible
elif displayoptions == 1:
visible = "block"
return visible
@app.callback(
[
Output("1graph1", "children"),
Output("1graph2", "children"),
Output("1graph3", "children"),
Output("1graph4", "children"),
],
Output("showbar1", "data"),
Output("showbar2", "data"),
Output("showbar3", "data"),
Output("showbar4", "data"),
Output("graph1col1", "figure"),
Output("graph2col1", "figure"),
Output("graph3col1", "figure"),
Output("graph4col1", "figure"),
Input("graph1col1", "clickData"),
Input("graph2col1", "clickData"),
Input("graph3col1", "clickData"),
Input("graph4col1", "clickData"),
Input("tabs", "active_tab"),
Input("graph1col1", "figure"),
Input("graph2col1", "figure"),
Input("graph3col1", "figure"),
Input("graph4col1", "figure"),
)
def graphupdate(g1c1, g2c1, g3c1, g4c1, tab, graph1, graph2, graph3, graph4):
"""
Updates the graphs and data based on user interactions.
Args:
g1c1: The click data for graph 1 column 1.
g2c1: The click data for graph 2 column 1.
g3c1: The click data for graph 3 column 1.
g4c1: The click data for graph 4 column 1.
tab: The active tab.
graph1: The figure for graph 1.
graph2: The figure for graph 2.
graph3: The figure for graph 3.
graph4: The figure for graph 4.
Returns:
A tuple containing the updated figures and data for the graphs.
Examples:
# Example 1: Updating the graphs and data
graphupdate(click_data1, click_data2, click_data3, click_data4, active_tab, fig1, fig2, fig3, fig4)
"""
gdict = {1: g1c1, 2: g2c1, 3: g3c1, 4: g4c1}
figlist = {"0": None, "1": None, "2": None, "3": None}
colfigdict = {"0": graph1, "1": graph2, "2": graph3, "3": graph4}
figdict1 = {
"Full Term Dataset": [
"v5-fulldataset.json",
"1,2v5-fulldataset.json",
"1,3v5-fulldataset.json",
"2,3v5-fulldataset.json",
],
"100-Topic Dataset": [
"v5-topics-100.json",
"1,2v5-topics-100.json",
"1,3v5-topics-100.json",
"2,3v5-topics-100.json",
],
"200-Topic Dataset": [
"v5-topics-200.json",
"1,2v5-topics-200.json",
"1,3v5-topics-200.json",
"2,3v5-topics-200.json",
],
"400-Topic Dataset": [
"v5-topics-400.json",
"1,2v5-topics-400.json",
"1,3v5-topics-400.json",
"2,3v5-topics-400.json",
],
"50-Topic Dataset": [
"v5-topics-50.json",
"1,2v5-topics-50.json",
"1,3v5-topics-50.json",
"2,3v5-topics-50.json",
],
}
figdict = {
"Full Term Dataset": "v5-fulldataset.csv",
"100-Topic Dataset": "v5-topics-100.csv",
"200-Topic Dataset": "v5-topics-200.csv",
"400-Topic Dataset": "v5-topics-400.csv",
"50-Topic Dataset": "v5-topics-50.csv",
}
D3list = [
"v5-fulldataset.json",
"v5-topics-100.json",
"v5-topics-200.json",
"v5-topics-400.json",
"v5-topics-50.json",
]
listographs = figdict1[tab]
gimper = {1: [0, 1], 2: [0, 2], 3: [1, 2]}
figlist2 = []
if not gdict == {1: None, 2: None, 3: None, 4: None}:
import csv
if not g1c1 == None:
dicval = list(gdict[1].values())
dival = dicval[0]
if "customdata" in dival[0]:
ddval = dival[0]["customdata"]
else:
try:
ddval = dival[0]["hovertext"]
except:
ddval = None
Dframe = {}
Dframe2 = {}
Dlist = {}
with open(join("CSVData", figdict[tab]), newline="") as f:
reader = csv.reader(f)
Dlist1 = list(reader)
for rowl in Dlist1:
if not rowl == []:
Dlist.update({rowl[0]: rowl[1]})
if "customdata" in dival[0]:
corr1 = [dival[0]["x"], dival[0]["y"], dival[0]["z"]]
else:
try:
corr = Dlist[ddval]
corr1 = corr.strip("][").split(", ")
for id in enumerate(corr1):
corr1[id[0]] = float(corr1[id[0]])
except:
corr1 = [dival[0]["x"], dival[0]["y"], dival[0]["z"]]
for cng in Dlist:
cng1 = Dlist[cng].strip("][").split(", ")
for id1 in enumerate(cng1):
cng1[id1[0]] = float(cng1[id1[0]])
dst = distance_finder(corr1, cng1)
Dframe2.update({cng: dst})
if dst == 0:
continue
Dframe.update({cng: dst})
srdict10 = list(
dict(
sorted(Dframe.items(), key=lambda item: item[1], reverse=False)
).items()
)[:10]
newd = []
das110 = list(
dict(sorted(srdict10, key=lambda item: item[1], reverse=True)).items()
)
for a in das110:
b = 1 / a[1]
newd.append([a[0], b])
dfn = pd.DataFrame(newd, columns=["Name", "1/Distance"])
fig = px.bar(
dfn,
y="Name",
x="1/Distance",
title=None,
color="1/Distance",
orientation="h",
color_continuous_scale="plasma",
height=900,
).update_traces(marker_colorbar_showticklabels=False)
fig.update_layout(
title_x=0.5,
hovermode="closest",
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
title="",
visible=False,
autorange="reversed"
),
yaxis=dict(
title="",
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
),
)
fig = dcc.Graph(figure=fig)
fig1 = listographs[0]
scale = MinMaxScaler()
cgrad1 = (
scale.fit_transform(array(list(Dframe2.values())).reshape(-1, 1))
.reshape(1, -1)
.tolist()[0]
)
fig2 = Figure(fig.figure)
Recolor(fig2, cgrad1)
fig.figure = fig2
figlist.update({"0": fig})
figlist2.append(fig1)
figc = Figure(colfigdict["0"])
Recolor(figc, cgrad1)
colfigdict["0"] = figc
else:
fig = px.bar(
title="Click on a point",
orientation="h",
color_continuous_scale="plasma_r",
height=900,
)
fig.update_layout(
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
yaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
)
fig = dcc.Graph(figure=fig)
figlist.update({"0": fig})
figlist2.append(no_update)
if not g2c1 == None:
dicval = list(gdict[2].values())
dival = dicval[0]
if "customdata" in dival[0]:
ddval = dival[0]["customdata"]
else:
try:
ddval = dival[0]["hovertext"]
except:
ddval = None
Dframe = {}
Dframe2 = {}
Dlist = {}
with open(join("CSVData", figdict[tab]), newline="") as f:
reader = csv.reader(f)
Dlist1 = list(reader)
for rowl in Dlist1:
if not rowl == []:
Dlist.update({rowl[0]: rowl[1]})
if "customdata" in dival[0]:
corr1 = [dival[0]["x"], dival[0]["y"]]
else:
try:
corr = Dlist[ddval]
corr1 = corr.strip("][").split(", ")
for id in enumerate(corr1):
corr1[id[0]] = float(corr1[id[0]])
except:
corr1 = [dival[0]["x"], dival[0]["y"]]
for id in enumerate(corr1):
corr1[id[0]] = float(corr1[id[0]])
for cng in Dlist:
cng1 = Dlist[cng].strip("][").split(", ")
for id1 in enumerate(cng1):
cng1[id1[0]] = float(cng1[id1[0]])
if len(corr1) >= 3:
dst = distance_finder2d(
[corr1[gimper[1][0]], corr1[gimper[1][1]]],
[cng1[gimper[1][0]], cng1[gimper[1][1]]],
)
elif len(corr1) == 2:
dst = distance_finder2d(
[corr1[0], corr1[1]], [cng1[gimper[1][0]], cng1[gimper[1][1]]]
)
Dframe2.update({cng: dst})
if dst == 0:
continue
Dframe.update({cng: dst})
srdict10 = list(
dict(
sorted(Dframe.items(), key=lambda item: item[1], reverse=False)
).items()
)[:10]
newd = []
das110 = list(
dict(sorted(srdict10, key=lambda item: item[1], reverse=True)).items()
)
for a in das110:
b = 1 / a[1]
newd.append([a[0], b])
dfn = pd.DataFrame(newd, columns=["Name", "1/Distance"])
fig = px.bar(
dfn,
y="Name",
x="1/Distance",
title=None,
color="1/Distance",
orientation="h",
color_continuous_scale="plasma",
height=900,
).update_traces(marker_colorbar_showticklabels=False)
fig.update_layout(
hovermode="closest",
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
title="",
visible=False,
autorange="reversed"
),
yaxis=dict(
title="",
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
),
)
fig = dcc.Graph(figure=fig)
print(dicval)
fig1 = listographs[0]
scale = MinMaxScaler()
cgrad1 = (
scale.fit_transform(array(list(Dframe2.values())).reshape(-1, 1))
.reshape(1, -1)
.tolist()[0]
)
fig2 = Figure(fig.figure)
Recolor(fig2, cgrad1)
fig.figure = fig2
figlist.update({"1": fig})
figlist2.append(fig1)
figc = Figure(colfigdict["1"])
Recolor(figc, cgrad1)
figc.update_traces(unselected_marker_opacity=1)
colfigdict["1"] = figc
else:
fig = px.bar(
title="Click on a point",
orientation="h",
color_continuous_scale="plasma_r",
height=900,
)
fig.update_layout(
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
yaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
)
fig = dcc.Graph(figure=fig)
figlist.update({"1": fig})
if not g3c1 == None:
dicval = list(gdict[3].values())
dival = dicval[0]
if "customdata" in dival[0]:
ddval = dival[0]["customdata"]
else:
try:
ddval = dival[0]["hovertext"]
except:
ddval = None
Dframe = {}
Dframe2 = {}
Dlist = {}
with open(join("CSVData", figdict[tab]), newline="") as f:
reader = csv.reader(f)
Dlist1 = list(reader)
for rowl in Dlist1:
if not rowl == []:
Dlist.update({rowl[0]: rowl[1]})
if "customdata" in dival[0]:
corr1 = [dival[0]["x"], dival[0]["y"]]
else:
try:
corr = Dlist[ddval]
corr1 = corr.strip("][").split(", ")
for id in enumerate(corr1):
corr1[id[0]] = float(corr1[id[0]])
except:
corr1 = [dival[0]["x"], dival[0]["y"]]
for cng in Dlist:
cng1 = Dlist[cng].strip("][").split(", ")
for id1 in enumerate(cng1):
cng1[id1[0]] = float(cng1[id1[0]])
if len(corr1) >= 3:
dst = distance_finder2d(
[corr1[gimper[2][0]], corr1[gimper[2][1]]],
[cng1[gimper[2][0]], cng1[gimper[2][1]]],
)
elif len(corr1) == 2:
dst = distance_finder2d(
[corr1[0], corr1[1]], [cng1[gimper[2][0]], cng1[gimper[2][1]]]
)
Dframe2.update({cng: dst})
if dst == 0:
continue
Dframe.update({cng: dst})
srdict10 = list(
dict(
sorted(Dframe.items(), key=lambda item: item[1], reverse=False)
).items()
)[:10]
newd = []
das110 = list(
dict(sorted(srdict10, key=lambda item: item[1], reverse=True)).items()
)
for a in das110:
b = 1 / a[1]
newd.append([a[0], b])
dfn = pd.DataFrame(newd, columns=["Name", "1/Distance"])
fig = px.bar(
dfn,
y="Name",
x="1/Distance",
title=None,
color="1/Distance",
orientation="h",
color_continuous_scale="plasma",
height=900,
).update_traces(marker_colorbar_showticklabels=False)
fig.update_layout(
hovermode="closest",
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
title="",
visible=False,
autorange="reversed"
),
yaxis=dict(
title="",
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
),
)
fig = dcc.Graph(figure=fig)
print(dicval)
fig1 = listographs[0]
scale = MinMaxScaler()
cgrad1 = (
scale.fit_transform(array(list(Dframe2.values())).reshape(-1, 1))
.reshape(1, -1)
.tolist()[0]
)
fig2 = Figure(fig.figure)
Recolor(fig2, cgrad1)
fig.figure = fig2
figlist.update({"2": fig})
figlist2.append(fig1)
figc = Figure(colfigdict["2"])
Recolor(figc, cgrad1)
figc.update_traces(unselected_marker_opacity=1)
colfigdict["2"] = figc
else:
fig = px.bar(
title="Click on a point",
orientation="h",
color_continuous_scale="plasma_r",
height=900,
)
fig.update_layout(
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
yaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
)
fig = dcc.Graph(figure=fig)
figlist.update({"2": fig})
if not g4c1 == None:
dicval = list(gdict[4].values())
dival = dicval[0]
if "customdata" in dival[0]:
ddval = dival[0]["customdata"]
else:
try:
ddval = dival[0]["hovertext"]
except:
ddval = None
Dframe = {}
Dframe2 = {}
Dlist = {}
with open(join("CSVData", figdict[tab]), newline="") as f:
reader = csv.reader(f)
Dlist1 = list(reader)
for rowl in Dlist1:
if not rowl == []:
Dlist.update({rowl[0]: rowl[1]})
if "customdata" in dival[0]:
corr1 = [dival[0]["x"], dival[0]["y"]]
else:
try:
corr = Dlist[ddval]
corr1 = corr.strip("][").split(", ")
for id in enumerate(corr1):
corr1[id[0]] = float(corr1[id[0]])
except:
corr1 = [dival[0]["x"], dival[0]["y"]]
for cng in Dlist:
cng1 = Dlist[cng].strip("][").split(", ")
for id1 in enumerate(cng1):
cng1[id1[0]] = float(cng1[id1[0]])
if len(corr1) >= 3:
dst = distance_finder2d(
[corr1[gimper[3][0]], corr1[gimper[3][1]]],
[cng1[gimper[3][0]], cng1[gimper[3][1]]],
)
elif len(corr1) == 2:
dst = distance_finder2d(
[corr1[0], corr1[1]], [cng1[gimper[3][0]], cng1[gimper[3][1]]]
)
Dframe2.update({cng: dst})
if dst == 0:
continue
Dframe.update({cng: dst})
srdict10 = list(
dict(
sorted(Dframe.items(), key=lambda item: item[1], reverse=False)
).items()
)[:10]
newd = []
das110 = list(
dict(sorted(srdict10, key=lambda item: item[1], reverse=True)).items()
)
for a in das110:
b = 1 / a[1]
newd.append([a[0], b])
dfn = pd.DataFrame(newd, columns=["Name", "1/Distance"])
fig = px.bar(
dfn,
y="Name",
x="1/Distance",
title=None,
color="1/Distance",
orientation="h",
color_continuous_scale="plasma",
height=900,
).update_traces(marker_colorbar_showticklabels=False)
fig.update_layout(
hovermode="closest",
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
title="",
visible=False,
autorange="reversed"
),
yaxis=dict(
title="",
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
),
)
fig = dcc.Graph(figure=fig)
print(dicval)
fig1 = listographs[0]
scale = MinMaxScaler()
cgrad1 = (
scale.fit_transform(array(list(Dframe2.values())).reshape(-1, 1))
.reshape(1, -1)
.tolist()[0]
)
fig2 = Figure(fig.figure)
Recolor(fig2, cgrad1)
fig.figure = fig2
figlist.update({"3": fig})
figlist2.append(fig1)
figc = Figure(colfigdict["3"])
Recolor(figc, cgrad1)
figc.update_traces(unselected_marker_opacity=1)
colfigdict["3"] = figc
else:
fig = px.bar(
title="Click on a point",
orientation="h",
color_continuous_scale="plasma_r",
height=900,
)
fig.update_layout(
title_x=0.5,
xaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
yaxis=dict(
showgrid=False, # thin lines in the background
zeroline=False, # thick line at x=0
visible=False, # numbers below
),
)
fig = dcc.Graph(figure=fig)
figlist.update({"3": fig})
return (
figlist["0"],
figlist["1"],
figlist["2"],
figlist["3"],
no_update,
no_update,
no_update,
no_update,
colfigdict["0"],
colfigdict["1"],
colfigdict["2"],
colfigdict["3"],
)
else:
return (
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
no_update,
)
@app.callback(
Output("session", "data"),
Output("button", "n_clicks"),
Output("loading-output", "children"),
[Input("upload-data", "filename"), Input("upload-data", "contents")],
)
def save_file(name, content):
"""
Save the uploaded file and return the necessary outputs for the callback.
Args:
name (str): The name of the uploaded file.
content (str): The content of the uploaded file.
Returns:
tuple: A tuple containing the following outputs:
- str: The path of the saved file in the upload directory.
- int: The number of times the button has been clicked (no update).
- str: The message indicating the status of the upload.
Examples:
>>> save_file("example.nii.gz", "file content")
("/path/to/upload_directory/example.nii.gz", no_update, "Upload Complete")
>>> save_file(None, None)
(None, None, "Drag and drop or select a .nii.gz or .zip archive containing fMRI data to begin")
"""
if not [name, content] == [None, None]:
SaveandEncode(name, content)