File size: 11,660 Bytes
8957853 |
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 |
from rdkit import Chem, RDLogger
RDLogger.DisableLog("rdApp.*")
import re
import random
import logging
from rdkit import Chem
from typing import List, Tuple, Optional
random.seed(0)
import torch
bond_dict = [
None,
Chem.rdchem.BondType.SINGLE,
Chem.rdchem.BondType.DOUBLE,
Chem.rdchem.BondType.TRIPLE,
Chem.rdchem.BondType.AROMATIC,
]
ATOM_VALENCY = {6: 4, 7: 3, 8: 2, 9: 1, 15: 3, 16: 2, 17: 1, 35: 1, 53: 1}
logger = logging.getLogger(__name__)
def check_polymer(smiles):
if "*" in smiles:
monomer = smiles.replace("*", "[H]")
if mol2smiles(get_mol(monomer)) is None:
logger.warning(f"Invalid polymerization point")
return False
else:
return True
return True
def graph_to_smiles(molecule_list: List[Tuple], atom_decoder: list) -> List[Optional[str]]:
smiles_list = []
for index, graph in enumerate(molecule_list):
try:
atom_types, edge_types = graph
mol_init = build_molecule_with_partial_charges(atom_types, edge_types, atom_decoder)
# Try to correct the molecule with connection=True, then False if needed
for connection in (True, False):
mol_conn, _ = correct_mol(mol_init, connection=connection)
if mol_conn is not None:
break
else:
logger.warning(f"Failed to correct molecule {index}")
mol_conn = mol_init # Fallback to initial molecule
# Convert to SMILES
smiles = mol2smiles(mol_conn)
if not smiles:
logger.warning(f"Failed to convert molecule {index} to SMILES, falling back to RDKit MolToSmiles")
smiles = Chem.MolToSmiles(mol_conn)
if smiles:
mol = get_mol(smiles)
if mol is not None:
# Get the largest fragment
mol_frags = Chem.rdmolops.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
largest_mol = max(mol_frags, key=lambda m: m.GetNumAtoms())
largest_smiles = mol2smiles(largest_mol)
if largest_smiles and len(largest_smiles) > 1:
if check_polymer(largest_smiles):
smiles_list.append(largest_smiles)
else:
smiles_list.append(None)
elif check_polymer(smiles):
smiles_list.append(smiles)
else:
smiles_list.append(None)
else:
logger.warning(f"Failed to convert SMILES back to molecule for index {index}")
smiles_list.append(None)
else:
logger.warning(f"Failed to generate SMILES for molecule {index}, appending None")
smiles_list.append(None)
except Exception as e:
logger.error(f"Error processing molecule {index}: {str(e)}")
try:
# Fallback to RDKit's MolToSmiles if everything else fails
fallback_smiles = Chem.MolToSmiles(mol_init)
if fallback_smiles:
smiles_list.append(fallback_smiles)
logger.warning(f"Used RDKit MolToSmiles fallback for molecule {index}")
else:
smiles_list.append(None)
logger.warning(f"RDKit MolToSmiles fallback failed for molecule {index}, appending None")
except Exception as e2:
logger.error(f"All attempts failed for molecule {index}: {str(e2)}")
smiles_list.append(None)
return smiles_list
def build_molecule_with_partial_charges(
atom_types, edge_types, atom_decoder, verbose=False
):
if verbose:
print("\nbuilding new molecule")
mol = Chem.RWMol()
for atom in atom_types:
a = Chem.Atom(atom_decoder[atom.item()])
mol.AddAtom(a)
if verbose:
print("Atom added: ", atom.item(), atom_decoder[atom.item()])
edge_types = torch.triu(edge_types)
all_bonds = torch.nonzero(edge_types)
for i, bond in enumerate(all_bonds):
if bond[0].item() != bond[1].item():
mol.AddBond(
bond[0].item(),
bond[1].item(),
bond_dict[edge_types[bond[0], bond[1]].item()],
)
if verbose:
print(
"bond added:",
bond[0].item(),
bond[1].item(),
edge_types[bond[0], bond[1]].item(),
bond_dict[edge_types[bond[0], bond[1]].item()],
)
# add formal charge to atom: e.g. [O+], [N+], [S+]
# not support [O-], [N-], [S-], [NH+] etc.
flag, atomid_valence = check_valency(mol)
if verbose:
print("flag, valence", flag, atomid_valence)
if flag:
continue
else:
if len(atomid_valence) == 2:
idx = atomid_valence[0]
v = atomid_valence[1]
an = mol.GetAtomWithIdx(idx).GetAtomicNum()
if verbose:
print("atomic num of atom with a large valence", an)
if an in (7, 8, 16) and (v - ATOM_VALENCY[an]) == 1:
mol.GetAtomWithIdx(idx).SetFormalCharge(1)
# print("Formal charge added")
else:
continue
return mol
def correct_mol(mol, connection=False):
#####
no_correct = False
flag, _ = check_valency(mol)
if flag:
no_correct = True
while True:
if connection:
mol_conn = connect_fragments(mol)
mol = mol_conn
if mol is None:
return None, no_correct
flag, atomid_valence = check_valency(mol)
if flag:
break
else:
try:
assert len(atomid_valence) == 2
idx = atomid_valence[0]
v = atomid_valence[1]
queue = []
check_idx = 0
for b in mol.GetAtomWithIdx(idx).GetBonds():
type = int(b.GetBondType())
queue.append(
(b.GetIdx(), type, b.GetBeginAtomIdx(), b.GetEndAtomIdx())
)
if type == 12:
check_idx += 1
queue.sort(key=lambda tup: tup[1], reverse=True)
if queue[-1][1] == 12:
return None, no_correct
elif len(queue) > 0:
start = queue[check_idx][2]
end = queue[check_idx][3]
t = queue[check_idx][1] - 1
mol.RemoveBond(start, end)
if t >= 1:
mol.AddBond(start, end, bond_dict[t])
except Exception as e:
# print(f"An error occurred in correction: {e}")
return None, no_correct
return mol, no_correct
def check_valid(smiles):
mol = get_mol(smiles)
if mol is None:
return False
smiles = mol2smiles(mol)
if smiles is None:
return False
return True
def get_mol(smiles_or_mol):
"""
Loads SMILES/molecule into RDKit's object
"""
if isinstance(smiles_or_mol, str):
if len(smiles_or_mol) == 0:
return None
mol = Chem.MolFromSmiles(smiles_or_mol)
if mol is None:
return None
try:
Chem.SanitizeMol(mol)
except ValueError:
return None
return mol
return smiles_or_mol
def mol2smiles(mol):
if mol is None:
return None
try:
Chem.SanitizeMol(mol)
except ValueError:
return None
return Chem.MolToSmiles(mol)
def check_valency(mol):
try:
# First attempt to sanitize with specific properties
Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES)
return True, None
except ValueError as e:
e = str(e)
p = e.find("#")
e_sub = e[p:]
atomid_valence = list(map(int, re.findall(r"\d+", e_sub)))
return False, atomid_valence
except Exception as e:
# print(f"An unexpected error occurred: {e}")
return False, []
##### connect fragements
def select_atom_with_available_valency(frag):
atoms = list(frag.GetAtoms())
random.shuffle(atoms)
for atom in atoms:
if atom.GetAtomicNum() > 1 and atom.GetImplicitValence() > 0:
return atom
return None
def select_atoms_with_available_valency(frag):
return [
atom
for atom in frag.GetAtoms()
if atom.GetAtomicNum() > 1 and atom.GetImplicitValence() > 0
]
def try_to_connect_fragments(combined_mol, frag, atom1, atom2):
# Make copies of the molecules to try the connection
trial_combined_mol = Chem.RWMol(combined_mol)
trial_frag = Chem.RWMol(frag)
# Add the new fragment to the combined molecule with new indices
new_indices = {
atom.GetIdx(): trial_combined_mol.AddAtom(atom)
for atom in trial_frag.GetAtoms()
}
# Add the bond between the suitable atoms from each fragment
trial_combined_mol.AddBond(
atom1.GetIdx(), new_indices[atom2.GetIdx()], Chem.BondType.SINGLE
)
# Adjust the hydrogen count of the connected atoms
for atom_idx in [atom1.GetIdx(), new_indices[atom2.GetIdx()]]:
atom = trial_combined_mol.GetAtomWithIdx(atom_idx)
num_h = atom.GetTotalNumHs()
atom.SetNumExplicitHs(max(0, num_h - 1))
# Add bonds for the new fragment
for bond in trial_frag.GetBonds():
trial_combined_mol.AddBond(
new_indices[bond.GetBeginAtomIdx()],
new_indices[bond.GetEndAtomIdx()],
bond.GetBondType(),
)
# Convert to a Mol object and try to sanitize it
new_mol = Chem.Mol(trial_combined_mol)
try:
Chem.SanitizeMol(new_mol)
return new_mol # Return the new valid molecule
except Chem.MolSanitizeException:
return None # If the molecule is not valid, return None
def connect_fragments(mol):
# Get the separate fragments
frags = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False)
if len(frags) < 2:
return mol
combined_mol = Chem.RWMol(frags[0])
for frag in frags[1:]:
# Select all atoms with available valency from both molecules
atoms1 = select_atoms_with_available_valency(combined_mol)
atoms2 = select_atoms_with_available_valency(frag)
# Try to connect using all combinations of available valency atoms
for atom1 in atoms1:
for atom2 in atoms2:
new_mol = try_to_connect_fragments(combined_mol, frag, atom1, atom2)
if new_mol is not None:
# If a valid connection is made, update the combined molecule and break
combined_mol = new_mol
break
else:
# Continue if the inner loop didn't break (no valid connection found for atom1)
continue
# Break if the inner loop did break (valid connection found)
break
else:
# If no valid connections could be made with any of the atoms, return None
return None
return combined_mol
#### connect fragements
|