forked from klocey/cms-stars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
3582 lines (3013 loc) · 150 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
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash import dash_table
from dash.exceptions import PreventUpdate
from sklearn.cluster import KMeans
import numpy as np
from scipy import stats
from scipy.stats import percentileofscore
import pandas as pd
import plotly
import plotly.graph_objects as go
import plotly.express as px
import warnings
import sys
import re
import csv
import math
import random
import json
from datetime import datetime
px.set_mapbox_access_token('pk.eyJ1Ijoia2xvY2V5IiwiYSI6ImNrYm9uaWhoYjI0ZDcycW56ZWExODRmYzcifQ.Mb27BYst186G4r5fjju6Pw')
latest_release_yr = 2024
latest_predict_yr = 2025
#########################################################################################
################################# CONFIG APP ############################################
#########################################################################################
FONT_AWESOME = "https://use.fontawesome.com/releases/v5.10.2/css/all.css"
warnings.filterwarnings('ignore')
pd.set_option('display.max_columns', None)
external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME, 'https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__,
external_stylesheets = external_stylesheets,
)
app.config.suppress_callback_exceptions = True
server = app.server
##############################################################################
def run_whatif(raw_data, pnum):
def adjust_edge_cases(row, centers, col):
"""
Adjust cluster labels for edge cases, accounting for cases where the distance to the assigned cluster is 0.0.
Args:
- row: The row of the DataFrame being processed.
- centers: Array of cluster centers.
- col: The column name of the measure used for clustering.
Returns:
- Adjusted cluster label.
"""
distances = np.abs(centers - row[col])
closest, second_closest = np.partition(distances, 1)[:2]
# Check if the closest distance is 0.0; if so, do not adjust the label
if closest == 0:
return row['cluster'] + 1
# If the closest and second closest centers are very close, consider adjusting the label
if np.isclose(closest, second_closest, atol=0.0001): # 'atol' might need adjustment
return row['cluster'] + 1 # Increment the cluster label for edge cases
else:
return row['cluster']
def kmeans_clustering(df, n_clusters=5, col='summary_score'):
# Step 1: Initial Data Preparation - Determine quintile medians as initial seeds
quintiles = np.percentile(df[col].dropna(),
[20.0, 40.0, 60.0, 80.0],
method='interpolated_inverted_cdf', # this is good
#method='linear',
)
df['grp'] = pd.cut(df[col], bins=[-np.inf] + quintiles.tolist() + [np.inf], labels=False) + 1
# Step 2: Initial K-Means Clustering - Compute median for initial seeds
initial_seeds = df.groupby('grp')[col].median().dropna().values.reshape(-1, 1)
kmeans_initial = KMeans(n_clusters=len(initial_seeds),
init=initial_seeds,
n_init=100,
max_iter=1000,
random_state=0,
tol=0.000001,
#algorithm='auto',
)
kmeans_initial.fit(df[[col]].dropna())
# Use cluster centers from initial k-means as seeds for the main clustering
main_seeds = kmeans_initial.cluster_centers_
# Step 3: Second K-Means Clustering - Main clustering with refined seeds
kmeans_main = KMeans(n_clusters=n_clusters,
init=main_seeds,
n_init=100,
max_iter=1000,
random_state=0,
tol=0.000001,
#algorithm='auto',
)
df['cluster'] = kmeans_main.fit_predict(df[[col]].dropna())
# Post-clustering adjustment for edge cases
centers = kmeans_main.cluster_centers_.flatten()
df['cluster'] = df.apply(adjust_edge_cases, centers=centers, col=col, axis=1)
# Step 4: Cluster Ordering and Labeling - Order clusters and assign 'star' ratings
cluster_means = df.groupby('cluster')[col].mean().sort_values().index
cluster_mapping = {old: new for new, old in enumerate(cluster_means, 1)}
df['star'] = df['cluster'].map(cluster_mapping)
df.drop('cluster', axis=1, inplace=True)
return df
# Define the measures you're interested in
measures = ['MORT_30_AMI', 'MORT_30_CABG', 'MORT_30_COPD', 'MORT_30_HF',
'MORT_30_PN', 'MORT_30_STK', 'PSI_4_SURG_COMP', 'COMP_HIP_KNEE',
'HAI_1', 'HAI_2', 'HAI_3', 'HAI_4', 'HAI_5', 'HAI_6',
'PSI_90_SAFETY', 'EDAC_30_AMI', 'EDAC_30_HF',
'EDAC_30_PN', 'OP_32', 'READM_30_CABG', 'READM_30_COPD',
'READM_30_HIP_KNEE', 'READM_30_HOSP_WIDE', 'OP_35_ADM',
'OP_35_ED', 'OP_36', 'H_COMP_1_STAR_RATING', 'H_COMP_2_STAR_RATING',
'H_COMP_3_STAR_RATING', 'H_COMP_5_STAR_RATING',
'H_COMP_6_STAR_RATING', 'H_COMP_7_STAR_RATING',
'H_GLOB_STAR_RATING', 'H_INDI_STAR_RATING', 'HCP_COVID_19',
'IMM_3', 'OP_10', 'OP_13', 'OP_18B', 'OP_2', 'OP_22',
'OP_23', 'OP_29', 'OP_3B', 'OP_8', 'PC_01', 'SEP_1',
]
#print(len(measures), 'measures')
prvdrs = raw_data['PROVIDER_ID']
raw_data = raw_data.filter(items=measures)
filtered_data = raw_data.dropna(axis=1, thresh=101)
filtered_measures = list(filtered_data)
excluded = [item for item in measures if item not in filtered_measures]
#print('Excluded measure(s):', excluded)
filtered_data.dropna(how='all', subset=filtered_measures, axis=0, inplace=True)
#print('Shape of filtered dataframe:', filtered_data.shape)
#print('Final no. of measures:', filtered_data.shape[1])
filtered_data['PROVIDER_ID'] = prvdrs
filtered_data = filtered_data[filtered_data.columns[-1:].tolist() + filtered_data.columns[:-1].tolist()]
ddof = 1
zscore_df = filtered_data.copy(deep=True)
for m in measures:
if m in excluded:
continue
zscore_df[m] = stats.zscore(zscore_df[m], ddof=ddof, nan_policy='omit')
rev_measures = ['MORT_30_AMI', 'MORT_30_CABG', 'MORT_30_COPD', 'MORT_30_HF',
'MORT_30_PN', 'MORT_30_STK', 'PSI_4_SURG_COMP', 'COMP_HIP_KNEE',
'HAI_1', 'HAI_2', 'HAI_3', 'HAI_4', 'HAI_5', 'HAI_6',
'PSI_90_SAFETY', 'EDAC_30_AMI', 'EDAC_30_HF', 'EDAC_30_PN',
'OP_32', 'READM_30_CABG', 'READM_30_COPD',
'READM_30_HIP_KNEE', 'READM_30_HOSP_WIDE',
'OP_35_ADM', 'OP_35_ED', 'OP_36', 'OP_22',
'PC_01', 'OP_3B', 'OP_18B', 'OP_8',
'OP_10','OP_13',
]
for m in rev_measures:
zscore_df[m] = -1*zscore_df[m]
zscore_df[m] = zscore_df[m]
final_df = pd.DataFrame(columns=['PROVIDER_ID'])
final_df['PROVIDER_ID'] = zscore_df['PROVIDER_ID']
# 7 Mortality measures
mort_measures = ['MORT_30_AMI', 'MORT_30_CABG', 'MORT_30_COPD', 'MORT_30_HF',
'MORT_30_PN', 'MORT_30_STK', 'PSI_4_SURG_COMP']
final_df['Std_Outcomes_Mortality_score'] = stats.zscore(zscore_df[mort_measures].mean(axis=1), ddof=ddof, nan_policy='omit')
final_df['Outcomes_Mortality_cnt'] = zscore_df[mort_measures].apply(lambda row: row.notna().sum(), axis=1)
# 11 Readmission measures
readm_measures = ['EDAC_30_AMI', 'EDAC_30_HF', 'EDAC_30_PN', 'OP_32',
'READM_30_CABG', 'READM_30_COPD', 'READM_30_HIP_KNEE',
'READM_30_HOSP_WIDE', 'OP_35_ADM', 'OP_35_ED', 'OP_36']
final_df['Std_Outcomes_Readmission_score'] = stats.zscore(zscore_df[readm_measures].mean(axis=1), ddof=ddof, nan_policy='omit')
final_df['Outcomes_Readmission_cnt'] = zscore_df[readm_measures].apply(lambda row: row.notna().sum(), axis=1)
# 8 SAFETY measures
safety_measures = ['COMP_HIP_KNEE', 'HAI_1', 'HAI_2', 'HAI_3', 'HAI_4',
'HAI_5', 'HAI_6', 'PSI_90_SAFETY']
final_df['Std_Outcomes_Safety_score'] = stats.zscore(zscore_df[safety_measures].mean(axis=1), ddof=ddof, nan_policy='omit')
final_df['Outcomes_safety_cnt'] = zscore_df[safety_measures].apply(lambda row: row.notna().sum(), axis=1)
# 8 Patient experience measures
patexp_measures = ['H_COMP_1_STAR_RATING', 'H_COMP_2_STAR_RATING',
'H_COMP_3_STAR_RATING', 'H_COMP_5_STAR_RATING',
'H_COMP_6_STAR_RATING', 'H_COMP_7_STAR_RATING',
'H_GLOB_STAR_RATING', 'H_INDI_STAR_RATING']
final_df['Std_PatientExp_score'] = stats.zscore(zscore_df[patexp_measures].mean(axis=1), ddof=ddof, nan_policy='omit')
final_df['Patient_Experience_cnt'] = zscore_df[patexp_measures].apply(lambda row: row.notna().sum(), axis=1)
# 13 Process measures
proc_measures = ['HCP_COVID_19', 'IMM_3', 'OP_10', 'OP_13', 'OP_18B',
#'OP_2',
'OP_22', 'OP_23', 'OP_29', 'OP_3B',
'OP_8', 'PC_01', 'SEP_1']
final_df['Std_Process_score'] = stats.zscore(zscore_df[proc_measures].mean(axis=1), ddof=ddof, nan_policy='omit')
final_df['Process_cnt'] = zscore_df[proc_measures].apply(lambda row: row.notna().sum(), axis=1)
mort_cnts = final_df['Outcomes_Mortality_cnt'].tolist()
safe_cnts = final_df['Outcomes_safety_cnt'].tolist()
read_cnts = final_df['Outcomes_Readmission_cnt'].tolist()
pate_cnts = final_df['Patient_Experience_cnt'].tolist()
proc_cnts = final_df['Process_cnt'].tolist()
tot_cnts = []
msg_cnts = []
grp_cnts = []
for i, m in enumerate(mort_cnts):
ct = 0
ct2 = 0
if m > 2:
ct += 1
ct2 +=1
if safe_cnts[i] > 2:
ct += 1
ct2 += 1
if read_cnts[i] > 2:
ct += 1
if pate_cnts[i] > 2:
ct += 1
if proc_cnts[i] > 2:
ct += 1
tot_cnts.append(ct)
msg_cnts.append(ct2)
if ct == 3:
grp_cnts.append('1) # of groups=3')
elif ct == 4:
grp_cnts.append('2) # of groups=4')
elif ct == 5:
grp_cnts.append('3) # of groups=5')
else:
grp_cnts.append('Not grouped')
final_df['Total_measure_group_cnt'] = tot_cnts
final_df['MortSafe_Group_cnt'] = msg_cnts
final_df['cnt_grp'] = grp_cnts
# Add standard group measure weights
final_df['std_weight_PatientExperience'] = 0.22
final_df['std_weight_Readmission'] = 0.22
final_df['std_weight_Mortality'] = 0.22
final_df['std_weight_safety'] = 0.22
final_df['std_weight_Process'] = 0.12
# Standard weights and their corresponding score columns
weights_info = {
'Std_PatientExp_score': ('weight_PatientExperience', 0.22),
'Std_Outcomes_Readmission_score': ('weight_Outcomes_Readmission', 0.22),
'Std_Outcomes_Mortality_score': ('weight_Outcomes_Mortality', 0.22),
'Std_Outcomes_Safety_score': ('weight_Outcomes_Safety', 0.22),
'Std_Process_score': ('weight_Process', 0.12)
}
# Function to adjust weights
def adjust_weights(row):
# Extract scores and check for NaN
scores = {score: row[score] for score in weights_info.keys()}
non_missing_scores = {k: v for k, v in scores.items() if pd.notnull(v)}
# Sum of weights for non-missing scores
sum_weights = sum(weights_info[k][1] for k in non_missing_scores.keys())
# Assign adjusted weights or 0 if score is missing
for score, (new_col, weight) in weights_info.items():
if score in non_missing_scores:
row[new_col] = weight / sum_weights
else:
row[new_col] = 0 # Set weight to 0 if score is missing
return row
# Apply the function to each row
final_df = final_df.apply(adjust_weights, axis=1)
# Define score columns and their corresponding adjusted weight columns
score_columns = [
'Std_PatientExp_score',
'Std_Outcomes_Readmission_score',
'Std_Outcomes_Mortality_score',
'Std_Outcomes_Safety_score',
'Std_Process_score'
]
weight_columns = [
'weight_PatientExperience',
'weight_Outcomes_Readmission',
'weight_Outcomes_Mortality',
'weight_Outcomes_Safety',
'weight_Process'
]
# Calculate weighted average for each row
final_df['summary_score'] = final_df.apply(lambda row: sum(row[score] * row[weight] for score, weight in zip(score_columns, weight_columns) if pd.notnull(row[score])), axis=1)
final_df = final_df[final_df['cnt_grp'] != 'Not grouped']
final_df = final_df[final_df['MortSafe_Group_cnt'] > 0]
final_df['report_indicator'] = 1
dfg3 = final_df[final_df['cnt_grp'] == '1) # of groups=3']
dfg3 = kmeans_clustering(dfg3)
dfg4 = final_df[final_df['cnt_grp'] == '2) # of groups=4']
dfg4 = kmeans_clustering(dfg4)
dfg5 = final_df[final_df['cnt_grp'] == '3) # of groups=5']
dfg5 = kmeans_clustering(dfg5)
complete_df = pd.concat([dfg3, dfg4, dfg5])
return complete_df
##############################################################################
################################# LOAD DATA ##################################
main_df = pd.read_pickle('dataframe_data/hosp_stars_dat.pkl')
beds_max = np.nanmax(main_df['Beds'])
whatif_df = pd.read_pickle('dataframe_data/data_for_whatifs.pkl')
######################## Create Features Dictionary #####################################
feature_dict = {}
feature_dict['filter categories'] = ['State',
'ZIP Code',
'County Name',
'Hospital Type',
'Hospital Ownership',
'Emergency Services',
'Meets criteria for promoting interoperability of EHRs',
#'Hospital overall rating', # from previous year
'cnt_grp',
'star',
'Beds',
]
feature_dict['date categories'] = ['file_month',
'file_year',
'Release year',
]
feature_dict['Standardized scores'] = ['Std_Outcomes_Mortality_score',
'Std_Outcomes_Readmission_score',
'Std_Outcomes_Safety_score',
'Std_PatientExp_score',
'Std_Process_score',
'summary_score',
]
feature_dict['Domain weights'] = ['std_weight_PatientExperience',
'std_weight_Readmission',
'std_weight_Mortality',
'std_weight_safety',
'std_weight_Process',
'weight_PatientExperience',
'weight_Outcomes_Readmission',
'weight_Outcomes_Mortality',
'weight_Outcomes_Safety',
'weight_Process',
]
feature_dict['Domain measure counts'] = ['Outcomes_Mortality_cnt',
'Outcomes_safety_cnt',
'Outcomes_Readmission_cnt',
'Patient_Experience_cnt',
'Process_cnt',
'Total_measure_group_cnt',
'MortSafe_Group_cnt',
]
feature_dict['Stars Domains'] = ['Patient Experience',
'Readmission',
'Mortality',
'Safety of Care',
'Timely and Effective Care',
]
feature_dict['Safety of Care'] = ['HAI_1', 'HAI_2',
'HAI_3', 'HAI_4',
'HAI_5', 'HAI_6',
'COMP_HIP_KNEE', 'PSI_90_SAFETY']
feature_dict['Safety of Care (std)'] = ['std_HAI_1', 'std_HAI_2',
'std_HAI_3', 'std_HAI_4',
'std_HAI_5', 'std_HAI_6',
'std_COMP_HIP_KNEE', 'std_PSI_90_SAFETY']
feature_dict['Safety of Care labels'] = ['CLABSI', 'CAUTI',
'SSI Colon', 'SSI Abd. Hysterectomy',
'MRSA Bacteremia', 'C. diff. infection',
'Hip-Knee Complication rate', 'PSI-90']
feature_dict['Readmission'] = ['READM_30_HOSP_WIDE',
'READM_30_HIP_KNEE',
'EDAC_30_HF',
'READM_30_COPD',
'EDAC_30_AMI',
'EDAC_30_PN',
'READM_30_CABG',
'OP_32',
'OP_35_ADM',
'OP_35_ED',
'OP_36']
feature_dict['Readmission (std)'] = ['std_READM_30_HOSP_WIDE',
'std_READM_30_HIP_KNEE',
'std_EDAC_30_HF',
'std_READM_30_COPD',
'std_EDAC_30_AMI',
'std_EDAC_30_PN',
'std_READM_30_CABG',
'std_OP_32',
'std_OP_35_ADM',
'std_OP_35_ED',
'std_OP_36']
feature_dict['Readmission labels'] = ['30-Day readmission rate, Hospital-wide',
'30-Day readmission rate, HIP KNEE',
'Excess days in Acute Care, HF',
'30-Day readmission rate, COPD',
'Excess days in Acute Care, AMI',
'Excess days in Acute Care, PN',
'30-Day readmission rate, CABG',
'7-Day visit rate after OP colonoscopy',
'Admissions for Patients Receiving OP Chemo',
'ED Visits for Patients Receiving OP Chemo',
'Hospital Visits after OP Surgery']
feature_dict['Mortality'] = ['MORT_30_STK',
'MORT_30_PN',
'MORT_30_HF',
'MORT_30_COPD',
'MORT_30_AMI',
'MORT_30_CABG',
'PSI_4_SURG_COMP']
feature_dict['Mortality (std)'] = ['std_MORT_30_STK',
'std_MORT_30_PN',
'std_MORT_30_HF',
'std_MORT_30_COPD',
'std_MORT_30_AMI',
'std_MORT_30_CABG',
'std_PSI_4_SURG_COMP']
feature_dict['Mortality labels'] = ['STK 30-Day Mortality Rate',
'PN 30-Day Mortality Rate',
'HF 30-Day Mortality Rate',
'COPD 30-Day Mortality Rate',
'AMI 30-Day Mortality Rate',
'CABG 30-Day Mortality Rate',
'PSI-04, Death Rate, Surg. Inpatients w/ STCs']
feature_dict['Patient Experience'] = ['H_COMP_1_STAR_RATING',
'H_COMP_2_STAR_RATING',
'H_COMP_3_STAR_RATING',
'H_COMP_5_STAR_RATING',
'H_COMP_6_STAR_RATING',
'H_COMP_7_STAR_RATING',
'H_GLOB_STAR_RATING', # H-HSP-RATING + H-RECMND / 2
'H_INDI_STAR_RATING'] # H-CLEAN-HSP + H-QUIET-HSP / 2
#'H_RESP_RATE_P',
#'H_NUMB_COMP']
feature_dict['Patient Experience (std)'] = ['std_H_COMP_1_STAR_RATING', 'std_H_COMP_2_STAR_RATING',
'std_H_COMP_3_STAR_RATING', 'std_H_COMP_5_STAR_RATING',
'std_H_COMP_6_STAR_RATING', 'std_H_COMP_7_STAR_RATING',
'std_H_GLOB_STAR_RATING', 'std_H_INDI_STAR_RATING']
feature_dict['Patient Experience labels'] = ['Nurse Communication',
'Doctor Communication',
'Staff responsiveness',
'Communication about medicines',
'Discharge information',
'Care transition',
'Overall Rating of Hospital', # H-HSP-RATING + H-RECMND / 2
'Cleanliness and Quietness'] # H-CLEAN-HSP + H-QUIET-HSP / 2
#'H_RESP_RATE_P',
#'H_NUMB_COMP',
feature_dict['Timely and Effective Care'] = ['OP_2', 'OP_3B', 'OP_8',
'OP_10', 'OP_13', 'OP_18B',
'OP_22', 'OP_23', 'OP_29',
'OP_33', 'OP_30', 'IMM_3',
'PC_01', 'SEP_1', 'ED_2B',
'HCP_COVID_19']
feature_dict['Timely and Effective Care (std)'] = ['std_OP_2', 'std_OP_3B', 'std_OP_8',
'std_OP_10', 'std_OP_13', 'std_OP_18B',
'std_OP_22', 'std_OP_23', 'std_OP_29',
'std_OP_33', 'std_OP_30', 'std_IMM_3',
'std_PC_01', 'std_SEP_1', 'std_ED_2B',
'std_HCP_COVID_19',
]
feature_dict['Timely and Effective Care labels'] = ['OP-2: Fibrinolytic therapy w/in 30 min of ED arrival',
'OP-3b: Median time to trans to other facility for Acute Coronary Int.',
'OP-8: MRI Lumbar Spine for Low Back Pain',
'OP-10: Abdomen CT Use of Contrast Material',
'OP-13: Cardiac Imaging for Preop Risk for non-cardiac low-risk surg.',
'OP-18b: Median Time from ED Arrival to ED Departure',
'OP-22: ED-Patient Left Without Being Seen',
'OP-23: Received interp. of head CT/MRI for stroke w/in 45 min of arrival',
'OP-29: Endoscopy/Polyp Surv.: appropriate follow-up int.',
'OP-33: External Beam Radiotherapy for Bone Metastases',
'OP-30: Endoscopy/Polyp Surv.: avoidance of inappropriate use',
'IMM-3: Healthcare Personnel Influenza Vaccination',
'PC-1: Percent babies elect. del. prior to 39 weeks gestation',
'SEP-1: Severe Sepsis and Septic Shock',
'ED-2b: Admit decision time to ED depart time, admitted patients',
'HCP COVID-19: COVID-19 Vaccination Coverage Among HCP',
]
HOSPITALS = main_df['Name and Num'].tolist()
beds = main_df['Beds'].tolist()
states = main_df['State'].tolist()
htypes = main_df['Hospital Type'].tolist()
ctypes = main_df['Hospital Ownership'].tolist()
lons = main_df['Lon'].tolist()
lats = main_df['Lat'].tolist()
main_df['Release year'] = main_df['Release year'].astype(int)
latest_yr = np.max(main_df['Release year'])
current_yr = datetime.now().year
current_mo = datetime.now().month
states = ['NaN' if x is np.nan else x for x in states]
htypes = ['NaN' if x is np.nan else x for x in htypes]
ctypes = ['NaN' if x is np.nan else x for x in ctypes]
HOSPITALS_SET = sorted(list(set(HOSPITALS)))
ddfs = "100%"
domains = ['Patient Experience', 'Readmission', 'Mortality',
'Safety of Care', 'Timely and Effective Care']
random.seed(42)
COLORS = []
for h in HOSPITALS:
if 'RUSH UNIVERSITY' in h:
clr = '#167e04'
else:
clr = '#' + "%06x" % random.randint(0, 0xFFFFFF)
COLORS.append(clr)
##############################################################################
domain = 'Patient Experience'
measures = ['H_COMP_1_STAR_RATING', 'H_COMP_2_STAR_RATING',
'H_COMP_3_STAR_RATING', 'H_COMP_5_STAR_RATING',
'H_COMP_6_STAR_RATING', 'H_COMP_7_STAR_RATING',
'H_GLOB_STAR_RATING', 'H_INDI_STAR_RATING']
tdf = whatif_df.filter(items=measures)
tdf = tdf.round(3)
mins = tdf.min().tolist()
maxs = tdf.max().tolist()
tdf = whatif_df[whatif_df['PROVIDER_ID'] == '140119']
tdf = tdf.filter(items=measures)
tdf = tdf.round(3)
# Compute values for columns
cols = ['Measure', 'Actual value', 'Min value', 'Max value', 'What-if value']
df_table = pd.DataFrame(columns=cols)
df_table['Measure'] = list(tdf)
df_table['Actual value'] = tdf.iloc[0].tolist()
df_table['Min value'] = mins
df_table['Max value'] = maxs
df_table['What-if value'] = tdf.iloc[0].tolist()
del tdf
##############################################################################
################# DASH APP CONTROL FUNCTIONS #################################
def description_card1():
"""
:return: A Div containing dashboard title & descriptions.
"""
return html.Div(
id="description-card1",
children=[
html.H5("Hospital Quality Star Ratings", style={
'textAlign': 'left',
}),
dcc.Markdown("The Centers for Medicare & Medicaid Services (CMS) Overall Hospital Quality Star Ratings " +
"provide summary measures of hospital quality and safety using publicly available data provided by " +
"CMS Care Compare."),
html.Br(),
#dcc.Markdown("Begin by choosing a hospital and a set of hospitals to compare to." )
],
)
def generate_control_card1():
"""
:return: A Div containing controls for graphs.
"""
return html.Div(
id="control-card1",
children=[
html.H5("Choose a hospital", style={
'display': 'inline-block',
#'width': '100%',
}),
dcc.Dropdown(
id="hospital-select1b",
options=[{"label": i, "value": i} for i in []],
value="RUSH UNIVERSITY MEDICAL CENTER (140119)",
placeholder='Select a focal hospital',
optionHeight=75,
style={
'width': '99%',
'font-size': 13,
#'display': 'inline-block',
'border-radius': '15px',
'padding': '0px',
#'margin-top': '15px',
'margin-left': '1px',
}
),
html.Br(),
html.H5("Set your filters"),
html.P("The hospital you chose will be compared to those in these filters."),
html.Br(),
dbc.Button("Hospital types",
id="open-centered4",
style={
"background-color": "#2a8cff",
'width': '80%',
'font-size': 12,
'display': 'inline-block',
'margin-left': '10%',
},
),
dbc.Modal(
[dbc.ModalBody([
html.P("Select hospital types",style={'font-size': 16,}),
dcc.Dropdown(
id="hospital_type1",
options=[{"label": i, "value": i} for i in sorted(list(set(htypes)))],
multi=True,
value=sorted(list(set(htypes))),
style={
'font-size': 16,
},
),
html.Br(),
html.Br(),
]),
dbc.ModalFooter(
dbc.Button("Save & Close", id="close-centered4", className="ml-auto",
style={'font-size': 12,})
),
],
id="modal-centered4",
is_open=False,
centered=True,
autoFocus=True,
size="xl",
keyboard=True,
fade=True,
backdrop=True,
),
html.Br(),
html.Br(),
dbc.Button("Hospital ownership",
id="open-centered1",
style={
"background-color": "#2a8cff",
'width': '80%',
'font-size': 12,
'display': 'inline-block',
'margin-left': '10%',
},
),
dbc.Modal(
[dbc.ModalBody([
html.P("Select hospital ownership types",style={'font-size': 16,}),
dcc.Dropdown(
id="control_type1",
options=[{"label": i, "value": i} for i in sorted(list(set(ctypes)))],
multi=True,
value=sorted(list(set(ctypes))),
style={
#'width': '320px',
'font-size': 16,
},
),
html.Br(),
html.Br(),
]),
dbc.ModalFooter(
dbc.Button("Save & Close", id="close-centered1", className="ml-auto",
style={'font-size': 12,})
),
],
id="modal-centered1",
is_open=False,
centered=True,
autoFocus=True,
size="xl",
keyboard=True,
fade=True,
backdrop=True,
),
html.Br(),
html.Br(),
dbc.Button("US states & territories",
id="open-centered3",
style={
"background-color": "#2a8cff",
'width': '80%',
'font-size': 12,
'display': 'inline-block',
'margin-left': '10%',
},
),
dbc.Modal(
[dbc.ModalBody([
html.P("Select a set of US states and/or territories",style={'font-size': 16,}),
dcc.Dropdown(
id="states-select1",
options=[{"label": i, "value": i} for i in sorted(list(set(states)))],
multi=True,
value=sorted(list(set(states))),
style={
'font-size': 16,
}
),
html.Br(),
html.Br(),
]),
dbc.ModalFooter(
dbc.Button("Save & Close", id="close-centered3", className="ml-auto",
style={'font-size': 12,})
),
],
id="modal-centered3",
is_open=False,
centered=True,
autoFocus=True,
size="xl",
keyboard=True,
fade=True,
backdrop=True,
),
html.Br(),
html.Br(),
html.Div(id='Filterbeds1'),
dcc.RangeSlider(
id='beds1',
min=0,
max=2500,
step=50,
marks={
100: '100',
500: '500',
1000: '1000',
1500: '1500',
2000: '2000',
2500: 'Max',
},
value=[0, beds_max],
),
html.Br(),
],
)
#########################################################################################
############################# DASH APP LAYOUT #######################################
#########################################################################################
app.layout = html.Div([
html.Div(
id="option_hospitals",
style={'display': 'none'}
),
dcc.Store(id="whatif_df"),
# Banner
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'})],
),
# Left column
html.Div(
id="left-column1",
className="three columns",
children=[description_card1(),
generate_control_card1(),
],
style={'width': '24%', 'display': 'inline-block',
'border-radius': '15px',
'box-shadow': '1px 1px 1px grey',
'background-color': '#f0f0f0',
'padding': '10px',
},
),
# Panel 1
html.Div(
id="panel-1",
className="eight columns",
children=[
html.Div(
children=[
html.H5(id="header-text",
style={'text-align': 'center'},
),
],
style={'width': '107%',
'display': 'inline-block',
'border-radius': '15px',
'box-shadow': '1px 1px 1px grey',
'background-color': '#f0f0f0',
'padding': '10px',
'margin-bottom': '10px',
},
),
html.Div(
#className="one columns",
children=[
html.H5(id="box-header-text",
style={'text-align': 'center'},
),
dcc.Dropdown(
id='year-select1',
options=[{"label": str(i)+' ', "value": i} for i in list(range(2021, latest_yr+1))],
value=latest_yr,
placeholder='Select a Stars year',
optionHeight=50,
style={
#'width': '30%',
#'font-size': 13,
'display': 'inline-block',
#'border-radius': '15px',
'padding': '0px 30px 0px 20px',
#"background-color": "#2a8cff",
'verticalAlign': 'bottom',
#'margin-top': '15px',
'margin-left': '3%',
},
),
dbc.Button("Compare to Filtered Hospitals",
id="selected_hosps_btn1",
style={
"background-color": "#2a8cff",
'font-size': 12,
'display': 'inline-block',
'margin-left': '5%',
},
),
dbc.Button("Compare to Stars Peer Group",
id="stars_peers_btn1",
style={
"background-color": "#2a8cff",
'font-size': 12,
'display': 'inline-block',
'margin-left': '5%',
},
),
html.Hr(),
dcc.Graph(id="figure1"),
],
style={'width': '107%',
'horizontal-align': 'center',
'display': 'inline-block',
'margin-bottom': '1%',
'border-radius': '15px',
'box-shadow': '1px 1px 1px grey',
'background-color': '#f0f0f0',
'padding': '10px',
},
),
html.Div(
children=[
html.Div(
id="box1",
className="two columns",
children=[
dbc.Container([
dbc.Row([
dbc.Col([
html.Div(
id="boxtext1",
style={
"backgroundColor": "LightSkyBlue",
"color": "RoyalBlue",
"textAlign": "center",
"padding": "10px",
"border": "2px solid RoyalBlue",
"borderRadius": "5px",
"fontSize": "16px"},
),
],
width=2,
),
dbc.Col([
html.Div(
id="boxtext2",
style={
"backgroundColor": "LightSkyBlue",
"color": "RoyalBlue",
"textAlign": "center",
"padding": "10px",
"border": "2px solid RoyalBlue",
"borderRadius": "5px",
"fontSize": "16px"},
),
],
width=4,
),
dbc.Col([
html.Div(
id="boxtext3",
style={
"backgroundColor": "LightSkyBlue",
"color": "RoyalBlue",
"textAlign": "center",
"padding": "10px",
"border": "2px solid RoyalBlue",
"borderRadius": "5px",
"fontSize": "16px"},