-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator_test.py
370 lines (301 loc) · 11.8 KB
/
calculator_test.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
import requests
import json
import logging
import os
import urllib3
from urllib3.util.ssl_ import create_urllib3_context
import urllib.parse
from .calculator import Calculator
from .chemical_information import SMILESFilter
headers = {'Content-Type': 'application/json'}
class TestWSCalc(Calculator):
"""
TEST WS Calculator at https://comptox.epa.gov/dashboard/web-test/
Additional documentation: Todd Martin's User's Guide
"""
def __init__(self):
Calculator.__init__(self)
self.postData = {"smiles" : ""}
self.name = "test"
# Example Request: https://comptox.epa.gov/dashboard/web-test/MP?smiles=CCCC&method=nn
self.baseUrl = os.environ.get('CTS_TEST_SERVER')
if not self.baseUrl:
self.baseUrl = "https://comptox.epa.gov/dashboard/web-test"
self.post_url = "https://comptox.epa.gov/dashboard-api/ccdapp1/webtest/predict"
self.methods = ['hc', 'nn', 'gc'] # general property methods
self.method = None
self.bcf_method = "sm"
self.timeout = 10
# map workflow parameters to test
self.propMap = {
'melting_point': {
'urlKey': 'MP'
},
'boiling_point': {
'urlKey': 'BP'
},
'water_sol': {
'urlKey': 'WS'
},
'vapor_press': {
'urlKey': 'VP'
},
'log_bcf': {
'urlKey': 'BCF'
}
# 'henrys_law_con': ,
# 'kow_no_ph':
}
self.test_prop_map = {
"MP": "melting_point",
"BP": "boiling_point",
"WS": "water_sol",
"VP": "vapor_press",
"BCF": "log_bcf"
}
self.request_post = {
"query": "CCO",
"queryType": "SMILES",
"endpoints": [
{
"endpointCode": "BCF",
"providerCode": "TEST"
},
{
"endpointCode": "BP",
"providerCode": "TEST"
},
{
"endpointCode": "MP",
"providerCode": "TEST"
},
{
"endpointCode": "VP",
"providerCode": "TEST"
},
{
"endpointCode": "WS",
"providerCode": "TEST"
}
]
}
self.result_keys = ['id', 'smiles', 'expValMass', 'expValMolarLog', 'predValMass',
'predValMolarLog', 'massUnits', 'molarLogUnits']
self.cts_testws_data_key = 'predValMass'
# TESTWS API responses map:
self.response_map = {
# NOTE: MP TESTWS endpoint is only returning '*ValMass', but with 'massUnits'="*C"
'melting_point': {
'data_type': 'predValMass'
},
# NOTE: BP TESTWS endpoint is only returning '*ValMass', but with 'massUnits'="*C"
'boiling_point': {
'data_type': 'predValMass'
},
'water_sol': {
'data_type': 'predValMass'
},
'vapor_press': {
'data_type': 'predValMass'
},
'log_bcf': {
'data_type': 'predValMolarLog'
}
}
def convertWaterSolubility(self, _response_dict):
"""
Converts water solubility from log(mol/L) => mg/L.
Expecting water sol data from TESTWS to have the following keys:
"expValMolarLog", "expValMass","predValMolarLog","predValMass","molarLogUnits","massUnits"
"""
# Requests mass from Jchem:
json_obj = self.getMass({'chemical': _response_dict['chemical']})
mass = json_obj['data'][0]['mass']
_response_dict.update({'mass': mass})
_ws_result = 1000 * float(_response_dict['mass']) * 10**-(float(_response_dict['data']))
_response_dict.update({'data': _ws_result})
return _response_dict
def makeDataRequest(self, structure, calc, prop, method):
test_prop = self.propMap[prop]['urlKey'] # prop name TEST understands
_url = self.baseUrl + "/{}".format(test_prop)
_payload = {'smiles': structure, 'method': method}
url = "{}/{}?{}".format(self.baseUrl, test_prop, urllib.parse.urlencode(_payload))
try:
response = self.ssl_legacy_request(url)
logging.warning("testws post response: {}".format(response))
except urllib3.exceptions.TimeoutError as te:
logging.warning("timeout exception: {}".format(te))
return {'error': 'timeout error'}
except urllib3.exceptions.HTTPError:
logging.warning("connection exception: {}".format(ce))
return {'error': 'connection error'}
except Exception as e:
logging.warning("exception: {}".format(e))
return {'error': 'general error'}
self.results = response
return response
def makeDataPostRequest(self, structure):
try:
response = self.ssl_legacy_post_request(structure)
except urllib3.exceptions.TimeoutError as te:
logging.warning("timeout exception: {}".format(te))
return {'error': 'timeout error'}
except urllib3.exceptions.HTTPError:
logging.warning("connection exception: {}".format(ce))
return {'error': 'connection error'}
except Exception as e:
logging.warning("exception: {}".format(e))
return {'error': 'general error'}
self.results = response
return response
def ssl_legacy_request(self, url):
"""
Bypassing SSL legacy error being thrown when making requests to comptox.
https://github.com/urllib3/urllib3/issues/2653
"""
response = None
ctx = create_urllib3_context()
ctx.load_default_certs()
ctx.options |= 0x4 # ssl.OP_LEGACY_SERVER_CONNECT
with urllib3.PoolManager(ssl_context=ctx) as http:
try:
response = http.request("GET", url)
except urllib3.exceptions.TimeoutError:
logging.warning("timeout exception: {}".format(te))
return {'error': 'timeout error'}
except urllib3.exceptions.HTTPError:
logging.warning("connection exception: {}".format(ce))
return {'error': 'connection error'}
response_obj = requests.Response()
response_obj.status_code = response.status
response_obj._content = response.data.decode("utf-8")
response_obj.content
return response_obj
def ssl_legacy_post_request(self, structure):
"""
Bypassing SSL legacy error being thrown when making requests to comptox.
https://github.com/urllib3/urllib3/issues/2653
"""
response = None
request_post = dict(self.request_post)
request_post["query"] = structure
ctx = create_urllib3_context()
ctx.load_default_certs()
ctx.options |= 0x4 # ssl.OP_LEGACY_SERVER_CONNECT
with urllib3.PoolManager(ssl_context=ctx) as http:
try:
response = http.request("POST", self.post_url, body=json.dumps(request_post), headers=headers)
except urllib3.exceptions.TimeoutError:
logging.warning("timeout exception: {}".format(te))
return {'error': 'timeout error'}
except urllib3.exceptions.HTTPError:
logging.warning("connection exception: {}".format(ce))
return {'error': 'connection error'}
response_obj = requests.Response()
response_obj.status_code = response.status
response_obj._content = response.data.decode("utf-8")
response_obj.content
return response_obj
def data_request_handler(self, request_dict):
_filtered_smiles = ''
_response_dict = {}
# fill any overlapping keys from request:
for key in request_dict.keys():
if not key == 'nodes':
_response_dict[key] = request_dict.get(key)
_response_dict.update({'request_post': request_dict})
# _response_dict.update({'request_post': {'service': "pchemprops"}}) # TODO: get rid of 'request_post' and double data
# filter smiles before sending to TEST:
# ++++++++++++++++++++++++ smiles filtering!!! ++++++++++++++++++++
try:
_filtered_smiles = SMILESFilter().parseSmilesByCalculator(request_dict.get('chemical'), self.name) # call smilesfilter
except Exception as err:
logging.warning("Error filtering SMILES: {}".format(err))
_response_dict.update({'data': "Cannot filter SMILES for TEST WS data"})
return _response_dict
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# logging.info("TEST WS Filtered SMILES: {}".format(_filtered_smiles))
# logging.info("Calling TEST WS for {} data...".format(request_dict['prop']))
if request_dict.get('method') and request_dict['method'] in self.methods + [self.bcf_method]:
# Uses method provided in request to get data from TESTWS, otherwise uses default
self.method = request_dict.get('method')
# Make sure method name is all caps (it's an acronym):
_response_dict['method'] = _response_dict.get('method').upper()
# _response = self.makeDataRequest(_filtered_smiles, self.name, request_dict.get('prop'), self.method)
_response = self.makeDataPostRequest(_filtered_smiles)
if 'error' in _response:
_response_dict.update({'data': _response['error']})
return _response_dict
if _response.status_code != 200:
_response_dict.update({'data': "Cannot reach TESTWS"})
return _response_dict
_response_obj = json.loads(_response.content)
_response_dict.update({"prop_results": []})
_response_dict["prop_results"] = _response_obj["results"][0]["results"]
return _response_dict
# def data_request_handler(self, request_dict):
# _filtered_smiles = ''
# _response_dict = {}
# # fill any overlapping keys from request:
# for key in request_dict.keys():
# if not key == 'nodes':
# _response_dict[key] = request_dict.get(key)
# _response_dict.update({'request_post': request_dict})
# # _response_dict.update({'request_post': {'service': "pchemprops"}}) # TODO: get rid of 'request_post' and double data
# # filter smiles before sending to TEST:
# # ++++++++++++++++++++++++ smiles filtering!!! ++++++++++++++++++++
# try:
# _filtered_smiles = SMILESFilter().parseSmilesByCalculator(request_dict.get('chemical'), self.name) # call smilesfilter
# except Exception as err:
# logging.warning("Error filtering SMILES: {}".format(err))
# _response_dict.update({'data': "Cannot filter SMILES for TEST WS data"})
# return _response_dict
# # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# # logging.info("TEST WS Filtered SMILES: {}".format(_filtered_smiles))
# # logging.info("Calling TEST WS for {} data...".format(request_dict['prop']))
# if request_dict.get('method') and request_dict['method'] in self.methods + [self.bcf_method]:
# # Uses method provided in request to get data from TESTWS, otherwise uses default
# self.method = request_dict.get('method')
# # Make sure method name is all caps (it's an acronym):
# _response_dict['method'] = _response_dict.get('method').upper()
# _response = self.makeDataRequest(_filtered_smiles, self.name, request_dict.get('prop'), self.method)
# if 'error' in _response:
# _response_dict.update({'data': _response['error']})
# return _response_dict
# if _response.status_code != 200:
# _response_dict.update({'data': "Cannot reach TESTWS"})
# return _response_dict
# _response_obj = json.loads(_response.content)
# logging.warning("response_obj: {}".format(_response_obj))
# _test_data = _response_obj['predictions'][0] # list of predictions (getting first because only one chemical comes back for GET requests)
# if 'error' in _test_data:
# _response_dict.update({'data': "Cannot parse SMILES"})
# return _response_dict
# # Gets response key for property:
# data_type = self.response_map[request_dict['prop']]['data_type']
# # Sets response data to property's data key (based on desired units)
# if _test_data.get(data_type):
# _response_dict['data'] = _test_data[data_type]
# # Returns "N/A" for data if there isn't any TESTWS data found:
# if not 'data' in _response_dict or not _response_dict.get('data'):
# _response_dict['data'] = "N/A"
# return _response_dict
# # Reformats TESTWS VP result, e.g., "3.14*10^-15" -> "3.14e-15":
# if request_dict['prop'] == 'vapor_press':
# _response_dict['data'] = self.convert_testws_scinot(_response_dict['data'])
# return _response_dict
def convert_testws_scinot(self, pchem_data):
"""
Converts TESTWS scientific notation format.
Ex: "3.14*10^-15" -> "3.14e-15"
"""
try:
split_val = pchem_data.split("*") # splits up number for reformatting
n = split_val[0] # gets float portion
p = split_val[1].split("^")[1] # gets power portion
new_num = "{}e{}".format(n, p)
return new_num
except Exception as e:
logging.warning("Failed trying to reformat TESTWS VP.. Returning as-is..")
logging.warning("Exception: {}".format(e))
return pchem_data