import sys
import time
from collections import defaultdict
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import PandasTools
import pandas as pd
IPythonConsole.ipython_3d=True
%pylab inline
# you need to install rxn4chemistry using pip
# pip install rxn4chemistry
#You will need to register and get an api key from here https://rxn.res.ibm.com/rxn/user/profile
api_key='Enter your api key here'
from rxn4chemistry import RXN4ChemistryWrapper
rxn4chemistry_wrapper = RXN4ChemistryWrapper(api_key=api_key)
# rxn4chemistry_wrapper.set_project('PROJECT_ID')
response = rxn4chemistry_wrapper.create_project('my_covid19_candidates')
# File locations, this is the final output from your selection
SelectedsdfFilePath = 'selectedposeH.sdf'
selected_df = PandasTools.LoadSDF(SelectedsdfFilePath,molColName='Molecule', removeHs=True)
selected_df.head(5)
selected_df['SMILES'] = selected_df.Molecule.apply(Chem.MolToSmiles)
selected_df.head(5)
ID = 'LMG 16204894'
theSMILES = selected_df.loc[selected_df['name'] == ID]['SMILES'].values[0]
theSMILES
response = rxn4chemistry_wrapper.predict_automatic_retrosynthesis(product=theSMILES)
# rerun this until the status is 'SUCCESS', keep in mind the server allows only 5 requests per minute
# and a timeout between consecutive requests of 2 seconds
#If it times out, wait a couple of minutes and rerun.
import time
while True:
results = rxn4chemistry_wrapper.get_predict_automatic_retrosynthesis_results(response['prediction_id'])
if results['status'] == 'SUCCESS':
break
time.sleep(30) #check every 30 secs
def collect_reactions(tree):
reactions = []
if 'children' in tree and len(tree['children']):
reactions.append(
AllChem.ReactionFromSmarts('{}>>{}'.format(
'.'.join([node['smiles'] for node in tree['children']]),
tree['smiles']
), useSmiles=True)
)
for node in tree['children']:
reactions.extend(collect_reactions(node))
return reactions
for index, path in enumerate(results['retrosynthetic_paths']):
print('Showing path {} with confidence {}:'.format(index, path['confidence']))
for reaction in collect_reactions(path):
display(Chem.Draw.ReactionToImage(reaction))
#to save images
for index, path in enumerate(results['retrosynthetic_paths']):
print('Showing path {} with confidence {}:'.format(index, path['confidence']))
for i, reaction in enumerate(collect_reactions(path)):
img = Chem.Draw.ReactionToImage(reaction)
img.save(f"{index}-{i}.png")