-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathatom.py
288 lines (255 loc) · 9.45 KB
/
atom.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
import copy
import importlib
import os
import re
from zulip_bots.bots.converter import utils
from typing import Any, Dict, List
import sympy
import requests
import logging
import re
import urllib
from zulip_bots.lib import Any
import wikipedia
from bs4 import BeautifulSoup
from urllib.request import urlopen
from googlesearch import search
import copy
import importlib
from zulip_bots.bots.converter import utils
from typing import Optional
ELEMENT_CLAUSE = re.compile("([A-Z][a-z]?)([0-9]*)")
def parse_compound(compound):
assert "(" not in compound, "This parser doesn't grok subclauses"
return {el: (int(num) if num else 1) for el, num in ELEMENT_CLAUSE.findall(compound)}
def balance_eqn(reactants, products):
lhs_strings = reactants
lhs_compounds = [parse_compound(compound) for compound in lhs_strings]
rhs_strings = products
rhs_compounds = [parse_compound(compound) for compound in rhs_strings]
els = sorted(set().union(*lhs_compounds, *rhs_compounds))
els_index = dict(zip(els, range(len(els))))
# Build matrix to solve
w = len(lhs_compounds) + len(rhs_compounds)
h = len(els)
A = [[0] * w for _ in range(h)]
# load with element coefficients
for col, compound in enumerate(lhs_compounds):
for el, num in compound.items():
row = els_index[el]
A[row][col] = num
for col, compound in enumerate(rhs_compounds, len(lhs_compounds)):
for el, num in compound.items():
row = els_index[el]
A[row][col] = -num # invert coefficients for RHS
# Solve using Sympy for absolute-precision math
A = sympy.Matrix(A)
# find first basis vector == primary solution
coeffs = A.nullspace()[0]
coeffs *= sympy.lcm([term.q for term in coeffs])
reactants = []
products = []
ans = ""
for i in range(len(lhs_strings)):
if coeffs[i] == 0:
reactants.append(lhs_strings[i])
for i in range(len(rhs_strings)):
if coeffs[i + len(lhs_strings)] == 0:
products.append(rhs_strings[i])
coeffs = list(coeffs)
if len(reactants) > 0:
ans += balance_eqn(reactants, products)
for i in reactants:
lhs_strings.remove(i)
coeffs.remove(0)
for i in products:
rhs_strings.remove(i)
coeffs.remove(0)
lhs = " + ".join(["{} {}".format(coeffs[i], s) if coeffs[i] > 0 else '' for i, s in enumerate(lhs_strings)])
rhs = " + ".join(["{} {}".format(coeffs[i], s) if coeffs[i] > 0 else '' for i, s in enumerate(rhs_strings, len(lhs_strings))])
if len(ans) > 0:
S = ans.split("->")
lhs += " + " + S[0]
rhs += " + " + S[1]
print(S)
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
revSUB = str.maketrans("₀₁₂₃₄₅₆₇₈₉", "0123456789")
ret = ("{} -> {}\n".format(lhs, rhs))
ret = ret.translate(SUB)
ret = list(ret)
ret[0] = ret[0].translate(revSUB)
for i in range(1, len(ret)):
if ret[i-1] == ' ':
ret[i] = ret[i].translate(revSUB)
ret = ''.join(ret)
return ret
Eqn_Hash = {}
def load_equations():
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
f = open(os.path.join(__location__, 'equations.txt'));
Lines = f.readlines()
for line in Lines:
x = (line.strip())
x = x.split(" ")
Eqn_Hash[x[0]] = x[1]
class Atom(object):
def usage(self) -> str:
return '''
This plugin allows users to solve equations and clear chemistry doubts.
'''
def handle_message(self, message: Dict[str, str], bot_handler: Any) -> None:
bot_response = get_bot_response(message, bot_handler)
bot_handler.send_reply(message, bot_response)
def get_bot_wiki_response(query):
help_text = 'Please enter your search term after {}'
new_content = 'Search term: ' + query + '\n'
query += ' chemistry'
if query == '':
return help_text.format(bot_handler.identity().mention)
query_wiki_url = 'https://en.wikipedia.org/w/api.php'
query_wiki_params = dict(
action='query',
list='search',
srsearch=query,
format='json'
)
try:
data = requests.get(query_wiki_url, params=query_wiki_params)
except requests.exceptions.RequestException:
logging.error('broken link')
return 'Uh-Oh ! Sorry ,couldn\'t process the request right now.:slightly_frowning_face:\n' \
'Please try again later.'
# Checking if the bot accessed the link.
if data.status_code != 200:
logging.error('Page not found.')
return 'Uh-Oh ! Sorry ,couldn\'t process the request right now.:slightly_frowning_face:\n' \
'Please try again later.'
if len(data.json()['query']['search']) == 0:
new_content = 'I am sorry. The search term you provided is not found :slightly_frowning_face:'
else:
search_string = data.json()['query']['search'][0]['title'].replace(' ', '_')
new_content += wikipedia.summary(search_string, sentences=2)
return new_content + "\n"
def get_bot_response(message: Dict[str, str], bot_handler: Any) -> str:
content = message['content']
words = content.split()
print(words)
if words[0] == "products":
load_equations()
compounds = []
for i in range(len(words)):
if i % 2 == 1:
compounds.append(words[i])
compounds.sort()
init_compounds = list(compounds)
return_answer = "The following equations were used to arrive at the final product\n"
reaction = "-1"
max_entropy = 0
while reaction != "0":
reaction = "0"
reactants = []
products = []
for i in range(1 << len(compounds)):
if bin(i).count('1') >= 2 and bin(i).count('1') <= 5:
S = ""
tem_reactants = []
for j in range(len(compounds)):
if ((i >> j) & 1) == 1:
S += compounds[j] + '+'
tem_reactants.append(compounds[j])
if S in Eqn_Hash.keys():
Temp = Eqn_Hash[S].split("+")
cur_entropy = int(Temp[len(Temp) - 1])
if max_entropy < cur_entropy:
reaction = Eqn_Hash[S]
reactants = tem_reactants
products = Temp
products.pop()
for i in reactants:
compounds.remove(i)
for i in products:
compounds.append(i)
if len(products) > 0:
return_answer += balance_eqn(reactants, products)
compounds.sort()
return_answer += "\nThe final product is \n"
return_answer += balance_eqn(init_compounds, compounds)
return return_answer
if words[0] == "add":
reactants = []
products = []
entropy = int(words[len(words) - 1])
i = 1
while i < len(words):
if words[i] == "=":
break
if (i & 1) == 1:
reactants.append(words[i])
i += 1
j = i + 1
while j < len(words) - 1:
if ((j - i) & 1) == 1:
products.append(words[j])
j += 1
reactants.sort()
products.sort()
R = ""
for i in reactants:
R += i + '+'
P = ""
for i in products:
P += i + '+'
P += str(entropy)
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
f = open(os.path.join(__location__, 'equations.txt'), "a");
f.write("\n" + R + " " + P)
return "Successfully added the reaction"
if words[0] == "explain_product":
compounds = []
return_answer = ""
for i in range(len(words)):
if i != 0:
compounds.append(words[i])
return_answer += "\nHere are some facts about the compounds\n"
for i in compounds:
return_answer += get_bot_wiki_response(i)
return return_answer
if words[0] == "structure":
compounds = []
return_answer = ""
for i in range(len(words)):
compounds.append(words[i])
return_answer += "\nAnswer:\n"
query = ''
for i in compounds:
query += i + ' '
query += ' chemistry wikipedia'
for i in search(query, tld="com", num=10, stop=1, pause=2):
store = i
break
html = urlopen(store)
soup = BeautifulSoup(html, 'html.parser')
title = soup.find("title").text
title = title[:-12]
print(soup.find_all('img'))
imgurl = soup.find('img')['src']
r = "[" + title + "](https:" + imgurl + ")"
return r
else:
compounds = []
return_answer = ""
for i in range(len(words)):
compounds.append(words[i])
return_answer += "\nAnswer:\n"
query = ''
for i in compounds:
query += i + ' '
query += ' chemistry wikipedia'
for i in search(query, tld="com", num=10, stop=1, pause=2):
store = i
break
html = urlopen(store)
title = BeautifulSoup(html, 'html.parser').find("title").text
title = title[:-12]
return get_bot_wiki_response(title)
handler_class = Atom