File size: 26,122 Bytes
233f6d4 | 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 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | import logging, sys
import numpy as np
from tqdm import tqdm
from scipy.linalg import eigh
from rdkit import Chem
from rdkit.Chem import MolFromSmiles, MolToSmiles, AddHs
from nfp.preprocessing import features
from nfp.preprocessing.features import Tokenizer
import time
class SmilesPreprocessor(object):
""" Given a list of SMILES strings, encode these molecules as atom and
connectivity feature matricies.
Example:
>>> preprocessor = SmilesPreprocessor(explicit_hs=False)
>>> inputs = preprocessor.fit(data.smiles)
"""
def __init__(self, explicit_hs=True, atom_features=None, bond_features=None):
"""
explicit_hs : bool
whether to tell RDkit to add H's to a molecule.
atom_features : function
A function applied to an rdkit.Atom that returns some
representation (i.e., string, integer) for the Tokenizer class.
bond_features : function
A function applied to an rdkit Bond to return some description.
"""
self.atom_tokenizer = Tokenizer()
self.bond_tokenizer = Tokenizer()
self.explicit_hs = explicit_hs
if atom_features is None:
atom_features = features.atom_features_v1
if bond_features is None:
bond_features = features.bond_features_v1
self.atom_features = atom_features
self.bond_features = bond_features
def fit(self, smiles_iterator):
""" Fit an iterator of SMILES strings, creating new atom and bond
tokens for unseen molecules. Returns a dictionary with 'atom' and
'connectivity' entries """
return list(self.preprocess(smiles_iterator, train=True))
def predict(self, smiles_iterator):
""" Uses previously determined atom and bond tokens to convert a SMILES
iterator into 'atom' and 'connectivity' matrices. Ensures that atom and
bond classes commute with previously determined results. """
return list(self.preprocess(smiles_iterator, train=False))
def preprocess(self, smiles_iterator, train=True):
self.atom_tokenizer.train = train
self.bond_tokenizer.train = train
for smiles in tqdm(smiles_iterator):
yield self.construct_feature_matrices(smiles)
@property
def atom_classes(self):
""" The number of atom types found (includes the 0 null-atom type) """
return self.atom_tokenizer.num_classes + 1
@property
def bond_classes(self):
""" The number of bond types found (includes the 0 null-bond type) """
return self.bond_tokenizer.num_classes + 1
def construct_feature_matrices(self, smiles):
""" construct a molecule from the given smiles string and return atom
and bond classes.
Returns
dict with entries
'n_atom' : number of atoms in the molecule
'n_bond' : number of bonds in the molecule
'atom' : (n_atom,) length list of atom classes
'bond' : (n_bond,) list of bond classes
'connectivity' : (n_bond, 2) array of source atom, target atom pairs.
"""
mol = MolFromSmiles(smiles)
if self.explicit_hs:
mol = AddHs(mol)
n_atom = len(mol.GetAtoms())
n_bond = 2 * len(mol.GetBonds())
# If its an isolated atom, add a self-link
if n_bond == 0:
n_bond = 1
atom_feature_matrix = np.zeros(n_atom, dtype='int')
bond_feature_matrix = np.zeros(n_bond, dtype='int')
connectivity = np.zeros((n_bond, 2), dtype='int')
bond_index = 0
atom_seq = mol.GetAtoms()
atoms = [atom_seq[i] for i in range(n_atom)]
for n, atom in enumerate(atoms):
# Atom Classes
atom_feature_matrix[n] = self.atom_tokenizer(
self.atom_features(atom))
start_index = atom.GetIdx()
for bond in atom.GetBonds():
# Is the bond pointing at the target atom
rev = bond.GetBeginAtomIdx() != start_index
# Bond Classes
bond_feature_matrix[n] = self.bond_tokenizer(
self.bond_features(bond, flipped=rev))
# Connectivity
if not rev: # Original direction
connectivity[bond_index, 0] = bond.GetBeginAtomIdx()
connectivity[bond_index, 1] = bond.GetEndAtomIdx()
else: # Reversed
connectivity[bond_index, 0] = bond.GetEndAtomIdx()
connectivity[bond_index, 1] = bond.GetBeginAtomIdx()
bond_index += 1
return {
'n_atom': n_atom,
'n_bond': n_bond,
'atom': atom_feature_matrix,
'bond': bond_feature_matrix,
'connectivity': connectivity,
}
class ConnectivityAPreprocessor(object):
""" Given a list of SMILES strings, encode these molecules as atom and
connectivity feature matricies.
Example:
>>> preprocessor = SmilesPreprocessor(explicit_hs=False)
>>> inputs = preprocessor.fit(data.smiles)
"""
def __init__(self, explicit_hs=True, atom_features=None, bond_features=None):
"""
explicit_hs : bool
whether to tell RDkit to add H's to a molecule.
atom_features : function
A function applied to an rdkit.Atom that returns some
representation (i.e., string, integer) for the Tokenizer class.
bond_features : function
A function applied to an rdkit Bond to return some description.
"""
self.atom_tokenizer = Tokenizer()
self.bond_tokenizer = Tokenizer()
self.explicit_hs = explicit_hs
if atom_features is None:
atom_features = features.atom_features_v1
if bond_features is None:
bond_features = features.bond_features_v1
self.atom_features = atom_features
self.bond_features = bond_features
def fit(self, smiles_iterator):
""" Fit an iterator of SMILES strings, creating new atom and bond
tokens for unseen molecules. Returns a dictionary with 'atom' and
'connectivity' entries """
return list(self.preprocess(smiles_iterator, train=True))
def predict(self, smiles_iterator):
""" Uses previously determined atom and bond tokens to convert a SMILES
iterator into 'atom' and 'connectivity' matrices. Ensures that atom and
bond classes commute with previously determined results. """
return list(self.preprocess(smiles_iterator, train=False))
def preprocess(self, smiles_iterator, train=True):
self.atom_tokenizer.train = train
self.bond_tokenizer.train = train
for smiles in tqdm(smiles_iterator):
yield self.construct_feature_matrices(smiles)
@property
def atom_classes(self):
""" The number of atom types found (includes the 0 null-atom type) """
return self.atom_tokenizer.num_classes + 1
@property
def bond_classes(self):
""" The number of bond types found (includes the 0 null-bond type) """
return self.bond_tokenizer.num_classes + 1
def construct_feature_matrices(self, smiles):
""" construct a molecule from the given smiles string and return atom
and bond classes.
Returns
dict with entries
'n_atom' : number of atoms in the molecule
'n_bond' : number of bonds in the molecule
'atom' : (n_atom,) length list of atom classes
'bond' : (n_bond,) list of bond classes
'connectivity' : (n_bond, 2) array of source atom, target atom pairs.
"""
mol = MolFromSmiles(smiles)
if self.explicit_hs:
mol = AddHs(mol)
n_atom = len(mol.GetAtoms())
n_bond = 2 * len(mol.GetBonds())
# If its an isolated atom, add a self-link
if n_bond == 0:
n_bond = 1
atom_feature_matrix = np.zeros(n_atom, dtype='int')
bond_feature_matrix = np.zeros(n_bond, dtype='int')
connectivity = np.zeros((n_bond, 2), dtype='int')
bond_index = 0
atom_seq = mol.GetAtoms()
atoms = [atom_seq[i] for i in range(n_atom)]
for n, atom in enumerate(atoms):
# Atom Classes
atom_feature_matrix[n] = self.atom_tokenizer(
self.atom_features(atom))
start_index = atom.GetIdx()
for bond in atom.GetBonds():
# Is the bond pointing at the target atom
rev = bond.GetBeginAtomIdx() != start_index
# Bond Classes
bond_feature_matrix[n] = self.bond_tokenizer(
self.bond_features(bond, flipped=rev))
# Connectivity
if not rev: # Original direction
connectivity[bond_index, 0] = bond.GetBeginAtomIdx()
connectivity[bond_index, 1] = bond.GetEndAtomIdx()
else: # Reversed
connectivity[bond_index, 0] = bond.GetEndAtomIdx()
connectivity[bond_index, 1] = bond.GetBeginAtomIdx()
bond_index += 1
return {
'n_atom': n_atom,
'n_bond': n_bond,
'atom': atom_feature_matrix,
'bond': bond_feature_matrix,
'connectivity': connectivity,
}
class MolPreprocessor(SmilesPreprocessor):
""" I should refactor this into a base class and separate
SmilesPreprocessor classes. But the idea is that we only need to redefine
the `construct_feature_matrices` method to have a working preprocessor that
handles 3D structures.
We'll pass an iterator of mol objects instead of SMILES strings this time,
though.
"""
def __init__(self, n_neighbors, cutoff, **kwargs):
""" A preprocessor class that also returns distances between
neighboring atoms. Adds edges for non-bonded atoms to include a maximum
of n_neighbors around each atom """
self.n_neighbors = n_neighbors
self.cutoff = cutoff
super(MolPreprocessor, self).__init__(**kwargs)
def construct_feature_matrices(self, mol):
""" Given an rdkit mol, return atom feature matrices, bond feature
matrices, and connectivity matrices.
Returns
dict with entries
'n_atom' : number of atoms in the molecule
'n_bond' : number of edges (likely n_atom * n_neighbors)
'atom' : (n_atom,) length list of atom classes
'bond' : (n_bond,) list of bond classes. 0 for no bond
'distance' : (n_bond,) list of bond distances
'connectivity' : (n_bond, 2) array of source atom, target atom pairs.
"""
n_atom = len(mol.GetAtoms())
# n_bond is actually the number of atom-atom pairs, so this is defined
# by the number of neighbors for each atom.
#if there is cutoff,
distance_matrix = Chem.Get3DDistanceMatrix(mol)
if self.n_neighbors <= (n_atom - 1):
n_bond = self.n_neighbors * n_atom
else:
# If there are fewer atoms than n_neighbors, all atoms will be
# connected
n_bond = distance_matrix[(distance_matrix < self.cutoff) & (distance_matrix != 0)].size
if n_bond == 0: n_bond = 1
# Initialize the matrices to be filled in during the following loop.
atom_feature_matrix = np.zeros(n_atom, dtype='int')
bond_feature_matrix = np.zeros(n_bond, dtype='int')
bond_distance_matrix = np.zeros(n_bond, dtype=np.float32)
connectivity = np.zeros((n_bond, 2), dtype='int')
# Hopefully we've filtered out all problem mols by now.
if mol is None:
raise RuntimeError("Issue in loading mol")
# Get a list of the atoms in the molecule.
atom_seq = mol.GetAtoms()
atoms = [atom_seq[i] for i in range(n_atom)]
# Here we loop over each atom, and the inner loop iterates over each
# neighbor of the current atom.
bond_index = 0 # keep track of our current bond.
for n, atom in enumerate(atoms):
# update atom feature matrix
atom_feature_matrix[n] = self.atom_tokenizer(
self.atom_features(atom))
# if n_neighbors is greater than total atoms, then each atom is a
# neighbor.
if (self.n_neighbors + 1) > len(mol.GetAtoms()):
neighbor_end_index = len(mol.GetAtoms())
else:
neighbor_end_index = (self.n_neighbors + 1)
distance_atom = distance_matrix[n, :]
cutoff_end_index = distance_atom[distance_atom < self.cutoff].size
end_index = min(neighbor_end_index, cutoff_end_index)
# Loop over each of the nearest neighbors
neighbor_inds = distance_matrix[n, :].argsort()[1:end_index]
if len(neighbor_inds)==0: neighbor_inds = [n]
for neighbor in neighbor_inds:
# update bond feature matrix
bond = mol.GetBondBetweenAtoms(n, int(neighbor))
if bond is None:
bond_feature_matrix[bond_index] = 0
else:
rev = False if bond.GetBeginAtomIdx() == n else True
bond_feature_matrix[bond_index] = self.bond_tokenizer(
self.bond_features(bond, flipped=rev))
distance = distance_matrix[n, neighbor]
bond_distance_matrix[bond_index] = distance
# update connectivity matrix
connectivity[bond_index, 0] = n
connectivity[bond_index, 1] = neighbor
bond_index += 1
return {
'n_atom': n_atom,
'n_bond': n_bond,
'atom': atom_feature_matrix,
'bond': bond_feature_matrix,
'distance': bond_distance_matrix,
'connectivity': connectivity,
}
class MolBPreprocessor(MolPreprocessor):
"""
This is a subclass of Molpreprocessor that preprocessor molecule with
bond property target
"""
def __init__(self, **kwargs):
"""
A preprocessor class that also returns bond_target_matrix, besides the bond matrix
returned by MolPreprocessor. The bond_target_matrix is then used as ref to reduce molecule
to bond property
"""
super(MolBPreprocessor, self).__init__(**kwargs)
def construct_feature_matrices(self, entry):
"""
Given an entry contining rdkit molecule, bond_index and for the target property,
return atom
feature matrices, bond feature matrices, distance matrices, connectivity matrices and bond
ref matrices.
returns
dict with entries
see MolPreproccessor
'bond_index' : ref array to the bond index
"""
mol, bond_index_array = entry
n_atom = len(mol.GetAtoms())
n_pro = len(bond_index_array)
# n_bond is actually the number of atom-atom pairs, so this is defined
# by the number of neighbors for each atom.
#if there is cutoff,
distance_matrix = Chem.Get3DDistanceMatrix(mol)
if self.n_neighbors <= (n_atom - 1):
n_bond = self.n_neighbors * n_atom
else:
# If there are fewer atoms than n_neighbors, all atoms will be
# connected
n_bond = distance_matrix[(distance_matrix < self.cutoff) & (distance_matrix != 0)].size
if n_bond == 0: n_bond = 1
# Initialize the matrices to be filled in during the following loop.
atom_feature_matrix = np.zeros(n_atom, dtype='int')
bond_feature_matrix = np.zeros(n_bond, dtype='int')
bond_distance_matrix = np.zeros(n_bond, dtype=np.float32)
bond_index_matrix = np.full(n_bond, -1, dtype='int')
connectivity = np.zeros((n_bond, 2), dtype='int')
# Hopefully we've filtered out all problem mols by now.
if mol is None:
raise RuntimeError("Issue in loading mol")
# Get a list of the atoms in the molecule.
atom_seq = mol.GetAtoms()
atoms = [atom_seq[i] for i in range(n_atom)]
# Here we loop over each atom, and the inner loop iterates over each
# neighbor of the current atom.
bond_index = 0 # keep track of our current bond.
for n, atom in enumerate(atoms):
# update atom feature matrix
atom_feature_matrix[n] = self.atom_tokenizer(
self.atom_features(atom))
# if n_neighbors is greater than total atoms, then each atom is a
# neighbor.
if (self.n_neighbors + 1) > len(mol.GetAtoms()):
neighbor_end_index = len(mol.GetAtoms())
else:
neighbor_end_index = (self.n_neighbors + 1)
distance_atom = distance_matrix[n, :]
cutoff_end_index = distance_atom[distance_atom < self.cutoff].size
end_index = min(neighbor_end_index, cutoff_end_index)
# Loop over each of the nearest neighbors
neighbor_inds = distance_matrix[n, :].argsort()[1:end_index]
if len(neighbor_inds)==0: neighbor_inds = [n]
for neighbor in neighbor_inds:
# update bond feature matrix
bond = mol.GetBondBetweenAtoms(n, int(neighbor))
if bond is None:
bond_feature_matrix[bond_index] = 0
else:
rev = False if bond.GetBeginAtomIdx() == n else True
bond_feature_matrix[bond_index] = self.bond_tokenizer(
self.bond_features(bond, flipped=rev))
try:
bond_index_matrix[bond_index] = bond_index_array.tolist().index(bond.GetIdx())
except:
pass
distance = distance_matrix[n, neighbor]
bond_distance_matrix[bond_index] = distance
# update connectivity matrix
connectivity[bond_index, 0] = n
connectivity[bond_index, 1] = neighbor
bond_index += 1
return {
'n_atom': n_atom,
'n_bond': n_bond,
'n_pro': n_pro,
'atom': atom_feature_matrix,
'bond': bond_feature_matrix,
'distance': bond_distance_matrix,
'connectivity': connectivity,
'bond_index': bond_index_matrix,
}
class MolAPreprocessor(MolPreprocessor):
"""
This is a subclass of Molpreprocessor that preprocessor molecule with
bond property target
"""
def __init__(self, **kwargs):
"""
A preprocessor class that also returns bond_target_matrix, besides the bond matrix
returned by MolPreprocessor. The bond_target_matrix is then used as ref to reduce molecule
to bond property
"""
super(MolAPreprocessor, self).__init__(**kwargs)
def construct_feature_matrices(self, entry):
"""
Given an entry contining rdkit molecule, bond_index and for the target property,
return atom
feature matrices, bond feature matrices, distance matrices, connectivity matrices and bond
ref matrices.
returns
dict with entries
see MolPreproccessor
'bond_index' : ref array to the bond index
"""
mol, atom_index_array = entry
n_atom = len(mol.GetAtoms())
n_pro = len(atom_index_array)
# n_bond is actually the number of atom-atom pairs, so this is defined
# by the number of neighbors for each atom.
#if there is cutoff,
distance_matrix = Chem.Get3DDistanceMatrix(mol)
if self.n_neighbors <= (n_atom - 1):
n_bond = self.n_neighbors * n_atom
else:
# If there are fewer atoms than n_neighbors, all atoms will be
# connected
n_bond = distance_matrix[(distance_matrix < self.cutoff) & (distance_matrix != 0)].size
if n_bond == 0: n_bond = 1
# Initialize the matrices to be filled in during the following loop.
atom_feature_matrix = np.zeros(n_atom, dtype='int')
bond_feature_matrix = np.zeros(n_bond, dtype='int')
bond_distance_matrix = np.zeros(n_bond, dtype=np.float32)
atom_index_matrix = np.full(n_atom, -1, dtype='int')
connectivity = np.zeros((n_bond, 2), dtype='int')
# Hopefully we've filtered out all problem mols by now.
if mol is None:
raise RuntimeError("Issue in loading mol")
# Get a list of the atoms in the molecule.
atom_seq = mol.GetAtoms()
atoms = [atom_seq[i] for i in range(n_atom)]
# Here we loop over each atom, and the inner loop iterates over each
# neighbor of the current atom.
bond_index = 0 # keep track of our current bond.
for n, atom in enumerate(atoms):
# update atom feature matrix
atom_feature_matrix[n] = self.atom_tokenizer(
self.atom_features(atom))
try:
atom_index_matrix[n] = atom_index_array.tolist().index(atom.GetIdx())
except:
pass
# if n_neighbors is greater than total atoms, then each atom is a
# neighbor.
if (self.n_neighbors + 1) > len(mol.GetAtoms()):
neighbor_end_index = len(mol.GetAtoms())
else:
neighbor_end_index = (self.n_neighbors + 1)
distance_atom = distance_matrix[n, :]
cutoff_end_index = distance_atom[distance_atom < self.cutoff].size
end_index = min(neighbor_end_index, cutoff_end_index)
# Loop over each of the nearest neighbors
neighbor_inds = distance_matrix[n, :].argsort()[1:end_index]
if len(neighbor_inds)==0: neighbor_inds = [n]
for neighbor in neighbor_inds:
# update bond feature matrix
bond = mol.GetBondBetweenAtoms(n, int(neighbor))
if bond is None:
bond_feature_matrix[bond_index] = 0
else:
rev = False if bond.GetBeginAtomIdx() == n else True
bond_feature_matrix[bond_index] = self.bond_tokenizer(
self.bond_features(bond, flipped=rev))
distance = distance_matrix[n, neighbor]
bond_distance_matrix[bond_index] = distance
# update connectivity matrix
connectivity[bond_index, 0] = n
connectivity[bond_index, 1] = neighbor
bond_index += 1
return {
'n_atom': n_atom,
'n_bond': n_bond,
'n_pro': n_pro,
'atom': atom_feature_matrix,
'bond': bond_feature_matrix,
'distance': bond_distance_matrix,
'connectivity': connectivity,
'atom_index': atom_index_matrix,
}
# TODO: rewrite this
# class LaplacianSmilesPreprocessor(SmilesPreprocessor):
# """ Extends the SmilesPreprocessor class to also return eigenvalues and
# eigenvectors of the graph laplacian matrix.
#
# Example:
# >>> preprocessor = SmilesPreprocessor(
# >>> max_atoms=55, max_bonds=62, max_degree=4, explicit_hs=False)
# >>> atom, connectivity, eigenvalues, eigenvectors = preprocessor.fit(
# data.smiles)
# """
#
# def preprocess(self, smiles_iterator, train=True):
#
# self.atom_tokenizer.train = train
# self.bond_tokenizer.train = train
#
# for smiles in tqdm(smiles_iterator):
# G = self._mol_to_nx(smiles)
# A = self._get_atom_feature_matrix(G)
# C = self._get_connectivity_matrix(G)
# W, V = self._get_laplacian_spectral_decomp(G)
# yield A, C, W, V
#
#
# def _get_laplacian_spectral_decomp(self, G):
# """ Return the eigenvalues and eigenvectors of the graph G, padded to
# `self.max_atoms`.
# """
#
# w0 = np.zeros((self.max_atoms, 1))
# v0 = np.zeros((self.max_atoms, self.max_atoms))
#
# w, v = eigh(nx.laplacian_matrix(G).todense())
#
# num_atoms = len(v)
#
# w0[:num_atoms, 0] = w
# v0[:num_atoms, :num_atoms] = v
#
# return w0, v0
#
#
# def fit(self, smiles_iterator):
# results = self._fit(smiles_iterator)
# return {'atom': results[0],
# 'connectivity': results[1],
# 'w': results[2],
# 'v': results[3]}
#
#
# def predict(self, smiles_iterator):
# results = self._predict(smiles_iterator)
# return {'atom': results[0],
# 'connectivity': results[1],
# 'w': results[2],
# 'v': results[3]}
def get_max_atom_bond_size(smiles_iterator, explicit_hs=True):
""" Convienence function to get max_atoms, max_bonds for a set of input
SMILES """
max_atoms = 0
max_bonds = 0
for smiles in tqdm(smiles_iterator):
mol = MolFromSmiles(smiles)
if explicit_hs:
mol = AddHs(mol)
max_atoms = max([max_atoms, len(mol.GetAtoms())])
max_bonds = max([max_bonds, len(mol.GetBonds())])
return dict(max_atoms=max_atoms, max_bonds=max_bonds*2)
def canonicalize_smiles(smiles, isomeric=True, sanitize=True):
try:
mol = MolFromSmiles(smiles, sanitize=sanitize)
return MolToSmiles(mol, isomericSmiles=isomeric)
except Exception:
pass
|