-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpatgen.py
More file actions
141 lines (111 loc) · 3.47 KB
/
Copy pathpatgen.py
File metadata and controls
141 lines (111 loc) · 3.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# program to generate a PATIENT_DIMENSION SQL statements from a transmart configuration file
import argparse
import csv
import requests
import json
import re
import string
import pandas as pd
import numpy as ny
import random
bulk = False
cfgfile = ''
datafile = ''
NAMESPACE = "cancer-reg"
KEYNS = "ties.model"
TAG_RE = re.compile(r'<[^>]+>')
transmart = False
delimiter = '\t'
outfilename = "patient_dim.sql"
bulkfilename = "patient_dim.csv"
TOP_PATH = '\\Public Studies\\'
PROJECT = ''
strMode = True
fori2b2 = False
def remove_tags(text):
tmp = TAG_RE.sub('', text)
scrubbed = tmp.replace('’', '')
return scrubbed
columns = ""
metadata = []
dataFrame = ''
cfgLevels = []
sqlStmts = []
def read_cfg_file(afile):
print ('Reading CFG file...')
with open(afile) as csvfile:
reader = csv.DictReader(csvfile, delimiter=delimiter)
cols = reader.fieldnames
for row in reader:
#print(row)
metadata.extend([{cols[i]:row[cols[i]] for i in range(len(cols))}])
csvfile.close()
def build_patients(filename):
try:
print('Loading data file...' + filename)
df = pd.read_csv(filename, delimiter='\t') #dtype=str,
#headers = list(df) # get a list of headers for the data
#print (headers)
#pats = df[headers[0]].unique()
for i,row in df.iterrows():
pid = row['SUBJ_ID']
age = row['AGE']
sex = row['SEX']
race = row['RACE']
srcId = PROJECT + ':'+ str(pid)
if bulk: #'patient_num': pid ,
sql = {'sex_cd': sex[0:49], 'age_in_years_num': age, 'race_cd': race, 'update_date': 'now',
'download_date':'now', 'import_date': 'now', 'sourcesystem_cd':srcId}
else:
sql = get_insert_stmt(sex, age, race, srcId)
sqlStmts.append(sql)
#print(sql)
except Exception as e:
raise
else:
pass
finally:
pass
def write_sql():
try:
print('Writing sql to ' + outfilename)
outfile = open(outfilename, "w")
for line in sqlStmts:
outfile.write(line)
outfile.write('\n')
except: print ('Error writing line')
finally:
outfile.close()
def get_insert_stmt(gender, age, race, srcId):
return 'insert into i2b2demodata.patient_dimension ' \
+ '(patient_num,sex_cd,age_in_years_num,race_cd,update_date,download_date,import_date,sourcesystem_cd)' \
+ 'values (nextval(\'i2b2demodata.seq_patient_num\'), \'' + gender + '\', ' + str(age) + ', \'' + race + '\',current_timestamp,current_timestamp,current_timestamp,' + '\'' + srcId + '\');'
def write_bulk():
#'patient_num',
headers = ['sex_cd', 'age_in_years_num', 'race_cd', 'update_date',
'download_date', 'import_date', 'sourcesystem_cd']
with open(bulkfilename, "w") as out:
writer = csv.DictWriter(out, fieldnames=headers, dialect='excel', lineterminator='\n', delimiter=',')
writer.writeheader()
for data in sqlStmts:
writer.writerow(data)
def main(cffile, dfile):
build_patients(dfile)
if bulk:
write_bulk()
else:
write_sql()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("datafile", help="Data file")
parser.add_argument("-p", help="Project name")
parser.add_argument("-b", action="store_true", help="generate file for bulk load")
# parser.add_argument("-tab", action="store_true", help="tab delimited file (default comma)")
args = parser.parse_args()
if args.datafile:
datafile = args.datafile
if args.p:
PROJECT = args.p
if args.b:
bulk = args.b
main(cfgfile, datafile)