-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreadreaxys.py
432 lines (343 loc) · 13.4 KB
/
readreaxys.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
# database to load data to
# if true will print out the sql statements and other data for debugging
debug = False
import xml.etree.ElementTree as ET
import psycopg2 as psql
from psycopg2.extensions import AsIs
import glob
import tempfile
import os
import time
import gzip
from myhash import myhash
from pathlib import Path
from dbconnect import getConnection
path = Path('.')
version = os.path.basename(path.parent.absolute())
print('loading version', version)
mydir = os.path.dirname(os.path.realpath(__file__))
CHUNKSIZE = 50000
lines = set()
def getid(element):
""" returns a hash code for the XML element and children to create a repeatable id for the element """
if element is None:
print("getid error: null element")
return -1
id = element.attrib.get('ID')
if id and id.isnumeric() and len(list(element)) == 1:
return int(id)
else:
text = ET.tostring(element)
hashcode = myhash(text)
if debug:
print('key:',text, 'hash', hashcode)
return hashcode
def readconditions(tree, conn):
"""
read an xml file into the designated database
"""
start = time.time()
insertcache = set()
root = tree.getroot()
sql = 'insert into reaxys_temp.conditions (%s) values %s;'
cur = conn.cursor()
for record in root.findall('REACTIONS'):
for elem in record.findall('.//CONDITIONS'):
data = {}
data['condition_id'] = getid(elem)
for condition in ['ATMOSPHERE','PREPARATION','REFLUX']:
subelem = elem.findall(condition)
if subelem:
for sselem in subelem:
tag = sselem.tag
value = sselem.text
data[tag] = value
#this set has ranges
for condition in ['PH','PRESSURE','REACTION_MOLARITY','TEMPERATURE','TIME','TOTAL_VOLUME']:
subelem = elem.find(condition)
if subelem:
mint = subelem.find('min')
maxt = subelem.find('max')
minval = mint.text
maxval = maxt.text
if minval == '-INF':
minval = '-1e100'
if maxval == 'INF':
maxval = '1e100'
array = '[' + minval + ',' + maxval + ']'
data[condition] = array
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode('utf-8') + "\n"
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadconditions load took %5.2f %6i records" % ((time.time() - start), len(lines)))
def readstages(tree, conn):
"""
read an xml file into the designated database
"""
start = time.time()
insertcache = set()
root = tree.getroot()
sql = 'insert into reaxys_temp.stages (%s) values %s;'
cur = conn.cursor()
for record in root.findall('REACTIONS/REACTION'):
for elem in record.findall('VARIATIONS/STAGES'):
data = {}
data['stage_id'] = getid(elem)
#this set has ranges
for item in ['CONDITIONS', 'REACTANTS', 'PRODUCTS', 'REAGENTS','CATALYSTS','SOLVENTS','METABOLITES']:
subelem = elem.findall(item)
if subelem:
ilist = list()
for sselem in subelem:
tag = getid(sselem)
ilist.append(tag)
data[item] = ilist
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode('utf-8') + "\n"
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadstages load took %5.2f %6i records" % ((time.time() - start), len(lines)))
def readvariations(tree, conn):
"""
read an xml file into the designated database
"""
start = time.time()
insertcache = set()
root = tree.getroot()
sql = 'insert into reaxys_temp.variation (%s) values %s;'
cur = conn.cursor()
for record in root.findall('REACTIONS/REACTION'):
for elem in record.findall('VARIATIONS'):
data = {}
data['variation_id'] = getid(elem)
#this set has lists
for item in ['CREATION_DATE', 'EXPERIMENT_ID','EXPERIMENT_TYPE','MODIFICATION_DATE','PROJECT_NAME','QUALIFICATION',
'SOURCE','DESTINATION','CONCLUSION_PHRASE','CREATED_AT_SITE','DUPLICATE_EXP_REF','PREPARATIVE','ELN_CITATION',
'REACTION_SCALE','NEXTMOVE_REACTION_TYPE','RXNO_REACTION_TYPE','ANALYTICAL_DATA_EXISTS']:
subelem = elem.find(item)
if subelem is not None:
tag = subelem.tag
value = subelem.text
data[tag] = value
for item in ['STAGES', 'COMMENTS', 'IDENTIFIERS', 'LINKS', 'GROUPS', 'ANIMALS', 'CONDITIONS', 'REACTANTS',
'PRODUCTS', 'REAGENTS','CATALYSTS','SOLVENTS','METABOLITES','KEYWORDS']:
subelem = elem.findall(item)
if subelem:
ilist = list()
for sselem in subelem:
tag = getid(sselem)
ilist.append(tag)
data[item] = ilist
for item in [ 'CIT_ID' ]:
subelem = elem.findall(item)
if subelem:
ilist = list()
for sselem in subelem:
tag = int(sselem.text)
ilist.append(tag)
data[item] = ilist
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode('utf-8') + "\n"
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadvariations load took %5.2f %6i records" % ((time.time() - start), len(lines)))
return
def readreactions(tree, conn):
"""
read an xml file into the designated database
"""
start = time.time()
insertcache = set()
root = tree.getroot()
sql = 'insert into reaxys_temp.reaction (%s) values %s;'
cur = conn.cursor()
for elem in root.findall('REACTIONS/REACTION'):
data = {}
data['reaction_id'] = getid(elem)
data['reaxys_reaction_id'] = elem.attrib.get('ID');
for item in ['RXNSTRUCTURE','RANK','MW_LARGEST_PRODUCT','SORT_CREATION_DATE','SORT_REACTION_SCALE','SORT_TOTAL_VOLUME']:
subelem = elem.find(item)
if subelem is not None:
tag = subelem.tag
value = subelem.text
data[tag] = value
for item in ['REACTANT_ID', 'METABOLITE_ID', 'PRODUCT_ID']:
subelem = elem.findall(item)
if subelem:
ilist = list()
for sselem in subelem:
# some of the data are MD5 hash strings, to be annoying
# we will just make this a hash to be compatible as integer key
# for this database
text = sselem.text
if text.startswith("MD5"):
text = myhash(text.encode('utf-8'))
text = int(text)
ilist.append(text)
data[item] = ilist
for item in ['VARIATIONS']:
subelem = elem.findall(item)
if subelem:
ilist = list()
for sselem in subelem:
tag = getid(sselem)
ilist.append(tag)
data[item] = ilist
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode('utf-8') + "\n"
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadreactions load took %5.2f %6i records" % ((time.time() - start), len(lines)))
return
def readsubstances(tree, conn):
"""
read an xml file into the designated database
"""
start = time.time()
insertcache = set()
root = tree.getroot()
sql = 'insert into reaxys_temp.substance (%s) values %s;'
cur = conn.cursor()
for record in root.findall('REACTIONS/REACTION'):
for elem in record.findall('VARIATIONS'):
#this set has lists
for item in ['REACTANTS', 'PRODUCTS', 'REAGENTS','CATALYSTS','SOLVENTS','METABOLITES']:
data = {}
subelem = elem.find(item)
if subelem:
data['substance_id'] = getid(subelem)
temp = subelem.attrib.get('ID')
if temp.isnumeric():
data['reaxys_id'] = temp
for subsubelem in subelem:
tag = subsubelem.tag
value = subsubelem.text
data[tag] = value
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode('utf-8') + "\n"
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadsubstances load took %5.2f %6i records" % ((time.time() - start), len(lines)) )
return
def readcitations(tree, conn):
"""
read an xml file into the designated database
"""
insertcache = set()
start = time.time()
root = tree.getroot()
sql = 'insert into reaxys_temp.citation (%s) values %s;'
cur = conn.cursor()
for elem in root.findall('CITATIONS/CITATION'):
data = {}
id = elem.attrib.get('ID')
data['citation_id'] = id
for subelem in elem:
value = subelem.text
tag = subelem.tag
data[tag] = value
columns = data.keys()
values = [data[column] for column in columns]
cmd = cur.mogrify(sql, (AsIs(','.join(columns)), tuple(values))).decode() + '\n'
h = hash(cmd)
if not h in lines:
lines.add(h)
insertcache.add(cmd)
if len(insertcache) > CHUNKSIZE:
cur.execute( '\n'.join(insertcache))
insertcache.clear()
if len(insertcache) > 0:
cur.execute( '\n'.join(insertcache))
cur.close()
conn.commit()
print("\treadcitations load took %5.2f %6i records" % ((time.time() - start), len(lines)))
return
def sqlfile(fname):
""" read and execute a sql file"""
c = getConnection()
with open(fname, 'r') as f:
sql = f.read()
commands = sql.split(';')
print('executing sql', fname)
with c.cursor() as cur:
for command in commands:
command = command.strip()
if command != '':
cur.execute(sql)
c.commit()
c.close()
def load():
conn = getConnection()
sqlfile(mydir + '/reaxys_schema')
with conn.cursor() as cur:
cur.execute('insert into reaxys_temp.version (version) values (%s);', (version,))
conn.commit()
file_list = glob.iglob('udm-cit/*citations*.xml.gz')
file_list.sort()
for i, filepath in enumerate(file_list):
print("file: ", filepath)
tree = ET.parse(gzip.open(filepath));
readcitations(tree, conn)
lines.clear()
file_list = glob.iglob('udm-rea/*reactions*.xml.gz')
file_list.sort()
for i, filepath in enumerate(file_list):
print("file: ", filepath)
tree = ET.parse(gzip.open(filepath));
readreactions(tree, conn)
readconditions(tree, conn)
readstages(tree, conn)
readvariations(tree, conn)
readsubstances(tree, conn)
load()