transform_medications.py 9.19 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3

'''Generate Medications Tables'''

import argparse
import datetime
import os
import pandas as pd
import numpy as np
10
from bs4 import BeautifulSoup
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


EPILOG = '''
For more details:
        %(prog)s --help
'''


def get_args():
    '''Define arguments.'''

    parser = argparse.ArgumentParser(
        description=__doc__, epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-f', '--file',
                        help="Epic File (csv format).",
                        required=True)

    parser.add_argument('-s', '--supportive',
                        help="Supportive Meds Filter (tsv format).",
                        required=True)

    parser.add_argument('-m', '--medsmap',
                        help="Medications mapping (csv format).",
                        required=True)

    parser.add_argument('-d', '--date',
                        help="Date Shift (tsv format).",
                        required=True)

    parser.add_argument('-o', '--out',
                        help="The output path (csv format).",
                        required=True)

    args = parser.parse_args()
    return args


Venkat Malladi's avatar
Venkat Malladi committed
50
51
def filter_supportive(epic, sup, meds_map):
    '''Filter by supportive med name'''
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

    # Filter for columns
    sup_list = list(sup['ID'])
    sup_filter = epic[epic['CONCEPT_CD'].isin(sup_list)]
    onco_list = list(meds_map['ID'])
    onco_filter = epic[epic['CONCEPT_CD'].isin(onco_list)]
    missing_meds = epic[~(epic['CONCEPT_CD'].isin(onco_list) | epic['CONCEPT_CD'].isin(sup_list)) ]

    # Merge supp meds mapping
    meds_named = pd.merge(onco_filter, meds_map, left_on = 'CONCEPT_CD', right_on = 'ID' )
    supmeds_named = pd.merge(sup_filter, sup, left_on = 'CONCEPT_CD', right_on = 'ID' )

    return supmeds_named, meds_named, missing_meds


67
68
def filter_supp(supp_meds):
    '''Filter supportive meds'''
69
70
71
72

    # Filter Adminstered drugs
    meds_admin = supp_meds[supp_meds['MODIFIER_CD'].isin(['RX|ADMIN', 'RX|FILLED'])]

73
74
75
    # Filter for Meds taken
    meds_taken = meds_admin[meds_admin['TVAL_CHAR'].isin(['Given', 'New Bag', 'IV Started', 'IV Stopped'])]
    meds_non_taken = meds_admin[~meds_admin['TVAL_CHAR'].isin(['Given', 'New Bag', 'IV Started', 'IV Stopped'])]
76

77
78
    # Make date
    meds_taken['START_DATE'] = pd.to_datetime(meds_taken['START_DATE'])
79

80
81
    #Filter columns
    supp_meds_reformated = meds_taken[['MRN', 'Meds', 'START_DATE']]
Venkat Malladi's avatar
Venkat Malladi committed
82
    supp_meds_reformated.columns = ['mrn', 'name', 'start_date']
83

84
    return supp_meds_reformated, meds_non_taken
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


def parse_blob(meds):
    '''Parse observation blob for values in blob'''

    meds_tups = []
    for index, row in meds.iterrows():
        mrn = row['MRN']
        name = row['Meds']
        order_type = row['MODIFIER_CD']
        date = row['START_DATE']
        ordering_date = ''
        start_date = ''
        end_date = ''
        quantity = ''
        sig = ''
        refills = ''
        frequency = ''
        pcori_freq = ''
        dispense_amt = ''
        dispense_date = ''
        dispense_sup = ''
        ndc = ''
        if pd.notnull(row['OBSERVATION_BLOB']):
            soup = BeautifulSoup(row['OBSERVATION_BLOB'], 'html.parser')
            tags = [tag.name for tag in soup.find_all()]

            if 'odering_date' in tags:
                ordering_date = soup.ordering_date.text
            if 'start_date' in tags:
                start_date = soup.start_date.text
            if 'end_date' in tags:
                end_date = soup.end_date.text
            if 'quantity' in tags:
                quantity = soup.quantity.text
            if 'sig' in tags:
                sig = soup.sig.text
            if 'refills' in tags:
                refills = soup.refills.text
            if 'frequency' in tags:
                frequency = soup.frequency.text
            if 'pcori_freq' in tags:
                pcori_freq = soup.pcori_freq.text
            if 'dispense_amt' in tags:
                dispense_amt = soup.dispense_amt.text
            if 'dispense_date' in tags:
                dispense_date = soup.dispense_date.text
            if 'dispense_sup' in tags:
                dispense_sup = soup.dispense_sup.text
            if 'ndc' in tags:
                ndc = soup.ndc.text

        meds_tups.append((
            mrn,
            name,
            order_type,
            date,
            ordering_date,
            start_date,
            end_date,
            quantity,
            sig,
            refills,
            frequency, pcori_freq, dispense_date, dispense_amt, dispense_sup, ndc ))

    meds_columns = ["mrn", 'name', 'order_type', "date",'ordering_date',
                   "start", "end", "quantity", 'sig', 'refills', 'frequency', 'pcori_freq', 'dispense_date',
                   'dispanse_amt', 'dispense_sup', 'ndc']
    meds_transformed = pd.DataFrame(meds_tups, columns=meds_columns)
    return meds_transformed


