-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
1748 lines (1455 loc) · 63.4 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
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.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
from dash import dcc, html
import dash
import statsmodels.api as sm
import pandas as pd
import warnings
import json
import os
import quantile_regression
import binary_classify
import Single_InDepth
import control_cards
import DecisionTree
import app_fxns
import survival
import IMMR
import MLR
import GLM
####################################################################################################
################################# CONFIG APP #############################################
####################################################################################################
FONT_AWESOME = "https://use.fontawesome.com/releases/v5.10.2/css/all.css"
chriddyp = 'https://codepen.io/chriddyp/pen/bWLwgP.css'
warnings.filterwarnings('ignore')
pd.set_option('display.max_columns', None)
external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME, chriddyp]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
server = app.server
xvars = ['Nothing uploaded']
yvar = 'Nothing uploaded'
statsmodels_tags = ["AIDS ","Down","WHO ","abortion","adolescent","adult","anxiety","arthritis",
"auditory","autism","behavior","biopsy","birth","blood","body","breast",
"cancer","cardiovascular","cell","child","cholera","cirrhosis","clinical",
"coma","consumption","contagious","contraceptive","coronary","covid","deaths",
"dengue","dependency","deprivation","diabetes","diarrhaea","disease","doctor",
"donation","drug","eating","ebola","efficacy","exercise","feet","fertility",
"food","freedom","gestation","headaches","health","healthcare","hepatocellular",
"hiv","illness","indomethacin","infant","insurance","liver","male","malignant",
"mammogram","marrow","medicaid","medical","medicare","medpar","melanoma",
"migraine","neuro","nutrition","obesity","obstetrics","organ","pancreatic",
"parents","periodontal","physician","prenatal","prostate","prothrombin",
"quarantine","radiation","recovery","remission","reporting","respiratory",
"risk","serum","sleep","smallpox","smoking","society","stress","syndrome",
"transplant","urine","vaccine","weight","wheeze","women"]
statsmodels_df = pd.read_csv('statsmodels_df.csv')
statsmodels_df.drop(labels=['Unnamed: 0'], axis=1, inplace=True)
statsmodels_df = statsmodels_df.rename(columns={'Dataset': 'id'})
statsmodels_df.set_index('id', inplace=True, drop=False)
####################################################################################################
############################## DASH APP LAYOUT #######################################
####################################################################################################
app.layout = html.Div([
dcc.Store(id='main_df', storage_type='memory'),
html.Div(
id='reset',
style={'display': 'none'}
),
html.Div(
id='cat_vars',
style={'display': 'none'}
),
html.Div(
id='di_numerical_vars',
style={'display': 'none'}
),
html.Div(
style={'background-color': '#f9f9f9'},
id="banner1",
className="banner",
children=[html.Img(src=app.get_asset_url("RUSH_full_color.jpg"),
style={'textAlign': 'left'},
),
html.Img(src=app.get_asset_url("plotly_logo.png"),
style={'textAlign': 'right'},
),
],
),
html.Div(
id="top-column1",
className="ten columns",
children=[control_cards.description_card1()],
style={'width': '95.3%',
'display': 'inline-block',
'border-radius': '15px',
'box-shadow': '1px 1px 1px grey',
'background-color': '#f0f0f0',
'margin-bottom': '1%',
},
),
html.Div(
className="ten columns",
children=[
dbc.Carousel(
items=[
{"key": "1", "src": "/assets/images_for_ap/a1.png"},
{"key": "2", "src": "/assets/images_for_ap/a2.png"},
{"key": "3", "src": "/assets/images_for_ap/a3.png"},
{"key": "4", "src": "/assets/images_for_ap/a4.png"},
{"key": "5", "src": "/assets/images_for_ap/a5.png"},
{"key": "6", "src": "/assets/images_for_ap/a6.png"},
{"key": "7", "src": "/assets/images_for_ap/a7.png"},
{"key": "8", "src": "/assets/images_for_ap/a8.png"},
],
controls=True,
indicators=True,
interval=5000,
ride="carousel",
style={"maxWidth": "100%"},
),
],
style={'width': '95%',
'display': 'block',
'margin-left': '2%',
'margin-right': '1%',
'margin-top': '1%',
'margin-bottom': '1%',
},
),
html.Div(
id="bottom-column1",
className="ten columns",
children=[control_cards.description_card_final()],
style={'width': '95.3%',
'display': 'inline-block',
'border-radius': '15px',
'box-shadow': '1px 1px 1px grey',
'background-color': '#f0f0f0',
'padding': '1%',
},
),
])
####################################################################################################
############################ Callbacks ############################################
####################################################################################################
############################# Modals #####################################################
@app.callback(
Output("modal-single_regression_residuals_plot", "is_open"),
[Input("open-single_regression_residuals_plot", "n_clicks"),
Input("close-single_regression_residuals_plot", "n_clicks")],
[State("modal-single_regression_residuals_plot", "is_open")],
prevent_initial_call=True,
)
def toggle_modal(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-quant_regression_table", "is_open"),
[Input("open-quant_regression_table", "n_clicks"),
Input("close-quant_regression_table", "n_clicks")],
[State("modal-quant_regression_table", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_quant(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered_single", "is_open"),
[Input("open-centered_single", "n_clicks"),
Input("close-centered_single", "n_clicks")],
[State("modal-centered_single", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_single(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-iterative_multimodel_ols_table1", "is_open"),
[Input("open-iterative_multimodel_ols_table1", "n_clicks"),
Input("close-iterative_multimodel_ols_table1", "n_clicks")],
[State("modal-iterative_multimodel_ols_table1", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_c2(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-iterative_ols', "is_open"),
[Input('open-iterative_ols', "n_clicks"),
Input('close-iterative_ols', "n_clicks")],
[State('modal-iterative_ols', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_iterative_ols(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-single_ols', "is_open"),
[Input('open-single_ols', "n_clicks"),
Input('close-single_ols', "n_clicks")],
[State('modal-single_ols', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_single_ols(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-quant_reg', "is_open"),
[Input('open-quant_reg', "n_clicks"),
Input('close-quant_reg', "n_clicks")],
[State('modal-quant_reg', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_quant_reg(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-multi_reg', "is_open"),
[Input('open-multi_reg', "n_clicks"),
Input('close-multi_reg', "n_clicks")],
[State('modal-multi_reg', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_multi_reg(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-dec_tree_reg_table_perf', "is_open"),
[Input('open-dec_tree_reg_table_perf', "n_clicks"),
Input('close-dec_tree_reg_table_perf', "n_clicks")],
[State('modal-dec_tree_reg_table_perf', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_dec_tree_reg_table_perf(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-dec_tree_reg_table_params', "is_open"),
[Input('open-dec_tree_reg_table_params', "n_clicks"),
Input('close-dec_tree_reg_table_params', "n_clicks")],
[State('modal-dec_tree_reg_table_params', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_dec_tree_reg_table_params(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-logistic_reg', "is_open"),
[Input('open-logistic_reg', "n_clicks"),
Input('close-logistic_reg', "n_clicks")],
[State('modal-logistic_reg', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_logistic_reg(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-glm', "is_open"),
[Input('open-glm', "n_clicks"),
Input('close-glm', "n_clicks")],
[State('modal-glm', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_glm(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered-controlcard", "is_open"),
[Input("open-centered-controlcard", "n_clicks"),
Input('main_df', 'data'),
],
[State("modal-centered-controlcard", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_cc(n1, df, is_open):
ctx1 = dash.callback_context
jd1 = json.dumps({'triggered': ctx1.triggered,})
jd1 = jd1[:50]
if n1:# or df == 1:
return not is_open
return is_open
@app.callback(
Output("modal-centered-controlcard_load", "is_open"),
[Input("open-centered-controlcard_load", "n_clicks"),
Input("close-centered-controlcard_load", "n_clicks"),
Input('main_df', 'data')],
[State("modal-centered-controlcard_load", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_ccl(n1, n2, df, is_open):
ctx1 = dash.callback_context
jd1 = json.dumps({'triggered': ctx1.triggered,})
jd1 = jd1[:50]
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-choose_regression", "is_open"),
[Input("open-choose_regression", "n_clicks"),
Input("close-choose_regression", "n_clicks")],
[State("modal-choose_regression", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_cc_choose_reg(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-inspect_main_datatable", "is_open"),
[Input("open-inspect_main_datatable", "n_clicks"),
Input("close-inspect_main_datatable", "n_clicks")],
[State("modal-inspect_main_datatable", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_inspect_main_datatable(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-level-group", "is_open"),
[Input("open-level-group", "n_clicks"),
Input("close-level-group", "n_clicks")],
[State("modal-level-group", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_level_group(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered-controlcard1", "is_open"),
[Input("open-centered-controlcard1", "n_clicks"),
Input("close-centered-controlcard1", "n_clicks")],
[State("modal-centered-controlcard1", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_cc1(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered3", "is_open"),
[Input("open-centered3", "n_clicks"),
Input("close-centered3", "n_clicks")],
[State("modal-centered3", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_c3(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-glm_parameters_table", "is_open"),
[Input("open-glm_parameters_table", "n_clicks"),
Input("close-glm_parameters_table", "n_clicks")],
[State("modal-glm_parameters_table", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_glm_params_table(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-glm_performance_table", "is_open"),
[Input("open-glm_performance_table", "n_clicks"),
Input("close-glm_performance_table", "n_clicks")],
[State("modal-glm_performance_table", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_glm_performance_table(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered4", "is_open"),
[Input("open-centered4", "n_clicks"),
Input("close-centered4", "n_clicks")],
[State("modal-centered4", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_c4(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered5", "is_open"),
[Input("open-centered5", "n_clicks"),
Input("close-centered5", "n_clicks")],
[State("modal-centered5", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_c5(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output("modal-centered6", "is_open"),
[Input("open-centered6", "n_clicks"),
Input("close-centered6", "n_clicks")],
[State("modal-centered6", "is_open")],
prevent_initial_call=True,
)
def toggle_modal_c6(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-survival', "is_open"),
[Input('survival_reg_btn', "n_clicks"),
Input('close-survival', "n_clicks")],
[State('modal-survival', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_survival(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-decision_tree', "is_open"),
[Input('open-decision_tree', "n_clicks"),
Input('close-decision_tree', "n_clicks")],
[State('modal-decision_tree', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_decision_tree(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-survival_params_table', "is_open"),
[Input('open-survival_params_table', "n_clicks"),
Input('close-survival_params_table', "n_clicks")],
[State('modal-survival_params_table', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_survival_params_table(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-survival_performance_table', "is_open"),
[Input('open-survival_performance_table', "n_clicks"),
Input('close-survival_performance_table', "n_clicks")],
[State('modal-survival_performance_table', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_survival_performance_table(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-statsmodels', "is_open"),
[Input('open-statsmodels', "n_clicks"),
Input('close-statsmodels', "n_clicks")],
[State('modal-statsmodels', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_statsmodals(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-statsmodels_data_doc', "is_open"),
[Input('open-statsmodels_data_doc', "n_clicks"),
Input('close-statsmodels_data_doc', "n_clicks")],
[State('modal-statsmodels_data_doc', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_statsmodals_data_doc(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('modal-lifelines', "is_open"),
[Input('open-lifelines', "n_clicks"),
Input('close-lifelines', "n_clicks")],
[State('modal-lifelines', "is_open")],
prevent_initial_call=True,
)
def toggle_modal_lifelines(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
####################################################################################################
############### Buttons, Main DataFrames, Main DataTable ########################################
####################################################################################################
@app.callback(Output('statsmodels_data_doc', 'children'),
[Input('statsmodels_data_table', 'active_cell'),
Input('statsmodels_data_table', 'data'),
],
)
def update_statmodels_data_doc(row, df):
if row is None:
raise PreventUpdate
df = pd.DataFrame(df)
if df.empty:
return 'Your data table is empty'
dataset = row['row_id']
doc = statsmodels_df[statsmodels_df['id'] == dataset]['docs'].iloc[0]
return doc
@app.callback([Output('main_df', 'data'),
Output('rt4', 'children')],
[Input('upload-data', 'contents'),
Input('hcris', 'n_clicks'),
Input('hais', 'n_clicks'),
Input('hacrp', 'n_clicks'),
Input('hrrp', 'n_clicks'),
Input('c_and_d', 'n_clicks'),
Input('p_and_v', 'n_clicks'),
Input('t_and_e', 'n_clicks'),
Input('unplanned_visits', 'n_clicks'),
Input('imaging', 'n_clicks'),
Input('load_statsmodels_dataset', 'n_clicks'),
],
[State('upload-data', 'filename'),
State('upload-data', 'last_modified'),
State('hcris-year', 'value'),
State('hais-year', 'value'),
State('hacrp-year', 'value'),
State('hrrp-year', 'value'),
State('c_and_d-year', 'value'),
State('p_and_v-year', 'value'),
State('t_and_e-year', 'value'),
State('unplanned_visits-year', 'value'),
State('imaging-year', 'value'),
State('statsmodels_data_table', 'active_cell'),
],
)
def update_main_DataFrame(list_of_contents, hcris, hais, hacrp, hrrp, c_and_d, p_and_v,
t_and_e, unplanned_visits, imaging, statsmodels_data,
file_name, list_of_dates, hcris_yr, hais_yr, hacrp_yr, hrrp_yr,
c_and_d_yr, p_and_v_yr, t_and_e_yr, unplanned_visits_yr,
imaging_yr, statsmodels_row):
ctx1 = dash.callback_context
jd1 = json.dumps({'triggered': ctx1.triggered,})
jd1 = jd1[:50]
labs = ['hcris', 'hais', 'hacrp', 'hrrp', 'c_and_d', 'p_and_v',
't_and_e', 'unplanned_visits', 'imaging', 'load_statsmodels_data']
yrs = [hcris_yr, hais_yr, hacrp_yr, hrrp_yr, c_and_d_yr, p_and_v_yr,
t_and_e_yr, unplanned_visits_yr, imaging_yr]
urls = ['https://github.com/klocey/HCRIS-databuilder/raw/master/filtered_datasets/HCRIS_filtered_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/HAIs/HAIs_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Hospital_Acquired_Conditions_Reduction_Program/Hospital_Acquired_Conditions_Reduction_Program_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Hospital_Readmissions_Reduction_Program/Hospital_Readmissions_Reduction_Program_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Complications_and_Deaths/Complications_and_Deaths_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Payment_and_Value_of_Care/Payment_and_Value_of_Care_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Timely_and_Effective_Care/Timely_and_Effective_Care_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Unplanned_Visits/Unplanned_Visits_',
'https://github.com/klocey/hospitals-data-archive/raw/main/dataframes/filtered_files/Outpatient_Imaging_Efficiency/Outpatient_Imaging_Efficiency_',
]
select_preprocessed = 'n'
for i, lab in enumerate(labs):
if lab in jd1:
select_preprocessed = 'y'
if lab == 'load_statsmodels_data':
dataset = statsmodels_row['row_id']
package = statsmodels_df[statsmodels_df['id'] == dataset]['package'].iloc[0]
item = statsmodels_df[statsmodels_df['id'] == dataset]['item'].iloc[0]
df = sm.datasets.get_rdataset(item, package).data
else:
try:
url = urls[i] + yrs[i] + '.csv'
df = pd.read_csv(url)
except:
raise PreventUpdate
break
if select_preprocessed == 'n':
if list_of_contents is None or file_name is None or list_of_dates is None:
# uploaded file contains nothing
return None, ""
elif file_name[-4:] != '.csv':
# uploaded file does not have the .csv extension
error_string = "Error: This application only accepts the universally useful "
error_string += "CSV file type. Ensure that your file has the .csv extension "
error_string += "and is correctly formatted."
return None, error_string
elif list_of_contents is not None:
error_string = "Error: Your .csv file was not processed. "
error_string += "Ensure there are only rows, columns, and one row of column headers. "
error_string += "Make sure your file contains enough data to analyze."
children = 0
df = 0
# Attempt to parse the content
try:
children = [app_fxns.parse_contents(c, n, d) for c, n, d in zip([list_of_contents],
[file_name],
[list_of_dates])]
except:
return None, error_string
# Attempt to assign contents to an object
try:
df = children[0]
except:
return None, error_string
# Attempt to read the object as a pandas dataframe
try:
df = pd.read_json(df)
except:
return None, error_string
# Check for variables named 'Unnamed' and removed them
var_ls = list(df)
ls1 = []
for i in var_ls:
if 'Unnamed' in i:
ls1.append(i)
df.drop(labels=ls1, axis=1, inplace=True)
del ls1, var_ls
# Check for whether the dataframe contains a trivial amount of data
try:
if df.shape[0] < 4 or df.shape[1] < 2:
error_string = "Error: Your .csv file was not processed. "
error_string += "Ensure there are only rows, columns, and one row of column headers. "
error_string += "Make sure your file contains enough data to analyze."
return None, error_string
except:
error_string = "Error: Your .csv file was not processed. "
error_string += "Ensure there are only rows, columns, and one row of column headers. "
error_string += "Make sure your file contains enough data to analyze."
return None, error_string
df.columns = df.columns.str.strip() # remove leading and trailing whitespaces
#df.columns = df.columns.str.replace(":", " ") # replace colons with white spaces
df = df.replace(',',' ', regex=True) # replace commas with white spaces
df = df.replace({None: 'None'}) # replace None objects with string objects of 'None'
df = df.replace({'?': 0}) # replace question marks with 0 integer values
df.dropna(how='all', axis=1, inplace=True) # drop all columns having no data
df.dropna(how='all', axis=0, inplace=True) # drop all rows having no data
# If the dataframe contains >5000 rows or >50 columns, sample at random to meet those constraints
if os.environ.get('DEPLOYMENT_ENV', 'local') != 'local':
if df.shape[0] > 10000: df = df.sample(n = 10000,
axis=0, replace=False, random_state=0)
if df.shape[1] > 50: df = df.sample(n = 50,
axis=1, replace=False, random_state=0)
df.dropna(how='all', axis=1, inplace=True) # drop all columns having no data
df.dropna(how='all', axis=0, inplace=True) # drop all rows having no data
df = df.loc[:, df.nunique() != 1] # drop all columns containing only one unique value
variables = list(df)
############################################################################################
# Attempt to detect datetime features based on their label.
# This is done because python's datetime library can easily convert numeric data to datetime
# objects (meaning it's no use to ask whether a feature can be converted to datetime).
datetime_ls1 = [' date ', ' DATE ', ' Date ', ' date', ' DATE', ' Date', '_date_', '_DATE_',
'_Date_', '_date', '_DATE', '_Date', ',date', ',DATE', ',Date', ';date',
';DATE', ';Date', '-date', '-DATE', '-Date', ':date', ':DATE', ':Date']
datetime_ls2 = ['date', 'DATE', 'Date']
for i in variables:
if i in datetime_ls2:
df.drop(labels = [i], axis=1, inplace=True)
continue
else:
for j in datetime_ls1:
if j in i:
df.drop(labels = [i], axis=1, inplace=True)
break
############################################################################################
############################################################################################
# A final check to dump any row containing no data
df.dropna(how='all', axis=0, inplace=True)
return df.to_json(), ""
@app.callback(Output('group_text', 'style'),
[Input('group-interval-component', 'n_intervals')]
)
def hide_text(n):
if n >= 2:
return {'display': 'none'}
else:
return {'textAlign': 'left',
'margin-left': '3%',
'color': '#ffffff'}
@app.callback(Output('level_vars', 'options'),
[Input('cat_var_group', 'value')],
[State('data_table', 'data')],
)
def update_level_vars_options(cat_var, data):
if data is None:
return [{"label": i, "value": i} for i in []]
elif cat_var is None:
data = pd.DataFrame(data)
ls = [{"label": i, "value": i} for i in []]
return ls
else:
data = pd.DataFrame(data)
ls = sorted(data[cat_var].unique().tolist())
ls = [{"label": i, "value": i} for i in ls]
return ls
@app.callback([Output('cat_var_group', 'options'),
Output('cat_var_group', 'value'),
],
[Input("open-level-group", 'n_clicks'),
Input('group_text', 'children'),
],
[State('cat_vars', 'children'),
State('data_table', 'selected_columns'),
],
)
def update_cat_vars_for_group(n_clicks, trigger, cat_vars, selected_cols):
if selected_cols is None or cat_vars is None:
raise PreventUpdate
else:
cat_vars = sorted([element for element in cat_vars if element in selected_cols])
if cat_vars is None or cat_vars == []:
return [], None
options = [{"label": i, "value": i} for i in cat_vars]
return options, cat_vars[0]
@app.callback([Output('statsmodels_data_table', 'data'),
Output('statsmodels_data_table', 'columns'),
],
[Input('statsmodels_tags', 'value'),
]
)
def update_statsmodels_data_table(tags):
if tags is None:
raise PreventUpdate
f_df = statsmodels_df.drop(labels=['docs', 'package', 'item'], axis=1)
f_df = f_df[f_df['id'].str.contains('|'.join(tags), case=True)]
data = f_df.to_dict('records')
columns = [{'id': c,
'name': c,
} for c in f_df.columns]
return data, columns
@app.callback([Output('data_table', 'data'),
Output('data_table', 'columns'),
Output('data_table', 'style_table'),
Output('Data-Table1', 'style'),
Output('cat_vars', 'children'),
Output('di_numerical_vars', 'children'),
Output('group_text', 'children'),
Output('group-interval-component', 'n_intervals'),
Output('data_table', 'selected_columns'),
],
[Input('main_df', 'data'),
Input('level-group-btn1', 'n_clicks'),
Input('data_table', 'columns'),
Input('data_table', 'selected_columns'),
],
[State('rt4', 'children'),
State('data_table', 'data'),
State('cat_var_group', 'value'),
State('level_vars', 'value'),
State('new_level_name', 'value'),
],
)
def update_main_DataTable(df, btn, Dcols, selected_cols, rt4, data, cat_var, level_vars, new_name):
if df is None:
raise PreventUpdate
else:
ctx1 = dash.callback_context
jd1 = json.dumps({'triggered': ctx1.triggered,})
jd1 = jd1[:50]
out_text = ""
if 'level-group-btn1' not in jd1:
df = pd.read_json(df)
if df.empty:
raise PreventUpdate
############################################################################################
################# GROUP SELECTED LEVELS FOR SELECTED CATEGORICAL VARIABLE ###############
elif 'level-group-btn1' in jd1:
if cat_var is None or level_vars is None:
raise PreventUpdate
else:
df = pd.DataFrame(data)
ls = df[cat_var].tolist()
ls = [new_name if i in level_vars else i for i in ls]
df[cat_var] = ls
out_text = "Level group complete! Continue collapsing levels or click the button below to close this window."
############################################################################################
################# UPDATE CHANGES IN SELECTED COLUMNS AND VARIABLE NAMES ####################
if 'data_table' in jd1:
names = [column['name'] for column in Dcols]
ids = [column['id'] for column in Dcols]
df = pd.DataFrame(data)
df = df.filter(items=names, axis=1)
if selected_cols is None:
pass
elif len(selected_cols) > 0:
s_cols2 = []
for col in selected_cols:
i = ids.index(col)
new_name = names[i]
s_cols2.append(new_name)
selected_cols = list(s_cols2)
df.columns = names
############################################################################################
########## DETECT VARIABLES THAT ARE NUMERIC, CATEGORICAL, OR POTENTIALLY BOTH #############
ct, cat_vars, dichotomous_numerical_vars = 1, [], []
variables = list(df)
for i in variables:
if 'Unnamed' in i:
new_lab = 'Unnamed ' + str(ct)
df.rename(columns={i: new_lab}, inplace=True)
i = new_lab
ct += 1
# 1. Convert df[i] to numeric and coerce all non-numbers to np.nan
df['temp'] = pd.to_numeric(df[i], errors='coerce')
# 2. Replace all the np.nan's in df['temp'] with values in df[i]
df['temp'].fillna(df[i], inplace=True)
# 3. Replace df[i] with df['temp']
df[i] = df['temp'].copy(deep=True)
# 4. Drop df['temp']
df.drop(labels=['temp'], axis=1, inplace=True)
ls = df[i].unique()
if all(isinstance(item, str) for item in ls) is True:
# if all items are strings, then call the feature categorical
cat_vars.append(i)
else:
# else call the feature numeric
df[i] = pd.to_numeric(df[i], errors='coerce')
if len(ls) == 2 and all(isinstance(item, str) for item in ls) is False:
dichotomous_numerical_vars.append(i)
data = df.to_dict('records')
columns = [{'id': c,
'name': c,
'deletable': True,
'renamable': True,
'selectable': True} for c in df.columns]
style_table={'overflowX': 'auto',
'overflowY': 'auto',
}