File size: 19,340 Bytes
ae9909c | 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 | """
Corruption engine using atom map numbers for stable atom identification.
Each corrupt_* function returns (wrong_rw, raw_correction_with_wrong_rw_indices).
corrupt_molecule() assigns atom map nums to wrong_rw, translates indices β map_nums,
and returns (wrong_smiles, wrong_smiles_mapped, correction_with_maps).
wrong_smiles : clean SMILES without maps (for display / training input)
wrong_smiles_mapped : SMILES with :[n] map tags (for executor to locate atoms)
correction : operation params use atom_map/anchor_map/atom1_map/atom2_map
instead of raw atom_idx β these survive SMILES round-trips.
"""
import copy
import random
from rdkit import Chem
from rdkit.Chem import AllChem
from mol_ops import (
BOND_TYPE_MAP, BOND_TYPE_NAME, ELEM_TO_NUM, NUM_TO_ELEM,
FUNCTIONAL_GROUPS,
change_atom_element, add_atom, remove_atom, change_charge,
change_bond_order, add_bond, remove_bond,
add_functional_group, remove_functional_group,
flip_chirality, flip_ez,
validate_mol,
)
CORRUPTION_TYPES = [
"change_atom_element",
"add_atom",
"remove_atom",
"change_charge",
"change_bond_order",
"add_bond",
"remove_bond",
"add_functional_group",
"remove_functional_group",
"flip_chirality",
"flip_ez",
"move_substituent",
"swap_substituents",
]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _random_other_elem(current_elem):
candidates = [e for e in ("C", "N", "O", "S") if e != current_elem]
return random.choice(candidates)
def _has_free_valence(atom):
try:
return atom.GetNumImplicitHs() > 0
except Exception:
return False
def _assign_atom_maps(rw):
"""Assign map_num = idx+1 to every atom in rw (in-place)."""
for atom in rw.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx() + 1)
def _strip_atom_maps(rw):
"""Return a copy of rw with all atom maps removed."""
c = copy.deepcopy(rw)
for atom in c.GetAtoms():
atom.SetAtomMapNum(0)
return c
def _translate_correction(wrong_rw, raw):
"""
Translate a raw correction (atom_idx β map_num) for stable cross-SMILES use.
raw = {'type': ..., 'params': {atom_idx: X, ...}, 'description': ...}
Returns new correction dict with map_num-based params.
"""
params = {}
for k, v in raw["params"].items():
if k == "atom_idx":
params["atom_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "anchor_idx":
params["anchor_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "atom_idx1":
params["atom1_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "atom_idx2":
params["atom2_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "substituent_idx":
params["substituent_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "from_idx":
params["from_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "to_idx":
params["to_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "ring_idx1":
params["ring1_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
elif k == "ring_idx2":
params["ring2_map"] = wrong_rw.GetAtomWithIdx(v).GetAtomMapNum()
else:
params[k] = v
return {"type": raw["type"], "params": params, "description": raw["description"]}
# ---------------------------------------------------------------------------
# Individual corruption functions
# Each returns (wrong_rw, raw_correction) or None
# raw_correction uses atom indices in wrong_rw space
# ---------------------------------------------------------------------------
def corrupt_change_atom_element(mol):
rw = Chem.RWMol(mol)
atoms = [a for a in rw.GetAtoms()
if a.GetAtomicNum() > 1 and not a.GetIsAromatic()]
if not atoms:
return None
atom = random.choice(atoms)
idx = atom.GetIdx()
old_elem = NUM_TO_ELEM.get(atom.GetAtomicNum(), "C")
new_elem = _random_other_elem(old_elem)
result = change_atom_element(rw, atom_idx=idx, to_elem=new_elem)
if result is None:
return None
return result, {
"type": "change_atom_element",
"params": {"atom_idx": idx, "from_elem": new_elem, "to_elem": old_elem},
"description": f"Change atom {idx} from {new_elem} back to {old_elem}",
}
def corrupt_add_atom(mol):
rw = Chem.RWMol(mol)
atoms = [a for a in rw.GetAtoms() if _has_free_valence(a)]
if not atoms:
return None
anchor = random.choice(atoms)
new_elem = random.choice(["C", "N", "O"])
result = add_atom(rw, anchor_idx=anchor.GetIdx(), new_elem=new_elem)
if result is None:
return None
new_idx = result.GetNumAtoms() - 1
return result, {
"type": "remove_atom",
"params": {"atom_idx": new_idx, "elem": new_elem},
"description": f"Remove extra {new_elem} atom (added by corruption)",
}
def corrupt_remove_atom(mol):
rw = Chem.RWMol(mol)
terminals = [a for a in rw.GetAtoms()
if a.GetDegree() == 1 and not a.IsInRing() and a.GetAtomicNum() > 1]
if not terminals:
return None
atom = random.choice(terminals)
idx = atom.GetIdx()
elem = NUM_TO_ELEM.get(atom.GetAtomicNum(), "C")
neighbor = atom.GetNeighbors()[0]
anchor_idx = neighbor.GetIdx()
bond = rw.GetBondBetweenAtoms(idx, anchor_idx)
bond_type = BOND_TYPE_NAME.get(bond.GetBondType(), "SINGLE")
result = remove_atom(rw, atom_idx=idx)
if result is None:
return None
# Atoms after idx shift down by 1
adj_anchor = anchor_idx if anchor_idx < idx else anchor_idx - 1
return result, {
"type": "add_atom",
"params": {"anchor_idx": adj_anchor, "new_elem": elem, "bond_type": bond_type},
"description": f"Add missing {elem} atom back to anchor",
}
def corrupt_change_charge(mol):
rw = Chem.RWMol(mol)
# Only corrupt atoms that currently have charge 0 (reversible: 0βΒ±1, then Β±1β0 is safe)
candidates = [a for a in rw.GetAtoms()
if a.GetAtomicNum() in (7, 8) and not a.GetIsAromatic()
and a.GetFormalCharge() == 0 and a.GetNumImplicitHs() == 0]
if not candidates:
return None
atom = random.choice(candidates)
idx = atom.GetIdx()
old_charge = 0
new_charge = random.choice([-1, 1])
result = change_charge(rw, atom_idx=idx, to_charge=new_charge)
if result is None:
return None
return result, {
"type": "change_charge",
"params": {"atom_idx": idx, "from_charge": new_charge, "to_charge": old_charge},
"description": f"Change charge at atom back from {new_charge:+d} to {old_charge:+d}",
}
def corrupt_change_bond_order(mol):
rw = Chem.RWMol(mol)
bonds = [b for b in rw.GetBonds()
if b.GetBondType() in (Chem.BondType.SINGLE, Chem.BondType.DOUBLE)
and not b.GetIsAromatic()]
if not bonds:
return None
bond = random.choice(bonds)
idx1, idx2 = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
old_order = BOND_TYPE_NAME[bond.GetBondType()]
new_order = "DOUBLE" if old_order == "SINGLE" else "SINGLE"
result = change_bond_order(rw, atom_idx1=idx1, atom_idx2=idx2, to_order=new_order)
if result is None:
return None
return result, {
"type": "change_bond_order",
"params": {"atom_idx1": idx1, "atom_idx2": idx2,
"from_order": new_order, "to_order": old_order},
"description": f"Change bond ({idx1}-{idx2}) from {new_order} back to {old_order}",
}
def corrupt_add_bond(mol):
rw = Chem.RWMol(mol)
n = rw.GetNumAtoms()
if n < 4:
return None
pairs = [(i, j) for i in range(n) for j in range(i + 2, n)
if rw.GetBondBetweenAtoms(i, j) is None]
if not pairs:
return None
i, j = random.choice(pairs)
result = add_bond(rw, atom_idx1=i, atom_idx2=j, bond_type="SINGLE")
if result is None:
return None
return result, {
"type": "remove_bond",
"params": {"atom_idx1": i, "atom_idx2": j},
"description": f"Remove spurious bond between atoms {i} and {j}",
}
def corrupt_remove_bond(mol):
rw = Chem.RWMol(mol)
bonds = [b for b in rw.GetBonds() if not b.IsInRing()]
if not bonds:
return None
bond = random.choice(bonds)
idx1, idx2 = bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()
order = BOND_TYPE_NAME.get(bond.GetBondType(), "SINGLE")
result = remove_bond(rw, atom_idx1=idx1, atom_idx2=idx2)
if result is None:
return None
return result, {
"type": "add_bond",
"params": {"atom_idx1": idx1, "atom_idx2": idx2, "bond_type": order},
"description": f"Add back {order} bond between atoms {idx1} and {idx2}",
}
def corrupt_add_functional_group(mol):
rw = Chem.RWMol(mol)
atoms = [a for a in rw.GetAtoms() if a.GetAtomicNum() == 6]
if not atoms:
return None
anchor = random.choice(atoms)
group = random.choice(["OH", "NH2", "F", "Cl", "Br", "CH3"])
result = add_functional_group(rw, anchor_idx=anchor.GetIdx(), group_name=group)
if result is None:
return None
# anchor idx unchanged after adding group atoms at the end
return result, {
"type": "remove_functional_group",
"params": {"anchor_idx": anchor.GetIdx(), "group_name": group},
"description": f"Remove extra -{group} group",
}
def corrupt_remove_functional_group(mol):
rw = Chem.RWMol(mol)
for group in ("OH", "NH2", "F", "Cl", "Br", "CH3"):
for atom in rw.GetAtoms():
if atom.GetAtomicNum() != 6:
continue
test = Chem.RWMol(mol)
result, removed = remove_functional_group(test, atom.GetIdx(), group)
if result is None:
continue
removed_idx = removed[0]
anchor_in_mol = atom.GetIdx()
# After removing atom at removed_idx, anchor shifts if removed_idx < anchor
adj_anchor = anchor_in_mol if removed_idx > anchor_in_mol else anchor_in_mol - 1
return result, {
"type": "add_functional_group",
"params": {"anchor_idx": adj_anchor, "group_name": group},
"description": f"Add -{group} back to anchor atom",
}
return None
def corrupt_flip_chirality(mol):
rw = Chem.RWMol(mol)
Chem.AssignStereochemistry(rw, cleanIt=True, force=True)
chiral = [a for a in rw.GetAtoms()
if a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED]
if not chiral:
return None
atom = random.choice(chiral)
idx = atom.GetIdx()
result = flip_chirality(rw, atom_idx=idx)
if result is None:
return None
return result, {
"type": "flip_chirality",
"params": {"atom_idx": idx},
"description": f"Flip chirality back at atom {idx}",
}
def corrupt_flip_ez(mol):
"""SMILES-level; returns (wrong_smi, raw_correction) directly."""
smi = Chem.MolToSmiles(mol, isomericSmiles=True)
if "/" not in smi and "\\" not in smi:
return None
wrong_smi = flip_ez(smi)
if wrong_smi is None or wrong_smi == smi:
return None
return wrong_smi, {
"type": "flip_ez",
"params": {},
"description": "Flip E/Z configuration back",
}
def corrupt_move_substituent(mol):
"""
Move a non-ring substituent from one ring atom to a different ring atom
in the same ring (e.g. orthoβmeta shift on benzene).
Operates in KekulΓ© form to avoid aromatic bond issues.
Correction: MoveSubstituent back.
"""
rw = Chem.RWMol(mol)
try:
Chem.Kekulize(rw, clearAromaticFlags=True)
except Exception:
return None
ri = rw.GetRingInfo()
rings = [set(r) for r in ri.AtomRings() if len(r) >= 5]
if not rings:
return None
# Build all (from_idx, sub_idx, to_idx) triples and shuffle
triples = []
for ring in rings:
ring_list = list(ring)
for from_idx in ring_list:
atom = rw.GetAtomWithIdx(from_idx)
subs = [nb for nb in atom.GetNeighbors()
if nb.GetIdx() not in ring and nb.GetAtomicNum() > 1]
for sub in subs:
sub_idx = sub.GetIdx()
for to_idx in ring_list:
if to_idx != from_idx and rw.GetBondBetweenAtoms(to_idx, sub_idx) is None:
triples.append((from_idx, sub_idx, to_idx))
random.shuffle(triples)
for from_idx, sub_idx, to_idx in triples:
rw2 = Chem.RWMol(copy.deepcopy(rw))
rw2.RemoveBond(from_idx, sub_idx)
rw2.AddBond(to_idx, sub_idx, Chem.BondType.SINGLE)
if not validate_mol(rw2):
continue
# Check it actually changed the molecule
wrong_smi = Chem.MolToSmiles(rw2)
orig_smi = Chem.MolToSmiles(mol)
if wrong_smi == orig_smi:
continue
return rw2, {
"type": "move_substituent",
"params": {
"substituent_idx": sub_idx,
"from_idx": to_idx, # correction reverses: from=to, to=from
"to_idx": from_idx,
},
"description": f"Move substituent {sub_idx} back from ring atom {to_idx} to {from_idx}",
}
return None
def corrupt_swap_substituents(mol):
"""
Swap the non-ring substituents of two ring atoms in the same ring.
Operates in KekulΓ© form to avoid aromatic bond issues.
Correction: SwapSubstituents back (same action).
"""
rw = Chem.RWMol(mol)
try:
Chem.Kekulize(rw, clearAromaticFlags=True)
except Exception:
return None
ri = rw.GetRingInfo()
rings = [list(r) for r in ri.AtomRings() if len(r) >= 5]
if not rings:
return None
random.shuffle(rings)
for ring in rings:
ring_set = set(ring)
substituted = []
for idx in ring:
subs = [nb.GetIdx() for nb in rw.GetAtomWithIdx(idx).GetNeighbors()
if nb.GetIdx() not in ring_set and nb.GetAtomicNum() > 1]
if subs:
substituted.append((idx, subs))
if len(substituted) < 2:
continue
random.shuffle(substituted)
(idx1, subs1), (idx2, subs2) = substituted[0], substituted[1]
def bonds_to(center, sub_list):
return [(s, rw.GetBondBetweenAtoms(center, s).GetBondType()) for s in sub_list]
b1 = bonds_to(idx1, subs1)
b2 = bonds_to(idx2, subs2)
if any(rw.GetBondBetweenAtoms(idx2, s) is not None for s, _ in b1):
continue
if any(rw.GetBondBetweenAtoms(idx1, s) is not None for s, _ in b2):
continue
rw2 = Chem.RWMol(copy.deepcopy(rw))
for s, _ in b1:
rw2.RemoveBond(idx1, s)
for s, _ in b2:
rw2.RemoveBond(idx2, s)
for s, bt in b1:
rw2.AddBond(idx2, s, Chem.BondType.SINGLE)
for s, bt in b2:
rw2.AddBond(idx1, s, Chem.BondType.SINGLE)
if not validate_mol(rw2):
continue
return rw2, {
"type": "swap_substituents",
"params": {
"ring_idx1": idx1,
"ring_idx2": idx2,
},
"description": f"Swap substituents back between ring atoms {idx1} and {idx2}",
}
return None
CORRUPT_FUNCS = {
"change_atom_element": corrupt_change_atom_element,
"add_atom": corrupt_add_atom,
"remove_atom": corrupt_remove_atom,
"change_charge": corrupt_change_charge,
"change_bond_order": corrupt_change_bond_order,
"add_bond": corrupt_add_bond,
"remove_bond": corrupt_remove_bond,
"add_functional_group": corrupt_add_functional_group,
"remove_functional_group": corrupt_remove_functional_group,
"flip_chirality": corrupt_flip_chirality,
"flip_ez": corrupt_flip_ez,
"move_substituent": corrupt_move_substituent,
"swap_substituents": corrupt_swap_substituents,
}
# ---------------------------------------------------------------------------
# Main API
# ---------------------------------------------------------------------------
def corrupt_molecule(smiles, op_type=None, max_retries=20):
"""
Returns (wrong_smiles, wrong_smiles_mapped, correction) or None.
wrong_smiles β clean SMILES (no atom maps), the erroneous input
wrong_smiles_mapped β SMILES with :[n] atom map tags for executor use
correction β dict with type, params (map_num-based), description
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
for _ in range(max_retries):
chosen_type = op_type or random.choice(CORRUPTION_TYPES)
func = CORRUPT_FUNCS[chosen_type]
raw = func(mol)
if raw is None:
continue
# flip_ez is SMILES-level β handle separately
if chosen_type == "flip_ez":
wrong_smi, raw_correction = raw
if wrong_smi == smiles:
continue
wrong_mol = Chem.MolFromSmiles(wrong_smi)
if wrong_mol is None:
continue
wrong_rw = Chem.RWMol(wrong_mol)
_assign_atom_maps(wrong_rw)
wrong_smiles_mapped = Chem.MolToSmiles(wrong_rw)
correction = {"type": "flip_ez", "params": {},
"description": raw_correction["description"]}
return wrong_smi, wrong_smiles_mapped, correction
wrong_rw, raw_correction = raw
if not validate_mol(wrong_rw):
continue
# Assign atom map numbers to wrong_rw (map_num = idx + 1)
_assign_atom_maps(wrong_rw)
# Translate index-based params β map-num-based params
try:
correction = _translate_correction(wrong_rw, raw_correction)
except (IndexError, RuntimeError):
continue
# Generate clean wrong SMILES (no maps)
wrong_smiles = Chem.MolToSmiles(_strip_atom_maps(wrong_rw))
if wrong_smiles == smiles:
continue
wrong_smiles_mapped = Chem.MolToSmiles(wrong_rw)
# ββ Verify round-trip before accepting ββββββββββββββββββββββββββββββ
from action_executor import ActionExecutor as _AE
from validate_with_executor import translate_operation
try:
action = translate_operation(correction)
restored = _AE().execute(wrong_smiles_mapped, action)
except Exception:
continue
restored_mol = Chem.MolFromSmiles(restored) if restored else None
if restored_mol is None or Chem.MolToSmiles(restored_mol) != smiles:
continue # bad sample β discard and retry
return wrong_smiles, wrong_smiles_mapped, correction
return None
|