def calculate_regime(meds):
    '''Calculate main meds regime'''

    # Filter for columns
    meds_transformed = parse_blob(meds)

    # Conver to dates
    meds_transformed['date'] = pd.to_datetime(meds_transformed['date'])
    meds_transformed['ordering_date'] = pd.to_datetime(meds_transformed['ordering_date'])
    meds_transformed['start'] = pd.to_datetime(meds_transformed['start'])
    meds_transformed['end'] = pd.to_datetime(meds_transformed['end'])
    meds_transformed['dispense_date'] = pd.to_datetime(meds_transformed['dispense_date'])

    # Format Oncological Meds
    meds_filtered_uniq = meds_transformed.groupby(['mrn', 'name'], as_index=False).agg({'date' : [np.min, np.max], 'start' : [np.min], 'end' : [np.max]   })
    meds_filtered_uniq.columns = ['mrn', 'name','date_start', 'date_end', 'start', 'end']
Venkat Malladi's avatar
Venkat Malladi committed
173
174
175
176
    meds_filtered_uniq['start_date'] = meds_filtered_uniq[['date_start', 'date_end', 'start', 'end']].min(axis=1)
    meds_filtered_uniq['end_date'] = meds_filtered_uniq[['date_start', 'date_end', 'start', 'end']].max(axis=1)
    meds_filtered_uniq['Duration'] = (meds_filtered_uniq['end_date'] - meds_filtered_uniq['start_date']).dt.days
    onco_meds_reformated = meds_filtered_uniq[['mrn', 'name', 'start_date', 'end_date', 'Duration']]
177
178

    # Reset duration for 0
Venkat Malladi's avatar
Venkat Malladi committed
179
    onco_meds_reformated.loc[onco_meds_reformated.Duration == 0, 'end_date'] = None
180
181
    onco_meds_reformated.loc[onco_meds_reformated.Duration == 0, 'Duration'] = None

Venkat Malladi's avatar
Venkat Malladi committed
182
    # If End Date > that current pull reset to null
Venkat Malladi's avatar
Venkat Malladi committed
183
184
    onco_meds_reformated.loc[onco_meds_reformated.end_date > datetime.datetime(2020, 3, 1), 'end_date'] = None
    onco_meds_reformated.loc[onco_meds_reformated.end_date > datetime.datetime(2020, 3, 1), 'Duration'] = None
185

Venkat Malladi's avatar
Venkat Malladi committed
186
    # If End_date is null
Venkat Malladi's avatar
Venkat Malladi committed
187
188
    onco_meds_reformated.loc[onco_meds_reformated.end_date.isnull(), 'end_date'] = datetime.datetime(2020, 3, 1)
    onco_meds_reformated['Duration'] = (onco_meds_reformated['end_date'] - onco_meds_reformated['start_date']).dt.days
Venkat Malladi's avatar
Venkat Malladi committed
189

190
191
192
193
194
    onco_meds_reformated = onco_meds_reformated.reset_index(drop=True)

    return onco_meds_reformated


195
196
def calculate_shift(meds, date_shift):
    '''Shift Date for dates'''
197
198
199

    # Convert to DateTime
    date_shift['Shift'] = pd.to_timedelta(date_shift['Shift'], unit='s')
Venkat Malladi's avatar
Venkat Malladi committed
200
    meds['start_date'] = pd.to_datetime(meds['start_date'])
201
202

    # Merge data
203
    merged = meds.merge(date_shift, left_on='mrn', right_on='MRN', how='inner')
204
205

    # Calculate Date Shift
Venkat Malladi's avatar
Venkat Malladi committed
206
207
208
209
210
    merged['start_date'] = merged['start_date'] + merged['Shift']
    merged['start_date'] = merged['start_date'].dt.date
    if 'end_date' in merged.columns:
        merged['end_date'] = merged['end_date'] + merged['Shift']
        merged['end_date'] = merged['end_date'].dt.date
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

    # Drop Shift column
    merged.drop(['Shift'], axis=1, inplace=True)

    # Int MRN
    merged.MRN = merged.MRN.astype(int)

    return merged


def main():
    args = get_args()
    epic = args.file
    sup = args.supportive
    medsmap = args.medsmap
    date = args.date
    out_path = args.out

    # Make output files
    meds_table = os.path.join(out_path + 'med_table.csv')
    unmapped_table = os.path.join(out_path + 'unmapped_med_table.csv')
    suppmeds_table = os.path.join(out_path + 'suppmed_table.csv')
233
    not_given_suppmeds_table = os.path.join(out_path + 'not_given_suppmed_table.csv')
234
235
236
237
238
239
240
241

    # Read in files
    epic_df = pd.read_csv(epic)
    supmedsmap_df = pd.read_csv(sup)
    medsmap_df = pd.read_csv(medsmap)
    date_shift = pd.read_csv(date)

    # Filter for supplemental meds
Venkat Malladi's avatar
Venkat Malladi committed
242
    supp_meds, onco_meds, missing_meds = filter_supportive(epic_df, supmedsmap_df, medsmap_df)
243
244

    # Find Supplemental Meds Frequency
245
    supp_meds_regime, filtered_supp_meds = filter_supp(supp_meds)
246
247
248
249
250
251

    # Calculate  start and end dates
    # Need to include Follow-up Date
    onco_meds_regime = calculate_regime(onco_meds)

    # Calculate Date Shift
252
    supp_meds_regime_shifted_df = calculate_shift(supp_meds_regime, date_shift)
253
    onco_meds_shifted_df = calculate_shift(onco_meds_regime, date_shift)
254
255

    # Write out meds tables
256
    supp_meds_regime_shifted_df.to_csv(suppmeds_table, index=False)
Venkat Malladi's avatar
Venkat Malladi committed
257
258
259
260
261
    onco_meds_shifted_df.to_csv(meds_table, index=False)
    if missing_meds.shape[0] > 1:
        missing_meds.to_csv(unmapped_table, index=False)
    if filtered_supp_meds.shape[0] > 1:
        filtered_supp_meds.to_csv(not_given_suppmeds_table, index=False)
262
263
264
265


if __name__ == '__main__':
    main()