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,11 @@
1
+ # MacrocycleWizard/Onion/__init__.py
2
+ """
3
+ Onion Module: Layered Scaffold Analysis
4
+
5
+ This module provides onion-layer analysis tools for macrocyclic molecules,
6
+ including various SMILES representations and Murcko scaffold extraction.
7
+ """
8
+
9
+ from .Onion import OnionAnalyzer
10
+
11
+ __all__ = ['OnionAnalyzer']
@@ -0,0 +1,219 @@
1
+ """MacrocycleWizard/__init__.py"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .MolD.base import MacrocycleCalculator
6
+
7
+ # Import all groups
8
+ from .MolD.basic.GroupA import GroupA
9
+ from .MolD.specific.GroupB import GroupB
10
+ from .MolD.specific.GroupC import GroupC
11
+ from .MolD.specific.GroupD import GroupD
12
+ from .MolD.specific.GroupE import GroupE
13
+ from .MolD.specific.GroupF import GroupF
14
+ from .MolD.specific.GroupG import GroupG
15
+ from .MolD.general.GroupH import GroupH
16
+ from .MolD.general.GroupI import GroupI
17
+ from .MolD.general.GroupJ import GroupJ
18
+ from .MolD.general.GroupK import GroupK
19
+ from .Onion.Onion import OnionAnalyzer
20
+ from .CreateFig.FigGenerator import MoleculeVisualizer
21
+
22
+ class MacrocycleWizard:
23
+ """Main interface class for managing all descriptor calculations"""
24
+
25
+ def __init__(self, smiles_list):
26
+ """
27
+ Initialize MacrocycleWizard
28
+
29
+ Parameters:
30
+ -----------
31
+ smiles_list : list
32
+ List of SMILES strings
33
+ """
34
+ self.smiles_list = smiles_list
35
+
36
+ # Initialize all groups as None (lazy loading)
37
+ self._groupa = None
38
+ self._groupb = None
39
+ self._groupc = None
40
+ self._groupd = None
41
+ self._groupe = None
42
+ self._groupf = None
43
+ self._groupg = None
44
+ self._grouph = None
45
+ self._groupi = None
46
+ self._groupj = None
47
+ self._groupk = None
48
+ self._onion = None
49
+ self._CreateFig = None
50
+
51
+
52
+ # ==================== Basic Group ====================
53
+ @property
54
+ def groupa(self):
55
+ """Lazy initialization of GroupA"""
56
+ if self._groupa is None:
57
+ self._groupa = GroupA(self.smiles_list)
58
+ return self._groupa
59
+
60
+ @property
61
+ def BasicMolD(self):
62
+ """BasicMolD is an alias for groupa"""
63
+ return self.groupa
64
+
65
+ # ==================== Specific Groups ====================
66
+ @property
67
+ def groupb(self):
68
+ """Lazy initialization of GroupB"""
69
+ if self._groupb is None:
70
+ self._groupb = GroupB(self.smiles_list)
71
+ return self._groupb
72
+
73
+ @property
74
+ def RingStrct(self):
75
+ """RingStrct is an alias for groupb"""
76
+ return self.groupb
77
+
78
+ @property
79
+ def groupc(self):
80
+ """Lazy initialization of GroupC"""
81
+ if self._groupc is None:
82
+ self._groupc = GroupC(self.smiles_list)
83
+ return self._groupc
84
+
85
+ @property
86
+ def RingHetero(self):
87
+ """RingHetero is an alias for groupc"""
88
+ return self.groupc
89
+
90
+ @property
91
+ def groupd(self):
92
+ """Lazy initialization of GroupD"""
93
+ if self._groupd is None:
94
+ self._groupd = GroupD(self.smiles_list)
95
+ return self._groupd
96
+
97
+ @property
98
+ def FragStrct(self):
99
+ """FragStrct is an alias for groupd"""
100
+ return self.groupd
101
+
102
+ @property
103
+ def groupe(self):
104
+ """Lazy initialization of GroupE"""
105
+ if self._groupe is None:
106
+ self._groupe = GroupE(self.smiles_list)
107
+ return self._groupe
108
+
109
+ @property
110
+ def FragHetro(self):
111
+ """FragHetro is an alias for groupe"""
112
+ return self.groupe
113
+
114
+ @property
115
+ def groupf(self):
116
+ """Lazy initialization of GroupF"""
117
+ if self._groupf is None:
118
+ self._groupf = GroupF(self.smiles_list)
119
+ return self._groupf
120
+
121
+ @property
122
+ def RingInter(self):
123
+ """RingInter is an alias for groupf"""
124
+ return self.groupf
125
+
126
+ @property
127
+ def groupg(self):
128
+ """Lazy initialization of GroupG"""
129
+ if self._groupg is None:
130
+ self._groupg = GroupG(self.smiles_list)
131
+ return self._groupg
132
+
133
+ @property
134
+ def RingTopoConn(self):
135
+ """RingTopoConn is an alias for groupg"""
136
+ return self.groupg
137
+
138
+ # ==================== General Groups ====================
139
+ @property
140
+ def grouph(self):
141
+ """Lazy initialization of GroupH"""
142
+ if self._grouph is None:
143
+ self._grouph = GroupH(self.smiles_list)
144
+ return self._grouph
145
+
146
+ @property
147
+ def OverallStrct(self):
148
+ """OverallStrct is an alias for grouph"""
149
+ return self.grouph
150
+
151
+ @property
152
+ def groupi(self):
153
+ """Lazy initialization of GroupI"""
154
+ if self._groupi is None:
155
+ self._groupi = GroupI(self.smiles_list)
156
+ return self._groupi
157
+
158
+ @property
159
+ def OverallHetero(self):
160
+ """OverallHetero is an alias for groupi"""
161
+ return self.groupi
162
+
163
+ @property
164
+ def groupj(self):
165
+ """Lazy initialization of GroupJ"""
166
+ if self._groupj is None:
167
+ self._groupj = GroupJ(self.smiles_list)
168
+ return self._groupj
169
+
170
+ @property
171
+ def FunctionalGroup(self):
172
+ """FunctionalGroup is an alias for groupj"""
173
+ return self.groupj
174
+
175
+ @property
176
+ def groupk(self):
177
+ """Lazy initialization of GroupK"""
178
+ if self._groupk is None:
179
+ self._groupk = GroupK(self.smiles_list)
180
+ return self._groupk
181
+
182
+ @property
183
+ def TopoConn(self):
184
+ """TopoConn is an alias for groupk"""
185
+ return self.groupk
186
+
187
+ # ==================== Onion Module ====================
188
+
189
+ @property
190
+ def onion(self):
191
+ """Lazy initialization of OnionAnalyzer"""
192
+ if self._onion is None:
193
+ self._onion = OnionAnalyzer(self.smiles_list)
194
+ return self._onion
195
+
196
+ @property
197
+ def Onion(self):
198
+ """Onion is an alias for onion"""
199
+ return self.onion
200
+ # ==================== CreateFig Module ====================
201
+
202
+ @property
203
+ def CreateFig(self):
204
+ if self._CreateFig is None:
205
+ self._CreateFig = MoleculeVisualizer(self.smiles_list)
206
+ return self._CreateFig
207
+
208
+
209
+ __all__ = [
210
+ 'MacrocycleWizard',
211
+ 'MacrocycleCalculator',
212
+
213
+ # All group classes
214
+ 'GroupA', 'GroupB', 'GroupC', 'GroupD', 'GroupE', 'GroupF', 'GroupG',
215
+ 'GroupH', 'GroupI', 'GroupJ', 'GroupK',
216
+
217
+ 'OnionAnalyzer',
218
+ 'MoleculeVisualizer',
219
+ ]
@@ -0,0 +1,467 @@
1
+ """MacrocycleWizard/Base.py"""
2
+ import os
3
+ import sys
4
+ import glob
5
+ import io
6
+ import subprocess
7
+ import multiprocessing
8
+ from itertools import chain
9
+ # Third-party imports
10
+ import numpy as np
11
+ import pandas as pd
12
+ from tqdm import tqdm
13
+ from rdkit import Chem, DataStructs, rdBase, RDLogger
14
+ from rdkit.Chem import (
15
+ Draw, PandasTools, AllChem, rdDepictor, rdMolDescriptors,
16
+ rdFMCS, rdmolops, Descriptors, FragmentOnBonds
17
+ )
18
+
19
+ from rdkit.Chem.Draw import rdMolDraw2D
20
+ from rdkit.Chem.Lipinski import HeavyAtomCount, NumHAcceptors, NumHDonors
21
+ from rdkit.Chem.Descriptors import ExactMolWt, TPSA
22
+ from rdkit.Chem.Crippen import MolLogP
23
+ from rdkit.Chem.rdMolDescriptors import (
24
+ CalcNumRotatableBonds, CalcKappa1, CalcKappa2,
25
+ CalcNumHeteroatoms, CalcFractionCSP3
26
+ )
27
+ from rdkit.Chem.Scaffolds import MurckoScaffold
28
+ from rdkit.Chem.FilterCatalog import FilterCatalog, FilterCatalogParams
29
+ from molvs import standardize_smiles
30
+ from PyBioMed.PyMolecule import topology,connectivity,molproperty
31
+ import networkx as nx
32
+ import warnings
33
+ warnings.filterwarnings("ignore", category=UserWarning, module="rdkit")
34
+ RDLogger.DisableLog('rdApp.*')
35
+
36
+
37
+
38
+ # Std the SMILES
39
+ def standardise(smiles):
40
+ std_smiles = standardize_smiles(smiles)
41
+ return standardize_smiles (smiles)
42
+
43
+ # Auxiliary Functions
44
+
45
+ ## Get Macrocycle's Ring
46
+ def _get_macrocycle_ring_mol(mol, strip=False):
47
+ if mol is None:
48
+ return None
49
+ mol = Chem.Mol(mol) # Make a copy
50
+ Chem.RemoveStereochemistry(mol)
51
+ Chem.Kekulize(mol, clearAromaticFlags=True)
52
+ ri = mol.GetRingInfo()
53
+ atom_rings = ri.AtomRings()
54
+ if not atom_rings:
55
+ return None
56
+ atoms_ring = max(atom_rings, key=len)
57
+ if strip:
58
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(mol, atomsToUse=list(atoms_ring))
59
+ else:
60
+ query = Chem.MolFromSmarts('[!#1;!#7]~[R]*')
61
+ matches = mol.GetSubstructMatches(query)
62
+ atoms_to_use = list(atoms_ring) + [m[0] for m in matches]
63
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(mol, atomsToUse=atoms_to_use)
64
+ macrocycle_mol = Chem.MolFromSmiles(macrocycle_smiles)
65
+ if macrocycle_mol is None:
66
+ return None
67
+ # In some cases, the macrocycle fragment may be disconnected due to the presence of substituents.
68
+ # We need to ensure we get the largest connected component as the macrocycle ring.
69
+ mol_frags = rdmolops.GetMolFrags(macrocycle_mol, asMols=True)
70
+ largest_mol = max(mol_frags, default=macrocycle_mol, key=lambda m: m.GetNumAtoms())
71
+ return largest_mol
72
+
73
+ def _get_macrocycle_ring_mol_2(mol, strip=True):
74
+ if mol is None:
75
+ return None, ()
76
+ mol = Chem.Mol(mol)
77
+ Chem.RemoveStereochemistry(mol)
78
+ Chem.Kekulize(mol, clearAromaticFlags=True)
79
+ ri = mol.GetRingInfo()
80
+ atom_rings = ri.AtomRings()
81
+ if not atom_rings:
82
+ return None, ()
83
+ atoms_ring = max(atom_rings, key=len)
84
+
85
+ if strip:
86
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(mol, atomsToUse=list(atoms_ring))
87
+ else:
88
+ query = Chem.MolFromSmarts('[!#1;!#7]~[R]*')
89
+ matches = mol.GetSubstructMatches(query)
90
+ atoms_to_use = list(atoms_ring) + [m[0] for m in matches]
91
+ macrocycle_smiles = AllChem.MolFragmentToSmiles(mol, atomsToUse=atoms_to_use)
92
+
93
+ macrocycle_mol = Chem.MolFromSmiles(macrocycle_smiles)
94
+ if macrocycle_mol is None:
95
+ return None, ()
96
+ mol_frags = rdmolops.GetMolFrags(macrocycle_mol, asMols=True)
97
+ largest_mol = max(mol_frags, default=macrocycle_mol, key=lambda m: m.GetNumAtoms())
98
+ return largest_mol, atoms_ring # Return both
99
+
100
+ def _get_R_fragment_from_macrocycle(mol):
101
+ R_fragments = []
102
+ if mol is None:
103
+ return R_fragments
104
+ macrocycle_mol, macrocycle_atoms = _get_macrocycle_ring_mol_2(mol)
105
+ if not macrocycle_atoms:
106
+ return R_fragments
107
+ remaining_atoms = [a.GetIdx() for a in mol.GetAtoms() if a.GetIdx() not in macrocycle_atoms]
108
+
109
+ if remaining_atoms:
110
+ fragment_smi = AllChem.MolFragmentToSmiles(
111
+ mol,
112
+ atomsToUse=remaining_atoms,
113
+ bondsToUse=[b.GetIdx() for b in mol.GetBonds()],
114
+ isomericSmiles=True,
115
+ kekuleSmiles=True
116
+ )
117
+
118
+ for smi in fragment_smi.split('.'):
119
+ try:
120
+ cleaned = standardize_smiles(smi)
121
+ except Exception:
122
+ cleaned = smi
123
+ if cleaned:
124
+ R_fragments.append(cleaned)
125
+ #print(cleaned)
126
+
127
+ return R_fragments
128
+
129
+
130
+ def _get_macrocycle_ring_size(mol):
131
+ if mol is None:
132
+ return 0
133
+ atom_rings = mol.GetRingInfo().AtomRings()
134
+ if not atom_rings:
135
+ return 0
136
+ return len(max(atom_rings, key=len))
137
+
138
+ def _get_heavy_atom_count(mol):
139
+ if mol is None:
140
+ return 0
141
+ heavy_atom_count = mol.GetNumHeavyAtoms()
142
+ return heavy_atom_count
143
+
144
+
145
+ def _get_macrocycle_spiro_atom_count(mol):
146
+
147
+ _, macrocycle_atoms = _get_macrocycle_ring_mol_2(mol)
148
+ macrocycle_atoms_set = set(macrocycle_atoms)
149
+ ri = mol.GetRingInfo()
150
+ rings = ri.AtomRings()
151
+
152
+ # Check macrocycle spiro
153
+ spiro_count = 0
154
+ for atom_idx in macrocycle_atoms:
155
+ rings_with_atom = [ring for ring in rings if atom_idx in ring]
156
+
157
+ if len(rings_with_atom) < 2:
158
+ continue
159
+ is_spiro = False
160
+ for i, ring1 in enumerate(rings_with_atom):
161
+ for ring2 in rings_with_atom[i+1:]:
162
+ shared_atoms = set(ring1).intersection(set(ring2))
163
+ if len(shared_atoms) == 1 and atom_idx in shared_atoms:
164
+ is_spiro = True
165
+ break
166
+ if is_spiro:
167
+ break
168
+ if is_spiro:
169
+ spiro_count += 1
170
+ return spiro_count
171
+
172
+ def _get_macrocycle_fused_bond_count(mol):
173
+ _, macrocycle_atoms = _get_macrocycle_ring_mol_2(mol)
174
+ macrocycle_atoms_set = set(macrocycle_atoms)
175
+ macrocycle_bonds = set()
176
+ for i in range(len(macrocycle_atoms)):
177
+ atom1 = macrocycle_atoms[i]
178
+ atom2 = macrocycle_atoms[(i+1) % len(macrocycle_atoms)]
179
+ bond = mol.GetBondBetweenAtoms(atom1, atom2)
180
+ if bond:
181
+ macrocycle_bonds.add(bond.GetIdx())
182
+ counted_fused_bonds = set()
183
+
184
+ ri = mol.GetRingInfo()
185
+ rings = ri.AtomRings()
186
+
187
+ for ring in rings:
188
+ if set(ring) == macrocycle_atoms_set:
189
+ continue
190
+ shared_atoms = set(ring).intersection(macrocycle_atoms_set)
191
+
192
+ if len(shared_atoms) == 2:
193
+ shared_atoms_list = list(shared_atoms)
194
+ bond = mol.GetBondBetweenAtoms(shared_atoms_list[0], shared_atoms_list[1])
195
+ if bond and bond.GetIdx() in macrocycle_bonds:
196
+ counted_fused_bonds.add(bond.GetIdx())
197
+
198
+ return len(counted_fused_bonds)
199
+
200
+ def _get_macrocycle_bridge_rings_count(mol):
201
+ chem_rings = _get_chemically_relevant_rings(mol)
202
+ if not chem_rings:
203
+ return 0
204
+ main_ring = max(chem_rings, key=len)
205
+ main_ring_atoms = set(main_ring)
206
+ bridge_rings = []
207
+ for ring in chem_rings:
208
+ if ring == main_ring:
209
+ continue
210
+ ring_atoms = set(ring)
211
+ common_atoms = ring_atoms.intersection(main_ring_atoms)
212
+ if len(common_atoms) >= 3:
213
+ bridge_rings.append(ring)
214
+ continue
215
+ if len(common_atoms) == 2:
216
+ common_list = list(common_atoms)
217
+ is_adjacent = False
218
+
219
+ for bond in mol.GetBonds():
220
+ begin_idx = bond.GetBeginAtomIdx()
221
+ end_idx = bond.GetEndAtomIdx()
222
+ if begin_idx in common_atoms and end_idx in common_atoms:
223
+ is_adjacent = True
224
+ break
225
+
226
+ if not is_adjacent:
227
+ bridge_rings.append(ring)
228
+
229
+ return len(bridge_rings)
230
+
231
+ def _get_chemically_relevant_rings(mol):
232
+ #sssr = Chem.GetSSSR(mol)
233
+ sssr = mol.GetRingInfo().AtomRings()
234
+ chem_rings = []
235
+ covered_bonds = set()
236
+
237
+ for ring in sssr:
238
+ ring_atoms = list(ring)
239
+ is_aromatic = True
240
+ for atom_idx in ring_atoms:
241
+ if not mol.GetAtomWithIdx(atom_idx).GetIsAromatic():
242
+ is_aromatic = False
243
+ break
244
+
245
+ if is_aromatic:
246
+ ring_bonds = set()
247
+ for bond in mol.GetBonds():
248
+ begin_idx = bond.GetBeginAtomIdx()
249
+ end_idx = bond.GetEndAtomIdx()
250
+ if begin_idx in ring_atoms and end_idx in ring_atoms:
251
+ ring_bonds.add(bond.GetIdx())
252
+ chem_rings.append(ring)
253
+ covered_bonds.update(ring_bonds)
254
+
255
+ for ring in sssr:
256
+ ring_atoms = list(ring)
257
+ if ring in chem_rings:
258
+ continue
259
+
260
+ ring_bonds = set()
261
+ for bond in mol.GetBonds():
262
+ begin_idx = bond.GetBeginAtomIdx()
263
+ end_idx = bond.GetEndAtomIdx()
264
+ if begin_idx in ring_atoms and end_idx in ring_atoms:
265
+ ring_bonds.add(bond.GetIdx())
266
+ if not ring_bonds.issubset(covered_bonds):
267
+ chem_rings.append(ring)
268
+ covered_bonds.update(ring_bonds)
269
+
270
+ return chem_rings
271
+
272
+ def _identify_bridge_rings(mol, chem_rings):
273
+ if not chem_rings:
274
+ return []
275
+
276
+
277
+ main_ring = max(chem_rings, key=len)
278
+ main_ring_atoms = set(main_ring)
279
+
280
+ # Label bridge rings
281
+ bridge_rings = []
282
+
283
+ for ring in chem_rings:
284
+ if ring == main_ring:
285
+ continue
286
+
287
+ ring_atoms = set(ring)
288
+ common_atoms = ring_atoms.intersection(main_ring_atoms)
289
+
290
+
291
+ if len(common_atoms) >= 3:
292
+ bridge_rings.append(ring)
293
+ continue
294
+
295
+
296
+ if len(common_atoms) == 2:
297
+ common_list = list(common_atoms)
298
+ is_adjacent = False
299
+
300
+
301
+ for bond in mol.GetBonds():
302
+ begin_idx = bond.GetBeginAtomIdx()
303
+ end_idx = bond.GetEndAtomIdx()
304
+ if (begin_idx in common_atoms and end_idx in common_atoms):
305
+ is_adjacent = True
306
+ break
307
+
308
+ if not is_adjacent:
309
+ bridge_rings.append(ring)
310
+
311
+ return bridge_rings
312
+
313
+
314
+ def _count_bridge_atoms_in_macrocycle(mol, macrocycle_atoms, bridge_rings):
315
+ bridge_atoms_in_macrocycle = set()
316
+ bridge_head_atoms = set()
317
+
318
+ for ring in bridge_rings:
319
+ ring_atoms = set(ring)
320
+ shared = ring_atoms.intersection(macrocycle_atoms)
321
+ outside = ring_atoms - macrocycle_atoms
322
+ bridge_atoms_in_macrocycle.update(shared)
323
+ # Bridgehead atoms are shared atoms directly bonded to non-macrocycle atoms of the bridge ring
324
+ for atom_idx in shared:
325
+ atom = mol.GetAtomWithIdx(atom_idx)
326
+ if any(nb.GetIdx() in outside for nb in atom.GetNeighbors()):
327
+ bridge_head_atoms.add(atom_idx)
328
+
329
+ return bridge_atoms_in_macrocycle, bridge_head_atoms
330
+
331
+ def _get_macrocycle_bridge_atoms_count(mol):
332
+ chem_rings = _get_chemically_relevant_rings(mol)
333
+
334
+ if not chem_rings:
335
+ return 0
336
+
337
+ # Assume the largest ring is the macrocycle
338
+ macrocycle = max(chem_rings, key=len)
339
+ macrocycle_atoms = set(macrocycle)
340
+
341
+ # Identify bridge rings
342
+ bridge_rings = _identify_bridge_rings(mol, chem_rings)
343
+
344
+ # Count bridge atoms in the macrocycle
345
+ bridge_atoms_in_macro, _ = _count_bridge_atoms_in_macrocycle(mol, macrocycle_atoms, bridge_rings)
346
+
347
+ return len(bridge_atoms_in_macro)
348
+
349
+ def _calculate_pair_spacing_for_bridged_rings(mol, connection_atoms, macrocycle_atoms):
350
+ """
351
+ Calculate distances (Pair_Spacing) between substituted atoms on the macrocycle,
352
+ using a graph representation to handle bridged structures
353
+
354
+ Note⚠️:The definition of Pair_Spacing is not same as (Viarengo-Baker et al.,2021) in that paper,
355
+ the detour(the longest distance) are also consider. For example, in a 6-member ring, if 1,3 Sub
356
+ the distance is both 1 and 3
357
+
358
+ """
359
+
360
+
361
+ # Extract macrocycle atoms connected to substituents
362
+ # If a macrocycle atom connects to multiple substituents, only use the first one
363
+ connection_ring_atoms = []
364
+ seen_ring_atoms = set()
365
+
366
+ for _, ring_atom_idx in connection_atoms:
367
+ if ring_atom_idx not in seen_ring_atoms:
368
+ connection_ring_atoms.append(ring_atom_idx)
369
+ seen_ring_atoms.add(ring_atom_idx)
370
+
371
+ # Create graph structure for the macrocycle
372
+ G = nx.Graph()
373
+
374
+ # Add all macrocycle nodes
375
+ for atom_idx in macrocycle_atoms:
376
+ G.add_node(atom_idx)
377
+
378
+ # Add all macrocycle edges
379
+ for atom_idx in macrocycle_atoms:
380
+ atom = mol.GetAtomWithIdx(atom_idx)
381
+ for neighbor in atom.GetNeighbors():
382
+ neighbor_idx = neighbor.GetIdx()
383
+ if neighbor_idx in macrocycle_atoms:
384
+ G.add_edge(atom_idx, neighbor_idx)
385
+
386
+ # Dictionary to store Pair_Spacing values
387
+ pair_spacings = {}
388
+
389
+ # Calculate Pair_Spacing for each pair of substituted atoms
390
+ n = len(connection_ring_atoms)
391
+ for i in range(n):
392
+ for j in range(i+1, n):
393
+ atom1 = connection_ring_atoms[i]
394
+ atom2 = connection_ring_atoms[j]
395
+
396
+ # Use NetworkX to calculate shortest path
397
+ if nx.has_path(G, atom1, atom2):
398
+ shortest_path = nx.shortest_path(G, source=atom1, target=atom2)
399
+
400
+ # Pair_Spacing = path length - 2
401
+ pair_spacing = len(shortest_path) - 1 - 1 # First -1 for endpoints, second -1 as required
402
+
403
+ # Store result
404
+ pair_spacings[(atom1, atom2)] = pair_spacing
405
+ else:
406
+ # If no path exists, atoms are not on the same ring
407
+ pair_spacings[(atom1, atom2)] = float('inf')
408
+
409
+ return pair_spacings
410
+
411
+
412
+ class MacrocycleCalculator:
413
+ # 类级别变量,用于存储预计算结果
414
+ _cache = {}
415
+ _initialized = False
416
+
417
+ def __init__(self, list_of_smiles):
418
+ cache_key = f"{list_of_smiles}"
419
+
420
+ if cache_key not in MacrocycleCalculator._cache:
421
+ print("Pre-calculating (only once)...\n")
422
+ self.smiles = list_of_smiles
423
+ self.mols = [Chem.MolFromSmiles(smi) for smi in self.smiles]
424
+ self.ring_mol = [_get_macrocycle_ring_mol(mol, strip=False) for mol in tqdm(self.mols)]
425
+ self.ring_mol_stripped = [_get_macrocycle_ring_mol(mol, strip=True) for mol in tqdm(self.mols)]
426
+ self.ring_size = [mol.GetNumBonds() if mol is not None else 0 for mol in tqdm(self.ring_mol_stripped)]
427
+ self.fragment_smiles = [_get_R_fragment_from_macrocycle(mol) for mol in tqdm(self.mols)]
428
+ self.HA = [_get_heavy_atom_count(mol) for mol in tqdm(self.mols)]
429
+
430
+ self.pair_spacings = []
431
+ for mol in tqdm(self.mols):
432
+ _, macrocycle_atoms = _get_macrocycle_ring_mol_2(mol)
433
+ if mol is None or not macrocycle_atoms:
434
+ self.pair_spacings.append({})
435
+ continue
436
+ connection_atoms = []
437
+ for atom_idx in range(mol.GetNumAtoms()):
438
+ if atom_idx not in macrocycle_atoms:
439
+ for neighbor in mol.GetAtomWithIdx(atom_idx).GetNeighbors():
440
+ if neighbor.GetIdx() in macrocycle_atoms:
441
+ connection_atoms.append((atom_idx, neighbor.GetIdx()))
442
+ pair_spacing = _calculate_pair_spacing_for_bridged_rings(mol, connection_atoms, macrocycle_atoms)
443
+ self.pair_spacings.append(pair_spacing)
444
+
445
+ # Store the pre-calculated results in the cache
446
+ MacrocycleCalculator._cache[cache_key] = {
447
+ 'smiles': self.smiles,
448
+ 'mols': self.mols,
449
+ 'ring_mol': self.ring_mol,
450
+ 'ring_mol_stripped': self.ring_mol_stripped,
451
+ 'ring_size': self.ring_size,
452
+ 'fragment_smiles': self.fragment_smiles,
453
+ 'HA': self.HA,
454
+ 'pair_spacings': self.pair_spacings
455
+ }
456
+ print("\nPre-calculation Done. Now MolD calculation can start!\n")
457
+ else:
458
+ print("Using cached pre-calculations...\n")
459
+ cached_data = MacrocycleCalculator._cache[cache_key]
460
+ self.smiles = cached_data['smiles']
461
+ self.mols = cached_data['mols']
462
+ self.ring_mol = cached_data['ring_mol']
463
+ self.ring_mol_stripped = cached_data['ring_mol_stripped']
464
+ self.ring_size = cached_data['ring_size']
465
+ self.fragment_smiles = cached_data['fragment_smiles']
466
+ self.HA = cached_data['HA']
467
+ self.pair_spacings = cached_data['pair_spacings']