-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAPI_Utilities.py
More file actions
212 lines (149 loc) · 6.55 KB
/
API_Utilities.py
File metadata and controls
212 lines (149 loc) · 6.55 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
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
import json
import requests
from indigo import Indigo
from utils import timer
import numpy as np
"""
This class assumes that server looks like: CIM_API_SERVER=https://hcd.rtpnc.epa.gov
"""
class DescriptorsAPI:
def check_structure(self, qsarSmiles):
indigo = Indigo()
molecule = indigo.loadMolecule(qsarSmiles)
if self.contains_unexpected_elements(molecule):
return qsarSmiles + ": Molecule contains unsupported element", 400
if molecule.countAtoms() == 1:
return "Only one non-hydrogen atom", 400
if molecule.countAtoms() == 0:
return "Number of atoms equals zero", 400
if not self.contains_carbon(molecule):
return "Molecule does not contain carbon", 400
return "ok", 200
def contains_carbon(self, molecule):
# Iterate over atoms in the molecule
for atom in molecule.iterateAtoms():
if atom.symbol() == "C":
return True # Return True if a carbon atom is found
return False # Return F
def contains_unexpected_elements(self, molecule):
# Define the set of allowed elements
allowed_elements = {"C", "H", "O", "N", "F", "Cl", "Br", "I", "S", "P", "Si", "As", "Hg", "Sn"}
# Use a set to store unique elements
unique_elements = set()
# Iterate over atoms in the molecule
for atom in molecule.iterateAtoms():
element = atom.symbol()
unique_elements.add(element)
# Check if there are any elements not in the allowed set
for element in unique_elements:
if element not in allowed_elements:
return True
return False
@timer
def calculate_descriptors(self, serverAPIs, qsarSmiles, descriptorService):
if "test" in descriptorService.lower():
check_results, code = self.check_structure(qsarSmiles)
if code != 200:
return check_results, code
response = self.call_descriptors_get(server_host=serverAPIs, qsar_smiles=qsarSmiles,
descriptor_name=descriptorService)
if response.status_code != 200:
return response.text,response.status_code
df_prediction = self.response_to_df(response, qsarSmiles)
return df_prediction, 200
def call_descriptors_get(self, server_host: str, qsar_smiles: str, descriptor_name: str):
# Construct the URL
url = f"{server_host}/api/descriptors"
# Set up query parameters
params = {
"type": descriptor_name,
"smiles": qsar_smiles,
"headers": "true"
# some descriptors dont have header option? Should be fixed so this doesnt cause issue if must be false
}
response = requests.get(url, params=params)
return response
def call_descriptors_post(self, server_host: str, qsar_smiles: list[str], descriptor_name: str):
# Construct the URL
url = f"{server_host}/api/descriptors"
# Set up query parameters
params = {
"type": descriptor_name,
"chemicals": qsar_smiles,
"headers": "true"
# some descriptors dont have header option? Should be fixed so this doesnt cause issue if must be false
}
response = requests.post(url, json=params)
if response.status_code == 200:
# Parse the response JSON and convert it to a list of Chemical objects
return response.json()
else:
# Handle the error appropriately
return response.text
def response_to_df(self, response, qsarSmiles):
descriptor_dict = response.json()
headers = descriptor_dict['headers']
headers.insert(0, "Property")
headers.insert(0, "ID")
chemicals = descriptor_dict['chemicals']
chemical = chemicals[0]
# descriptors = chemical['descriptors']
# for some reason they were getting stored as strings when I was trying to access them later- will this break null descriptors for ones like padel or mordred
descriptors = [float(descriptor) if descriptor is not None else np.nan for descriptor in chemical['descriptors']]
# for descriptor in descriptors:
# print(type(descriptor), descriptor)
# print(descriptors)
descriptors.insert(0, None)
descriptors.insert(0, qsarSmiles)
# print(headers)
# print(descriptors)
import pandas as pd
df = pd.DataFrame([descriptors], columns=headers)
# print(df.shape)
return df
class SearchAPI:
@staticmethod
def call_resolver_get(server_host, identifier):
url = f"{server_host}/api/resolver/lookup"
response = requests.get(url, params={"query": identifier})
if response.status_code == 200:
# Parse the response JSON and convert it to a list of Chemical objects
return response.json(), 200
else:
# Handle the error appropriately
return response.text, response.status_code
class QsarSmilesAPI:
@staticmethod
def call_qsar_ready_standardize_post(server_host, smiles, full, workflow):
# Construct the JSON body
jo_body = {
"full": full,
"options": {"workflow": workflow},
"chemicals": [{"smiles": smiles}]
}
json_body = json.dumps(jo_body)
# Make the POST request
headers = {"Content-Type": "application/json"}
url = f"{server_host}/api/stdizer/chemicals"
response = requests.post(url, headers=headers, data=json_body)
# print(response.text)
# Check if the request was successful
if response.status_code == 200:
# Parse the response JSON and convert it to a list of Chemical objects
return response.json(), 200
else:
# Handle the error appropriately
return response.text, response.status_code
if __name__ == '__main__':
from dotenv import load_dotenv
load_dotenv()
import os
serverAPIs = os.getenv("CIM_API_SERVER", "https://cim-dev.sciencedataexperts.com")
identifier='71-43-2X'
chemicals, code = SearchAPI.call_resolver_get(serverAPIs, identifier)
print(chemicals, code)
if code == 200:
for chemical in chemicals:
print(json.dumps(chemical))
else:
print(chemicals)