MacrocycleWizard 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1115 @@
1
+ """
2
+ Onion Module: Layered Scaffold Analysis
3
+
4
+ This module provides methods to extract various scaffold representations
5
+ from macrocyclic molecules, including ring SMILES, peripheral structures,
6
+ and Murcko scaffolds.
7
+ """
8
+ from tqdm import tqdm
9
+ from rdkit import Chem
10
+ from rdkit.Chem import AllChem
11
+ from rdkit.Chem.Scaffolds import MurckoScaffold
12
+ from rdkit.Chem import rdmolops
13
+ from ..base import MacrocycleCalculator
14
+
15
+
16
+ def _get_macrocycle_ring_mol_2(mol, strip=True):
17
+ """
18
+ Helper to identify the macrocycle ring and its atoms.
19
+
20
+ Stereochemistry is removed.
21
+ The molecule is kekulized before extracting the macrocycle ring so that
22
+ the macrocycle ring has a fixed single/double bond representation.
23
+ """
24
+ mol = Chem.Mol(mol)
25
+ Chem.RemoveStereochemistry(mol)
26
+
27
+ try:
28
+ Chem.Kekulize(mol, clearAromaticFlags=True)
29
+ except Exception:
30
+ pass
31
+
32
+ ri = mol.GetRingInfo()
33
+ if not ri.AtomRings():
34
+ return None, set()
35
+
36
+ atoms_ring = max(ri.AtomRings(), key=len)
37
+
38
+ if strip:
39
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(
40
+ mol,
41
+ atomsToUse=list(atoms_ring),
42
+ isomericSmiles=False,
43
+ kekuleSmiles=True,
44
+ canonical=True,
45
+ )
46
+ else:
47
+ query = Chem.MolFromSmarts('[!#1;!#7]~[R]*')
48
+ matches = mol.GetSubstructMatches(query)
49
+ atoms_to_use = list(atoms_ring) + [m[0] for m in matches]
50
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(
51
+ mol,
52
+ atomsToUse=atoms_to_use,
53
+ isomericSmiles=False,
54
+ kekuleSmiles=True,
55
+ canonical=True,
56
+ )
57
+
58
+ macrocycle_mol = Chem.MolFromSmiles(macrocycle_smiles)
59
+
60
+ if macrocycle_mol:
61
+ mol_frags = rdmolops.GetMolFrags(macrocycle_mol, asMols=True)
62
+ largest_mol = max(
63
+ mol_frags,
64
+ default=macrocycle_mol,
65
+ key=lambda m: m.GetNumAtoms()
66
+ )
67
+ return largest_mol, set(atoms_ring)
68
+
69
+ return None, set(atoms_ring)
70
+
71
+
72
+ class OnionAnalyzer(MacrocycleCalculator):
73
+ """
74
+ OnionAnalyzer: Extract and analyse molecule scaffolds layer by layer.
75
+ """
76
+
77
+ def _fallback_ring_smiles(self, mol_index):
78
+ """
79
+ Fallback to the precomputed first-layer macrocycle ring.
80
+ """
81
+ if hasattr(self, 'ring_mol_stripped') and mol_index < len(self.ring_mol_stripped):
82
+ return Chem.MolToSmiles(
83
+ self.ring_mol_stripped[mol_index],
84
+ isomericSmiles=False
85
+ )
86
+ return ""
87
+
88
+ def _prepare_layer_mol_and_ring(self, mol):
89
+ """
90
+ Prepare a molecule for all macrocycle layers.
91
+
92
+ This is the key consistency step.
93
+
94
+ All layer functions should use this molecule when generating
95
+ SMILES/SMARTS fragments so that the macrocycle ring internal
96
+ single/double bond pattern is the same across:
97
+
98
+ - macrocycle ring;
99
+ - peripheral layer;
100
+ - alpha atom layer;
101
+ - substituent layer;
102
+ - alpha SMARTS layers.
103
+
104
+ The molecule is copied, stereochemistry is removed, and aromatic
105
+ systems are kekulized once with clearAromaticFlags=True.
106
+ """
107
+ layer_mol = Chem.Mol(mol)
108
+ Chem.RemoveStereochemistry(layer_mol)
109
+
110
+ kekule_mol = Chem.Mol(layer_mol)
111
+ try:
112
+ Chem.Kekulize(kekule_mol, clearAromaticFlags=True)
113
+ layer_mol = kekule_mol
114
+ except Exception:
115
+ # If kekulization fails, keep the stereo-stripped molecule.
116
+ # Downstream MolFragmentToSmiles(..., kekuleSmiles=True) will
117
+ # still attempt a kekulized representation.
118
+ pass
119
+
120
+ ri = layer_mol.GetRingInfo()
121
+ if not ri.AtomRings():
122
+ return layer_mol, set()
123
+
124
+ atoms_ring = set(max(ri.AtomRings(), key=len))
125
+ return layer_mol, atoms_ring
126
+
127
+ def _is_peripheral_atom(self, atom, ring_atom_idx, atoms_ring):
128
+ """
129
+ Same peripheral definition used by get_macrocycle_peripheral_smiles().
130
+
131
+ A peripheral atom is:
132
+ - outside the macrocycle ring;
133
+ - not hydrogen;
134
+ - not itself in any ring;
135
+ - attached only to the macrocycle ring atom and hydrogens.
136
+ """
137
+ atom_idx = atom.GetIdx()
138
+
139
+ if atom_idx in atoms_ring:
140
+ return False
141
+ if atom.GetAtomicNum() == 1:
142
+ return False
143
+ if atom.IsInRing():
144
+ return False
145
+
146
+ return all(
147
+ nb.GetAtomicNum() == 1 or nb.GetIdx() == ring_atom_idx
148
+ for nb in atom.GetNeighbors()
149
+ )
150
+
151
+ def _force_ring_to_target_bonds_single(self, mol, atoms_ring, target_atoms):
152
+ """
153
+ Return a copy of mol where bonds between macrocycle ring atoms and
154
+ target atoms are forced to simple single bonds.
155
+
156
+ This does not modify macrocycle ring internal bonds.
157
+ """
158
+ rw_mol = Chem.RWMol(mol)
159
+
160
+ for bond in rw_mol.GetBonds():
161
+ begin_idx = bond.GetBeginAtomIdx()
162
+ end_idx = bond.GetEndAtomIdx()
163
+
164
+ begin_is_ring = begin_idx in atoms_ring
165
+ end_is_ring = end_idx in atoms_ring
166
+ begin_is_target = begin_idx in target_atoms
167
+ end_is_target = end_idx in target_atoms
168
+
169
+ is_ring_target_bond = (
170
+ begin_is_ring and end_is_target
171
+ ) or (
172
+ end_is_ring and begin_is_target
173
+ )
174
+
175
+ if is_ring_target_bond:
176
+ bond.SetBondType(Chem.rdchem.BondType.SINGLE)
177
+ bond.SetIsAromatic(False)
178
+ bond.SetStereo(Chem.rdchem.BondStereo.STEREONONE)
179
+
180
+ new_mol = rw_mol.GetMol()
181
+ new_mol.UpdatePropertyCache(strict=False)
182
+ return new_mol
183
+
184
+ def _alpha_atom_smarts(self, atom, ring_info):
185
+ """
186
+ Only included aromatic information and hybridisation
187
+
188
+ """
189
+ symbol = atom.GetSymbol()
190
+ if atom.GetIsAromatic():
191
+ symbol = symbol.lower()
192
+
193
+ #deg = atom.GetDegree()
194
+ #num_hs = atom.GetTotalNumHs()
195
+ #
196
+ #ring_sizes = [
197
+ # len(ring)
198
+ # for ring in ring_info.AtomRings()
199
+ # if atom.GetIdx() in ring
200
+ #]
201
+ #ring_str = "".join(f"&r{size}" for size in sorted(ring_sizes))
202
+
203
+ hyb = atom.GetHybridization()
204
+ hyb_map = {
205
+ Chem.HybridizationType.SP: "&^1",
206
+ Chem.HybridizationType.SP2: "&^2",
207
+ Chem.HybridizationType.SP3: "&^3",
208
+ Chem.HybridizationType.SP3D: "&^4",
209
+ Chem.HybridizationType.SP3D2: "&^5",
210
+ }
211
+ hyb_str = hyb_map.get(hyb, "")
212
+
213
+ return f"[{symbol}{hyb_str}]"
214
+
215
+ @staticmethod
216
+ def _layer_bond_symbol(bond):
217
+ """
218
+ Bond token for a bond of the shared kekulized layer molecule.
219
+
220
+ This mirrors the token RDKit's SMILES/SMARTS writer would emit on its
221
+ own, so that passing an explicit ``bondSymbols`` list (needed to force
222
+ the macrocycle-ring-to-alpha-atom bonds to '-') does not erase the
223
+ macrocycle ring double/triple bond information.
224
+
225
+ Single bonds stay implicit, exactly like the default writer.
226
+ """
227
+ bond_type = bond.GetBondType()
228
+
229
+ if bond_type == Chem.BondType.DOUBLE:
230
+ return "="
231
+ if bond_type == Chem.BondType.TRIPLE:
232
+ return "#"
233
+ if bond_type == Chem.BondType.AROMATIC:
234
+ return ":"
235
+
236
+ return ""
237
+
238
+ def get_macrocycle_ring_smiles(self):
239
+ """
240
+ Macrocycle Ring SMILES, first layer.
241
+
242
+ This remains the reference layer.
243
+ """
244
+ ring_smiles = []
245
+
246
+ for mol in tqdm(self.ring_mol_stripped):
247
+ ring_smiles.append(
248
+ Chem.MolToSmiles(
249
+ mol,
250
+ isomericSmiles=False
251
+ )
252
+ )
253
+
254
+ return ring_smiles
255
+
256
+ def get_macrocycle_peripheral_smiles(self):
257
+ """
258
+ Macrocycle Peripheral SMILES.
259
+
260
+ Rule:
261
+ - keep the macrocycle ring;
262
+ - keep only single-heavy-atom peripheral substituents;
263
+ - preserve the macrocycle ring internal single/double bond pattern
264
+ from the shared kekulized layer molecule.
265
+ """
266
+ peripheral_smiles_list = []
267
+
268
+ for i, mol in enumerate(tqdm(self.mols)):
269
+ layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
270
+
271
+ if not atoms_ring:
272
+ peripheral_smiles_list.append(self._fallback_ring_smiles(i))
273
+ continue
274
+
275
+ peripheral_atoms = set()
276
+
277
+ for ring_atom_idx in atoms_ring:
278
+ ring_atom = layer_mol.GetAtomWithIdx(ring_atom_idx)
279
+
280
+ for neighbor in ring_atom.GetNeighbors():
281
+ ni = neighbor.GetIdx()
282
+
283
+ if self._is_peripheral_atom(
284
+ atom=neighbor,
285
+ ring_atom_idx=ring_atom_idx,
286
+ atoms_ring=atoms_ring
287
+ ):
288
+ peripheral_atoms.add(ni)
289
+
290
+ atoms_to_use = atoms_ring | peripheral_atoms
291
+
292
+ try:
293
+ peripheral_smiles = Chem.MolFragmentToSmiles(
294
+ layer_mol,
295
+ atomsToUse=list(atoms_to_use),
296
+ isomericSmiles=False,
297
+ kekuleSmiles=True,
298
+ canonical=True,
299
+ )
300
+ peripheral_smiles_list.append(peripheral_smiles)
301
+
302
+ except Exception:
303
+ peripheral_smiles_list.append(self._fallback_ring_smiles(i))
304
+
305
+ return peripheral_smiles_list
306
+
307
+ def get_macrocycle_alpha_atoms_smiles(self):
308
+ """
309
+ Macrocycle Alpha Atoms SMILES.
310
+
311
+ Output contains:
312
+ 1. the macrocycle ring itself;
313
+ 2. all first heavy atoms directly attached to the macrocycle ring.
314
+
315
+ Rules:
316
+ - macrocycle ring internal single/double bonds are preserved from the
317
+ shared kekulized layer molecule;
318
+ - every macrocycle-ring-to-alpha-atom bond is forced to a simple
319
+ single bond;
320
+ - bonds between alpha atoms are not shown, even when those atoms are
321
+ part of the same bridge ring on the macrocycle;
322
+ - alpha atom chemical environment is deliberately ignored.
323
+ """
324
+ alpha_smiles_list = []
325
+
326
+ for i, mol in enumerate(tqdm(self.mols)):
327
+ layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
328
+
329
+ if not atoms_ring:
330
+ alpha_smiles_list.append(self._fallback_ring_smiles(i))
331
+ continue
332
+
333
+ alpha_atoms = set()
334
+
335
+ for ring_atom_idx in atoms_ring:
336
+ ring_atom = layer_mol.GetAtomWithIdx(ring_atom_idx)
337
+
338
+ for neighbor in ring_atom.GetNeighbors():
339
+ neighbor_idx = neighbor.GetIdx()
340
+
341
+ if neighbor_idx in atoms_ring:
342
+ continue
343
+ if neighbor.GetAtomicNum() == 1:
344
+ continue
345
+
346
+ # Keep every first directly attached heavy atom.
347
+ # This includes aromatic atoms, ketone oxygen atoms,
348
+ # atoms connected by multiple bonds, and atoms that belong
349
+ # to another ring, including fused aromatic systems.
350
+ alpha_atoms.add(neighbor_idx)
351
+
352
+ atoms_to_use = atoms_ring | alpha_atoms
353
+
354
+ try:
355
+ alpha_mol = self._force_ring_to_target_bonds_single(
356
+ mol=layer_mol,
357
+ atoms_ring=atoms_ring,
358
+ target_atoms=alpha_atoms
359
+ )
360
+
361
+ bonds_to_use = []
362
+ for bond in alpha_mol.GetBonds():
363
+ begin_idx = bond.GetBeginAtomIdx()
364
+ end_idx = bond.GetEndAtomIdx()
365
+
366
+ if begin_idx not in atoms_to_use or end_idx not in atoms_to_use:
367
+ continue
368
+
369
+ # Alpha atoms are intentionally rendered as isolated first
370
+ # atoms attached to the macrocycle. This avoids showing
371
+ # bridge-ring bonds between selected alpha atoms.
372
+ if begin_idx in alpha_atoms and end_idx in alpha_atoms:
373
+ continue
374
+
375
+ bonds_to_use.append(bond.GetIdx())
376
+
377
+ alpha_smiles = Chem.MolFragmentToSmiles(
378
+ alpha_mol,
379
+ atomsToUse=list(atoms_to_use),
380
+ bondsToUse=bonds_to_use,
381
+ isomericSmiles=False,
382
+ kekuleSmiles=True,
383
+ canonical=True,
384
+ )
385
+
386
+ alpha_smiles_list.append(alpha_smiles)
387
+
388
+ except Exception:
389
+ alpha_smiles_list.append(self._fallback_ring_smiles(i))
390
+
391
+ return alpha_smiles_list
392
+
393
+ # def get_macrocycle_alpha_atoms_smiles(self):
394
+ # """
395
+ # Macrocycle Alpha Atoms SMILES.
396
+ #
397
+ # Output contains:
398
+ # 1. the macrocycle ring itself;
399
+ # 2. all first heavy atoms directly attached to the macrocycle ring.
400
+ #
401
+ # Rules:
402
+ # - macrocycle ring internal single/double bonds are preserved from the
403
+ # shared kekulized layer molecule;
404
+ # - every first heavy atom directly attached to the macrocycle ring is kept;
405
+ # - the bond between the macrocycle ring and each alpha atom is explicitly
406
+ # shown as '-', '=', '#', or ':' according to the original molecule.
407
+ # """
408
+ # def ring_alpha_bond_symbol(original_bond):
409
+ # """
410
+ # Convert the original ring-alpha bond type into an explicit
411
+ # SMILES/SMARTS-like bond symbol.
412
+ # """
413
+ # if original_bond is None:
414
+ # return ""
415
+ #
416
+ # bond_type = original_bond.GetBondType()
417
+ #
418
+ # if bond_type == Chem.rdchem.BondType.SINGLE:
419
+ # return "-"
420
+ # if bond_type == Chem.rdchem.BondType.DOUBLE:
421
+ # return "="
422
+ # if bond_type == Chem.rdchem.BondType.TRIPLE:
423
+ # return "#"
424
+ # if bond_type == Chem.rdchem.BondType.AROMATIC:
425
+ # return ":"
426
+ #
427
+ # # Fallback for uncommon bond types.
428
+ # return ""
429
+ #
430
+ # alpha_smiles_list = []
431
+ #
432
+ # for i, mol in enumerate(tqdm(self.mols)):
433
+ # # original_mol keeps the original bond type information for
434
+ # # ring-alpha connections, especially aromatic ':' bonds.
435
+ # original_mol = Chem.Mol(mol)
436
+ # Chem.RemoveStereochemistry(original_mol)
437
+ #
438
+ # # layer_mol is the shared kekulized molecule used for rendering the
439
+ # # macrocycle ring consistently across all layers.
440
+ # layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
441
+ #
442
+ # if not atoms_ring:
443
+ # alpha_smiles_list.append(self._fallback_ring_smiles(i))
444
+ # continue
445
+ #
446
+ # alpha_atoms = set()
447
+ #
448
+ # for ring_atom_idx in atoms_ring:
449
+ # ring_atom = layer_mol.GetAtomWithIdx(ring_atom_idx)
450
+ #
451
+ # for neighbor in ring_atom.GetNeighbors():
452
+ # neighbor_idx = neighbor.GetIdx()
453
+ #
454
+ # if neighbor_idx in atoms_ring:
455
+ # continue
456
+ # if neighbor.GetAtomicNum() == 1:
457
+ # continue
458
+ #
459
+ # # Keep every first directly attached heavy atom.
460
+ # #
461
+ # # This includes:
462
+ # # - atoms attached by single bonds;
463
+ # # - atoms attached by double bonds, e.g. carbonyl oxygen;
464
+ # # - atoms attached by triple bonds;
465
+ # # - aromatic atoms;
466
+ # # - atoms belonging to another ring;
467
+ # # - fused-ring alpha atoms.
468
+ # alpha_atoms.add(neighbor_idx)
469
+ #
470
+ # atoms_to_use = atoms_ring | alpha_atoms
471
+ #
472
+ # try:
473
+ # # Do not change the molecule's bond orders here.
474
+ # # The macrocycle ring internal bond pattern remains the same as
475
+ # # layer_mol, while ring-alpha bond symbols are controlled only
476
+ # # by bondSymbols below.
477
+ # alpha_mol = Chem.Mol(layer_mol)
478
+ #
479
+ # bond_symbols = [""] * alpha_mol.GetNumBonds()
480
+ #
481
+ # for bond in alpha_mol.GetBonds():
482
+ # begin_idx = bond.GetBeginAtomIdx()
483
+ # end_idx = bond.GetEndAtomIdx()
484
+ #
485
+ # if begin_idx not in atoms_to_use or end_idx not in atoms_to_use:
486
+ # continue
487
+ #
488
+ # begin_is_ring = begin_idx in atoms_ring
489
+ # end_is_ring = end_idx in atoms_ring
490
+ # begin_is_alpha = begin_idx in alpha_atoms
491
+ # end_is_alpha = end_idx in alpha_atoms
492
+ #
493
+ # is_ring_alpha_bond = (
494
+ # begin_is_ring and end_is_alpha
495
+ # ) or (
496
+ # end_is_ring and begin_is_alpha
497
+ # )
498
+ #
499
+ # if is_ring_alpha_bond:
500
+ # # Read the original bond type from the original molecule,
501
+ # # not from the kekulized rendering molecule.
502
+ # original_bond = original_mol.GetBondBetweenAtoms(
503
+ # begin_idx,
504
+ # end_idx
505
+ # )
506
+ #
507
+ # bond_symbols[bond.GetIdx()] = ring_alpha_bond_symbol(
508
+ # original_bond
509
+ # )
510
+ #
511
+ # alpha_smiles = Chem.MolFragmentToSmiles(
512
+ # alpha_mol,
513
+ # atomsToUse=list(atoms_to_use),
514
+ # bondSymbols=bond_symbols,
515
+ # isomericSmiles=False,
516
+ # kekuleSmiles=True,
517
+ # canonical=True,
518
+ # allBondsExplicit=False,
519
+ # )
520
+ #
521
+ # alpha_smiles_list.append(alpha_smiles)
522
+ #
523
+ # except Exception:
524
+ # alpha_smiles_list.append(self._fallback_ring_smiles(i))
525
+ #
526
+ # return alpha_smiles_list
527
+
528
+ def get_macrocycle_alpha_atoms_smarts(self):
529
+ """
530
+ Detailed SMARTS pattern for the macrocycle ring plus alpha atoms.
531
+
532
+ The atom SMARTS tokens preserve rich atom information from the original
533
+ molecule, but the bond framework is generated from the same kekulized
534
+ layer molecule used by the SMILES layers.
535
+
536
+ Rules:
537
+ - macrocycle ring internal single/double bond pattern is consistent
538
+ with the other layers;
539
+ - macrocycle-ring-to-alpha-atom bonds are forced to single bonds.
540
+ """
541
+ smarts_list = []
542
+
543
+ for i, mol in enumerate(tqdm(self.mols)):
544
+ query_mol = Chem.Mol(mol)
545
+ Chem.RemoveStereochemistry(query_mol)
546
+
547
+ query_ri = query_mol.GetRingInfo()
548
+ if not query_ri.AtomRings():
549
+ smarts_list.append(self._fallback_ring_smiles(i))
550
+ continue
551
+
552
+ layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
553
+
554
+ if not atoms_ring:
555
+ smarts_list.append(self._fallback_ring_smiles(i))
556
+ continue
557
+
558
+ alpha_atoms = set()
559
+
560
+ for ring_atom_idx in atoms_ring:
561
+ ring_atom = query_mol.GetAtomWithIdx(ring_atom_idx)
562
+
563
+ for neighbor in ring_atom.GetNeighbors():
564
+ ni = neighbor.GetIdx()
565
+
566
+ if ni in atoms_ring:
567
+ continue
568
+ if neighbor.GetAtomicNum() == 1:
569
+ continue
570
+
571
+ alpha_atoms.add(ni)
572
+
573
+ atoms_to_use = atoms_ring | alpha_atoms
574
+
575
+ if not atoms_to_use:
576
+ smarts_list.append(self._fallback_ring_smiles(i))
577
+ continue
578
+
579
+ try:
580
+ smarts_mol = self._force_ring_to_target_bonds_single(
581
+ mol=layer_mol,
582
+ atoms_ring=atoms_ring,
583
+ target_atoms=alpha_atoms
584
+ )
585
+
586
+ custom_symbols = [""] * smarts_mol.GetNumAtoms()
587
+
588
+ for idx in atoms_to_use:
589
+ atom = query_mol.GetAtomWithIdx(idx)
590
+ custom_symbols[idx] = self._alpha_atom_smarts(
591
+ atom=atom,
592
+ ring_info=query_ri
593
+ )
594
+
595
+ bonds_to_use = []
596
+ for bond in smarts_mol.GetBonds():
597
+ b_idx = bond.GetBeginAtomIdx()
598
+ e_idx = bond.GetEndAtomIdx()
599
+ if b_idx in atoms_to_use and e_idx in atoms_to_use:
600
+ if b_idx in alpha_atoms and e_idx in alpha_atoms:
601
+ continue
602
+ bonds_to_use.append(bond.GetIdx())
603
+
604
+ fragment_smarts = Chem.MolFragmentToSmiles(
605
+ smarts_mol,
606
+ atomsToUse=list(atoms_to_use),
607
+ bondsToUse=bonds_to_use,
608
+ atomSymbols=custom_symbols,
609
+ allBondsExplicit=True,
610
+ isomericSmiles=False,
611
+ kekuleSmiles=True,
612
+ canonical=True,
613
+ )
614
+
615
+ smarts_list.append(fragment_smarts)
616
+
617
+ except Exception:
618
+ smarts_list.append(self._fallback_ring_smiles(i))
619
+
620
+ return smarts_list
621
+
622
+ def get_macrocycle_alpha_atoms_smarts_simple(self):
623
+ """
624
+ Hybrid SMARTS pattern for the macrocycle ring plus alpha atoms.
625
+
626
+ Rules:
627
+ - macrocycle ring atoms are emitted as ordinary SMILES-like atom tokens;
628
+ - alpha atoms are emitted as detailed SMARTS atom tokens;
629
+ - macrocycle ring internal single/double bond pattern is consistent
630
+ with the SMILES layers;
631
+ - macrocycle-ring-to-alpha-atom bonds are always explicit single bonds.
632
+ """
633
+ smarts_list = []
634
+
635
+ for i, mol in enumerate(tqdm(self.mols)):
636
+ query_mol = Chem.Mol(mol)
637
+ Chem.RemoveStereochemistry(query_mol)
638
+
639
+ query_ri = query_mol.GetRingInfo()
640
+ if not query_ri.AtomRings():
641
+ smarts_list.append(self._fallback_ring_smiles(i))
642
+ continue
643
+
644
+ layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
645
+
646
+ if not atoms_ring:
647
+ smarts_list.append(self._fallback_ring_smiles(i))
648
+ continue
649
+
650
+ alpha_atoms = set()
651
+
652
+ for ring_atom_idx in atoms_ring:
653
+ ring_atom = query_mol.GetAtomWithIdx(ring_atom_idx)
654
+
655
+ for neighbor in ring_atom.GetNeighbors():
656
+ ni = neighbor.GetIdx()
657
+
658
+ if ni in atoms_ring:
659
+ continue
660
+ if neighbor.GetAtomicNum() == 1:
661
+ continue
662
+
663
+ alpha_atoms.add(ni)
664
+
665
+ atoms_to_use = atoms_ring | alpha_atoms
666
+
667
+ if not atoms_to_use:
668
+ smarts_list.append(self._fallback_ring_smiles(i))
669
+ continue
670
+
671
+ try:
672
+ smarts_mol = self._force_ring_to_target_bonds_single(
673
+ mol=layer_mol,
674
+ atoms_ring=atoms_ring,
675
+ target_atoms=alpha_atoms
676
+ )
677
+
678
+ atom_symbols = [""] * smarts_mol.GetNumAtoms()
679
+
680
+ for idx in atoms_to_use:
681
+ if idx in alpha_atoms:
682
+ atom_symbols[idx] = self._alpha_atom_smarts(
683
+ atom=query_mol.GetAtomWithIdx(idx),
684
+ ring_info=query_ri
685
+ )
686
+ else:
687
+ # Ring atoms are kept as normal SMILES atoms from the
688
+ # shared kekulized layer molecule.
689
+ atom = smarts_mol.GetAtomWithIdx(idx)
690
+ atom_symbols[idx] = atom.GetSymbol()
691
+
692
+ # ``bondSymbols`` replaces RDKit's own bond tokens instead of
693
+ # only overriding the ones that are set, so every bond needs
694
+ # its regular token here. Otherwise the empty default would
695
+ # silently drop the macrocycle ring double bonds (they would be
696
+ # written as nothing instead of "=").
697
+ bond_symbols = [""] * smarts_mol.GetNumBonds()
698
+
699
+ for bond in smarts_mol.GetBonds():
700
+ begin = bond.GetBeginAtomIdx()
701
+ end = bond.GetEndAtomIdx()
702
+
703
+ bond_symbols[bond.GetIdx()] = self._layer_bond_symbol(bond)
704
+
705
+ if begin not in atoms_to_use or end not in atoms_to_use:
706
+ continue
707
+
708
+ begin_is_ring = begin in atoms_ring
709
+ end_is_ring = end in atoms_ring
710
+ begin_is_alpha = begin in alpha_atoms
711
+ end_is_alpha = end in alpha_atoms
712
+
713
+ is_ring_alpha_bond = (
714
+ begin_is_ring and end_is_alpha
715
+ ) or (
716
+ end_is_ring and begin_is_alpha
717
+ )
718
+
719
+ if is_ring_alpha_bond:
720
+ # Alpha bond is always shown as a simple single bond.
721
+ bond_symbols[bond.GetIdx()] = "-"
722
+
723
+ bonds_to_use = []
724
+ for bond in smarts_mol.GetBonds():
725
+ b_idx = bond.GetBeginAtomIdx()
726
+ e_idx = bond.GetEndAtomIdx()
727
+ if b_idx in atoms_to_use and e_idx in atoms_to_use:
728
+ if b_idx in alpha_atoms and e_idx in alpha_atoms:
729
+ continue
730
+ bonds_to_use.append(bond.GetIdx())
731
+
732
+ hybrid_smarts = Chem.MolFragmentToSmiles(
733
+ smarts_mol,
734
+ atomsToUse=list(atoms_to_use),
735
+ bondsToUse=bonds_to_use,
736
+ atomSymbols=atom_symbols,
737
+ bondSymbols=bond_symbols,
738
+ isomericSmiles=False,
739
+ kekuleSmiles=True,
740
+ canonical=True,
741
+ allBondsExplicit=False,
742
+ )
743
+
744
+ smarts_list.append(hybrid_smarts)
745
+
746
+ except Exception:
747
+ smarts_list.append(self._fallback_ring_smiles(i))
748
+
749
+ return smarts_list
750
+
751
+ def get_macrocycle_substituent_smiles(self):
752
+ """
753
+ Macrocycle Substituent SMILES without stereochemistry.
754
+
755
+ Rule:
756
+ - keep the macrocycle ring;
757
+ - define peripheral atoms using the same rule as
758
+ get_macrocycle_peripheral_smiles();
759
+ - any non-ring heavy-atom substituent attached to the macrocycle ring
760
+ that is not peripheral is counted as substituent;
761
+ - preserve the macrocycle ring internal single/double bond pattern
762
+ from the shared kekulized layer molecule.
763
+ """
764
+ substituent_smiles_list = []
765
+
766
+ for i, mol in enumerate(tqdm(self.mols)):
767
+ layer_mol, atoms_ring = self._prepare_layer_mol_and_ring(mol)
768
+
769
+ if not atoms_ring:
770
+ substituent_smiles_list.append(self._fallback_ring_smiles(i))
771
+ continue
772
+
773
+ peripheral_atoms = set()
774
+ substituent_start_atoms = set()
775
+
776
+ for ring_atom_idx in atoms_ring:
777
+ ring_atom = layer_mol.GetAtomWithIdx(ring_atom_idx)
778
+
779
+ for neighbor in ring_atom.GetNeighbors():
780
+ ni = neighbor.GetIdx()
781
+
782
+ if ni in atoms_ring:
783
+ continue
784
+ if neighbor.GetAtomicNum() == 1:
785
+ continue
786
+
787
+ if self._is_peripheral_atom(
788
+ atom=neighbor,
789
+ ring_atom_idx=ring_atom_idx,
790
+ atoms_ring=atoms_ring
791
+ ):
792
+ peripheral_atoms.add(ni)
793
+ else:
794
+ substituent_start_atoms.add(ni)
795
+
796
+ def collect_substituent_component(start_idx):
797
+ """
798
+ Collect all heavy atoms outside the macrocycle ring,
799
+ excluding peripheral atoms.
800
+ """
801
+ component = set()
802
+ stack = [start_idx]
803
+
804
+ while stack:
805
+ atom_idx = stack.pop()
806
+
807
+ if atom_idx in component:
808
+ continue
809
+ if atom_idx in atoms_ring:
810
+ continue
811
+ if atom_idx in peripheral_atoms:
812
+ continue
813
+
814
+ atom = layer_mol.GetAtomWithIdx(atom_idx)
815
+
816
+ if atom.GetAtomicNum() == 1:
817
+ continue
818
+
819
+ component.add(atom_idx)
820
+
821
+ for nb in atom.GetNeighbors():
822
+ nb_idx = nb.GetIdx()
823
+
824
+ if nb_idx in atoms_ring:
825
+ continue
826
+ if nb_idx in peripheral_atoms:
827
+ continue
828
+ if nb.GetAtomicNum() == 1:
829
+ continue
830
+
831
+ stack.append(nb_idx)
832
+
833
+ return component
834
+
835
+ substituent_atoms = set()
836
+
837
+ for start_idx in substituent_start_atoms:
838
+ substituent_atoms.update(
839
+ collect_substituent_component(start_idx)
840
+ )
841
+
842
+ atoms_to_use = atoms_ring | substituent_atoms
843
+
844
+ try:
845
+ substituent_smiles = Chem.MolFragmentToSmiles(
846
+ layer_mol,
847
+ atomsToUse=list(atoms_to_use),
848
+ isomericSmiles=False,
849
+ kekuleSmiles=True,
850
+ canonical=True,
851
+ )
852
+
853
+ substituent_smiles_list.append(substituent_smiles)
854
+
855
+ except Exception:
856
+ substituent_smiles_list.append(self._fallback_ring_smiles(i))
857
+
858
+ return substituent_smiles_list
859
+
860
+ # ======================================================================
861
+ # Attached Groups
862
+ # ======================================================================
863
+ #
864
+ # def get_attached_groups(self):
865
+ # """
866
+ # Attached Groups: One SMILES per molecule.
867
+ # Output contains the macrocycle ring and ALL correctly identified AGs.
868
+ # """
869
+ # out = []
870
+ # for mol in tqdm(self.mols):
871
+ # # Step 1: Remove stereochemistry to ensure a flat structure
872
+ # temp_mol = Chem.Mol(mol)
873
+ # Chem.RemoveStereochemistry(temp_mol)
874
+ #
875
+ # # Step 2: Extract macrocycle atoms
876
+ # try:
877
+ # _, mac_atoms = _get_macrocycle_ring_mol_2(temp_mol)
878
+ # except Exception:
879
+ # out.append("")
880
+ # continue
881
+ #
882
+ # if not mac_atoms:
883
+ # out.append("")
884
+ # continue
885
+ #
886
+ # mac_set = set(mac_atoms)
887
+ #
888
+ # # Step 3: Find all alpha atoms (heavy atoms bonded to macrocycle, not in it)
889
+ # alpha_atoms = set()
890
+ # for m_idx in mac_atoms:
891
+ # for nb in temp_mol.GetAtomWithIdx(m_idx).GetNeighbors():
892
+ # ni = nb.GetIdx()
893
+ # if ni in mac_set or nb.GetAtomicNum() == 1:
894
+ # continue
895
+ # alpha_atoms.add(ni)
896
+ #
897
+ # # Step 4: Aggregate all valid AG atoms
898
+ # total_atoms_to_use = set(mac_set)
899
+ # for alpha_idx in sorted(alpha_atoms):
900
+ # ag = self._compute_ag_atoms(temp_mol, alpha_idx, mac_set)
901
+ # if ag:
902
+ # total_atoms_to_use |= set(ag)
903
+ #
904
+ # # Step 5: Convert the combined fragment to SMILES
905
+ # try:
906
+ # combined_smiles = Chem.MolFragmentToSmiles(
907
+ # temp_mol,
908
+ # atomsToUse=list(total_atoms_to_use),
909
+ # canonical=True,
910
+ # isomericSmiles=False
911
+ # )
912
+ # out.append(combined_smiles)
913
+ # except Exception:
914
+ # out.append("")
915
+ #
916
+ # return out
917
+ #
918
+ # @staticmethod
919
+ # def _compute_ag_atoms(mol, alpha_idx, mac_set):
920
+ # """
921
+ # Calculates atoms for an Attached Group starting from alpha_idx.
922
+ # Implements Rules 1-4.
923
+ # """
924
+ # alpha = mol.GetAtomWithIdx(alpha_idx)
925
+ #
926
+ # # Rule 3: alpha is part of a ring system
927
+ # if alpha.IsInRing():
928
+ # return OnionAnalyzer._ring_system_atoms(mol, alpha_idx, mac_set)
929
+ #
930
+ # # Rule 1 / 2 / 4: Build alpha's Unit
931
+ # unit = OnionAnalyzer._build_unit(mol, alpha_idx, mac_set)
932
+ #
933
+ # # Find external heavy-atom neighbours of the Unit (excluding macrocycle)
934
+ # external = set()
935
+ # for u in unit:
936
+ # for nb in mol.GetAtomWithIdx(u).GetNeighbors():
937
+ # ni = nb.GetIdx()
938
+ # if ni in unit or ni in mac_set or nb.GetAtomicNum() == 1:
939
+ # continue
940
+ # external.add(ni)
941
+ #
942
+ # # Rule 1(iii) - Check for non-ring heteroatoms
943
+ # # If any external atom is a non-ring heteroatom, AG is only the Unit.
944
+ # ring_ext = {i for i in external if mol.GetAtomWithIdx(i).IsInRing()}
945
+ # non_ring_ext = external - ring_ext
946
+ #
947
+ # # Checking Rule 1(iii): any non-ring heteroatom in external?
948
+ # has_non_ring_heteroatom = any(
949
+ # mol.GetAtomWithIdx(i).GetAtomicNum() not in (1, 6)
950
+ # for i in non_ring_ext
951
+ # )
952
+ #
953
+ # if has_non_ring_heteroatom:
954
+ # return set(unit)
955
+ #
956
+ # # Rule 1(ii): only connected to rings
957
+ # if ring_ext and not non_ring_ext:
958
+ # ag = set(unit)
959
+ # for ri in ring_ext:
960
+ # ag |= OnionAnalyzer._ring_system_atoms(mol, ri, mac_set)
961
+ # return ag
962
+ #
963
+ # # Rule 1(i): connected to non-ring carbon, or nothing (terminal)
964
+ # return set(unit)
965
+ #
966
+ # @staticmethod
967
+ # def _build_unit(mol, start_idx, mac_set):
968
+ # """Build Unit for a non-ring starting atom via Rule A and Rule B."""
969
+ # unit = {start_idx}
970
+ # frontier = {start_idx}
971
+ # while frontier:
972
+ # new_f = set()
973
+ # for idx in frontier:
974
+ # a = mol.GetAtomWithIdx(idx)
975
+ # for bond in a.GetBonds():
976
+ # if bond.IsInRing(): continue
977
+ # oi = bond.GetOtherAtomIdx(idx)
978
+ # if oi in unit or oi in mac_set: continue
979
+ # o = mol.GetAtomWithIdx(oi)
980
+ # if o.GetAtomicNum() == 1: continue
981
+ # bt = bond.GetBondType()
982
+ #
983
+ # # Rule A: double/triple bonds
984
+ # if bt in (Chem.BondType.DOUBLE, Chem.BondType.TRIPLE):
985
+ # unit.add(oi)
986
+ # new_f.add(oi)
987
+ # continue
988
+ # # Rule B: heteroatom <-> sp3 carbon single bond
989
+ # if bt == Chem.BondType.SINGLE:
990
+ # a_het = a.GetAtomicNum() not in (1, 6)
991
+ # o_het = o.GetAtomicNum() not in (1, 6)
992
+ # a_sp3c = (a.GetAtomicNum() == 6 and
993
+ # a.GetHybridization() == Chem.HybridizationType.SP3 and
994
+ # not a.IsInRing())
995
+ # o_sp3c = (o.GetAtomicNum() == 6 and
996
+ # o.GetHybridization() == Chem.HybridizationType.SP3 and
997
+ # not o.IsInRing())
998
+ # if (a_het and o_sp3c) or (a_sp3c and o_het):
999
+ # unit.add(oi)
1000
+ # new_f.add(oi)
1001
+ # frontier = new_f
1002
+ # return unit
1003
+ #
1004
+ # @staticmethod
1005
+ # def _ring_system_atoms(mol, start_idx, mac_set):
1006
+ # """Extract connected ring system atoms."""
1007
+ # ri = mol.GetRingInfo()
1008
+ # rings = [set(r) for r in ri.AtomRings()]
1009
+ # pool = [r for r in rings if r != mac_set]
1010
+ # seeds = [r for r in pool if start_idx in r]
1011
+ # if not seeds: return {start_idx}
1012
+ # atoms, visited = set(), set()
1013
+ # queue = list(seeds)
1014
+ # while queue:
1015
+ # r = queue.pop(0)
1016
+ # key = tuple(sorted(r))
1017
+ # if key in visited: continue
1018
+ # visited.add(key)
1019
+ # atoms |= r
1020
+ # for other in pool:
1021
+ # ok = tuple(sorted(other))
1022
+ # if ok in visited: continue
1023
+ # if (r & other) - mac_set:
1024
+ # queue.append(other)
1025
+ # atoms -= mac_set
1026
+ # return atoms
1027
+ #
1028
+ # def get_macrocycle_ring_smiles_nonstripped(self):
1029
+ # """
1030
+ # Macrocycle Ring SMILES (Non-stripped)
1031
+ #
1032
+ # Extract the non-stripped macrocycle ring SMILES for each molecule.
1033
+ # """
1034
+ # ring_smiles_nonstripped = []
1035
+ # for mol in tqdm(self.ring_mol):
1036
+ # macrocycle_ring_smiles_nonstripped = Chem.MolToSmiles(mol)
1037
+ # ring_smiles_nonstripped.append(macrocycle_ring_smiles_nonstripped)
1038
+ # return ring_smiles_nonstripped
1039
+ #
1040
+ # def get_murcko_scaffold_smiles(self):
1041
+ # """
1042
+ # Murcko Scaffold SMILES
1043
+ #
1044
+ # Get Murcko scaffold SMILES for each molecule.
1045
+ # The Murcko scaffold is the core structure obtained by removing
1046
+ # side chains while retaining all ring systems and linkers.
1047
+ # """
1048
+ # murcko_scaffold_smiles = []
1049
+ # for mol in tqdm(self.mols):
1050
+ # # Skip invalid molecules
1051
+ # if mol is None:
1052
+ # murcko_scaffold_smiles.append(None)
1053
+ # continue
1054
+ # # Get scaffold directly from RDKit
1055
+ # scaffold = MurckoScaffold.GetScaffoldForMol(mol)
1056
+ # scaffold_smiles = Chem.MolToSmiles(scaffold)
1057
+ # murcko_scaffold_smiles.append(scaffold_smiles)
1058
+ # return murcko_scaffold_smiles
1059
+ #
1060
+ # def get_generic_murcko_scaffold_smiles(self):
1061
+ # """
1062
+ # Generic Murcko Scaffold SMILES
1063
+ #
1064
+ # Get generic Murcko scaffold SMILES for each molecule.
1065
+ # The generic scaffold replaces all atoms with carbon and all
1066
+ # bonds with single bonds, representing only the topological skeleton.
1067
+ # """
1068
+ # generic_murcko_scaffold_smiles = []
1069
+ # for mol in tqdm(self.mols):
1070
+ # # Skip invalid molecules
1071
+ # if mol is None:
1072
+ # generic_murcko_scaffold_smiles.append(None)
1073
+ # continue
1074
+ # # Get scaffold and make it generic
1075
+ # scaffold = MurckoScaffold.GetScaffoldForMol(mol)
1076
+ # generic_scaffold = MurckoScaffold.MakeScaffoldGeneric(scaffold)
1077
+ # generic_scaffold_smiles = Chem.MolToSmiles(generic_scaffold)
1078
+ # generic_murcko_scaffold_smiles.append(generic_scaffold_smiles)
1079
+ # return generic_murcko_scaffold_smiles
1080
+
1081
+ def get_all_onion_layers(self):
1082
+ """
1083
+ Get all onion layer representations in a single DataFrame
1084
+
1085
+ Returns:
1086
+ pandas.DataFrame: DataFrame containing all onion layer representations
1087
+ from the core ring to peripheral structures and Murcko scaffolds
1088
+ """
1089
+ import pandas as pd
1090
+
1091
+ # Get all onion layers
1092
+ ring_smiles = self.get_macrocycle_ring_smiles()
1093
+ peripheral_smiles = self.get_macrocycle_peripheral_smiles()
1094
+ substituent_smiles = self.get_macrocycle_substituent_smiles()
1095
+ alpha_atoms_smarts = self.get_macrocycle_alpha_atoms_smarts()
1096
+ alpha_atoms_smarts_simple = self.get_macrocycle_alpha_atoms_smarts_simple()
1097
+ alpha_atoms_smiles = self.get_macrocycle_alpha_atoms_smiles()
1098
+
1099
+ #attached_smiles = self.get_attached_groups()
1100
+ #ring_smiles_nonstripped = self.get_macrocycle_ring_smiles_nonstripped()
1101
+ #murcko_scaffolds = self.get_murcko_scaffold_smiles()
1102
+ #generic_scaffolds = self.get_generic_murcko_scaffold_smiles()
1103
+
1104
+ # Create DataFrame with original SMILES and all onion layers
1105
+ onion_df = pd.DataFrame({
1106
+ 'SMILES': self.smiles,
1107
+ 'Macrocycle_Ring_SMILES': ring_smiles,
1108
+ 'Macrocycle_Peripheral_SMILES': peripheral_smiles,
1109
+ 'Macrocycle_Substituent_SMILES': substituent_smiles,
1110
+ 'Macrocycle_Alpha_Atoms_SMILES': alpha_atoms_smiles,
1111
+ 'Macrocycle_Alpha_Atoms_SMARTS': alpha_atoms_smarts,
1112
+ 'Macrocycle_Alpha_Atoms_SMARTS_Simple': alpha_atoms_smarts_simple,
1113
+ })
1114
+
1115
+ return onion_df