MacrocycleWizard 0.1.0__tar.gz

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.
Files changed (34) hide show
  1. macrocyclewizard-0.1.0/LICENSE +21 -0
  2. macrocyclewizard-0.1.0/MacrocycleWizard/CreateFig/FigGenerator.py +316 -0
  3. macrocyclewizard-0.1.0/MacrocycleWizard/CreateFig/__init__.py +10 -0
  4. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/__init__.py +65 -0
  5. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/base.py +467 -0
  6. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/basic/GroupA.py +64 -0
  7. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/basic/__init__.py +5 -0
  8. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/calculator.py +211 -0
  9. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/general/GroupH.py +458 -0
  10. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/general/GroupI.py +219 -0
  11. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/general/GroupJ.py +643 -0
  12. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/general/GroupK.py +92 -0
  13. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/general/__init__.py +8 -0
  14. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupB.py +363 -0
  15. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupC.py +132 -0
  16. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupD.py +426 -0
  17. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupE.py +343 -0
  18. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupF.py +222 -0
  19. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/GroupG.py +80 -0
  20. macrocyclewizard-0.1.0/MacrocycleWizard/MolD/specific/__init__.py +10 -0
  21. macrocyclewizard-0.1.0/MacrocycleWizard/Onion/Onion.py +1115 -0
  22. macrocyclewizard-0.1.0/MacrocycleWizard/Onion/__init__.py +11 -0
  23. macrocyclewizard-0.1.0/MacrocycleWizard/__init__.py +219 -0
  24. macrocyclewizard-0.1.0/MacrocycleWizard/base.py +467 -0
  25. macrocyclewizard-0.1.0/MacrocycleWizard.egg-info/PKG-INFO +407 -0
  26. macrocyclewizard-0.1.0/MacrocycleWizard.egg-info/SOURCES.txt +32 -0
  27. macrocyclewizard-0.1.0/MacrocycleWizard.egg-info/dependency_links.txt +1 -0
  28. macrocyclewizard-0.1.0/MacrocycleWizard.egg-info/requires.txt +9 -0
  29. macrocyclewizard-0.1.0/MacrocycleWizard.egg-info/top_level.txt +1 -0
  30. macrocyclewizard-0.1.0/PKG-INFO +407 -0
  31. macrocyclewizard-0.1.0/README.md +365 -0
  32. macrocyclewizard-0.1.0/pyproject.toml +3 -0
  33. macrocyclewizard-0.1.0/setup.cfg +4 -0
  34. macrocyclewizard-0.1.0/setup.py +47 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MedChemBeyond
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,316 @@
1
+ # MacrocycleWizard/CreateFig/FigGenerator.py
2
+
3
+ import io
4
+ import os
5
+ from xml.sax.saxutils import escape
6
+
7
+ from rdkit import Chem
8
+ from rdkit.Chem import rdDepictor
9
+ from rdkit.Chem.Draw import rdMolDraw2D
10
+ from tqdm import tqdm
11
+ from molvs import standardize_smiles
12
+
13
+ from ..base import MacrocycleCalculator
14
+
15
+ # Enable CoordGen as the preferred 2D coordinate generator
16
+ # (gives ChemDraw-like zig-zag macrocycles instead of regular polygons)
17
+ rdDepictor.SetPreferCoordGen(True)
18
+
19
+
20
+ def _find_font(candidates):
21
+ for path in candidates:
22
+ if os.path.exists(path):
23
+ return path
24
+ return None
25
+
26
+
27
+ # ChemDraw (ACS 1996) uses Arial for labels and Arial Bold for captions
28
+ _FONT_REGULAR = _find_font([
29
+ "/System/Library/Fonts/Supplemental/Arial.ttf", # macOS
30
+ "C:/Windows/Fonts/arial.ttf", # Windows
31
+ "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf", # Linux
32
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", # Docker / Streamlit Cloud
33
+ "/usr/share/fonts/truetype/liberation2/LiberationSans-Regular.ttf",
34
+ ])
35
+ _FONT_BOLD = _find_font([
36
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
37
+ "C:/Windows/Fonts/arialbd.ttf",
38
+ "/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf",
39
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
40
+ "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf",
41
+ ])
42
+
43
+ # Soft peach halo, identical to the ChemDraw highlight colour used in the manuscript
44
+ DEFAULT_HIGHLIGHT = (1.0, 0.85, 0.80)
45
+
46
+
47
+ class MoleculeVisualizer(MacrocycleCalculator):
48
+ """
49
+ MoleculeVisualizer: Generate visual representations of macrocyclic molecules
50
+
51
+ This class provides methods to create PNG and SVG images with optional
52
+ macrocycle ring highlighting.
53
+
54
+ Two styles are available:
55
+ - "chemdraw" (default): black atom labels, Arial, thicker bonds, a soft
56
+ continuous halo behind the macrocycle and a bold caption, mimicking
57
+ the ACS 1996 ChemDraw document style.
58
+ - "classic": the original RDKit look (coloured heteroatoms, red highlight).
59
+ """
60
+
61
+ def __init__(self, list_of_smiles):
62
+ self.smiles = list_of_smiles
63
+
64
+ # ------------------------------------------------------------------ helpers
65
+ def _standardise(self, smiles):
66
+ """Standardize a SMILES string"""
67
+ try:
68
+ return standardize_smiles(smiles)
69
+ except Exception:
70
+ return smiles
71
+
72
+ def _create_directory(self, path):
73
+ """Create a directory if it doesn't exist"""
74
+ try:
75
+ os.makedirs(path, exist_ok=True)
76
+ return True
77
+ except OSError as e:
78
+ print(f"Error creating directory {path}: {e}")
79
+ return False
80
+
81
+ def _get_macrocycle_atoms(self, mol):
82
+ """Return the atom indices of the largest ring (the macrocycle)."""
83
+ if mol is None:
84
+ return []
85
+ try:
86
+ rings = mol.GetRingInfo().AtomRings()
87
+ return list(max(rings, key=len)) if rings else []
88
+ except Exception:
89
+ return []
90
+
91
+ def _get_macrocycle_bonds(self, mol, ring_atoms):
92
+ """Return the bond indices whose two atoms both lie in the macrocycle."""
93
+ if not ring_atoms:
94
+ return []
95
+ ring_atoms_set = set(ring_atoms)
96
+ return [b.GetIdx() for b in mol.GetBonds()
97
+ if b.GetBeginAtomIdx() in ring_atoms_set
98
+ and b.GetEndAtomIdx() in ring_atoms_set]
99
+
100
+ # ----------------------------------------------------------- draw options
101
+ @staticmethod
102
+ def _apply_chemdraw_style(opts, line_width, color_atoms):
103
+ if color_atoms:
104
+ # Coloured heteroatom labels (O red, N blue, ...) but black bonds,
105
+ # the way ChemDraw colours atoms
106
+ if hasattr(opts, "singleColourBonds"):
107
+ opts.singleColourBonds = True
108
+ else:
109
+ opts.useBWAtomPalette() # all-black labels, as in ChemDraw
110
+ if _FONT_REGULAR:
111
+ opts.fontFile = _FONT_REGULAR
112
+ opts.bondLineWidth = line_width
113
+ opts.scaleBondWidth = False
114
+ opts.multipleBondOffset = 0.18 # ChemDraw BondSpacing = 18 %
115
+ opts.additionalAtomLabelPadding = 0.08
116
+ opts.fillHighlights = True
117
+ opts.continuousHighlight = True
118
+ opts.atomHighlightsAreCircles = True
119
+ opts.highlightRadius = 0.22 # round joints, no big blobs
120
+ opts.highlightBondWidthMultiplier = 10 # wide, soft halo band
121
+ opts.padding = 0.06
122
+
123
+ def _prepare_mol(self, smiles):
124
+ mol = Chem.MolFromSmiles(smiles)
125
+ if mol is None:
126
+ return None
127
+ rdDepictor.Compute2DCoords(mol)
128
+ rdDepictor.StraightenDepiction(mol) # snap to 30 deg angles, like ChemDraw
129
+ return mol
130
+
131
+ def _render(self, mol, legend, fmt, highlight_ring, img_size, legend_font_size,
132
+ style, highlight_color, bond_length, line_width, color_atoms):
133
+ """Draw one molecule; returns bytes (PNG) or str (SVG)."""
134
+ width, height = img_size
135
+ chemdraw = style == "chemdraw"
136
+
137
+ # In ChemDraw style the caption is drawn separately (bold), so the
138
+ # molecule gets a panel that leaves room for it underneath. PNG needs a
139
+ # bold TTF for that; without one, fall back to RDKit's own legend.
140
+ bold_caption = chemdraw and bool(legend) and (fmt == "svg" or _FONT_BOLD is not None)
141
+ legend_h = int(legend_font_size * 2.0) if bold_caption else 0
142
+ panel_h = height - legend_h
143
+ if fmt == "png":
144
+ drawer = rdMolDraw2D.MolDraw2DCairo(width, height, width, panel_h)
145
+ else:
146
+ drawer = rdMolDraw2D.MolDraw2DSVG(width, height, width, panel_h)
147
+
148
+ opts = drawer.drawOptions()
149
+ opts.clearBackground = False # transparent background
150
+ opts.addStereoAnnotation = False
151
+ opts.legendFontSize = legend_font_size
152
+ if chemdraw:
153
+ self._apply_chemdraw_style(opts, line_width, color_atoms)
154
+ if bond_length:
155
+ opts.fixedBondLength = bond_length # same scale for every molecule
156
+
157
+ kwargs = {}
158
+ if highlight_ring:
159
+ ring_atoms = self._get_macrocycle_atoms(mol)
160
+ ring_bonds = self._get_macrocycle_bonds(mol, ring_atoms)
161
+ if chemdraw:
162
+ atom_col = bond_col = highlight_color or DEFAULT_HIGHLIGHT
163
+ else:
164
+ atom_col = highlight_color or (1.0, 0.8, 0.8)
165
+ bond_col = highlight_color or (1.0, 0.3, 0.3)
166
+ kwargs = dict(
167
+ highlightAtoms=ring_atoms,
168
+ highlightBonds=ring_bonds,
169
+ highlightAtomColors={a: atom_col for a in ring_atoms},
170
+ highlightBondColors={b: bond_col for b in ring_bonds},
171
+ )
172
+
173
+ drawer.DrawMolecule(mol, legend="" if bold_caption else str(legend), **kwargs)
174
+ drawer.FinishDrawing()
175
+ data = drawer.GetDrawingText()
176
+
177
+ if not bold_caption:
178
+ return data
179
+
180
+ # Place the bold caption just under the lowest atom (+ label room)
181
+ lowest = max(drawer.GetDrawCoords(i).y for i in range(mol.GetNumAtoms()))
182
+ y_top = min(lowest + 0.9 * legend_font_size, height - 1.3 * legend_font_size)
183
+ return self._add_caption(data, fmt, str(legend), width, y_top, legend_font_size)
184
+
185
+ @staticmethod
186
+ def _add_caption(data, fmt, text, width, y_top, size):
187
+ if fmt == "svg":
188
+ y = y_top + 0.8 * size # SVG y is the baseline
189
+ caption = (f"<text x='{width / 2:.1f}' y='{y:.1f}' text-anchor='middle' "
190
+ f"font-family='Arial, Helvetica, sans-serif' font-weight='bold' "
191
+ f"font-size='{size}px' fill='#000000'>{escape(text)}</text>\n")
192
+ return data.replace("</svg>", caption + "</svg>")
193
+
194
+ from PIL import Image, ImageDraw, ImageFont
195
+ img = Image.open(io.BytesIO(data)).convert("RGBA")
196
+ draw = ImageDraw.Draw(img)
197
+ font = ImageFont.truetype(_FONT_BOLD, size)
198
+ text_w = draw.textlength(text, font=font)
199
+ draw.text(((width - text_w) / 2, y_top), text, font=font, fill=(0, 0, 0, 255))
200
+ buf = io.BytesIO()
201
+ img.save(buf, format="PNG")
202
+ return buf.getvalue()
203
+
204
+ # ------------------------------------------------------------ main driver
205
+ def _generate(self, fmt, mol_ids, output_dir, highlight_ring, img_size,
206
+ legend_font_size, style, highlight_color, bond_length, line_width,
207
+ color_atoms):
208
+ if output_dir is None:
209
+ output_dir = os.path.join(os.getcwd(), "Overall_images")
210
+ if not self._create_directory(output_dir):
211
+ print("Failed to create output directory. Exiting.")
212
+ return
213
+
214
+ if mol_ids is None:
215
+ mol_ids = [f"Molecule_{i}" for i in range(len(self.smiles))]
216
+ if len(mol_ids) != len(self.smiles):
217
+ print("Error: Length of mol_ids must match length of smiles_list.")
218
+ return
219
+
220
+ # Standardize SMILES and keep only unique molecules
221
+ unique_mols = {}
222
+ for i, smiles in enumerate(self.smiles):
223
+ std_smiles = self._standardise(smiles)
224
+ if std_smiles and std_smiles not in unique_mols:
225
+ unique_mols[std_smiles] = mol_ids[i]
226
+
227
+ print(f"Generating {fmt.upper()} images for {len(unique_mols)} unique molecules...")
228
+ for smiles, mol_id in tqdm(unique_mols.items(), total=len(unique_mols)):
229
+ try:
230
+ mol = self._prepare_mol(smiles)
231
+ if mol is None:
232
+ print(f"Failed to parse SMILES for {mol_id}: {smiles}")
233
+ continue
234
+ data = self._render(mol, mol_id, fmt, highlight_ring, img_size,
235
+ legend_font_size, style, highlight_color,
236
+ bond_length, line_width, color_atoms)
237
+ path = os.path.join(output_dir, f"{mol_id}.{fmt}")
238
+ with open(path, "wb" if fmt == "png" else "w") as f:
239
+ f.write(data)
240
+ except Exception as e:
241
+ print(f"Error creating {fmt.upper()} for molecule {mol_id}: {e}")
242
+
243
+ print(f"Processing completed. {fmt.upper()} images saved to: {output_dir}")
244
+
245
+ # ------------------------------------------------------------- public API
246
+ def generate_png(self, mol_ids=None, output_dir=None, highlight_ring=False,
247
+ img_size=(600, 600), legend_font_size=24, style="chemdraw",
248
+ highlight_color=None, bond_length=None, line_width=2.0,
249
+ color_atoms=False):
250
+ """
251
+ Generate PNG images (transparent background) for all molecules
252
+
253
+ Parameters:
254
+ -----------
255
+ mol_ids : list, optional
256
+ List of molecule IDs/names. If None, auto-generated as "Molecule_0", ...
257
+ output_dir : str, optional
258
+ Output directory path. If None, uses "./Overall_images"
259
+ highlight_ring : bool, optional
260
+ Whether to highlight the macrocycle ring (default: False)
261
+ img_size : tuple, optional
262
+ Image size as (width, height) in pixels (default: (600, 600))
263
+ legend_font_size : int, optional
264
+ Font size for molecule legend (default: 24)
265
+ style : str, optional
266
+ "chemdraw" (default) or "classic" (original RDKit look)
267
+ highlight_color : tuple, optional
268
+ RGB tuple (0-1) for the ring halo. Default: ChemDraw peach (1, 0.85, 0.80)
269
+ bond_length : float, optional
270
+ Fixed bond length in pixels so all molecules share the same scale
271
+ (like a ChemDraw sheet). None = fit each molecule to the canvas.
272
+ line_width : float, optional
273
+ Bond line width in pixels for the "chemdraw" style (default: 2.0)
274
+ color_atoms : bool, optional
275
+ "chemdraw" style only: colour heteroatom labels (O red, N blue, ...)
276
+ while keeping bonds black. Default False (all black, like ChemDraw).
277
+ """
278
+ self._generate("png", mol_ids, output_dir, highlight_ring, img_size,
279
+ legend_font_size, style, highlight_color, bond_length, line_width,
280
+ color_atoms)
281
+
282
+ def generate_svg(self, mol_ids=None, output_dir=None, highlight_ring=False,
283
+ img_size=(600, 600), legend_font_size=24, style="chemdraw",
284
+ highlight_color=None, bond_length=None, line_width=2.0,
285
+ color_atoms=False):
286
+ """
287
+ Generate SVG images (transparent background) for all molecules.
288
+ Parameters are identical to generate_png.
289
+ """
290
+ self._generate("svg", mol_ids, output_dir, highlight_ring, img_size,
291
+ legend_font_size, style, highlight_color, bond_length, line_width,
292
+ color_atoms)
293
+
294
+ def generate_both(self, mol_ids=None, output_dir=None, highlight_ring=False,
295
+ img_size=(600, 600), legend_font_size=24, style="chemdraw",
296
+ highlight_color=None, bond_length=None, line_width=2.0,
297
+ color_atoms=False):
298
+ """
299
+ Generate both PNG and SVG images for all molecules.
300
+ Parameters are identical to generate_png.
301
+ """
302
+ args = (mol_ids, output_dir, highlight_ring, img_size, legend_font_size,
303
+ style, highlight_color, bond_length, line_width, color_atoms)
304
+ print("=" * 60)
305
+ print("Generating PNG images...")
306
+ print("=" * 60)
307
+ self.generate_png(*args)
308
+
309
+ print("\n" + "=" * 60)
310
+ print("Generating SVG images...")
311
+ print("=" * 60)
312
+ self.generate_svg(*args)
313
+
314
+ print("\n" + "=" * 60)
315
+ print("All images generated successfully!")
316
+ print("=" * 60)
@@ -0,0 +1,10 @@
1
+ """
2
+ CreateFig Module: Molecular Structure Visualization
3
+
4
+ This module provides tools to generate PNG and SVG images of molecules
5
+ with optional macrocycle ring highlighting.
6
+ """
7
+
8
+ from .FigGenerator import MoleculeVisualizer
9
+
10
+ __all__ = ['MoleculeVisualizer']
@@ -0,0 +1,65 @@
1
+ """MacrocycleWizard/MolD/__init__.py"""
2
+
3
+
4
+ from . import base
5
+ from . import basic
6
+ from . import general
7
+ from . import specific
8
+
9
+ # Import Basic Group
10
+ from .basic.GroupA import GroupA
11
+
12
+ # Import Specific Groups
13
+ from .specific.GroupB import GroupB
14
+ from .specific.GroupC import GroupC
15
+ from .specific.GroupD import GroupD
16
+ from .specific.GroupE import GroupE
17
+ from .specific.GroupF import GroupF
18
+ from .specific.GroupG import GroupG
19
+
20
+ # Import General Groups
21
+ from .general.GroupH import GroupH
22
+ from .general.GroupI import GroupI
23
+ from .general.GroupJ import GroupJ
24
+ from .general.GroupK import GroupK
25
+ # from .general.GroupL import GroupL # Uncomment when GroupL is ready
26
+
27
+ # Create aliases for Basic Group
28
+ BasicMolD = GroupA
29
+
30
+ # Create aliases for Specific Groups
31
+ RingStrct = GroupB
32
+ RingHetero = GroupC
33
+ FragStrct = GroupD
34
+ FragHetro = GroupE
35
+ RingInter = GroupF
36
+ RingTopoConn = GroupG
37
+
38
+ # Create aliases for General Groups
39
+ OverallStrct = GroupH
40
+ OverallHetero = GroupI
41
+ FunctionalGroup = GroupJ
42
+ TopoConn = GroupK
43
+
44
+ __all__ = [
45
+ # Base modules
46
+ 'base', 'basic', 'general', 'specific',
47
+
48
+ # Basic Group
49
+ 'GroupA', 'BasicMolD',
50
+
51
+ # Specific Groups
52
+ 'GroupB', 'RingStrct',
53
+ 'GroupC', 'RingHetero',
54
+ 'GroupD', 'FragStrct',
55
+ 'GroupE', 'FragHetro',
56
+ 'GroupF', 'RingInter',
57
+ 'GroupG', 'RingTopoConn',
58
+
59
+ # General Groups
60
+ 'GroupH', 'OverallStrct',
61
+ 'GroupI', 'OverallHetero',
62
+ 'GroupJ', 'FunctionalGroup',
63
+ 'GroupK', 'TopoConn',
64
+ # 'GroupL' # Uncomment when ready
65
+ ]