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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from openbabel import pybel
|
| 3 |
+
except:
|
| 4 |
+
import pybel
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import argparse
|
| 7 |
+
from functools import partial
|
| 8 |
+
from multiprocessing import Pool
|
| 9 |
+
from tqdm.auto import tqdm
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import rdkit
|
| 13 |
+
from rdkit import Chem
|
| 14 |
+
from func_timeout import func_set_timeout
|
| 15 |
+
# from pebble import concurrent, ProcessPool
|
| 16 |
+
# from concurrent.futures import TimeoutError
|
| 17 |
+
|
| 18 |
+
######## Gilde enviroment setting
|
| 19 |
+
schrodinger_root_path='/public/software/schrodinger/2021-2'
|
| 20 |
+
# schrodinger_root_path='/opt/schrodinger2021-2'
|
| 21 |
+
glide = f"{schrodinger_root_path}/glide"
|
| 22 |
+
structconvert = f"{schrodinger_root_path}/utilities/structconvert"
|
| 23 |
+
prepwizard = f"{schrodinger_root_path}/utilities/prepwizard"
|
| 24 |
+
ligprep = f"{schrodinger_root_path}/ligprep"
|
| 25 |
+
glide_sort = f"{schrodinger_root_path}/utilities/glide_sort"
|
| 26 |
+
mol2convert = f"{schrodinger_root_path}/utilities/mol2convert"
|
| 27 |
+
|
| 28 |
+
#################################
|
| 29 |
+
|
| 30 |
+
def smi_mae(id_smi, size_upper_limit=60, fast_flag=0):
|
| 31 |
+
''' The SMILES of ligand will be transformed into maestro format.
|
| 32 |
+
id_smi:[name, SMILES]
|
| 33 |
+
output file: {id_smi[0]}.mae
|
| 34 |
+
fast_flag: only explore the best tautormers
|
| 35 |
+
'''
|
| 36 |
+
# chembl_id = col['ChEMBL ID']
|
| 37 |
+
chembl_id = str(id_smi[0])
|
| 38 |
+
smi = id_smi[1]
|
| 39 |
+
# path=Path(path)
|
| 40 |
+
opfile = f'{chembl_id}'
|
| 41 |
+
try:
|
| 42 |
+
# if 1:
|
| 43 |
+
# smi = col['Smiles']
|
| 44 |
+
mol = pybel.readstring("smi", smi)
|
| 45 |
+
# strip salt
|
| 46 |
+
mol.OBMol.StripSalts(10)
|
| 47 |
+
mols = mol.OBMol.Separate()
|
| 48 |
+
# print(pybel.Molecule(mols))
|
| 49 |
+
mol = pybel.Molecule(mols[0])
|
| 50 |
+
for imol in mols:
|
| 51 |
+
imol = pybel.Molecule(imol)
|
| 52 |
+
if len(imol.atoms) > len(mol.atoms):
|
| 53 |
+
mol = imol
|
| 54 |
+
if len(mol.atoms)>size_upper_limit:
|
| 55 |
+
print(f'SMILES is larger than {size_upper_limit}')
|
| 56 |
+
return 0
|
| 57 |
+
# print(mol)
|
| 58 |
+
mol.addh()
|
| 59 |
+
mol.title = chembl_id
|
| 60 |
+
# print(mol)
|
| 61 |
+
mol.make3D(forcefield='mmff94', steps=100)
|
| 62 |
+
mol.localopt()
|
| 63 |
+
mol.write(format='mol2', filename=f'{opfile}.mol2', overwrite=True)
|
| 64 |
+
os.system(f'{structconvert} -imol2 {opfile}.mol2 -omae {opfile}_raw.mae')
|
| 65 |
+
if fast_flag:
|
| 66 |
+
os.system(f'{ligprep} -imae {opfile}_raw.mae -omae {opfile}.mae -epik -s 1 -t 1 -WAIT -NOJOBID')
|
| 67 |
+
else:
|
| 68 |
+
os.system(f'{ligprep} -imae {opfile}_raw.mae -omae {opfile}.mae -epik -WAIT -NOJOBID')
|
| 69 |
+
# clean
|
| 70 |
+
if os.path.exists(f'{opfile}.mol2'):
|
| 71 |
+
os.system(f'rm {opfile}.mol2')
|
| 72 |
+
return 1
|
| 73 |
+
except:
|
| 74 |
+
print(f"Tranformation of {smi} failed! ")
|
| 75 |
+
if os.path.exists(f'{opfile}.mol2'):
|
| 76 |
+
os.system(f'rm {opfile}.mol2')
|
| 77 |
+
return 0
|
| 78 |
+
|
| 79 |
+
def write_dockInput(id_smi, dockInput_template):
|
| 80 |
+
'''Prepare the docking control script of glide'''
|
| 81 |
+
dockInput_new_file = f'{id_smi[0]}.in'
|
| 82 |
+
dockInput_new_f = open(dockInput_new_file, 'w')
|
| 83 |
+
with open(dockInput_template, 'r') as dockInput_template_f:
|
| 84 |
+
for line in dockInput_template_f.readlines():
|
| 85 |
+
line_new = line.replace('$MaeFile', f'{str(id_smi[0])}.mae')
|
| 86 |
+
# line_new = line_new.replace('$n_jobs', str(n_jobs))
|
| 87 |
+
dockInput_new_f.write(line_new)
|
| 88 |
+
dockInput_template_f.close()
|
| 89 |
+
dockInput_new_f.close()
|
| 90 |
+
return dockInput_new_file
|
| 91 |
+
|
| 92 |
+
# @func_set_timeout(100)
|
| 93 |
+
def dock(id_smi, dockInput_template,fast_flag=0):
|
| 94 |
+
#### dock a single compound
|
| 95 |
+
if 'sdf' in str(dockInput_template):
|
| 96 |
+
suffix='pv.sdfgz'
|
| 97 |
+
if 'mae' in str(dockInput_template):
|
| 98 |
+
suffix='pv.maegz'
|
| 99 |
+
if Path(f"{id_smi[0]}_{suffix}").exists():
|
| 100 |
+
return f"{id_smi[0]}_{suffix}"
|
| 101 |
+
else:
|
| 102 |
+
mae_stat=smi_mae(id_smi,fast_flag=fast_flag)
|
| 103 |
+
if mae_stat:
|
| 104 |
+
dockInput_new_file = write_dockInput(id_smi, dockInput_template)
|
| 105 |
+
print(f'dockInput_new_f= {dockInput_new_file}')
|
| 106 |
+
os.system(f'{glide} -WAIT -OVERWRITE -NOJOBID {dockInput_new_file}')
|
| 107 |
+
# clean the output
|
| 108 |
+
tempFiles = [f"{id_smi[0]}.in", f"{id_smi[0]}.mae", f"{id_smi[0]}_raw.mae"]
|
| 109 |
+
for ifile in tempFiles:
|
| 110 |
+
try:
|
| 111 |
+
os.system(f'rm {ifile}')
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print(e)
|
| 114 |
+
continue
|
| 115 |
+
return f"{id_smi[0]}_{suffix}"
|
| 116 |
+
else:
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
def get_docking_score(imaegz):
|
| 120 |
+
try:
|
| 121 |
+
isimple_name = imaegz.replace('_pv.sdfgz', '')
|
| 122 |
+
isimple_name=isimple_name.replace('_pv.maegz', '')
|
| 123 |
+
report_file=f'{isimple_name}.rept'
|
| 124 |
+
if not Path(report_file).exists():
|
| 125 |
+
os.system(
|
| 126 |
+
f'{glide_sort} -r {report_file} {imaegz} -o ./{isimple_name}.mae')
|
| 127 |
+
with open(report_file, 'r') as report_file_f:
|
| 128 |
+
parse_mark = 0
|
| 129 |
+
dockScore_list = []
|
| 130 |
+
for line in report_file_f.readlines():
|
| 131 |
+
line_sp = line.strip().split()
|
| 132 |
+
if parse_mark > 0 and len(line_sp) == 0:
|
| 133 |
+
break
|
| 134 |
+
if len(line_sp) > 0:
|
| 135 |
+
if line_sp[0] == '====':
|
| 136 |
+
parse_mark += 1
|
| 137 |
+
continue
|
| 138 |
+
if len(line_sp) == 19 and parse_mark > 0:
|
| 139 |
+
dockScore_list.append([line_sp[0], line_sp[3], line_sp[1]])
|
| 140 |
+
return dockScore_list
|
| 141 |
+
except:
|
| 142 |
+
return [[0.0,0.0,0.0]]
|
| 143 |
+
|
| 144 |
+
def dock_score(id_smi, dockInput_template,fast_flag=0):
|
| 145 |
+
'''The Dock results will be saved locally!'''
|
| 146 |
+
try:
|
| 147 |
+
maegz_file=dock(id_smi, dockInput_template,fast_flag=fast_flag)
|
| 148 |
+
except Exception as e:
|
| 149 |
+
print(e)
|
| 150 |
+
return 0.0
|
| 151 |
+
if maegz_file:
|
| 152 |
+
score=get_docking_score(maegz_file)
|
| 153 |
+
if len(score)>0:
|
| 154 |
+
return score[0][1]
|
| 155 |
+
else:
|
| 156 |
+
return 0
|
| 157 |
+
return 0.0
|
| 158 |
+
|
| 159 |
+
### Test of code
|
| 160 |
+
if __name__ == "__main__":
|
| 161 |
+
os.system('mkdir test')
|
| 162 |
+
os.chdir('test')
|
| 163 |
+
id_smi=['test','CC(C)C1C2C(NC=1C1C=C(OC)C3=NC=NN3C=1)=CC=C(N=2)C1CCC(CC1)N1CCCC1']
|
| 164 |
+
dockInput_template='../TLR7_dock.in'
|
| 165 |
+
d_score = dock_score(id_smi,dockInput_template)
|
| 166 |
+
print(d_score)
|
my_toolset/drawing_utils.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from rdkit.Chem import AllChem,Draw,rdFMCS
|
| 4 |
+
from rdkit import Chem, DataStructs
|
| 5 |
+
from rdkit.Chem.Draw import rdDepictor
|
| 6 |
+
from svglib.svglib import svg2rlg
|
| 7 |
+
from reportlab.graphics import renderPDF, renderPM
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
import seaborn as sns
|
| 10 |
+
from .my_utils import get_mol
|
| 11 |
+
import warnings
|
| 12 |
+
warnings.filterwarnings('ignore')
|
| 13 |
+
|
| 14 |
+
def view_difference(mol1, mol2,legends):
|
| 15 |
+
mol1=get_mol(mol1)
|
| 16 |
+
mol2=get_mol(mol2)
|
| 17 |
+
mcs = rdFMCS.FindMCS([mol1,mol2])
|
| 18 |
+
mcs_mol = Chem.MolFromSmarts(mcs.smartsString)
|
| 19 |
+
match1 = mol1.GetSubstructMatch(mcs_mol)
|
| 20 |
+
target_atm1 = []
|
| 21 |
+
for atom in mol1.GetAtoms():
|
| 22 |
+
if atom.GetIdx() not in match1:
|
| 23 |
+
target_atm1.append(atom.GetIdx())
|
| 24 |
+
match2 = mol2.GetSubstructMatch(mcs_mol)
|
| 25 |
+
target_atm2 = []
|
| 26 |
+
for atom in mol2.GetAtoms():
|
| 27 |
+
if atom.GetIdx() not in match2:
|
| 28 |
+
target_atm2.append(atom.GetIdx())
|
| 29 |
+
|
| 30 |
+
png=Draw.MolsToGridImage([mol1, mol2],subImgSize=(300,300),useSVG=False,highlightAtomLists=[target_atm1, target_atm2],legends=legends)
|
| 31 |
+
# svg=Draw.MolsToGridImage([mol1, mol2],subImgSize=(300,300), useSVG=True,highlightAtomLists=[target_atm1, target_atm2],legends=legends)
|
| 32 |
+
svg=''
|
| 33 |
+
return (png,svg)
|
| 34 |
+
|
| 35 |
+
def save_svg(png_svg, svg_file, ipython=False):
|
| 36 |
+
'''Save the png and svg to file
|
| 37 |
+
- png_svg [png,svg]
|
| 38 |
+
- svg_file file_name.svg
|
| 39 |
+
- ipython In ipython something interesting is heppening!
|
| 40 |
+
'''
|
| 41 |
+
if ipython:
|
| 42 |
+
png=png_svg[0].data
|
| 43 |
+
svg=png_svg[1].data
|
| 44 |
+
else:
|
| 45 |
+
png=png_svg[0]#.data
|
| 46 |
+
svg=png_svg[1]#.data
|
| 47 |
+
with open(svg_file, 'w') as f:
|
| 48 |
+
f.write(svg)
|
| 49 |
+
# drawing = svg2rlg(svg_file)
|
| 50 |
+
# renderPDF.drawToFile(drawing, f"{svg_file.replace('.svg')}+'.pdf'")
|
| 51 |
+
# renderPM.drawToFile(drawing, svg_file.replace('.svg','')+'.png', fmt="PNG")
|
| 52 |
+
# plot=plt.imshow(png.data)
|
| 53 |
+
if ipython:
|
| 54 |
+
with open(svg_file.replace('.svg','')+'.png', 'wb+') as f:
|
| 55 |
+
f.write(png)
|
| 56 |
+
else:
|
| 57 |
+
png.save(svg_file.replace('.svg','')+'.png')
|
| 58 |
+
|
| 59 |
+
def show_mols(smiles_mols,legends=[],subImgSize=(800,600)):
|
| 60 |
+
'''Display multiple mols with legends'''
|
| 61 |
+
mols=[get_mol(ismiles_mol) for ismiles_mol in smiles_mols]
|
| 62 |
+
mol_cls,legends_cls=[],[]
|
| 63 |
+
for i in range(len(mols)):
|
| 64 |
+
if mols[i]==None:
|
| 65 |
+
continue
|
| 66 |
+
mol_cls.append(mols[i])
|
| 67 |
+
if len(legends)>i:
|
| 68 |
+
legends_cls.append(legends[i])
|
| 69 |
+
else:
|
| 70 |
+
legends_cls.append('')
|
| 71 |
+
svg=Draw.MolsToGridImage(mol_cls,subImgSize=subImgSize, molsPerRow=3,useSVG=True,legends=legends_cls)
|
| 72 |
+
png=Draw.MolsToGridImage(mol_cls,subImgSize=subImgSize,useSVG=False,molsPerRow=3,legends=legends_cls)
|
| 73 |
+
return png,svg
|
| 74 |
+
|
| 75 |
+
def plot_xy(x,y,x_label='',y_label='',save_file=''):
|
| 76 |
+
'''Plot x-y graph'''
|
| 77 |
+
plt.figure(figsize=(7, 4.5), dpi=500)
|
| 78 |
+
plt.rc('font', family='Times New Roman', size=12, weight='bold')
|
| 79 |
+
plt.plot(x,y)
|
| 80 |
+
plt.xlabel(x_label)
|
| 81 |
+
plt.ylabel(y_label)
|
| 82 |
+
if save_file!='':
|
| 83 |
+
plt.savefig(save_file, dpi=500)
|
| 84 |
+
plt.show()
|
| 85 |
+
|
| 86 |
+
def scatter_xy(x,y,x_label='',y_label='',save_file='', xlims=None, ylims=None):
|
| 87 |
+
'''Plot x-y graph'''
|
| 88 |
+
plt.figure(figsize=(7, 4.5), dpi=500)
|
| 89 |
+
plt.rc('font', family='Times New Roman', size=12, weight='bold')
|
| 90 |
+
plt.scatter(x,y)
|
| 91 |
+
plt.xlabel(x_label)
|
| 92 |
+
plt.ylabel(y_label)
|
| 93 |
+
if xlims != None:
|
| 94 |
+
plt.xlim(xlims[0],xlims[1])
|
| 95 |
+
if ylims != None:
|
| 96 |
+
plt.ylim(ylims[0],ylims[1])
|
| 97 |
+
if save_file!='':
|
| 98 |
+
plt.savefig(save_file, dpi=500)
|
| 99 |
+
plt.show()
|
| 100 |
+
|
| 101 |
+
def plot_density(x,x_label='',y_label='Density (%)',save_file=''):
|
| 102 |
+
'''Plot x-y graph'''
|
| 103 |
+
plt.figure(figsize=(7, 4.5), dpi=500)
|
| 104 |
+
plt.rc('font', family='Times New Roman', size=12, weight='bold')
|
| 105 |
+
sns.displot(x, stat="density")
|
| 106 |
+
plt.xlabel(x_label)
|
| 107 |
+
plt.ylabel(y_label)
|
| 108 |
+
if save_file!='':
|
| 109 |
+
plt.savefig(save_file, dpi=500)
|
| 110 |
+
plt.show()
|
my_toolset/my_utils.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import print_function
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import os.path as op
|
| 5 |
+
import pickle
|
| 6 |
+
from collections import Counter,UserList, defaultdict
|
| 7 |
+
from functools import partial
|
| 8 |
+
from tkinter import N
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import scipy.sparse
|
| 12 |
+
from rdkit import Chem, DataStructs
|
| 13 |
+
from rdkit.Chem import AllChem
|
| 14 |
+
from rdkit.Chem import rdMolDescriptors
|
| 15 |
+
#from rdkit.six import iteritems
|
| 16 |
+
from rdkit.Chem.QED import qed
|
| 17 |
+
from rdkit.Chem.Scaffolds import MurckoScaffold
|
| 18 |
+
from rdkit.Chem import Descriptors
|
| 19 |
+
from rdkit.Chem import MACCSkeys
|
| 20 |
+
from rdkit.Chem import Draw
|
| 21 |
+
from rdkit.Chem.AllChem import GetMorganFingerprintAsBitVect as Morgan
|
| 22 |
+
from multiprocessing import Pool
|
| 23 |
+
from rdkit.Chem.Pharm2D import Generate
|
| 24 |
+
from .pharmacophore import factory
|
| 25 |
+
from rdkit.Chem import GetDistanceMatrix
|
| 26 |
+
from rdkit.Chem.Descriptors import MolWt
|
| 27 |
+
from rdkit.Chem.Lipinski import NumHAcceptors, NumHDonors, NumRotatableBonds
|
| 28 |
+
from rdkit.Chem.MolSurf import TPSA
|
| 29 |
+
from rdkit.Chem.rdMolDescriptors import CalcNumRings, CalcNumAtomStereoCenters, CalcNumAromaticRings, \
|
| 30 |
+
CalcNumAliphaticRings
|
| 31 |
+
from rdkit.Chem.Crippen import MolLogP
|
| 32 |
+
from tqdm.auto import tqdm
|
| 33 |
+
from rdkit.ML.Cluster import Butina
|
| 34 |
+
|
| 35 |
+
_fscores = None
|
| 36 |
+
##### Calculate systhesize score
|
| 37 |
+
def strip_pose(idx, keep_num=2):
|
| 38 |
+
idx_nopose = ''
|
| 39 |
+
idx_sp = idx.split("_")
|
| 40 |
+
for itm in range(keep_num):
|
| 41 |
+
if idx_nopose == '':
|
| 42 |
+
idx_nopose = idx_sp[itm]
|
| 43 |
+
else:
|
| 44 |
+
idx_nopose += f'_{idx_sp[itm]}'
|
| 45 |
+
return idx_nopose
|
| 46 |
+
|
| 47 |
+
def readFragmentScores(name='fpscores'):
|
| 48 |
+
import gzip
|
| 49 |
+
global _fscores
|
| 50 |
+
# generate the full path filename:
|
| 51 |
+
if name == "fpscores":
|
| 52 |
+
name = op.join(op.dirname(__file__), name)
|
| 53 |
+
_fscores = pickle.load(gzip.open('%s.pkl.gz' % name))
|
| 54 |
+
outDict = {}
|
| 55 |
+
for i in _fscores:
|
| 56 |
+
for j in range(1, len(i)):
|
| 57 |
+
outDict[i[j]] = float(i[0])
|
| 58 |
+
_fscores = outDict
|
| 59 |
+
|
| 60 |
+
def numBridgeheadsAndSpiro(mol, ri=None):
|
| 61 |
+
nSpiro = rdMolDescriptors.CalcNumSpiroAtoms(mol)
|
| 62 |
+
nBridgehead = rdMolDescriptors.CalcNumBridgeheadAtoms(mol)
|
| 63 |
+
return nBridgehead, nSpiro
|
| 64 |
+
|
| 65 |
+
def calculateScore(m):
|
| 66 |
+
if _fscores is None:
|
| 67 |
+
readFragmentScores()
|
| 68 |
+
|
| 69 |
+
# fragment score
|
| 70 |
+
fp = rdMolDescriptors.GetMorganFingerprint(
|
| 71 |
+
m, 2 # <- 2 is the *radius* of the circular fingerprint
|
| 72 |
+
)
|
| 73 |
+
fps = fp.GetNonzeroElements()
|
| 74 |
+
score1 = 0.
|
| 75 |
+
nf = 0
|
| 76 |
+
for bitId, v in iteritems(fps):
|
| 77 |
+
nf += v
|
| 78 |
+
sfp = bitId
|
| 79 |
+
score1 += _fscores.get(sfp, -4) * v
|
| 80 |
+
score1 /= nf
|
| 81 |
+
|
| 82 |
+
# features score
|
| 83 |
+
nAtoms = m.GetNumAtoms()
|
| 84 |
+
nChiralCenters = len(Chem.FindMolChiralCenters(m, includeUnassigned=True))
|
| 85 |
+
ri = m.GetRingInfo()
|
| 86 |
+
nBridgeheads, nSpiro = numBridgeheadsAndSpiro(m, ri)
|
| 87 |
+
nMacrocycles = 0
|
| 88 |
+
for x in ri.AtomRings():
|
| 89 |
+
if len(x) > 8:
|
| 90 |
+
nMacrocycles += 1
|
| 91 |
+
|
| 92 |
+
sizePenalty = nAtoms ** 1.005 - nAtoms
|
| 93 |
+
stereoPenalty = math.log10(nChiralCenters + 1)
|
| 94 |
+
spiroPenalty = math.log10(nSpiro + 1)
|
| 95 |
+
bridgePenalty = math.log10(nBridgeheads + 1)
|
| 96 |
+
macrocyclePenalty = 0.
|
| 97 |
+
# ---------------------------------------
|
| 98 |
+
# This differs from the paper, which defines:
|
| 99 |
+
# macrocyclePenalty = math.log10(nMacrocycles+1)
|
| 100 |
+
# This form generates better results when 2 or more macrocycles are present
|
| 101 |
+
if nMacrocycles > 0:
|
| 102 |
+
macrocyclePenalty = math.log10(2)
|
| 103 |
+
|
| 104 |
+
score2 = (0. - sizePenalty - stereoPenalty -
|
| 105 |
+
spiroPenalty - bridgePenalty - macrocyclePenalty)
|
| 106 |
+
|
| 107 |
+
# correction for the fingerprint density
|
| 108 |
+
# not in the original publication, added in version 1.1
|
| 109 |
+
# to make highly symmetrical molecules easier to synthetise
|
| 110 |
+
score3 = 0.
|
| 111 |
+
if nAtoms > len(fps):
|
| 112 |
+
score3 = math.log(float(nAtoms) / len(fps)) * .5
|
| 113 |
+
|
| 114 |
+
sascore = score1 + score2 + score3
|
| 115 |
+
|
| 116 |
+
# need to transform "raw" value into scale between 1 and 10
|
| 117 |
+
min = -4.0
|
| 118 |
+
max = 2.5
|
| 119 |
+
sascore = 11. - (sascore - min + 1) / (max - min) * 9.
|
| 120 |
+
# smooth the 10-end
|
| 121 |
+
if sascore > 8.:
|
| 122 |
+
sascore = 8. + math.log(sascore + 1. - 9.)
|
| 123 |
+
if sascore > 10.:
|
| 124 |
+
sascore = 10.0
|
| 125 |
+
elif sascore < 1.:
|
| 126 |
+
sascore = 1.0
|
| 127 |
+
|
| 128 |
+
return sascore
|
| 129 |
+
|
| 130 |
+
def get_mol(smiles_or_mol):
|
| 131 |
+
'''
|
| 132 |
+
Loads SMILES/molecule into RDKit's object
|
| 133 |
+
'''
|
| 134 |
+
if isinstance(smiles_or_mol, str):
|
| 135 |
+
if len(smiles_or_mol) == 0:
|
| 136 |
+
return None
|
| 137 |
+
mol = Chem.MolFromSmiles(smiles_or_mol)
|
| 138 |
+
if mol is None:
|
| 139 |
+
return None
|
| 140 |
+
try:
|
| 141 |
+
Chem.SanitizeMol(mol)
|
| 142 |
+
except ValueError:
|
| 143 |
+
return None
|
| 144 |
+
return mol
|
| 145 |
+
return smiles_or_mol
|
| 146 |
+
|
| 147 |
+
def canonic_smiles(smiles_or_mol):
|
| 148 |
+
try:
|
| 149 |
+
mol = get_mol(smiles_or_mol)
|
| 150 |
+
if mol is None:
|
| 151 |
+
return None
|
| 152 |
+
return Chem.MolToSmiles(mol,isomericSmiles=False)
|
| 153 |
+
except Exception as e:
|
| 154 |
+
print(e)
|
| 155 |
+
return None
|
| 156 |
+
|
| 157 |
+
def SA(smiles_or_mol):
|
| 158 |
+
"""
|
| 159 |
+
Computes RDKit's Synthetic Accessibility score
|
| 160 |
+
"""
|
| 161 |
+
mol = get_mol(smiles_or_mol)
|
| 162 |
+
if mol is None:
|
| 163 |
+
return None
|
| 164 |
+
return calculateScore(mol)
|
| 165 |
+
|
| 166 |
+
def QED(smiles_or_mol):
|
| 167 |
+
"""
|
| 168 |
+
Computes RDKit's QED score
|
| 169 |
+
"""
|
| 170 |
+
mol = get_mol(smiles_or_mol)
|
| 171 |
+
if mol is None:
|
| 172 |
+
return None
|
| 173 |
+
return qed(mol)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def weight(smiles_or_mol):
|
| 177 |
+
"""
|
| 178 |
+
Computes molecular weight for given molecule.
|
| 179 |
+
Returns float,
|
| 180 |
+
"""
|
| 181 |
+
mol = get_mol(smiles_or_mol)
|
| 182 |
+
if mol==None:
|
| 183 |
+
return 0
|
| 184 |
+
return Descriptors.MolWt(mol)
|
| 185 |
+
|
| 186 |
+
def slog_p(smiles_or_mol) -> float:
|
| 187 |
+
mol = get_mol(smiles_or_mol)
|
| 188 |
+
if mol==None:
|
| 189 |
+
return 0
|
| 190 |
+
return MolLogP(mol)
|
| 191 |
+
|
| 192 |
+
def get_n_rings(mol):
|
| 193 |
+
"""
|
| 194 |
+
Computes the number of rings in a molecule
|
| 195 |
+
"""
|
| 196 |
+
return mol.GetRingInfo().NumRings()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def fragmenter(mol):
|
| 200 |
+
"""
|
| 201 |
+
fragment mol using BRICS and return smiles list
|
| 202 |
+
"""
|
| 203 |
+
fgs = AllChem.FragmentOnBRICSBonds(get_mol(mol))
|
| 204 |
+
fgs_smi = Chem.MolToSmiles(fgs).split(".")
|
| 205 |
+
return fgs_smi
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def compute_fragments(mol_list, n_jobs=1):
|
| 209 |
+
"""
|
| 210 |
+
fragment list of mols using BRICS and return smiles list
|
| 211 |
+
"""
|
| 212 |
+
fragments = Counter()
|
| 213 |
+
for mol_frag in mapper(n_jobs)(fragmenter, mol_list):
|
| 214 |
+
fragments.update(mol_frag)
|
| 215 |
+
return fragments
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def compute_scaffolds(mol_list, n_jobs=1, min_rings=2):
|
| 219 |
+
"""
|
| 220 |
+
Extracts a scafold from a molecule in a form of a canonic SMILES
|
| 221 |
+
"""
|
| 222 |
+
# scaffolds = Counter()
|
| 223 |
+
map_ = mapper(n_jobs)
|
| 224 |
+
scaffolds = map_(partial(compute_scaffold, min_rings=min_rings), mol_list)
|
| 225 |
+
# if None in scaffolds:
|
| 226 |
+
# scaffolds.pop(None)
|
| 227 |
+
return scaffolds
|
| 228 |
+
|
| 229 |
+
def counter_to_df(counter):
|
| 230 |
+
scalf_list=[]
|
| 231 |
+
for key in counter.keys():
|
| 232 |
+
scalf_list.append([key, counter[key]])
|
| 233 |
+
df=pd.DataFrame(scalf_list, columns=['SMILES','Count'])
|
| 234 |
+
return df
|
| 235 |
+
|
| 236 |
+
def df_valid(df, row_smi='SMILES'):
|
| 237 |
+
valid_idx=[idx for idx, row in df.iterrows() if canonic_smiles(row[row_smi])!=None]
|
| 238 |
+
df_valid=df.loc[valid_idx]
|
| 239 |
+
return df_valid
|
| 240 |
+
|
| 241 |
+
def ClusterFps(fps,cutoff=0.2):
|
| 242 |
+
# first generate the distance matrix:
|
| 243 |
+
dists = []
|
| 244 |
+
nfps = len(fps)
|
| 245 |
+
for i in range(1,nfps):
|
| 246 |
+
sims = DataStructs.BulkTanimotoSimilarity(fps[i],fps[:i])
|
| 247 |
+
dists.extend([1-x for x in sims])
|
| 248 |
+
# now cluster the data:
|
| 249 |
+
cs = Butina.ClusterData(dists,nfps,cutoff,isDistData=True)
|
| 250 |
+
return cs
|
| 251 |
+
|
| 252 |
+
def save_svg(png_svg, svg_file):
|
| 253 |
+
png=png_svg[0]
|
| 254 |
+
svg=png_svg[1]
|
| 255 |
+
with open(svg_file, 'w') as f:
|
| 256 |
+
f.write(svg)
|
| 257 |
+
# renderPDF.drawToFile(drawing, f"{svg_file.replace('.svg')}+'.pdf'")
|
| 258 |
+
# renderPM.drawToFile(drawing, svg_file.replace('.svg','')+'.png', fmt="PNG")
|
| 259 |
+
# plot=plt.imshow(png.data)
|
| 260 |
+
# with open(svg_file.replace('.svg','')+'.png', 'wb+') as f:
|
| 261 |
+
# f.write(png)
|
| 262 |
+
png.save(svg_file.replace('.svg','')+'.png')
|
| 263 |
+
|
| 264 |
+
def draw_smis(smis, svg_file):
|
| 265 |
+
## svg_file with suffix as .svg
|
| 266 |
+
mols=[get_mol(ismi) for ismi in smis if get_mol(ismi)!=None]
|
| 267 |
+
svg=Draw.MolsToGridImage(mols,subImgSize=(300,150),molsPerRow=4,useSVG=True)
|
| 268 |
+
png=Draw.MolsToGridImage(mols,subImgSize=(300,150),molsPerRow=4,useSVG=False)
|
| 269 |
+
save_svg([png,svg], svg_file)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def compute_FP(mol, radius=2, nBits=1024):
|
| 273 |
+
mol = get_mol(mol)
|
| 274 |
+
FP = AllChem.GetMorganFingerprintAsBitVect(
|
| 275 |
+
mol, radius, nBits=nBits)
|
| 276 |
+
return FP
|
| 277 |
+
|
| 278 |
+
def compute_scaffold(mol, min_rings=2):
|
| 279 |
+
mol = get_mol(mol)
|
| 280 |
+
try:
|
| 281 |
+
scaffold = MurckoScaffold.GetScaffoldForMol(mol)
|
| 282 |
+
except (ValueError, RuntimeError):
|
| 283 |
+
return None
|
| 284 |
+
n_rings = get_n_rings(scaffold)
|
| 285 |
+
scaffold_smiles = Chem.MolToSmiles(scaffold)
|
| 286 |
+
if scaffold_smiles == '' or n_rings < min_rings:
|
| 287 |
+
return None
|
| 288 |
+
return scaffold_smiles
|
| 289 |
+
|
| 290 |
+
def compute_sim(smi, smi_list, mode='smi-smis'):
|
| 291 |
+
if mode=='smi-smis':
|
| 292 |
+
mol1 = Chem.MolFromSmiles(smi)
|
| 293 |
+
FP1 = AllChem.GetMorganFingerprintAsBitVect(
|
| 294 |
+
mol1, 2, nBits=1024)
|
| 295 |
+
mols = [Chem.MolFromSmiles(ismi)
|
| 296 |
+
for ismi in smi_list]
|
| 297 |
+
FPs = [AllChem.GetMorganFingerprintAsBitVect(
|
| 298 |
+
imol, 2, nBits=1024) for imol in mols]
|
| 299 |
+
if mode=='smi-FPs':
|
| 300 |
+
mol1 = Chem.MolFromSmiles(smi)
|
| 301 |
+
FP1 = AllChem.GetMorganFingerprintAsBitVect(
|
| 302 |
+
mol1, 2, nBits=1024)
|
| 303 |
+
FPs=smi_list
|
| 304 |
+
molSims = [DataStructs.TanimotoSimilarity(
|
| 305 |
+
FP, FP1) for FP in FPs]
|
| 306 |
+
return molSims
|
| 307 |
+
|
| 308 |
+
def remove_invalid(smi_list):
|
| 309 |
+
valid_smis=[]
|
| 310 |
+
for ismi in smi_list:
|
| 311 |
+
try:
|
| 312 |
+
mol=Chem.MolFromSmiles(ismi)
|
| 313 |
+
if mol != None:
|
| 314 |
+
valid_smis.append(ismi)
|
| 315 |
+
except Exception as e:
|
| 316 |
+
continue
|
| 317 |
+
print(f'Total: {len(smi_list)} Valid: {len(valid_smis)}')
|
| 318 |
+
return valid_smis
|
| 319 |
+
|
| 320 |
+
def fingerprints_from_mols(mols, desc_type):
|
| 321 |
+
if desc_type == 'Trust':
|
| 322 |
+
fps = [Generate.Gen2DFingerprint(mol, factory) for mol in mols]
|
| 323 |
+
size = 4096
|
| 324 |
+
X = np.zeros((len(mols), size))
|
| 325 |
+
for i, fp in enumerate(fps):
|
| 326 |
+
for k, v in fp.GetNonzeroElements().items():
|
| 327 |
+
idx = k % size
|
| 328 |
+
X[i, idx] = v
|
| 329 |
+
return X
|
| 330 |
+
elif desc_type == 'ECFP6_c':
|
| 331 |
+
fps = [
|
| 332 |
+
AllChem.GetMorganFingerprint(
|
| 333 |
+
mol,
|
| 334 |
+
3,
|
| 335 |
+
useCounts=True,
|
| 336 |
+
useFeatures=True,
|
| 337 |
+
) for mol in mols
|
| 338 |
+
]
|
| 339 |
+
size = 2048
|
| 340 |
+
nfp = np.zeros((len(fps), size), np.int32)
|
| 341 |
+
for i, fp in enumerate(fps):
|
| 342 |
+
for idx, v in fp.GetNonzeroElements().items():
|
| 343 |
+
nidx = idx % size
|
| 344 |
+
nfp[i, nidx] += int(v)
|
| 345 |
+
return nfp
|
| 346 |
+
elif desc_type == 'ECFP6':
|
| 347 |
+
fps = [
|
| 348 |
+
AllChem.GetMorganFingerprintAsBitVect(mol, 3, nBits=2048)
|
| 349 |
+
for mol in mols
|
| 350 |
+
]
|
| 351 |
+
size = 2048
|
| 352 |
+
nfp = np.zeros((len(fps), size), np.int32)
|
| 353 |
+
for i, fp in enumerate(fps):
|
| 354 |
+
for idx, v in enumerate(fp):
|
| 355 |
+
nfp[i, idx] = v
|
| 356 |
+
return nfp
|
| 357 |
+
|
| 358 |
+
def mapper(n_jobs):
|
| 359 |
+
'''
|
| 360 |
+
Returns function for map call.
|
| 361 |
+
If n_jobs == 1, will use standard map
|
| 362 |
+
If n_jobs > 1, will use multiprocessing pool
|
| 363 |
+
If n_jobs is a pool object, will return its map function
|
| 364 |
+
'''
|
| 365 |
+
if n_jobs == 1:
|
| 366 |
+
def _mapper(*args, **kwargs):
|
| 367 |
+
return list(map(*args, **kwargs))
|
| 368 |
+
|
| 369 |
+
return _mapper
|
| 370 |
+
if isinstance(n_jobs, int):
|
| 371 |
+
pool = Pool(n_jobs)
|
| 372 |
+
|
| 373 |
+
def _mapper(*args, **kwargs):
|
| 374 |
+
try:
|
| 375 |
+
result = pool.map(*args, **kwargs)
|
| 376 |
+
finally:
|
| 377 |
+
pool.terminate()
|
| 378 |
+
return result
|
| 379 |
+
|
| 380 |
+
return _mapper
|
| 381 |
+
return n_jobs.map
|
| 382 |
+
|
| 383 |
+
def imapper(n_jobs):
|
| 384 |
+
'''
|
| 385 |
+
Returns function for map call.
|
| 386 |
+
If n_jobs == 1, will use standard map
|
| 387 |
+
If n_jobs > 1, will use multiprocessing pool
|
| 388 |
+
If n_jobs is a pool object, will return its map function
|
| 389 |
+
'''
|
| 390 |
+
if n_jobs == 1:
|
| 391 |
+
def _mapper(*args, **kwargs):
|
| 392 |
+
return list(map(*args, **kwargs))
|
| 393 |
+
return _mapper
|
| 394 |
+
|
| 395 |
+
if isinstance(n_jobs, int):
|
| 396 |
+
pool = Pool(n_jobs)
|
| 397 |
+
def _mapper(*args,**kwargs):
|
| 398 |
+
try:
|
| 399 |
+
result = [x for x in tqdm(
|
| 400 |
+
pool.imap(*args, kwargs['input']),
|
| 401 |
+
total=len(kwargs['input']),
|
| 402 |
+
miniters=n_jobs)]
|
| 403 |
+
finally:
|
| 404 |
+
pool.terminate()
|
| 405 |
+
return result
|
| 406 |
+
return _mapper
|
| 407 |
+
return n_jobs.map
|
| 408 |
+
|
| 409 |
+
def read_txt(fname, cols=[], ftype='csv',header_pass=False):
|
| 410 |
+
res_list=''
|
| 411 |
+
with open(fname, "r") as f:
|
| 412 |
+
if header_pass:
|
| 413 |
+
next(f)
|
| 414 |
+
for line in f:
|
| 415 |
+
if ftype=='csv':
|
| 416 |
+
fields = line.split(',')
|
| 417 |
+
else:
|
| 418 |
+
fields = line.split()
|
| 419 |
+
if res_list=='':
|
| 420 |
+
res_list=[[]]*len(fields)
|
| 421 |
+
for icol in cols:
|
| 422 |
+
res_list[icol].append(fields[icol])
|
| 423 |
+
return res_list
|
| 424 |
+
|
| 425 |
+
class PhysChemDescriptors:
|
| 426 |
+
"""Molecular descriptors.
|
| 427 |
+
The descriptors in this class are mostly calculated RDKit phys-chem properties.
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
def maximum_graph_length(self, mol) -> int:
|
| 431 |
+
mol = get_mol(mol)
|
| 432 |
+
if mol==None:
|
| 433 |
+
return 0
|
| 434 |
+
return int(np.max(GetDistanceMatrix(mol)))
|
| 435 |
+
|
| 436 |
+
def hba_libinski(self, mol) -> int:
|
| 437 |
+
mol = get_mol(mol)
|
| 438 |
+
if mol==None:
|
| 439 |
+
return 0
|
| 440 |
+
return NumHAcceptors(mol)
|
| 441 |
+
|
| 442 |
+
def hbd_libinski(self, mol) -> int:
|
| 443 |
+
mol = get_mol(mol)
|
| 444 |
+
if mol==None:
|
| 445 |
+
return 0
|
| 446 |
+
return NumHDonors(mol)
|
| 447 |
+
|
| 448 |
+
def mol_weight(self, mol) -> float:
|
| 449 |
+
mol = get_mol(mol)
|
| 450 |
+
if mol==None:
|
| 451 |
+
return 0
|
| 452 |
+
return MolWt(mol)
|
| 453 |
+
|
| 454 |
+
def number_of_rings(self, mol) -> int:
|
| 455 |
+
mol = get_mol(mol)
|
| 456 |
+
if mol==None:
|
| 457 |
+
return 0
|
| 458 |
+
return CalcNumRings(mol)
|
| 459 |
+
|
| 460 |
+
def number_of_aromatic_rings(self, mol) -> int:
|
| 461 |
+
mol = get_mol(mol)
|
| 462 |
+
if mol==None:
|
| 463 |
+
return 0
|
| 464 |
+
return CalcNumAromaticRings(mol)
|
| 465 |
+
|
| 466 |
+
def number_of_aliphatic_rings(self, mol) -> int:
|
| 467 |
+
mol = get_mol(mol)
|
| 468 |
+
if mol==None:
|
| 469 |
+
return 0
|
| 470 |
+
return CalcNumAliphaticRings(mol)
|
| 471 |
+
|
| 472 |
+
def number_of_rotatable_bonds(self, mol) -> int:
|
| 473 |
+
mol = get_mol(mol)
|
| 474 |
+
if mol==None:
|
| 475 |
+
return 0
|
| 476 |
+
return NumRotatableBonds(mol)
|
| 477 |
+
|
| 478 |
+
def slog_p(self, mol) -> float:
|
| 479 |
+
mol = get_mol(mol)
|
| 480 |
+
if mol==None:
|
| 481 |
+
return 0
|
| 482 |
+
return MolLogP(mol)
|
| 483 |
+
|
| 484 |
+
def tpsa(self, mol) -> float:
|
| 485 |
+
mol = get_mol(mol)
|
| 486 |
+
if mol==None:
|
| 487 |
+
return 0
|
| 488 |
+
return TPSA(mol)
|
| 489 |
+
|
| 490 |
+
def sa(self, mol) -> float:
|
| 491 |
+
mol = get_mol(mol)
|
| 492 |
+
if mol==None:
|
| 493 |
+
return 0
|
| 494 |
+
return SA(mol)
|
| 495 |
+
|
| 496 |
+
def qed(self, mol) -> float:
|
| 497 |
+
mol = get_mol(mol)
|
| 498 |
+
if mol==None:
|
| 499 |
+
return 0
|
| 500 |
+
return qed(mol)
|
| 501 |
+
|
| 502 |
+
def number_of_stereo_centers(self, mol) -> int:
|
| 503 |
+
mol = get_mol(mol)
|
| 504 |
+
if mol==None:
|
| 505 |
+
return 0
|
| 506 |
+
return CalcNumAtomStereoCenters(mol)
|
| 507 |
+
|
| 508 |
+
def number_atoms_in_largest_ring(self, mol) -> int:
|
| 509 |
+
mol = get_mol(mol)
|
| 510 |
+
if mol==None:
|
| 511 |
+
return 0
|
| 512 |
+
ring_info = mol.GetRingInfo()
|
| 513 |
+
ring_size = [len(ring) for ring in ring_info.AtomRings()]
|
| 514 |
+
max_ring_size = max(ring_size) if ring_size else 0
|
| 515 |
+
return int(max_ring_size)
|
| 516 |
+
|
| 517 |
+
def valid_index(smi_list):
|
| 518 |
+
valid_mol_indices=[]
|
| 519 |
+
for idx, ismi in enumerate(smi_list):
|
| 520 |
+
mol = get_mol(ismi)
|
| 521 |
+
if mol!=None:
|
| 522 |
+
valid_mol_indices.append(idx)
|
| 523 |
+
return valid_mol_indices
|
my_toolset/pharmacophore.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from rdkit.Chem import ChemicalFeatures
|
| 2 |
+
from rdkit.Chem.Pharm2D.SigFactory import SigFactory
|
| 3 |
+
|
| 4 |
+
fdef = """
|
| 5 |
+
DefineFeature Hydrophobic [$([$([#6&!H0]);!$([#6][$([#7,#8,#15,$([#6,#16]=[O,N])])])]),$([$([#16&D2]);!$([#16][$([#7,#8,#15])])]),Cl,Br,I]
|
| 6 |
+
Family LH
|
| 7 |
+
Weights 1.0
|
| 8 |
+
EndFeature
|
| 9 |
+
DefineFeature Donor [$([N;!H0;v3]),$([N;!H0;+1;v4]),$([O,S;H1;+0]),$([n;H1;+0])]
|
| 10 |
+
Family HD
|
| 11 |
+
Weights 1.0
|
| 12 |
+
EndFeature
|
| 13 |
+
DefineFeature Acceptor [$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F]
|
| 14 |
+
Family HA
|
| 15 |
+
Weights 1.0
|
| 16 |
+
EndFeature
|
| 17 |
+
DefineFeature BasicGroup [$([N;H2&+0][$([C,a]);!$([C,a](=O))]),$([N;H1&+0]([$([C,a]);!$([C,a](=O))])[$([C,a]);!$([C,a](=O))]),$([N;H0&+0]([C;!$(C(=O))])([C;!$(C(=O))])[C;!$(C(=O))]),$([N,n;X2;+0])]
|
| 18 |
+
Family BG
|
| 19 |
+
Weights 1.0
|
| 20 |
+
EndFeature
|
| 21 |
+
DefineFeature AcidicGroup [$([C,S](=[O,S,P])-[O;H1])]
|
| 22 |
+
Family AG
|
| 23 |
+
Weights 1.0
|
| 24 |
+
EndFeature
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
defaultBins = [(2, 3), (3, 4), (4, 6), (5, 8), (7, 10), (9, 13), (11, 16), (14, 21)]
|
| 28 |
+
|
| 29 |
+
def get_factory():
|
| 30 |
+
featFactory = ChemicalFeatures.BuildFeatureFactoryFromString(fdef)
|
| 31 |
+
factory = SigFactory(featFactory, minPointCount=2, maxPointCount=3, useCounts=True, trianglePruneBins=False)
|
| 32 |
+
factory.SetBins(defaultBins)
|
| 33 |
+
factory.Init()
|
| 34 |
+
return factory
|
| 35 |
+
|
| 36 |
+
factory = get_factory()
|
| 37 |
+
|
| 38 |
+
if (__name__ == "__main__"):
|
| 39 |
+
print("Number of bins: {}".format(factory.GetNumBins()))
|
| 40 |
+
print("Number of features: {}".format(factory.GetSigSize()))
|
| 41 |
+
print(1+2)
|