-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallbacks.py
More file actions
1336 lines (1256 loc) · 67.3 KB
/
callbacks.py
File metadata and controls
1336 lines (1256 loc) · 67.3 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
import base64
import io
import os
from textwrap import fill
import pandas as pd
import numpy as np
from dash import html, callback, Input, Output, State, no_update, ALL, ctx
import utils
import layout
#------------- Begin simple error message popup functionality --------------
#
@callback(Output('err-modal', 'is_open', allow_duplicate=True),
Input('err-msg', 'children'),
prevent_initial_call=True) # was: 'initial_duplicate')
def show_error_message(msg : str):
"""
Any callback can trigger a popup error message by sending an error message
to Output('err_msg', 'children').
"""
return True
@callback(Output('err-modal', 'is_open', allow_duplicate=True),
Input('close-err-modal', 'n_clicks'),
prevent_initial_call='initial_duplicate')
def close_error_modal(n_clicks : int):
if n_clicks > 0:
return False # close the window: 'is_open' = False
return no_update
#
#------------- End simple error message popup functionality ----------------
@callback(Output('lineplot-dataGroups-div', 'hidden'),
Output('lineplot-df-melted-dict', 'data'),
Output('lineplot-facetVars-checklist', 'options'),
Output('lineplot-facetVars-checklist', 'value'),
Output('lineplot-groupBy-dropdown', 'options'),
Output('metrics-dict', 'data'),
Output('err-msg', 'children', allow_duplicate=True),
Input('demo-welcome-banner-div', 'title'),
prevent_initial_call='initial_duplicate') # necessary due to err-msg usage
def load_fake_demo_data(_):
"""
Load fake data for the demo. Currently hardcoded. Will replace with interactive data loading.
"""
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
infile_timeseries = 'assets/fake_timeseries_data.csv'
infile_demographics = 'assets/fake_demographic_data.csv'
groupBy_options = ['Treatment', 'Home location'] # BUGBUG: Hardcoded for demo. Use a checkbox?
try:
df_infile_timeseries = pd.read_csv(infile_timeseries)
except FileNotFoundError:
err_msg = f"Whoops, file {infile_timeseries} was not found."
no_updates[-1] = err_msg
return tuple(no_updates)
except Exception as e:
err_msg = f"Failed to connect to the data source.\nReceived the following exception:\n{e}."
no_updates[-1] = err_msg
return tuple(no_updates)
try:
df_infile_demographics = pd.read_csv(infile_demographics)
except FileNotFoundError:
err_msg = f"Whoops, file {infile_demographics} was not found."
no_updates[-1] = err_msg
return tuple(no_updates)
except Exception as e:
err_msg = f"Failed to connect to the data source.\nReceived the following exception:\n{e}."
no_updates[-1] = err_msg
return tuple(no_updates)
vv_timeseries = list(set(df_infile_timeseries.columns.tolist()) - set(['Patient ID', 'Day'])
- set(groupBy_options)) # "vv_" for "value_vars"
df_all = df_infile_timeseries.melt(id_vars=list(set(['Patient ID', 'Day']+groupBy_options)),
value_vars=vv_timeseries,
var_name='prop name', value_name='prop value',
ignore_index=True) # .dropna()
df_all['Patient ID'] = df_all['Patient ID'].astype(str)
del(df_infile_timeseries)
vv_demog = list(set(df_infile_demographics.columns.tolist()) - set(['Patient ID']))
df_metrics = df_infile_demographics.melt(id_vars=['Patient ID'],
value_vars=vv_demog,
var_name='prop name', value_name='prop value',
ignore_index=True) # .dropna()
del(df_infile_demographics)
df_metrics['Patient ID'] = df_metrics['Patient ID'].astype(str)
# groupBy_options = list(set(df_all.columns.tolist()) - set(['Patient ID','Day','prop name','prop value']))
for opt in groupBy_options:
if opt not in df_all.columns:
err_msg = f"Whoops, groupBy option {opt} is not an option."
no_updates[-1] = err_msg
return tuple(no_updates)
lineplot_facet_options = df_all['prop name'].unique().tolist()
lineplot_facet_options = [{'label':' '+opt, 'value':opt} for opt in lineplot_facet_options]
lineplot_facet_values = [] # initialize to "no items checked"
# Put 'Patient ID' into column 0. Other functions will expect it to be there.
df_all = df_all[['Patient ID', *list(set(df_all.columns) - set(['Patient ID']))]]
df_metrics = df_metrics[['Patient ID', *list(set(df_metrics.columns) - set(['Patient ID']))]]
return False, df_all.to_dict('records'), lineplot_facet_options, lineplot_facet_values, groupBy_options, \
df_metrics.to_dict('records'), no_update
#---------------Begin initialization and 'initial click' callbacks-----------------
#
@callback(Output('barplot-div', 'hidden'),
Output('err-msg', 'children', allow_duplicate=True),
Input('metrics-dict', 'data'),
prevent_initial_call='initial_duplicate')
def hide_bar_plot(df_as_dict : list):
"""
This function is called after "metrics" data (demographics or other snapshots in time)
has been loaded into a DataFrame. If this data is present and has been loaded,
this function "creates" a Div into which a bar plot will be created by "un-hiding" it.
This action then triggers a call to initialize_barplot_components().
"""
if not df_as_dict:
return no_update, no_update
if len(pd.DataFrame.from_dict(df_as_dict)) == 0:
err_msg = "No metrics data was found,\nso the bar plot of metrics will not be shown."
return no_update, err_msg
# The bar plot is hidden, so to show it, we return False, thereby "un-hiding" it.
return False, no_update
@callback(Output('sample-to-color-map', 'data', allow_duplicate=True),
Output('sample-to-IsDefaultColor-map', 'data', allow_duplicate=True),
Output('samples-dropdown', 'options', allow_duplicate=True),
Output('sortorder-dropdown', 'options'),
Output('sortorder-dropdown', 'value'),
Output('barplot-facetVars-checklist', 'options'),
Output('barplot-facetVars-checklist', 'value'),
Input('barplot-div', 'hidden'),
State('metrics-dict', 'data'),
prevent_initial_call='initial_duplicate')
def initialize_barplot_components(_, df_as_dict : list):
"""
Function to initialize the components for a bar plot of "metrics" data.
The input DataFrame, received here as a dict, was validated by the loading function.
This callback initializes the color maps for the sample names and the contents of the
"sort order" dropdown (sort bar plot by age, or by sample name, or...)
and the "choose which properties to show as facets" dropdown.
Notes
-----
If your x-column values (sample IDs, patient IDs, etc.) require a custom sort order
(not simple string sorting), you'll need to add code for this. Coding hints
are given below.
"""
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
if not df_as_dict:
return tuple(no_updates)
# Get the initial values for populating the bar plot's accompanying maps and dropdowns.
df_metrics = pd.DataFrame.from_dict(df_as_dict)
sample_id_string = df_metrics.columns[0]
facet_options = df_metrics['prop name'].unique().tolist()
sort_options = [sample_id_string, *facet_options]
facet_values = [opt for opt in facet_options] # initialize to "all items checked"
facet_options = [{'label':' '+opt, 'value':opt} for opt in facet_options]
# Coding hint: If your bar labels (x-axis values) require a custom sort order,
# add a sort key (lambda function) to the following line.
the_samples = sorted(df_metrics[sample_id_string].unique().tolist())
all_gray = [utils.LIGHT_GRAY]*len(the_samples)
all_true = [True]*len(the_samples)
color_mapping = dict(zip(the_samples, all_gray))
is_default = dict(zip(the_samples, all_true)) # whether a sample should be given the default color
sample_list = []
for sample in the_samples:
sample_list.append({'label':html.Span([html.Span('■',
style={'color':utils.LIGHT_GRAY,'font-size':36}),
html.Span(sample, style={'padding-left':6})]),
'value':sample,
# Note: you can use something like 'search':int(sample.split('-')[-1])
# to enable the user to search a long list of samples by something other than
# the alphanumeric beginning of each sample name.
'search':sample})
return color_mapping, is_default, sample_list, sort_options, sort_options[-1], facet_options, facet_values
@callback(Output('new-cat-modal', 'is_open', allow_duplicate=True),
Output('edit-cat-modal', 'is_open', allow_duplicate=True),
Input('categories-dropdown', 'value'),
prevent_initial_call='initial_duplicate')
def category_chosen_from_dropdown(choice):
"""
Dropdown of categories (labels): Add a new one, or edit an existing one.
Selection triggers the display of the approprate modal.
"""
if choice is None:
return no_update, no_update
if utils.ADD_NEW_CATEGORY['value'] == choice:
return True, no_update
return no_update, True
#
#-----------------End initialization and 'initial click' callbacks-----------------
#-------------------Begin 'define new label' callbacks-----------------------------
#
@callback(Output('color-picker', 'is_open', allow_duplicate=True),
Output('idx-of-parent-modal', 'data', allow_duplicate=True),
Input('choose-new-color-btn', 'n_clicks'),
prevent_initial_call='initial_duplicate')
def new_label__show_color_picker(n_clicks : int):
if n_clicks > 0:
return True, utils.div_display['new cat']
return no_update, no_update
@callback(Output('categories-dropdown', 'options', allow_duplicate=True),
Output('label-assignment-dropdown', 'options', allow_duplicate=True),
Output('categories-dropdown', 'value', allow_duplicate=True),
Output('new-cat-modal', 'is_open', allow_duplicate=True),
Output('samples-dropdown', 'options', allow_duplicate=True),
Output('sample-to-color-map', 'data', allow_duplicate=True),
Output('default-color', 'data', allow_duplicate=True),
Input('new-cat-ok', 'n_clicks'),
State('new-category-name', 'value'),
State({'type':'color-displayed', 'index':utils.div_display['new cat']}, 'style'),
State('categories-dropdown', 'options'),
State('new-default-cat', 'value'),
State('samples-dropdown', 'options'),
State('sample-to-color-map', 'data'),
State('sample-to-IsDefaultColor-map', 'data'),
prevent_initial_call='initial_duplicate')
def accept_new_label(n_clicks : int, name : str, style : dict, options : list, is_default : bool,
sample_options : list, color_map : dict, isDefaultColor_map : dict):
"""
User clicked 'OK' in the 'create new label' modal.
Because this is a new label (introducing a new color), it hasn't been assigned to any sample.
If the user checked the 'make this the default label' box, this means 'find all samples
flagged as having the default label, and change their label to this new label (and color).'
"""
num_outputs = len(ctx.outputs_list)
ret_vals = [no_update]*num_outputs
if n_clicks > 0:
new_color = style['background']
new_option = {'label':html.Span([html.Span('■',style={'color':new_color,'font-size':36}),
html.Span(name, style={'padding-left':6})]),
'value':name,
'search':name}
options.append(new_option)
options_sans_option0 = options[1:]
ret_vals[0] = options # the updated label options
ret_vals[1] = options_sans_option0 # the updated label options, sans the 'click to add new label' option
ret_vals[2] = None # clear the value in categories_dropdown
ret_vals[3] = False # close the modal (window)
sample_label_changed = False
if is_default:
# Any sample marked as being 'the default' receives this new color.
for i in range(len(sample_options)):
sample_name = sample_options[i]['label']['props']['children'][1]['props']['children']
if True == isDefaultColor_map[sample_name]:
color_map[sample_name] = new_color
sample_options[i]['label'] = html.Span([html.Span('■',
style={'color':new_color,
'font-size':36}),
html.Span(sample_name,
style={'padding-left':6})])
sample_label_changed = True
ret_vals[6] = new_color # propagate the default color to storage
if sample_label_changed:
ret_vals[4] = sample_options
ret_vals[5] = color_map
return tuple(ret_vals)
@callback(Output('new-cat-modal', 'is_open', allow_duplicate=True),
Output('new-category-name', 'value', allow_duplicate=True),
Output({'type':'color-displayed', 'index':utils.div_display['new cat']}, 'style', allow_duplicate=True),
Output('categories-dropdown', 'value', allow_duplicate=True),
Input('new-cat-cancel', 'n_clicks'),
State({'type':'color-displayed', 'index':utils.div_display['new cat']}, 'style'),
prevent_initial_call='initial_duplicate')
def cancel_new_label(n_clicks : int, style_to_cancel : dict):
"""
User clicked 'Cancel' in the 'create new label' modal
"""
if n_clicks > 0:
blank_style = style_to_cancel.copy()
blank_style['background'] = 'white'
blank_style['color'] = blank_style['background']
return False, '', blank_style, None
return no_update, no_update, no_update, no_update
@callback(Output('new-category-name', 'value', allow_duplicate=True),
Output({'type':'color-displayed', 'index':utils.div_display['new cat']}, 'style', allow_duplicate=True),
Output('new-default-cat', 'value', allow_duplicate=True),
Input('new-cat-modal', 'is_open'),
State({'type':'color-displayed', 'index':utils.div_display['new cat']}, 'style'),
prevent_initial_call='initial_duplicate')
def on_new_cat_modal_close(is_opening : bool, style_to_reset : dict):
"""
Set/reset the components of the 'define a new category' modal when it closes.
"""
if is_opening:
return no_update, no_update, no_update
style_to_reset['background'] = 'white'
style_to_reset['color'] = style_to_reset['background']
return None, style_to_reset, False
#
#---------------------End 'define new label' callbacks-----------------------------
#-------------------Begin 'edit new label' callbacks-------------------------------
#
@callback(Output('color-picker', 'is_open', allow_duplicate=True),
Output('idx-of-parent-modal', 'data', allow_duplicate=True),
Input('edit-color-btn', 'n_clicks'),
prevent_initial_call='initial_duplicate')
def edit_label__show_color_picker(n_clicks : int):
if n_clicks > 0:
return True, utils.div_display['edit cat']
return no_update, no_update
@callback(Output('cat-to-edit', 'children', allow_duplicate=True),
Output('edit-category-name', 'value', allow_duplicate=True),
Output({'type':'color-displayed', 'index':utils.div_display['edit cat']}, 'style', allow_duplicate=True),
Output('edit-default-cat', 'value', allow_duplicate=True),
Output('edit-default-cat', 'disabled', allow_duplicate=True),
Input('edit-cat-modal', 'is_open'),
State('categories-dropdown', 'value'),
State('categories-dropdown', 'options'),
State({'type':'color-displayed', 'index':utils.div_display['edit cat']}, 'style'),
State('default-color', 'data'),
prevent_initial_call='initial_duplicate')
def process_edit_cat_modal_OpeningClosing(is_opening : bool, choice : str, label_options : list,
old_editing_modal_style : dict, default_color : str):
"""
This callback handles the 'edit existing category' modal when it opens and closes.
"""
if not is_opening:
# Set/reset things. It seems helpful to have this in here... is it truly?
old_editing_modal_style['background'] = 'white'
old_editing_modal_style['color'] = old_editing_modal_style['background']
return '', None, old_editing_modal_style, False, False
for i in range(len(label_options)):
# Get the formatted label (with color).
if label_options[i]['value'] == choice:
current_color = label_options[i]['label']['props']['children'][0]['props']['style']['color']
formatted_choice = label_options[i]['label'].copy() # contains the color swatch
new_editing_modal_style = old_editing_modal_style.copy()
new_editing_modal_style['background'] = current_color
new_editing_modal_style['color'] = new_editing_modal_style['background']
if current_color == default_color:
return formatted_choice, choice, new_editing_modal_style, True, True
return formatted_choice, choice, new_editing_modal_style, False, False
return no_update, no_update, no_update, no_update, no_update
@callback(Output('categories-dropdown', 'options', allow_duplicate=True),
Output('label-assignment-dropdown', 'options', allow_duplicate=True),
Output('categories-dropdown', 'value', allow_duplicate=True),
Output('edit-cat-modal', 'is_open', allow_duplicate=True),
Output('samples-dropdown', 'options', allow_duplicate=True),
Output('sample-to-color-map', 'data', allow_duplicate=True),
Output('sample-to-IsDefaultColor-map', 'data', allow_duplicate=True),
Output('default-color', 'data', allow_duplicate=True),
Input('edit-cat-ok', 'n_clicks'),
State('edit-category-name', 'value'),
State({'type':'color-displayed', 'index':utils.div_display['edit cat']}, 'style'),
State('categories-dropdown', 'options'),
State('categories-dropdown', 'value'),
State('edit-default-cat', 'value'),
State('samples-dropdown', 'options'),
State('sample-to-color-map', 'data'),
State('sample-to-IsDefaultColor-map', 'data'),
prevent_initial_call='initial_duplicate')
def accept_edited_label(n_clicks : int, new_name : str, style : dict, label_options : list,
unedited_name : str, is_default : bool, sample_options : list,
color_map : dict, isDefaultColor_map : dict):
"""
User clicked 'OK' in the 'edit existing label' modal
Note: The user's 'edit' can be to only the color or only the color's 'is default' status;
in these cases, new_name and unedited_choice will be equal. (This is just an "FYI.")
"""
num_outputs = len(ctx.outputs_list)
ret_vals = [no_update]*num_outputs
if n_clicks > 0:
ret_vals[2] = None # clear the value in categories_dropdown
ret_vals[3] = False # close the modal (window)
new_color = style['background']
new_option = {'label':html.Span([html.Span('■',style={'color':new_color,'font-size':36}),
html.Span(new_name, style={'padding-left':6})]),
'value':new_name,
'search':new_name}
label_option_changed = False # Typically True; will be False if the 'edit' was "notDefaut -> default."
# Find this label among the 'options' of the Dropdown of labels and replace it if necessary.
for i in range(len(label_options)):
if label_options[i]['value'] == unedited_name:
unedited_color = label_options[i]['label']['props']['children'][0]['props']['style']['color']
if new_name != unedited_name or new_color != unedited_color:
label_options[i] = new_option
label_option_changed = True
break
sample_option_changed = False
color_map_changed = False
isDefaultColor_map_changed = False
# Traverse the samples (sample = color label + parent ID) and make any necessary updates.
for i in range(len(sample_options)):
sample_name = sample_options[i]['label']['props']['children'][1]['props']['children']
sample_color = sample_options[i]['label']['props']['children'][0]['props']['style']['color']
# Make changes if:
# 1. The sample has the original (unedited) color and that color has changed.
# 2. The sample is flagged as needing the 'default' color and this edit makes new_color the default.
# 3. The sample already has the new color and this edit makes new_color the default.
# In this case, change its 'is default' flag to True.
if sample_color == unedited_color and unedited_color != new_color: # case 1
color_map[sample_name] = new_color
sample_options[i]['label']['props']['children'][0]['props']['style']['color'] = new_color
color_map_changed = True
sample_option_changed = True
if is_default:
if isDefaultColor_map[sample_name]:
if sample_color != new_color: # case 2
color_map[sample_name] = new_color
sample_options[i]['label']['props']['children'][0]['props']['style']['color'] = new_color
color_map_changed = True
sample_option_changed = True
# Otherwise new_color is the default, the sample needs the default color,
# and the sample already has it.
elif sample_color == new_color: # case 3
isDefaultColor_map[sample_name] = True
isDefaultColor_map_changed = True
if label_option_changed:
label_options_sans_option0 = label_options[1:]
ret_vals[0] = label_options
ret_vals[1] = label_options_sans_option0
if sample_option_changed:
ret_vals[4] = sample_options
if color_map_changed:
ret_vals[5] = color_map
if isDefaultColor_map_changed:
ret_vals[6] = isDefaultColor_map
if is_default:
ret_vals[7] = new_color # Update even if new_color==unedited_color. Edit could be 'make default' alone.
return tuple(ret_vals)
@callback(Output('edit-cat-modal', 'is_open', allow_duplicate=True),
Output('edit-category-name', 'value', allow_duplicate=True),
Output({'type':'color-displayed', 'index':utils.div_display['edit cat']}, 'style', allow_duplicate=True),
Output('categories-dropdown', 'value', allow_duplicate=True),
Input('edit-cat-cancel', 'n_clicks'),
State({'type':'color-displayed', 'index':utils.div_display['edit cat']}, 'style'),
prevent_initial_call='initial_duplicate')
def cancel_edited_label(n_clicks : int, style_to_cancel : dict):
"""
User clicked 'Cancel' in the 'edit existing label' modal
"""
if n_clicks > 0:
blank_style = style_to_cancel.copy()
blank_style['background'] = 'white'
blank_style['color'] = blank_style['background']
return False, None, blank_style, None
return no_update, no_update, no_update, no_update
#
#---------------------End 'edit new label' callbacks-------------------------------
#-------------------Begin 'color picker' callbacks---------------------------------
#
"""
Within the 'color picker', there are 3 ways to specify a color:
1. click a swatch within the grid of swatches
2. click what I'm calling a "color wheel" in the lower left-hand corner of the modal
3. type a hex string into the Input box and hit 'enter'
Options 1 and 2 will update the hex string in the Input box.
That update, or a direct update to it (option 3 above), will update the
color swatch (Div) immediately to the left of the Input box.
Clicking the 'OK' button will send the color of the Div to the appropriate component
and close the 'color picker' modal.
"""
@callback(Output('color-choice-string', 'value', allow_duplicate=True),
Output('color-choice-string', 'n_submit', allow_duplicate=True),
Input({'type':'ColorChoice', 'index':ALL}, 'n_clicks'),
State('color-choice-string', 'n_submit'),
prevent_initial_call='initial_duplicate')
def on_color_swatch_click(n_clicks : list, n_submit : int):
"""
Option 1 above: click a swatch within the grid of swatches.
Forwards the hex color string to the Input and mimics the user clicking 'enter'.
"""
if n_clicks and ctx.triggered_id:
# ctx.triggered_id is a Dash extension of dict
triggered_index = ctx.triggered_id['index']
color_chosen = utils.tableau20[triggered_index]
return color_chosen, n_submit+1
return no_update, no_update
@callback(Output('color-choice-string', 'value', allow_duplicate=True),
Output('color-choice-string', 'n_submit', allow_duplicate=True),
Input('color-wheel', 'value'),
State('color-choice-string', 'n_submit'),
prevent_initial_call='initial_duplicate')
def on_color_wheel_click(this_hex_color : str, n_submit : int):
"""
Option 2 above: click the "show color wheel" button and choose a color.
Forwards the hex color string to the Input and mimics the user clicking 'enter'.
"""
return this_hex_color, n_submit+1
@callback(Output('final-color-choice', 'style'),
Output('color-choice-string', 'value', allow_duplicate=True),
Output('err-msg', 'children', allow_duplicate=True),
Input('color-choice-string', 'n_submit'),
State('color-choice-string', 'value'),
State('final-color-choice', 'style'),
prevent_initial_call='initial_duplicate')
def on_hex_color_string_input(n_submit : int, hex_string : str, style : dict):
"""
This can be triggered by option 3 above (user enters a string and clicks 'enter')
or by options 1 and 2 automatically "entering the string and clicking 'enter'."
"""
if n_submit > 0:
# Validate hex_string before proceeding!
# Note: Eric first used try/raise on int_value = int(hex_string[1:], 16),
# but the edge cases were annoying. Hence what follows.
invalid_hex_string = False
if len(hex_string) == 6:
hex_string = '#' + hex_string
if len(hex_string) != 7 or hex_string[0] != '#':
invalid_hex_string = True
i = 1
while i < 7 and not invalid_hex_string:
c = hex_string[i]
if c.isalpha():
if c.lower() > 'f':
invalid_hex_string = True
elif not c.isdigit():
invalid_hex_string = True
i += 1
if invalid_hex_string:
err_msg = f'\"{hex_string}\" is not a valid color specification.\n' \
+'This must be a 6-digit hexadecimal value, e.g. \"#FF0000\" for \"red.\"'
# Reset the hex string and the accompanying Div that displays that color.
style['color'] = style['background'] = '#FFFFFF'
return style, '#FFFFFF', err_msg
style['color'] = style['background'] = hex_string
return style, no_update, no_update
return no_update, no_update, no_update
@callback(Output({'type':'color-displayed', 'index':ALL}, 'style', allow_duplicate=True),
Output('color-wheel', 'value', allow_duplicate=True),
Output('color-picker', 'is_open', allow_duplicate=True),
Input('ok-color-choice', 'n_clicks'),
State('final-color-choice', 'style'),
State({'type':'color-displayed', 'index':ALL}, 'style'),
State('idx-of-parent-modal', 'data'),
prevent_initial_call='initial_duplicate')
def apply_color(n_clicks : int, style_with_color_choice : dict, old_styles : list, idx : int):
"""
Display the chosen color in the parent modal and close the 'color-picker' modal.
Also reset the "color wheel" button to white.
"""
output_style_list = [no_update]*len(old_styles)
if n_clicks > 0:
color_choice = style_with_color_choice['color']
new_style = old_styles[idx].copy()
new_style['color'] = new_style['background'] = color_choice
output_style_list[idx] = new_style
return output_style_list, "#FFFFFF", False
return output_style_list, "#FFFFFF", no_update
@callback(Output('color-picker', 'is_open', allow_duplicate=True),
Output('color-wheel', 'value', allow_duplicate=True),
Output('lineplot-graph-id', 'clickData', allow_duplicate=True),
Input('cancel-color-choice', 'n_clicks'),
State('idx-of-parent-modal', 'data'),
prevent_initial_call='initial_duplicate')
def cancel_color_picker(n_clicks : int, idx : int):
"""
This is for the canceling/closing the modal of color options.
If the color picker was triggered by the user clicking on a trace in a plot,
we reset that plot's clickData so the user can edit that trace by clicking on it.
(If we don't reset clickData, repeated clicks on the trace will do nothing.)
"""
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
if n_clicks > 0:
if idx == utils.div_display['line plot']:
return False, utils.WHITE, None
return False, utils.WHITE, no_update
return no_updates
#
#---------------------End 'color picker' callbacks---------------------------------
#-------------------Begin 'label a sample' callbacks-------------------------------
#
@callback(Output('assign-label-modal', 'is_open', allow_duplicate=True),
Output('labeled-sample', 'children', allow_duplicate=True),
Input('samples-dropdown', 'value'),
State('samples-dropdown', 'options'),
prevent_initial_call='initial_duplicate')
def sample_chosen_from_dropdown(choice, samples_options):
"""
Dropdown of labeled samples: selection triggers label-assignment modal.
"""
for i in range(len(samples_options)):
if samples_options[i]['value'] == choice:
return True, samples_options[i]['label'].copy()
return no_update, no_update
@callback(Output('sample-to-color-map', 'data', allow_duplicate=True),
Output('samples-dropdown', 'options', allow_duplicate=True),
Output('samples-dropdown', 'value', allow_duplicate=True),
Output('assign-label-modal', 'is_open', allow_duplicate=True),
Output('label-assignment-dropdown', 'value', allow_duplicate=True),
Output('sample-to-IsDefaultColor-map', 'data', allow_duplicate=True),
Input('label-assignment-ok', 'n_clicks'),
State('labeled-sample', 'children'),
State('label-assignment-dropdown', 'value'),
State('label-assignment-dropdown', 'options'),
State('samples-dropdown', 'options'),
State('sample-to-color-map', 'data'),
State('sample-to-IsDefaultColor-map', 'data'),
State('default-color', 'data'),
prevent_initial_call='initial_duplicate')
def assign_label_to_sample(n_clicks : int, sample_to_be_labeled, new_label_str, label_options,
sample_options, color_map, isDefaultColor_map : dict, default_color : str):
"""
User clicked 'OK' to assign a label to a sample.
"""
if n_clicks > 0:
sample_name = sample_to_be_labeled['props']['children'][1]['props']['children']
for i in range(len(label_options)):
if label_options[i]['value'] == new_label_str:
new_sample_color = label_options[i]['label']['props']['children'][0]['props']['style']['color']
break
newly_labeled_sample = html.Span([html.Span('■', style={'color':new_sample_color,'font-size':36}),
html.Span(sample_name, style={'padding-left':6})])
for i in range(len(sample_options)):
if sample_options[i]['value'] == sample_name:
sample_options[i]['label'] = newly_labeled_sample
break
color_map[sample_name] = new_sample_color
orig_bool_entry = isDefaultColor_map[sample_name]
isDefaultColor_map[sample_name] = (new_sample_color == default_color)
if isDefaultColor_map[sample_name] != orig_bool_entry:
return color_map, sample_options, None, False, None, isDefaultColor_map
return color_map, sample_options, None, False, None, no_update
return no_update, no_update, no_update, no_update, no_update, no_update
@callback(Output('assign-label-modal', 'is_open', allow_duplicate=True),
Output('labeled-sample', 'children', allow_duplicate=True),
Output('samples-dropdown', 'value', allow_duplicate=True),
Output('label-assignment-dropdown', 'value', allow_duplicate=True),
Input('label-assignment-cancel', 'n_clicks'),
prevent_initial_call='initial_duplicate')
def cancel_label_assignment(n_clicks : int):
"""
User clicked 'Cancel' while on the modal for assigning a label to a sample.
"""
if n_clicks > 0:
return False, None, None, None
return no_update, no_update, no_update, no_update
@callback(Output('subset-label-assignment', 'is_open', allow_duplicate=True),
Output('err-msg', 'children', allow_duplicate=True),
Input('label-a-subset-button', 'n_clicks'),
State('label-assignment-dropdown', 'options'),
prevent_initial_call='initial_duplicate')
def show_subset_label_assignment_modal(n_clicks : int, label_options : list):
"""
User clicked the 'Label a subset' button above the bar plot.
Opens the modal for doing this, or displays an error message
if the user has not yet created any labels.
"""
if n_clicks:
if not label_options:
err_msg = 'Click the "Labels for samples" dropdown menu\n' \
+'to create a label for one or more samples.'
return no_update, err_msg
return True, no_update
return no_update, no_update
@callback(Output('label-assignment-dropdown-2', 'options'),
Output('expanding-query-div', 'children', allow_duplicate=True),
Output('query-results-tally', 'children', allow_duplicate=True),
Output('err-msg', 'children', allow_duplicate=True),
Input('subset-label-assignment', 'is_open'),
State('label-assignment-dropdown', 'options'),
State('metrics-dict', 'data'),
prevent_initial_call='initial_duplicate')
def load_subset_label_assignment_modal(is_opening : bool, label_options : list,
df_as_dicts : list):
"""
Function to populate the "subset label assignment" modal when it opens.
Parameters
----------
is_opening : bool
Whether the modal is opening or closing.
label_options : list
The 'options' list of available labels, from the dropdown on the dashboard.
df_as_dicts : list
The "metrics" records, i.e. a list of rows with each row expressed as a dict.
Returns
-------
list of dbc.Row(), str, str
A one-element list of dbc.Row(), the string '0 samples selected', and no_update,
or no_update, no_update, and an error message.
"""
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
if not is_opening or not label_options or not df_as_dicts:
return tuple(no_updates)
for required_column in ['prop value', 'prop name']:
if required_column not in df_as_dicts[0]:
err_msg = f"Error: Required column {required_column} was not found in 'metrics'."
no_updates[-1] = err_msg
return tuple(no_updates)
df_in = pd.DataFrame.from_dict(df_as_dicts)
non_prop_columns = list(set(df_in.columns.to_list()) - set(['prop name', 'prop value']))
if len(non_prop_columns) != 1:
err_msg = f"Found 0 or multiple non-'property' columns in 'metrics' {non_prop_columns}. Expected 1."
no_updates[-1] = err_msg
return tuple(no_updates)
x_column = non_prop_columns[0] # typically 'sample'
rows = []
return label_options, layout.make_query_row(rows, [*list(df_in['prop name'].unique()), x_column]), \
'0 samples selected', no_update
@callback(Output('expanding-query-div', 'children', allow_duplicate=True),
Input({'type':'add-another', 'index':ALL}, 'n_clicks'),
State('expanding-query-div', 'children'),
prevent_initial_call=True)
def add_row_to_query(n_clicks : int, rows : list):
if not rows or not n_clicks or not n_clicks[-1]:
return no_update
prop_names_and_xcolumn = rows[-1]['props']['children'][2]['props']['children']['props']['options']
return layout.make_query_row(rows, prop_names_and_xcolumn)
@callback(Output('samples-dropdown', 'options', allow_duplicate=True),
Output('sample-to-color-map', 'data', allow_duplicate=True),
Output('sample-to-IsDefaultColor-map', 'data', allow_duplicate=True),
Output('subset-label-assignment', 'is_open', allow_duplicate=True),
Output('err-msg', 'children', allow_duplicate=True),
Input('subset-label-assignment-ok', 'n_clicks'),
State('expanding-query-div', 'children'),
State('metrics-dict', 'data'),
State('label-assignment-dropdown-2', 'value'),
State('label-assignment-dropdown-2', 'options'),
State('samples-dropdown', 'options'),
State('sample-to-color-map', 'data'),
State('sample-to-IsDefaultColor-map', 'data'),
State('default-color', 'data'),
prevent_initial_call=True)
def do_query(n_clicks : int, rows : list, df_as_dicts : list,
new_label_str, label_options, sample_options,
color_map, isDefaultColor_map : dict, default_color : str):
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
if not n_clicks or not rows:
return tuple(no_updates)
if not new_label_str:
err_msg = 'Choose a label from the available options, or click Cancel.'
no_updates[-1] = err_msg
return tuple(no_updates)
df_in = pd.DataFrame.from_dict(df_as_dicts)
num_rows = len(rows)
subset = []
raw_query = []
for entry in ctx.args_grouping:
if entry['id'] == 'expanding-query-div':
for j in range(len(entry['value'])):
raw_query_row = []
err_msg = ""
for i in range(int(j==0),6): # 1,...,5 for the initial row; 0,...,5 otherwise
# Slots 2, 3, and 4 are mandatory. Display an error message if any are missing.
props_dict = entry['value'][j]['props']['children'][i]['props']['children']['props']
if i==2 and ('value' not in props_dict or props_dict['value'] is None):
err_msg = "Choose a property on which to filter, or click Cancel."
break
if i==3 and ('value' not in props_dict or props_dict['value'] is None):
err_msg = "Choose an operator (>, ==, etc.) for the filter, or click Cancel."
break
if i==4 and ('value' not in props_dict or not props_dict['value']):
err_msg = 'Enter a bound for the filter (e.g. 1.5, "mean", "%ile 95"),\nor click Cancel.'
break
raw_query_row.append(entry['value'][j]['props']['children'][i]['props']['children']['props']['value'])
if err_msg:
no_updates[-1] = err_msg
return tuple(no_updates)
raw_query.append(raw_query_row)
break
try:
subset = set(utils.process_subsetting_query(raw_query, df_in))
if not subset:
err_msg = "No results were found for this query."
no_updates[-1] = err_msg
return tuple(no_updates)
except ValueError as e:
err_msg = str(e)
no_updates[-1] = err_msg
return tuple(no_updates)
# Get the color corresponding to new_label_str:
for i in range(len(label_options)):
if label_options[i]['value'] == new_label_str:
new_sample_color = label_options[i]['label']['props']['children'][0]['props']['style']['color']
break
newColor_is_the_defaultColor = (new_sample_color == default_color)
isDefaultColor_map_changed = False
color_map_changed = False
# Assign the label to all samples in the selected subset and update the color map(s).
for i in range(len(sample_options)):
sample_name = sample_options[i]['value']
if sample_name in subset:
old_sample_color = color_map[sample_name]
oldColor_was_the_defaultColor = (old_sample_color == default_color)
if old_sample_color == new_sample_color:
continue
newly_labeled_sample = html.Span([html.Span('■', style={'color':new_sample_color,'font-size':36}),
html.Span(sample_name, style={'padding-left':6})])
sample_options[i]['label'] = newly_labeled_sample
color_map[sample_name] = new_sample_color
color_map_changed = True
if newColor_is_the_defaultColor:
isDefaultColor_map[sample_name] = True
isDefaultColor_map_changed = True
elif oldColor_was_the_defaultColor:
isDefaultColor_map[sample_name] = False
isDefaultColor_map_changed = True
retvals = [sample_options, no_update, no_update, False, no_update] # False = "close the modal"
if color_map_changed:
retvals[1] = color_map
if isDefaultColor_map_changed:
retvals[2] = isDefaultColor_map
return tuple(retvals)
@callback(Output('subset-label-assignment', 'is_open', allow_duplicate=True),
Input('subset-label-assignment-cancel', 'n_clicks'),
prevent_initial_call='initial_duplicate')
def cancel_subset_label_assignment(n_clicks : int):
"""
User clicked 'Cancel' while on the modal for assigning a label to a sample.
"""
if n_clicks:
return False
return no_update
#
#---------------------End 'label a sample' callbacks-------------------------------
#-------------Begin 'interactive plotting options' callbacks-----------------------
#
@callback(Output('barplot-graph-id', 'figure'),
Output('samples-dropdown', 'options', allow_duplicate=True),
Output('sortorder-dropdown', 'options', allow_duplicate=True),
Output('sortorder-dropdown', 'value', allow_duplicate=True),
Output('err-msg', 'children', allow_duplicate=True),
Input('render-barplot-button', 'n_clicks'),
Input('sample-to-color-map', 'data'),
Input('label-assignment-dropdown', 'options'),
Input('barPlot-hideXticks-checkbox', 'value'),
Input('sortorder-dropdown', 'value'),
Input('sortorder-radioitems', 'value'),
State('metrics-dict', 'data'),
State('samples-dropdown', 'options'),
State('barplot-facetVars-checklist', 'value'),
prevent_initial_call='initial_duplicate')
def update_barplot(n_clicks : int, color_map : dict, list_of_labels : list,
hide_x_ticks : bool, sorting_key : str,
sorting_direction : int, df_as_dict : list, labeled_samples : list,
props_to_plot : list):
"""
Function to make/update the faceted bar plot.
This will be called (the plot will be updated) when the user:
* sets or changes the map from ID to color (includes actions defining the 'default' label)
* assigns a new label to a sample
* clicks the checkbox to hide or "un-hide" the x-axis tick labels
* changes the property by which the data should be sorted
* changes the direction of the sort
Parameters
----------
n_clicks : int
The number of times this button has been clicked.
color_map : dict
A mapping from ID (str) to color (hex str).
list_of_labels : list
The current list of options in the 'labels' dropdown (color swatch + label name).
hide_x_ticks : bool
Whether to hide the x-axis tick labels.
sorting_key : str
The property name (or column, e.g. 'Patient ID') by whose values the bars should be sorted.
sorting_direction : int
1 = ascending, 0 = descending
df_as_dict : list
List of dicts (one per DF row) created by calling "to_dict" on a DataFrame in another callback.
Should contain, at minimum, columns [x-axis name], 'prop name', and 'prop value'.
labeled_samples : list
The current list of options in the 'samples' dropdown (color swatch + parent ID).
props_to_plot : list
The properties to plot (one facet for each) vs. ID ('Patient ID', 'Sample ID', etc.).
Returns
-------
figure, list (of labeled samples), str (error message)
The figure will be displayed and the 'samples' dropdown options will get re-sorted if necessary.
Or a modal window displaying the error message will appear.
Notes
-----
If your bar labels (x-axis values, e.g. for 'Patient ID' or 'Sample') require a custom sort order,
you will need to add code to this function to handle it. Coding hints are included below.
"""
num_outputs = len(ctx.outputs_list)
no_updates = [no_update]*num_outputs
if not df_as_dict:
return tuple(no_updates)
for required_column in ['prop value', 'prop name']:
if required_column not in df_as_dict[0]:
err_msg = f"Cannot make the bar plot; required column {required_column} was not found."
no_updates[-1] = err_msg
return tuple(no_updates)
if ctx.triggered_id == 'render-barplot-button' and n_clicks > 0:
# Presumably the facets have changed?
if sorting_key not in props_to_plot:
sorting_key = props_to_plot[0]
df_in = pd.DataFrame.from_dict(df_as_dict)
non_prop_columns = list(set(df_in.columns.to_list()) - set(['prop name', 'prop value']))
if len(non_prop_columns) != 1:
err_msg = f"Found 0 or multiple non-'property' columns in 'metrics' {non_prop_columns}. Expected 1."
no_updates[-1] = err_msg
return tuple(no_updates)
x_column = non_prop_columns[0] # typically 'sample', 'Patient ID', etc.
if not props_to_plot:
err_msg = "No properties were selected for the y-axes.\n"
err_msg += "Select one or more properties and click the 'plot' button."
no_updates[-1] = err_msg
return tuple(no_updates)
# At least for now, drop any row with a NaN.
df_facets = df_in[[True if prop in props_to_plot \
else False for prop in df_in['prop name']]].dropna(how='any',
ignore_index=True,
axis=0)
if len(df_facets)==0:
err_msg = "Missing data was found for the selected properties.\n"
err_msg += "Select different properties and click the 'plot' button."
no_updates[-1] = err_msg
return tuple(no_updates)
if sorting_key != x_column and sorting_key not in df_facets['prop name'].unique():
err_msg = f"Required property '{sorting_key}' was not found in the 'prop name' column of the DataFrame."
no_updates[-1] = err_msg
return tuple(no_updates)
ascending = bool(sorting_direction)
if x_column == sorting_key:
# Coding hint: If your x_column values require a sort order different from
# standard string sort order, add code here to implement that.
# Hint: If your x_column values have different parts ('part1_part2', 'p1-p2-p3', etc.),
# you can add columns to a copy of df_facets, sort on those, and then drop those columns.
# E.g.:
# df_final = df_facets.copy()
# df_final['p1'] = list of 'part1' substrings from your x_column values
# df_final['p2'] = ditto for 'part2' substrings
# df_final = df_final.sort_values(by=['p1','p2'],
# ascending=[ascending,ascending]).drop(['p1','p2'],
# axis=1).reset_index(drop=True)
# It might be best to use an if/else block:
# if fancy_sort_needed: fancy_sort else: standard_sort
df_final = df_facets.sort_values(by=[x_column], ascending=[ascending])
props = df_final['prop name'].unique().tolist()
else:
props = df_facets['prop name'].unique().tolist() # returned in the order in which they appear at the moment
props[props.index(sorting_key)] = props[0]
props[0] = sorting_key
this_sort_order = dict(zip(props, range(len(props))))
df_prelim = df_facets.sort_values(by=['prop value'], ascending=[ascending])
# Critically important: Must choose a final 'kind' of sorting that's stable, i.e. that preserves the prelim sort.
# According to the pandas docs, the two stable options are 'stable' and 'mergesort'.
df_final = df_prelim.sort_values(by=['prop name'], key=lambda z : z.map(this_sort_order), kind='stable')
# Currently there's no code in the following call that explicitly raises an exception. But try/except doesn't hurt.
try:
fig = utils.make_custom_multifaceted_bar_plot(df_final, props, color_map,
list_of_labels, x_column, hide_x_ticks)
except Exception as e:
err_msg = f"Unable to render the bar plot. {e}"
no_updates[-1] = err_msg
return tuple(no_updates)