/
__init__.py
2655 lines (1866 loc) · 94.3 KB
/
__init__.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[ant] libaries @('_')@
import hl7
import pandas as pd
import numpy as np
import regex as re
import os
import math
import time
import datetime
# Plotting!
import seaborn as sns
import matplotlib.pylab as plt
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import colors
# Plotly--yeet
import plotly.figure_factory as ff
import plotly
from plotly.offline import iplot
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Clears display if you need to manual loop
from IPython.display import clear_output
# For accessing supporting docs within supporting folder
import pkg_resources
from tqdm import tqdm
###################################################
def NoError(func, *args, **kw):
'''
Determine whether or not a function and its arguments gives an error
For purposes of this HL7 Project, it is typically used in conjunction with the functions index(),index_n(), or exec()
Parameters
----------
func: function, required
*args: varies, required
Returns
-------
bool
True if function does not cause error.
False if function causes error.
Requirements
------------
-none
'''
try:
func(*args, **kw)
return True
except Exception:
return False
def index(m,ind):
'''
Simple function to return m[ind]
For purposes of this HL7 parsing project, this is typically used in conjunction with the NoError() function.
'''
return m[ind]
def LIKE(array,word):
'''
Finds all parts of list that have a word in them
Parameters
----------
array : list/array type, required
word : str, required
Returns
-------
np.array
An array which is a subset of the original containing the word
Requirements
------------
-import numpy as np
'''
# Convert to numpy array. Everything's easier with numpy
array = np.array(array)
# Create in-condition. List of True/False for each element
cond = np.array([str(word) in array[i] for i in np.arange(0,len(array))])
# Enact that condition
subset = array[cond]
# Return the subset
return subset
###################################################
def completeness_facvisits(df, Timed = False):
'''
1. Read in Pandas Dataframe outputted from NSSP_Element_Grabber() function.
2. Group events by Facility->Patient MRN->Patient Visit Num
to find unique visits
3. Return Dataframe.
dataframe.index -> Facility Name, Number of Visits
dataframe.frame -> Percents of visits within hospital with
non-null values in specified column
Parameters
----------
df : pandas.DataFrame, required
should have format outputted from NSSP_Element_Grabber() function
*Timed : bool, optional
If True, gives completion time in seconds
Returns
-------
DataFrame
A pandas dataframe object is returned as a two dimensional data
structure with labeled axes.
Requirements
------------
*Libraries*
-from pj_funcs import *
'''
start_time = time.time()
# Make a visit indicator that combines facility|mrn|visit_num
df['VISIT_INDICATOR'] = df[['FACILITY_NAME', 'PATIENT_MRN', 'PATIENT_VISIT_NUMBER']].astype(str).agg('|'.join, axis=1)
# Create array of Falses. Useful down the road
false_array = np.array([False] * len(df.columns))
# Create empty dataframe we will eventually insert into
empty = pd.DataFrame(columns=df.columns)
# Create empty lists for facility_names (facs) and number of patients in a facility (num_patients)
# These lists will serve as our output's descriptive indexes
num_visits = []
facs = []
# First sort our data by Facility Name. Sort=False speeds up runtime
fac_sort = df.groupby('FACILITY_NAME',sort=False)
# Iterate through the groupby object
for facility, df1 in fac_sort:
# Append facility name to empty list
facs.append(facility)
# Initiate visit count
visit_count = 0
# Sort by Patient MRN
MRN_sort = df1.groupby(['VISIT_INDICATOR'],sort=False)
# Initiate list of 0s. Each column gets +1 for each visit with a non-null column value.
countz = false_array.copy().astype(int)
for visit, df3 in MRN_sort:
# Initiate array of falses
init = false_array.copy()
# Looping through the visits ADT data rows, look for non_null values. True if non-null.
# Use OR-logic to replace 0s in init with 1s and keep 1s as 1s for each iterated row.
for i in np.arange(0,len(df3)):
init = init | (df3.iloc[i].notnull())
# Add information on null (0) vs. non-null (1) columns to countz which is initially all 0 but updates for each patient.
countz += init.astype(int)
# Show that the number of visits has increased
visit_count += 1
# Append visit number to empty list
num_visits.append(visit_count)
# Update empty dataframe with information on completeness (out of 100%) we had for each column
# * note countz is a 1D array that counts how many visits have non-null values in each column.
empty.loc[facility,:] = (countz/visit_count)*100
# Clarify and Create index information for output Dataframe
empty['Num_Visits'] = num_visits
empty['Facility'] = facs
empty = empty.set_index(['Facility','Num_Visits'])
# Keep track of end time
end_time = time.time()
# If user requests to see elapsed time, show them it in seconds
if Timed == True:
print('Time Elapsed: '+str(round((end_time-start_time),3))+' seconds')
# Return filled dataframe.
return empty
################################################################
def to_hours(item):
'''
Takes a datetime object and converts them to the time in hours,
as a float rounded to the 3rd decimal.
Input
-----
item - DateTime object, required
Output
-----
Time in hours (dtype: Float)
Requirements
------------
*Libraries*
-import datetime
*Functions*
none
'''
return round((datetime.timedelta.total_seconds(item) / (60*60)),3)
#####################################################################
def to_days(item):
'''
Takes a datetime object and converts them to the time in days,
as a float rounded to the 3rd decimal.
Input
-----
item - DateTime object, required
Output
-----
Time in days (dtype: Float)
Requirements
------------
*Libraries*
-import datetime
*Functions*
none
'''
return round((datetime.timedelta.total_seconds(item) / (24*60*60)),3)
####################################################################
def timeliness_facvisits_days(df, Timed = False):
'''
1. Read in Pandas Dataframe straight from PHESS SQL Query-pulled file.
2. Group events by Facility->Patient MRN->Patient Visit Num
to find unique visits.
3. Return Dataframe
dataframe.index -> Facility Name
dataframe.frame -> Statistics on time differences between MSG_DATETIME
and ADMIT_DATETIME
Parameters
----------
df : pandas.DataFrame, required
example: df = pd.read_csv('some/path/PHESS_OUTPUT_FILE.csv', encoding = 'Cp1252')
*Timed : bool, optional
If True, gives completion time in seconds
Returns
-------
DataFrame
A pandas dataframe object is returned as a two dimensional data
structure with labeled axes.
Requirements
------------
*Libraries*
-import pandas as pd
-import numpy as np
-import datetime
-import time
-from pj_funcs import *
*Functions*
- to_days (found in pj_funcs.py file)
'''
start_time = time.time()
# Cleanup 1: ADMIT_DATETIME == 'Missing admit datetime'
df = df[df['ADMIT_DATETIME'] != 'Missing admit datetime']
# Cleanup 2: Some datetimes (meaning 1/1000+) have a decimal in them
# They cannot be interpreted as datetimes via pd.to_datetime
# so we need to convert them.
# Interperet ADMIT_DATETIME as string
admit_time = df['ADMIT_DATETIME'].astype(str)
# Use Pandas str.split function to divide on decimal, expand, and
# take the first argument (everything before the decimal).
admit_time = admit_time.str.split('\.',expand=True)[0]
# Convert our newly cleaned strings to datetime type. For uniformity, choose UTC
admit_time = pd.to_datetime(admit_time, utc=True)
# Do the exact same thing to 'MSG_DATETIME'
msg_time = df['MSG_DATETIME'].astype(str)
msg_time = msg_time.str.split('\.',expand=True)[0]
msg_time = pd.to_datetime(msg_time, utc=True)
# Update 'ADMIT_DATETIME' and 'MSG_DATETIME' columns to new format
df['ADMIT_DATETIME'] = admit_time
df['MSG_DATETIME'] = msg_time
##################################################################
# Create TimeDif Column!!
TimeDif = msg_time - admit_time
# Apply my personal to_days function to see datetime differences in days.
# Information can be found in pj_funcs.py or by typing 'to_days?' in a cell
df['TimeDif (days)'] = TimeDif.apply(to_days)
# Only take the important columns in sub-dataframe
sub_df = df[['ADMIT_DATETIME','MSG_DATETIME','PATIENT_MRN',
'PATIENT_VISIT_NUMBER','FACILITY_NAME','TimeDif (days)']]
##################################################################
facs = []
# First sort our data by Facility Name. Sort=False speeds up runtime
fac_sort = sub_df.groupby('FACILITY_NAME',sort=False)
# Label columns we will eventully populate in empty dataframe
stats_cols = ['Num_Visits','Median','Avg','StdDev','Min','Max']
empty = pd.DataFrame(columns=stats_cols)
# Iterate through the groupby object
for facility, df1 in fac_sort:
# Create empty list to fill with TimeDif (days) values for visits
fillme = []
# Sort by Patient MRN
MRN_sort = df1.groupby(['PATIENT_MRN'],sort=False)
# Loop through MRN groupings
for patient, df2 in MRN_sort:
# If there is a null value in the MRN group, we have a problem
if sum(df2['PATIENT_VISIT_NUMBER'].isnull()) > 0:
# If there is only one row and its null, its one patient.
if len(df2) == 1:
fillme.append(df2.iloc[0]['TimeDif (days)'])
# Cases where all PATIENT_VISIT_NUMBER are non-null!
else:
# Sort further by Patient Visit Number
VisNum_sort = df2.groupby(['PATIENT_VISIT_NUMBER'],sort=False)
# Loop through Patient Visit Numbers
for visit, df3 in VisNum_sort:
# Find the row with the newest
index_earliest = df3['ADMIT_DATETIME'].idxmin()
# Within our early admit datetime row, pull TimeDif
dif_we_take = df3.loc[index_earliest]['TimeDif (days)']
# Append correct TimeDif to fillme list
fillme.append(dif_we_take)
# Convert list (that we appended to) into np array and perform stats
fillme = np.array(fillme)
stats = [len(fillme),np.median(fillme),np.mean(fillme),np.std(fillme),
np.min(fillme),np.max(fillme)]
# Fill stats into dataframe for that facility. Rounded to 2 decimals
empty.loc[facility,:] = np.array(stats).round(2)
###########################################################################
# Keep track of end time
end_time = time.time()
# If user requests to see elapsed time, show them it in seconds
if Timed == True:
print('Time Elapsed: '+str(round((end_time-start_time),3))+' seconds')
# Return filled dataframe.
return empty
##############################################################################################################################
def timeliness_facvisits_hours(df, Timed = False):
'''
1. Read in Pandas Dataframe straight from PHESS SQL Query-pulled file.
2. Group events by Facility->Patient MRN->Patient Visit Num
to find unique visits.
3. Return Dataframe
dataframe.index -> Facility Name
dataframe.frame -> Statistics on time differences between MSG_DATETIME
and ADMIT_DATETIME
Parameters
----------
df : pandas.DataFrame, required
example: df = pd.read_csv('some/path/PHESS_OUTPUT_FILE.csv', encoding = 'Cp1252')
*Timed : bool, optional
If True, gives completion time in seconds
Returns
-------
DataFrame
A pandas dataframe object is returned as a two dimensional data
structure with labeled axes.
Requirements
------------
*Libraries*
-import pandas as pd
-import numpy as np
-import datetime
-import time
*Functions*
- to_hours (found in pj_funcs.py file)
'''
start_time = time.time()
# Cleanup 1: ADMIT_DATETIME == 'Missing admit datetime'
df = df[df['ADMIT_DATETIME'] != 'Missing admit datetime']
# Cleanup 2: Some datetimes (meaning 1/1000+) have a decimal in them
# They cannot be interpreted as datetimes via pd.to_datetime
# so we need to convert them.
# Interperet ADMIT_DATETIME as string
admit_time = df['ADMIT_DATETIME'].astype(str)
# Use Pandas str.split function to divide on decimal, expand, and
# take the first argument (everything before the decimal).
admit_time = admit_time.str.split('\.',expand=True)[0]
# Convert our newly cleaned strings to datetime type. For uniformity, choose UTC
admit_time = pd.to_datetime(admit_time, utc=True)
# Do the exact same thing to 'MSG_DATETIME'
msg_time = df['MSG_DATETIME'].astype(str)
msg_time = msg_time.str.split('\.',expand=True)[0]
msg_time = pd.to_datetime(msg_time, utc=True)
# Update 'ADMIT_DATETIME' and 'MSG_DATETIME' columns to new format
df['ADMIT_DATETIME'] = admit_time
df['MSG_DATETIME'] = msg_time
##################################################################
# Create TimeDif Column!!
TimeDif = msg_time - admit_time
# Apply my personal to_days function to see datetime differences in days.
# Information can be found in pj_funcs.py or by typing 'to_days?' in a cell
df['TimeDif (hrs)'] = TimeDif.apply(to_hours)
# Only take the important columns in sub-dataframe
sub_df = df[['ADMIT_DATETIME','MSG_DATETIME','PATIENT_MRN',
'PATIENT_VISIT_NUMBER','FACILITY_NAME','TimeDif (hrs)']]
##################################################################
facs = []
# First sort our data by Facility Name. Sort=False speeds up runtime
fac_sort = sub_df.groupby('FACILITY_NAME',sort=False)
# Label columns we will eventully populate in empty dataframe
stats_cols = ['Num_Visits','Avg TimeDif (hrs)','% visits recieved within 24 hours','% visits recieved between 24 and 48 hours ',
'% visits recieved after 48 hours']
empty = pd.DataFrame(columns=stats_cols)
# Iterate through the groupby object
for facility, df1 in fac_sort:
# Create empty list to fill with TimeDif (hrs) values for visits
fillme = []
# Sort by Patient MRN
MRN_sort = df1.groupby(['PATIENT_MRN'],sort=False)
# Loop through MRN groupings
for patient, df2 in MRN_sort:
# If there is a null value in the MRN group, we have a problem
if sum(df2['PATIENT_VISIT_NUMBER'].isnull()) > 0:
# If there is only one row and its null, its one patient.
if len(df2) == 1:
fillme.append(df2.iloc[0]['TimeDif (hrs)'])
# Cases where all PATIENT_VISIT_NUMBER are non-null!
else:
# Sort further by Patient Visit Number
VisNum_sort = df2.groupby(['PATIENT_VISIT_NUMBER'],sort=False)
# Loop through Patient Visit Numbers
for visit, df3 in VisNum_sort:
# Find the row with the newest
index_earliest = df3['ADMIT_DATETIME'].idxmin()
# Within our early admit datetime row, pull TimeDif
dif_we_take = df3.loc[index_earliest]['TimeDif (hrs)']
# Append correct TimeDif to fillme list
fillme.append(dif_we_take)
# Convert list (that we appended to) into np array and perform stats
fillme = np.array(fillme)
cond_bottom = (fillme <= 24)
cond_middle = (fillme > 24)&(fillme < 48)
cond_top = (fillme >= 48)
percent_bottom = round((sum(cond_bottom)/len(fillme)),3)*100
percent_middle = round((sum(cond_middle)/len(fillme)),3)*100
percent_top = round((sum(cond_top)/len(fillme)),3)*100
stats = [len(fillme),np.mean(fillme),percent_bottom,percent_middle,percent_top]
# Fill stats into dataframe for that facility. Rounded to 2 decimals
empty.loc[facility,:] = np.array(stats).round(2)
###########################################################################
# Keep track of end time
end_time = time.time()
# If user requests to see elapsed time, show them it in seconds
if Timed == True:
print('Time Elapsed: '+str(round((end_time-start_time),3))+' seconds')
# Return filled dataframe.
return empty
##################################################################################
def index_n(m,ind):
'''
Indexes some object 'm' by each element in the list 'ind'
Parameters
----------
m: type varies, required
ind: list, required
Returns
-------
m[ind[0]][ind[1]][ind[...]][ind[n]]
Requirements
------------
-Numpy as np
'''
for i in np.arange(0,len(ind)):
m = m[ind[i]]
return m
###################################################################################
def Index_pull(ind,m):
'''
Locates and returns the element within a message 'm' thats location
is described by indeces, 'ind'
Parameters
----------
ind: list, required, full index path as list indicating HL7 location.
m: hl7 type object, required, m = hl7.parse(some_message)
Returns
-------
Str
Element
Requirements
------------
-NoError from pj_funcs.py
-index_n from pj_funcs.py
-hl7
'''
output = ''
# Try indexing the message by ind
if NoError(index_n,m,ind):
# If the indexing up to the 2nd to last element returns a string, accept it. Call it 'output'
if type(index_n(m,ind[:-1])) == str:
output = index_n(m,ind[:-1])
# Normally, we will take the exact, full-indexed value. Call it 'output'
else:
output = str(index_n(m,ind))
# Return output. If none found, return empty string, ''
return output
######################################################################################
def Index_pull_CONC(field,rest_index,m):
'''
Returns a concetated string for elements with repeating fields. Seperated by '|' characters.
Example: consider the case of Ethnicity Code where a patient may have multiple selected ethnicities.
For our example we will assume this element is always located in PID-22.1.
print(Index_pull_CONC('PID', [22,0,0], m))
Ethnicity1|Ethnicity2
Note: Ethnicity1 and Ethnicity2 are pulled from PID|x|-22.1 and PID|y|-22.1 respectively where
x,y are non-equal integers representing different repetitions of a repeated field.
Parameters
----------
field: list (with one element), required, for non-empty return choose valid 3 letter HL7 field
rest: list, required, integer list indicating where to find it.
m: hl7 type object, required, m = hl7.parse(some_message)
Returns
-------
Str
Concetation represented by '|'
Requirements
------------
-NoError from pj_funcs.py
-index_n from pj_funcs.py
-Numpy as np
-hl7
'''
# Initialize empty output
output = ''
# Read in field
field_str = field[0]
# Check to see if the field exists in our message
if NoError(index,m,field_str):
# Set the field equal to 'fi'
fi = m[field_str]
# If the field repeats, it has a non-zero length. Loop through its length 1 by 1
for u in np.arange(0,len(fi)):
# Identify the total index by summing strings: field, loop_number, rest_index
tot_index = field+[u]+rest_index
# Make sure message can be indexed by the total index
if NoError(index_n,m,tot_index):
# If the indexing up to the 2nd to last element returns a string, accept it. Call it 'output'
if type(index_n(m,tot_index[:-1])) == str:
full = index_n(m,tot_index[:-1])
# If this string, 'full', has non-zero length, add it to our output and end with '|'
if len(full)>0:
output += full
output += '|'
# Normally, we will take the exact, full-indexed value. Call it 'output'
else:
full = str(index_n(m,tot_index))
# If this string, 'full', has non-zero length, add it to our output and end with '|'
if len(full)>0:
output += full
output += '|'
# Go back and loop through more repeated fields until no more exist
# if non-zero length output, clean up last trailing '|' character
if len(output)>0:
if output[-1] == '|':
output = output[:-1]
# Return output. If none found, this will be '' (empty string)
return output
############################################################################################################
def DI_One(ind,m,df,z,col_name):
'''
Returns the element value of 'm' indexed by 'ind'.
Updates the dataframe 'df' cell value indexed by 'z' and 'col_name'
Parameters
----------
ind: list, required, complete index path (as list) to desired element
m: hl7 type object, required, m = hl7.parse(some_message)
df: pandas DataFrame, required
z: int, required, valid integer row index of df
col_name: str, required, valid column in df
Returns
-------
Str
Element
Output
------
Updates dataframe
df.loc[z,col_name] = Element
Requirements
------------
-Index_pull from pj_funcs.py
-Pandas
-hl7
'''
# Call the index on the message.
obj = Index_pull(ind,m)
# See if the 'obj' is an actual non-zero thing.
if len(obj)>0:
# If so, append to the row_z, col_colname in Dataframe, df
df.loc[z,col_name] = obj
# Else: Do nothing.
# Return the object. If none found, will return empty str, '' with no df update
return obj
####################################################################
def DI_One_CONC(field,ind,m,df,z,col_name):
'''
Returns the CONCETATED element value of 'm' indexed by its respective
repeating field, 'field', and 'ind'.
Updates the dataframe 'df' cell value indexed by 'z' and 'col_name'
Parameters
----------
field: list (with one element), required, for non-empty return choose valid 3 letter HL7 field
ind: list, required, complete index path (as list) to desired element
m: hl7 type object, required, m = hl7.parse(some_message)
df: pandas DataFrame, required
z: int, required, valid integer row index of df
col_name: str, required, valid column in df
Returns
-------
Str
Concetated_Element separated by '|'
Output
------
Updates dataframe
df.loc[z,col_name] = Concetated_Element
Requirements
------------
-Index_pull_CONC from pj_funcs.py
-Pandas
-hl7
'''
# Call the index on the message.
obj = Index_pull_CONC(field,ind,m)
# See if the 'obj' is an actual non-zero thing.
if len(obj)>0:
# If so, append to the row_z, col_colname in Dataframe, df
df.loc[z,col_name] = obj
# Else: Do nothing.
# Return the object
return obj
############################################################################################################
def list_elements(include_priority=False):
'''
Displays all potential elements we can search for
Parameters
----------
include_priority: bool, optional (default is False)
- returns 2 column pandas dataframe. Element Name & Priority
Returns
-------
np.array() (list-like) that contains all elements we can search for
dataframe IF include_priority = True
'''
DATA_PATH = pkg_resources.resource_filename('ADTdq', 'supporting/')
FILE = pkg_resources.resource_filename('ADTdq', 'supporting/NSSP_Element_Reader.xlsx')
els = pd.read_excel(FILE)
if include_priority == True:
return els[['Processed Column','Priority']]
else:
return np.array(els['Processed Column'])
############################################################################################################
def return_NSSPElementReader():
DATA_PATH = pkg_resources.resource_filename('ADTdq', 'supporting/')
FILE = pkg_resources.resource_filename('ADTdq', 'supporting/NSSP_Element_Reader.xlsx')
reader = pd.read_excel(FILE)
return reader
def return_NSSPValidityReader():
DATA_PATH = pkg_resources.resource_filename('ADTdq', 'supporting/')
FILE = pkg_resources.resource_filename('ADTdq', 'supporting/NSSP_Validity_Reader.xlsx')
reader = pd.read_excel(FILE)
return reader
def return_MessageCorrectorKey():
DATA_PATH = pkg_resources.resource_filename('ADTdq', 'supporting/')
FILE = pkg_resources.resource_filename('ADTdq', 'supporting/Message_Corrector_Key.xlsx')
reader = pd.read_excel(FILE)
return reader
def NSSP_Element_Grabber(data,explicit_search=None,Priority_only=False,outfile='None',no_FAC=False,no_MRN=False,no_VisNum=False):
'''
Creates dataframe of important elements from PHESS data.
Timed with cool updating progressbar (tqdm library).
NOTE: Your input should contain the column titles:
MESSAGE , FACILITY_NAME
Parameters
----------
data: pandas DataFrame, required
- input containing columns MESSAGE, FACILITY_NAME
explicit_search: list, optional (default is None)
- list of priority element names you want specifically.
Use argument-less list_elements() function to see all options
Priority_only: bool, optional (default is False)
- If True, only gives priority 1 or 2 elements
outfile: str, optional (default is 'None')
- Replace with file name for dataframe to be wrote to as csv
Will be located in working directory.
DO NOT INCLUDE .csv IF YOU CHOOSE TO MAKE ONE
no_FAC: Bool, optional (default is False)
- If you don't have a FACILITY_NAME in your input, change to True
NOTE: without a FACILITY_NAME, usage of other functions within library can return errors
no_MRN: Bool, optional (default is False)
- If you do not want output to contain MRN information, change to True
NOTE: without a MRN, usage of other functions within library can return errors
no_VisNum: Bool, optional (default is False)
- If you do not want output to contain patient_visit_number information, change to True
NOTE: without a VisNum, usage of other functions within library can return errors
Returns
-------
dataframe
Requirements
------------
- import pandas as pd
- import numpy as np
- import time
'''
# capitalize input columns for easier matching
data.columns = np.array(data.columns.str.upper())
# Read in reader file as pandas dataframe
DATA_PATH = pkg_resources.resource_filename('ADTdq', 'supporting/')
FILE = pkg_resources.resource_filename('ADTdq', 'supporting/NSSP_Element_Reader.xlsx')
reader = pd.read_excel(FILE)
if explicit_search != None:
explicit_search = list(explicit_search)
if no_VisNum == False:
explicit_search.append('Visit_ID')
if no_MRN == False:
explicit_search.append('C_Unique_Patient_ID')
base = np.array(reader[reader['Processed Column'].isin(explicit_search)]['num'])
base = np.unique(base)
newbase = base.copy()
trigger = 0
while (trigger == 0):
newones = np.array(reader.loc[reader.num.isin(newbase),'dependencies'])
iter_nums = []
for i in np.arange(0,len(newones)):
if ',' in str(newones[i]):
listy = list(np.array(newones[i].split(',')).astype(int))
for item in listy:
iter_nums.append(item)
else:
iter_nums.append(int(newones[i]))
iter_nums = np.array(iter_nums)
iter_nums = np.unique(iter_nums)
if len(iter_nums)==len(newbase):
trigger = 1
else:
newbase = iter_nums.copy()
reader = reader.loc[reader.num.isin(newbase)]
# Create the dataframe to fill
df = pd.DataFrame(columns=reader['Processed Column'])
# Create a few extra columns straight from our data file
df['MESSAGE'] = data['MESSAGE']
if no_FAC == False:
df['FACILITY_NAME'] = data['FACILITY_NAME']
# Create a subset of rows from our reader file. Only ones to loop through.
# Order by 'Group_Order' so that some run before others that rely on previous.
reader_sub = reader[reader.Ignore == 0].sort_values('Group_Order')