qcinf 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.
qcinf/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ from importlib import metadata as _metadata
2
+
3
+ try:
4
+ __version__ = _metadata.version(__name__)
5
+ except _metadata.PackageNotFoundError:
6
+ # Source tree / build hook / CI checkout
7
+ __version__ = "0.0.0+local"
8
+
9
+ from .algorithms.conversion import * # noqa: F401, F403
10
+ from .algorithms.geometry import * # noqa: F401, F403
File without changes
@@ -0,0 +1,166 @@
1
+ """Open Babel backend (wrapper functions) for qcinf."""
2
+
3
+ import functools
4
+ from typing import Callable, TypeVar, Union
5
+
6
+ import numpy as np
7
+ import qcconst.periodic_table as pt
8
+ from qcconst import constants
9
+ from qcio import Structure
10
+ from typing_extensions import ParamSpec
11
+
12
+ try:
13
+ from openbabel import openbabel as ob
14
+ from openbabel import pybel
15
+ except ModuleNotFoundError as _e:
16
+ _OB_ERR: Union[Exception, None] = _e
17
+ else:
18
+ _OB_ERR = None
19
+
20
+ P = ParamSpec("P")
21
+ R = TypeVar("R")
22
+
23
+
24
+ def requires_openbabel(func: Callable[P, R]) -> Callable[P, R]:
25
+ """
26
+ Decorator that raises a clean error *at call-time* if Open Babel
27
+ isn't installed.
28
+ """
29
+
30
+ @functools.wraps(func)
31
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[misc]
32
+ if _OB_ERR is not None:
33
+ raise ModuleNotFoundError(
34
+ "Optional dependency 'openbabel' is not installed. "
35
+ "Install with one of:\n"
36
+ " python -m pip install 'qcinf[openbabel]'\n"
37
+ " python -m pip install 'qcinf[all]'"
38
+ ) from _OB_ERR
39
+ return func(*args, **kwargs)
40
+
41
+ return wrapper
42
+
43
+
44
+ # --- main wrapper functions for Open Babel --- #
45
+
46
+
47
+ @requires_openbabel
48
+ def _smiles_to_structure_ob(
49
+ smiles: str, force_field: str = "mmff94", **struct_kwargs
50
+ ) -> Structure:
51
+ """Convert a SMILES string to a Structure object.
52
+
53
+ Args:
54
+ smiles: The SMILES string to convert.
55
+ force_field: The force field to use for geometry embedding. Defaults to
56
+ "mmff94". Options are "uff", "mmff94", and "ghemical".
57
+ **struct_kwargs: Additional keyword arguments to pass to the Structure
58
+ constructor such as multiplicity, extras, identifiers, etc.
59
+
60
+ Returns:
61
+ A Structure object.
62
+
63
+ Raises:
64
+ ValueError: If the force field is not one of the supported options.
65
+ AssertionError: If the conversion to an Open Babel Mol fails.
66
+ """
67
+ # Validate force field
68
+ force_field = force_field.lower()
69
+ if force_field not in ["uff", "mmff94", "ghemical"]:
70
+ raise ValueError(
71
+ f"Invalid force field '{force_field}'. "
72
+ "Options are 'uff', 'mmff94', and 'ghemical'."
73
+ )
74
+
75
+ # Convert SMILES to Open Babel Mol object
76
+ mol = pybel.readstring("smi", smiles)
77
+ if mol is None:
78
+ raise ValueError(
79
+ f"Failed to convert SMILES to Open Babel Mol: {smiles}. "
80
+ "Please check the SMILES string for validity."
81
+ )
82
+
83
+ # Add hydrogens
84
+ mol.addh() # type: ignore
85
+
86
+ # Generate 3D coordinates and optimize
87
+ mol.make3D(forcefield=force_field, steps=250) # type: ignore
88
+
89
+ # Get atom symbols
90
+ atoms = [pt.number(atom.atomicnum).symbol for atom in mol.atoms] # type: ignore
91
+
92
+ # Get atom positions
93
+ geometry_angstrom = np.array([atom.coords for atom in mol.atoms]) # type: ignore # noqa: E501
94
+ geometry_bohr = geometry_angstrom * constants.ANGSTROM_TO_BOHR
95
+
96
+ # Get canonical SMILES
97
+ canonical_smiles = mol.write("can").strip() # type: ignore
98
+
99
+ # Get charge
100
+ charge = mol.charge # type: ignore
101
+
102
+ return Structure(
103
+ symbols=atoms,
104
+ geometry=geometry_bohr,
105
+ charge=charge,
106
+ identifiers={
107
+ "canonical_smiles": canonical_smiles,
108
+ "smiles": smiles,
109
+ "canonical_smiles_program": "openbabel",
110
+ },
111
+ **struct_kwargs,
112
+ )
113
+
114
+
115
+ @requires_openbabel
116
+ def _structure_to_smiles_ob(struct: Structure, *, hydrogens: bool = False) -> str:
117
+ """Convert a Structure to a SMILES string.
118
+
119
+ Args:
120
+ struct: The Structure object to convert.
121
+ hydrogens: Whether to include explicit hydrogens in the SMILES string.
122
+
123
+ Returns:
124
+ A canonical SMILES string.
125
+ """
126
+ # Must remove data in second line for Open Babel
127
+ xyz_lines = struct.to_xyz().splitlines()
128
+ xyz_lines[1] = ""
129
+
130
+ # Create Open Babel OBMol object
131
+ mol = pybel.readstring("xyz", "\n".join(xyz_lines))
132
+
133
+ # Assign charges
134
+ partial_charges = mol.calccharges()
135
+
136
+ # Check if the sum of the partial charges matches the total charge
137
+ if sum(partial_charges) != struct.charge:
138
+ raise ValueError(
139
+ f"Charge mismatch. Open Babel: {sum(partial_charges)} vs Structure: "
140
+ f"{struct.charge}"
141
+ )
142
+
143
+ # Set the formal charges on the atoms
144
+ if sum(partial_charges) != 0:
145
+ for atom, charge in zip(mol.atoms, partial_charges):
146
+ atom.OBAtom.SetFormalCharge(int(round(charge)))
147
+
148
+ # Ensure the total charge matches the structure
149
+ if mol.charge != struct.charge:
150
+ raise ValueError(
151
+ f"Charge mismatch. Open Babel: {sum(partial_charges)} vs Structure: "
152
+ f"{struct.charge}"
153
+ )
154
+
155
+ # Create an OBConversion object to handle output format
156
+ conv = ob.OBConversion()
157
+ conv.SetOutFormat("can")
158
+
159
+ if hydrogens:
160
+ conv.AddOption("h", ob.OBConversion.OUTOPTIONS)
161
+
162
+ # Generate canonical SMILES with explicit hydrogens
163
+ return conv.WriteString(mol.OBMol).strip()
164
+
165
+
166
+ # --- internal helper functions for Open Babel --- #
File without changes
@@ -0,0 +1,565 @@
1
+ """RDKit backend (wrapper functions) for qcinf."""
2
+
3
+ import functools
4
+ from collections import Counter
5
+ from pathlib import Path
6
+ from typing import Callable, TypeVar, Union
7
+
8
+ import numpy as np
9
+ from qcconst import constants
10
+ from qcio import LengthUnit, Structure
11
+ from typing_extensions import ParamSpec
12
+
13
+ from .utils import mute_c_stderr
14
+
15
+ try:
16
+ from rdkit import Chem
17
+ from rdkit.Chem import AllChem, Mol, rdDetermineBonds, rdMolAlign
18
+ except ModuleNotFoundError as _e:
19
+ _RDKIT_ERR: Union[Exception, None] = _e
20
+ else:
21
+ _RDKIT_ERR = None
22
+
23
+
24
+ P = ParamSpec("P")
25
+ R = TypeVar("R")
26
+
27
+
28
+ def requires_rdkit(func: Callable[P, R]) -> Callable[P, R]:
29
+ """
30
+ Decorator that raises a clean error *at call-time* if RDKit
31
+ isn't installed.
32
+ """
33
+
34
+ @functools.wraps(func)
35
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[misc]
36
+ if _RDKIT_ERR is not None:
37
+ raise ModuleNotFoundError(
38
+ "Optional dependency 'rdkit' is not installed. "
39
+ "Install with: python -m pip install 'qcinf[rdkit]' or "
40
+ "python -m pip install 'qcinf[all]'."
41
+ ) from _RDKIT_ERR
42
+ return func(*args, **kwargs)
43
+
44
+ return wrapper
45
+
46
+
47
+ # --- main wrapper functions for rdkit --- #
48
+
49
+
50
+ @requires_rdkit
51
+ def _rmsd_rdkit(
52
+ struct1: Structure,
53
+ struct2: Structure,
54
+ *,
55
+ symmetry: bool = True,
56
+ numthreads: int = 1,
57
+ use_hueckel: bool = True,
58
+ use_vdw: bool = False,
59
+ cov_factor: float = 1.3,
60
+ length_unit: LengthUnit = LengthUnit.BOHR,
61
+ ) -> float:
62
+ """
63
+ Calculate the root mean square deviation between two structures in Bohr or Angstrom.
64
+
65
+ May lead to a 'combinatorial explosion' if symmetry=True and many molecule symmetries
66
+ (e.g., many hydrogens) are present. If this function is taking a long time to
67
+ compute, consider passing `symmetry=False` to disable symmetry consideration. Or
68
+ pass `numthreads=an_integer` to increase the number of threads used for the
69
+ symmetry consideration step.
70
+
71
+ Args:
72
+ struct1: The first structure.
73
+ struct2: The second structure.
74
+ symmetry: Whether to consider symmetries in the structures before calculating
75
+ the RMSD, i.e., to allow atom renumbering. This relies on the RDKit
76
+ `DetermineConnectivity` and `GetBestRMS` functions. If False, the RMSD is
77
+ calculated with alignment but without considering symmetry, i.e., naively
78
+ assuming the atoms are already correctly indexed across structures.
79
+ numthreads: The number of threads to use for the RMSD calculation. Applies only
80
+ to the alignment step if `symmetry=True`.
81
+ use_hueckel: Whether to use Hueckel method when determining connectivity.
82
+ Applies only to `symmetry=True`.
83
+ use_vdw: Whether to use Van der Waals radii when determining connectivity.
84
+ Applies only to `symmetry=True`.
85
+ cov_factor: The scaling factor for the covalent radii when determining
86
+ connectivity. Applies only to `symmetry=True`.
87
+ length_unit: The unit of length to use for the RMSD calculation. Default is
88
+ "bohr". If "angstrom", the RMSD will be in Angstroms.
89
+
90
+ Returns:
91
+ The RMSD between the two structures in Angstroms.
92
+ """
93
+ # Create RDKit molecules
94
+ mol1 = _structure_to_rdkit_mol(struct1)
95
+ mol2 = _structure_to_rdkit_mol(struct2)
96
+
97
+ # Compute RMSD
98
+ if symmetry:
99
+ # Determine connectivity
100
+ _determine_connectivity_rdkit(
101
+ mol1,
102
+ charge=struct1.charge,
103
+ use_hueckel=use_hueckel,
104
+ use_vdw=use_vdw,
105
+ cov_factor=cov_factor,
106
+ )
107
+
108
+ _determine_connectivity_rdkit(
109
+ mol2,
110
+ charge=struct2.charge,
111
+ use_hueckel=use_hueckel,
112
+ use_vdw=use_vdw,
113
+ cov_factor=cov_factor,
114
+ )
115
+ # Take symmetry into account, align the two molecules, compute RMSD
116
+ try:
117
+ rmsd = rdMolAlign.GetBestRMS(mol2, mol1, numThreads=numthreads)
118
+ except RuntimeError as e: # Possible failure to make substructure match
119
+ try: # Swap the order of the molecules and try again.
120
+ rmsd = rdMolAlign.GetBestRMS(mol1, mol2, numThreads=numthreads)
121
+ except RuntimeError: # If it fails again, raise the original error
122
+ raise e
123
+
124
+ else: # Do not take symmetry into account. Structs aligned by atom index.
125
+ rmsd = rdMolAlign.AlignMol(mol2, mol1)
126
+
127
+ return rmsd * constants.ANGSTROM_TO_BOHR if length_unit == LengthUnit.BOHR else rmsd
128
+
129
+
130
+ @requires_rdkit
131
+ def _align_rdkit(
132
+ struct: Structure,
133
+ refstruct: Structure,
134
+ symmetry: bool = True,
135
+ use_hueckel: bool = True,
136
+ use_vdw: bool = False,
137
+ cov_factor: float = 1.3,
138
+ length_unit: LengthUnit = LengthUnit.BOHR,
139
+ ) -> tuple[Structure, float]:
140
+ """
141
+ Return a new structure that is optimally aligned to the reference structure and
142
+ the RMSD between the two structures in Bohr or Angstroms.
143
+
144
+ May lead to a 'combinatorial explosion' especially if many molecule symmetries
145
+ (e.g., many hydrogens) are present.If this function is taking a long time to
146
+ compute, consider passing `symmetry=False` to disable symmetry consideration.
147
+
148
+ Args:
149
+ struct: The structure to align.
150
+ refstruct: The reference structure.
151
+ symmetry: Whether to consider symmetries in the structures before aligning and
152
+ calculating the RMSD, i.e., to allow atom renumbering. This relies on the
153
+ RDKit's `GetBestAlignmentTransform` method and `GetBestRMS` functions. If False, the RMSD is
154
+ calculated with alignment but without considering symmetry, i.e., naively
155
+ assuming the atoms are already correctly indexed across structures.
156
+ use_hueckel: Whether to use Hueckel method when determining connectivity.
157
+ Applies only to `best=True`.
158
+ use_vdw: Whether to use Van der Waals radii when determining connectivity.
159
+ Applies only to `best=True`.
160
+ cov_factor: The scaling factor for the covalent radii when determining
161
+ connectivity. Applies only to `best=True`.
162
+ length_unit: The unit of length to use for the RMSD calculation. Default is
163
+ "bohr". If "angstrom", the RMSD will be in Angstroms.
164
+
165
+ Returns:
166
+ Tuple of the aligned structure and the RMSD in Angstroms.
167
+ """
168
+ # Create RDKit molecules
169
+ mol = _structure_to_rdkit_mol(struct)
170
+ refmol = _structure_to_rdkit_mol(refstruct)
171
+
172
+ # Determine connectivity
173
+ _determine_connectivity_rdkit(
174
+ mol,
175
+ charge=struct.charge,
176
+ use_hueckel=use_hueckel,
177
+ use_vdw=use_vdw,
178
+ cov_factor=cov_factor,
179
+ )
180
+ _determine_connectivity_rdkit(
181
+ refmol,
182
+ charge=refstruct.charge,
183
+ use_hueckel=use_hueckel,
184
+ use_vdw=use_vdw,
185
+ cov_factor=cov_factor,
186
+ )
187
+
188
+ # Align mol to refmol and compute RMSD
189
+ if symmetry:
190
+ rmsd_val, trnsfm_matrix, atm_map = rdMolAlign.GetBestAlignmentTransform(
191
+ mol, refmol
192
+ )
193
+ else:
194
+ rmsd_val, trnsfm_matrix = rdMolAlign.GetAlignmentTransform(mol, refmol)
195
+
196
+ # Convert to homogeneous coordinates in Angstroms
197
+ coords_homogeneous = np.hstack(
198
+ [struct.geometry_angstrom, np.ones((struct.geometry.shape[0], 1))]
199
+ )
200
+
201
+ # Apply the transformation matrix
202
+ transformed_coords_homogeneous = coords_homogeneous @ trnsfm_matrix.T
203
+
204
+ # Extract the transformed 3D coordinates and convert to Bohr
205
+ transformed_coords = (
206
+ transformed_coords_homogeneous[:, :3] * constants.ANGSTROM_TO_BOHR
207
+ )
208
+
209
+ # Reorder the atoms to match the reference structure
210
+ if symmetry:
211
+ if Counter(struct.symbols) != Counter(refstruct.symbols):
212
+ raise ValueError(
213
+ "Structures must have the same number and type of atoms for "
214
+ "`symmetry=True` at this time. Pass "
215
+ "`symmetry=False` to align structures with different atom "
216
+ "counts."
217
+ )
218
+ symbols = refstruct.symbols
219
+ geometry = np.zeros((len(atm_map), 3))
220
+
221
+ for probe_idx, ref_idx in atm_map:
222
+ geometry[ref_idx] = transformed_coords[probe_idx]
223
+
224
+ # Otherwise, keep the original atom order
225
+ else:
226
+ symbols = struct.symbols
227
+ geometry = transformed_coords
228
+
229
+ return (
230
+ Structure(
231
+ symbols=symbols,
232
+ geometry=geometry,
233
+ charge=struct.charge,
234
+ multiplicity=struct.multiplicity,
235
+ connectivity=struct.connectivity,
236
+ identifiers=struct.identifiers,
237
+ ),
238
+ rmsd_val * constants.ANGSTROM_TO_BOHR
239
+ if length_unit == LengthUnit.BOHR
240
+ else rmsd_val,
241
+ )
242
+
243
+
244
+ @requires_rdkit
245
+ def _smiles_to_structure_rdkit(
246
+ smiles: str, force_field: str = "MMFF94s", **struct_kwargs
247
+ ) -> Structure:
248
+ """Convert a SMILES string to a Structure object.
249
+
250
+ Args:
251
+ smiles: The SMILES string to convert.
252
+ force_field: The force field to use for geometry embedding. Defaults to
253
+ "MMFF94s". Options are "UFF", "MMFF94", and "MMFF94s".
254
+ **struct_kwargs: Additional keyword arguments to pass to the Structure
255
+ constructor such as multiplicity, extras, identifiers, etc.
256
+
257
+ Returns:
258
+ A Structure object.
259
+
260
+ Raises:
261
+ ValueError: If the force field is not one of the supported options.
262
+ ValueError: If the SMILES string contains multiple molecules (i.e., the SMILES
263
+ string contains "." characters).
264
+ AssertionError: If the conversion to an RDKit Mol fails.
265
+ """
266
+ # Validate force field
267
+ force_field = force_field.upper()
268
+ if force_field not in ["UFF", "MMFF94", "MMFF94S"]:
269
+ raise ValueError(
270
+ f"Unsupported force field: {force_field}. "
271
+ "Supported force fields are: UFF, MMFF94, MMFF94s."
272
+ )
273
+
274
+ # Remove newline characters if present
275
+ smiles = smiles.strip()
276
+
277
+ if "." in smiles:
278
+ raise ValueError(
279
+ "Multiple molecules are not supported by RDKit. "
280
+ "Please provide a single molecule or use openbabel instead."
281
+ )
282
+
283
+ # Convert SMILES to RDKit Mol object
284
+ mol = Chem.MolFromSmiles(smiles) # type: ignore
285
+ if mol is None:
286
+ raise ValueError(
287
+ f"Failed to convert SMILES to RDKit Mol: {smiles}. "
288
+ "Please check the SMILES string for validity."
289
+ )
290
+
291
+ # Compute smiles
292
+ canonical_smiles = Chem.MolToSmiles(mol, canonical=True) # type: ignore
293
+ mol = Chem.AddHs(mol) # type: ignore
294
+
295
+ # Generate 3D coordinates
296
+ # https://www.rdkit.org/docs/Cookbook.html#conformer-generation-with-etkdg
297
+ AllChem.EmbedMolecule(mol, AllChem.ETKDGv2()) # type: ignore
298
+ # Optimize the molecule using the specified force field
299
+ if force_field == "UFF":
300
+ AllChem.UFFOptimizeMolecule(mol) # type: ignore
301
+ elif force_field == "MMFF94":
302
+ AllChem.MMFFOptimizeMolecule(mol, mmffVariant="MMFF94") # type: ignore
303
+ elif force_field == "MMFF94S":
304
+ AllChem.MMFFOptimizeMolecule(mol, mmffVariant="MMFF94s") # type: ignore
305
+
306
+ # Get atom symbols
307
+ atoms = [atom.GetSymbol() for atom in mol.GetAtoms()] # type: ignore
308
+
309
+ # Get atom positions
310
+ conf = mol.GetConformer()
311
+ geometry_angstrom = conf.GetPositions()
312
+ geometry_bohr = geometry_angstrom * constants.ANGSTROM_TO_BOHR
313
+
314
+ # Get charge
315
+ charge = Chem.GetFormalCharge(mol) # type: ignore
316
+
317
+ return Structure(
318
+ symbols=atoms,
319
+ geometry=geometry_bohr,
320
+ charge=charge,
321
+ identifiers={
322
+ "canonical_smiles": canonical_smiles,
323
+ "smiles": smiles,
324
+ "canonical_smiles_program": "rdkit",
325
+ },
326
+ **struct_kwargs,
327
+ )
328
+
329
+
330
+ @requires_rdkit
331
+ def _structure_to_smiles_rdkit(
332
+ structure: Structure,
333
+ *,
334
+ hydrogens: bool = False,
335
+ robust: bool = True,
336
+ use_hueckel: bool = True,
337
+ use_vdw: bool = False,
338
+ cov_factor: float = 1.3,
339
+ allow_charged_fragments: bool = False,
340
+ ) -> str:
341
+ """Convert a Structure to a SMILES string.
342
+
343
+ Args:
344
+ structure: The Structure object to convert.
345
+ hydrogens: Whether to include hydrogens in the SMILES string.
346
+ robust: Whether to use a robust method for bond determination by trying
347
+ different parameters for the DetermineBonds function automatically.
348
+ use_hueckel: Whether to use the Hueckel method for bond determination.
349
+ use_vdw: Whether to use Van der Waals radii for bond determination.
350
+ cov_factor: The scaling factor for the covalent radii when determining
351
+ connectivity.
352
+ allow_charged_fragments: Whether to allow charged fragments in the bond
353
+ determination step. When allow_charged_fragments=False, RDKit
354
+ avoids assigning formal charges and instead satisfies valence with radicals
355
+ (unpaired electrons) if necessary. Bonding and valence will be reconciled
356
+ without fragments. When True, RDKit will assign formal charges to atoms and
357
+ reconcile bonding and valence with charged fragments.
358
+
359
+ Returns:
360
+ A canonical SMILES string.
361
+ """
362
+ if use_hueckel and use_vdw:
363
+ raise ValueError(
364
+ "Cannot use both the Hueckel and Van der Waals methods for bond detection. "
365
+ "Pass use_hueckel=False if you want to use the VdW method. Hueckel method "
366
+ "is used by default."
367
+ )
368
+
369
+ # Details: https://greglandrum.github.io/rdkit-blog/posts/2022-12-18-introducing-rdDetermineBonds.html # noqa: E501
370
+ # Create RDKit molecule and use rdDetermineBonds module to infer bonds
371
+ mol = _determine_bonds_rdkit(
372
+ structure,
373
+ charge=structure.charge,
374
+ robust=robust,
375
+ use_hueckel=use_hueckel,
376
+ use_vdw=use_vdw,
377
+ cov_factor=cov_factor,
378
+ allow_charged_fragments=allow_charged_fragments,
379
+ )
380
+
381
+ # Remove hydrogens if necessary
382
+ if not hydrogens:
383
+ mol = Chem.RemoveHs(mol) # type: ignore
384
+
385
+ return Chem.MolToSmiles(mol, canonical=True) # type: ignore
386
+
387
+
388
+ # --- internal helper functions for rdkit --- #
389
+
390
+
391
+ @requires_rdkit
392
+ def _structure_to_rdkit_mol(
393
+ struct: Structure,
394
+ ) -> "rdkit.Chem.Mol": # type: ignore # noqa: F821
395
+ """Create an RDKit molecule from a Structure object."""
396
+ # Create RDKit molecule
397
+ mol = Chem.MolFromXYZBlock(struct.to_xyz()) # type: ignore
398
+
399
+ if mol is None:
400
+ raise ValueError("Failed create rdkit Molecule from xyz string.")
401
+
402
+ # Ensure molecule has conformers
403
+ if mol.GetNumConformers() == 0:
404
+ raise ValueError("Molecule lacks 3D coordinates.")
405
+
406
+ return mol
407
+
408
+
409
+ @requires_rdkit
410
+ def _determine_bonds_rdkit(
411
+ structure: Structure,
412
+ charge: int,
413
+ robust: bool = True,
414
+ use_hueckel: bool = True,
415
+ use_vdw: bool = False,
416
+ cov_factor: float = 1.3,
417
+ allow_charged_fragments: bool = False,
418
+ ) -> Mol:
419
+ """
420
+ Determine the bonds in an RDKit molecule, using robust fallback parameters.
421
+
422
+ Hueckel method is most robust; may useVdw=True use VdW radii; default method
423
+ is connect-the-dots (fastest but least robust)
424
+
425
+ Developer Note:
426
+ - I am passing a Structure object to this function rather than a Mol object
427
+ because each attempt to determine the bonds modifies the Mol in place and a
428
+ fresh object is required for each attempt as a formerly failed attempt may
429
+ have left the Mol in a state that is not recoverable
430
+
431
+ """
432
+ mol = Chem.MolFromXYZBlock(structure.to_xyz()) # type: ignore
433
+
434
+ with mute_c_stderr():
435
+ # to suppress superfluous RDKit warnings such as
436
+ # '!!! Warning !!! Distance between atoms ... is suspicious.'
437
+ try:
438
+ # Execute the wrapped code block
439
+ if robust:
440
+ try: # Original parameters
441
+ rdDetermineBonds.DetermineBonds(
442
+ mol,
443
+ charge=charge,
444
+ useHueckel=use_hueckel,
445
+ useVdw=use_vdw,
446
+ covFactor=cov_factor,
447
+ allowChargedFragments=allow_charged_fragments,
448
+ )
449
+ except Exception as e: # noqa: E722
450
+ mol = Chem.MolFromXYZBlock(structure.to_xyz())
451
+ try: # Swap allow_charged_fragments
452
+ rdDetermineBonds.DetermineBonds(
453
+ mol,
454
+ charge=charge,
455
+ useHueckel=use_hueckel,
456
+ useVdw=use_vdw,
457
+ covFactor=cov_factor,
458
+ allowChargedFragments=not allow_charged_fragments,
459
+ )
460
+ except Exception: # noqa: E722
461
+ mol = Chem.MolFromXYZBlock(structure.to_xyz())
462
+ try: # Swap method
463
+ rdDetermineBonds.DetermineBonds(
464
+ mol,
465
+ charge=charge,
466
+ useHueckel=not use_hueckel,
467
+ useVdw=not use_vdw,
468
+ covFactor=cov_factor,
469
+ allowChargedFragments=allow_charged_fragments,
470
+ )
471
+ except Exception: # noqa: E722
472
+ mol = Chem.MolFromXYZBlock(structure.to_xyz())
473
+ try: # Swap method and allow_charged_fragments
474
+ rdDetermineBonds.DetermineBonds(
475
+ mol,
476
+ charge=charge,
477
+ useHueckel=not use_hueckel,
478
+ useVdw=not use_vdw,
479
+ covFactor=cov_factor,
480
+ allowChargedFragments=not allow_charged_fragments,
481
+ )
482
+ except Exception:
483
+ mol = Chem.MolFromXYZBlock(structure.to_xyz())
484
+ try: # Try connect-the-dots method
485
+ rdDetermineBonds.DetermineBonds(
486
+ mol,
487
+ charge=charge,
488
+ useHueckel=False,
489
+ useVdw=False,
490
+ covFactor=cov_factor,
491
+ allowChargedFragments=True,
492
+ )
493
+ except Exception:
494
+ mol = Chem.MolFromXYZBlock(structure.to_xyz())
495
+ try: # Swap allow_charged_fragments
496
+ rdDetermineBonds.DetermineBonds(
497
+ mol,
498
+ charge=charge,
499
+ useHueckel=False,
500
+ useVdw=False,
501
+ covFactor=cov_factor,
502
+ allowChargedFragments=False,
503
+ )
504
+ except Exception:
505
+ raise e
506
+ else:
507
+ rdDetermineBonds.DetermineBonds(
508
+ mol,
509
+ charge=charge,
510
+ useHueckel=use_hueckel,
511
+ useVdw=use_vdw,
512
+ covFactor=cov_factor,
513
+ allowChargedFragments=allow_charged_fragments,
514
+ )
515
+ finally:
516
+ # Delete the run.out and nul files created by rdkit
517
+ # Remove run.out and nul files if they exist
518
+ for filename in ["run.out", "nul"]:
519
+ file = Path(filename)
520
+ if file.exists():
521
+ try:
522
+ file.unlink()
523
+ except Exception:
524
+ pass
525
+ return mol
526
+
527
+
528
+ @requires_rdkit
529
+ def _determine_connectivity_rdkit(
530
+ mol: Mol,
531
+ charge: int,
532
+ use_hueckel: bool = True,
533
+ use_vdw: bool = True,
534
+ cov_factor: float = 1.3,
535
+ ) -> None:
536
+ """Determine connectivity for an RDKit molecule.
537
+
538
+ Args:
539
+ mol: The RDKit molecule.
540
+ charge: The charge of the molecule.
541
+ use_hueckel: Whether to use Hueckel method when determining connectivity.
542
+ use_vdw: Whether to use Van der Waals radii when determining connectivity.
543
+ cov_factor: The scaling factor for the covalent radii when determining
544
+ connectivity.
545
+ """
546
+ try:
547
+ with mute_c_stderr():
548
+ # to suppress superfluous RDKit warnings such as
549
+ # '!!! Warning !!! Distance between atoms ... is suspicious.'
550
+ rdDetermineBonds.DetermineConnectivity(
551
+ mol,
552
+ charge=charge,
553
+ useHueckel=use_hueckel,
554
+ useVdw=use_vdw,
555
+ covFactor=cov_factor,
556
+ )
557
+ finally:
558
+ # Delete the run.out and nul files created by rdkit
559
+ for filename in ["run.out", "nul"]:
560
+ file = Path(filename)
561
+ if file.exists():
562
+ try:
563
+ file.unlink()
564
+ except Exception:
565
+ pass
@@ -0,0 +1,33 @@
1
+ import os
2
+ import threading
3
+ from contextlib import contextmanager
4
+
5
+ # one global lock per process
6
+ _STDERR_LOCK = threading.Lock()
7
+
8
+
9
+ @contextmanager
10
+ def mute_c_stderr():
11
+ """
12
+ Redirect the C-level `stderr` (fd 2) to /dev/null for the duration
13
+ of the context. This silences C / C++ libraries like RDKit that
14
+ write directly with `fprintf(stderr, …)` or `std::cerr`.
15
+
16
+ Acquires a global lock (to make it thread-safe), redirects fd 2 to /dev/null,
17
+ runs the body, then restores stderr and releases the lock.
18
+
19
+ Be aware that if another thread NOT using this context manager writes to
20
+ stderr while this lock is held, it will be lost (written to /dev/null).
21
+ In practice this is rare, just be aware of it.
22
+ """
23
+ with _STDERR_LOCK:
24
+ # Duplicate the original fd so we can restore later
25
+ orig_fd = os.dup(2)
26
+
27
+ try:
28
+ with open(os.devnull, "w") as devnull:
29
+ os.dup2(devnull.fileno(), 2) # ← fd 2 now points to /dev/null
30
+ yield
31
+ finally:
32
+ os.dup2(orig_fd, 2) # Restore real stderr
33
+ os.close(orig_fd)
File without changes
@@ -0,0 +1,78 @@
1
+ """Top-level functions for structure conversion algorithms."""
2
+
3
+ from typing import Any, Callable, Union
4
+
5
+ from qcio import Structure
6
+
7
+ from qcinf._backends import openbabel, rdkit
8
+
9
+ _SMILES_TO_STRUCTURE_BACKENDS: dict[str, Callable[..., Structure]] = {
10
+ "rdkit": rdkit._smiles_to_structure_rdkit,
11
+ "openbabel": openbabel._smiles_to_structure_ob,
12
+ }
13
+
14
+
15
+ def smiles_to_structure(
16
+ smiles: str, *, backend: str = "rdkit", force_field: str = "MMFF94", **struct_kwargs
17
+ ) -> Structure:
18
+ """Convert a SMILES string to a Structure object.
19
+
20
+ Args:
21
+ smiles: The SMILES string to convert.
22
+ backend: The backend to use for the conversion. Can be 'rdkit' or 'openbabel'.
23
+ force_field: The force field to use for geometry embedding. Defaults to
24
+ "MMFF94". Options are "UFF", "MMFF94", and "MMFF94s" for rdkit and
25
+ "UFF", "MMFF94" and "GHEMICAL" for openbabel.
26
+ **struct_kwargs: Additional keyword arguments to pass to the Structure
27
+ constructor such as multiplicity, extras, identifiers, etc.
28
+
29
+ Returns:
30
+ A Structure object.
31
+
32
+ Raises:
33
+ ValueError: If the backend is not one of the supported options.
34
+ """
35
+ try:
36
+ fn = _SMILES_TO_STRUCTURE_BACKENDS[backend.lower()]
37
+ except KeyError as e:
38
+ raise ValueError(
39
+ f"Unknown backend '{backend}'. Known: {_SMILES_TO_STRUCTURE_BACKENDS.keys()}"
40
+ ) from e
41
+ return fn(smiles, force_field=force_field, **struct_kwargs)
42
+
43
+
44
+ _SMILES_BACKENDS: dict[str, Callable[..., str]] = {
45
+ "rdkit": rdkit._structure_to_smiles_rdkit,
46
+ "openbabel": openbabel._structure_to_smiles_ob,
47
+ }
48
+
49
+
50
+ def structure_to_smiles(
51
+ struct: Structure,
52
+ *,
53
+ backend: str = "rdkit",
54
+ hydrogens: bool = False,
55
+ options: Union[dict[str, Any], None] = None,
56
+ ) -> str:
57
+ """
58
+ Convert a [`qcio.Structure`][qcio.Structure] into a canonical SMILES string.
59
+
60
+ Args:
61
+ struct: The Structure object to convert.
62
+ backend: The backend to use for the conversion. Can be 'rdkit' or 'openbabel'.
63
+ Defaults to 'rdkit'.
64
+ hydrogens: If True, include explicit hydrogens in the SMILES string.
65
+ options: A dictionary of backend-specific keywords. See
66
+ `qcinf._backends.<backend>._structure_to_smiles` for details.
67
+
68
+ Returns:
69
+ Canonical SMILES str.
70
+ """
71
+ opts = options or {}
72
+ try:
73
+ fn = _SMILES_BACKENDS[backend.lower()]
74
+ except KeyError as e:
75
+ raise ValueError(
76
+ f"Unknown backend '{backend}'. Known: {_SMILES_BACKENDS.keys()}"
77
+ ) from e
78
+ return fn(struct, hydrogens=hydrogens, **opts) # type: ignore[arg-type]
@@ -0,0 +1,123 @@
1
+ """Top-level functions for geometry-related algorithms."""
2
+
3
+ from typing import Callable
4
+
5
+ from qcio import ConformerSearchResults, Structure
6
+
7
+ from qcinf._backends import rdkit
8
+
9
+ _RMSD_BACKEND_MAP: dict[str, Callable[..., float]] = {
10
+ "rdkit": rdkit._rmsd_rdkit,
11
+ }
12
+
13
+
14
+ def rmsd(
15
+ struct1: Structure,
16
+ struct2: Structure,
17
+ *,
18
+ backend: str = "rdkit",
19
+ **kwargs,
20
+ ) -> float:
21
+ """Calculate the root mean square deviation (RMSD) between two structures.
22
+
23
+ Args:
24
+ struct1: The first structure.
25
+ struct2: The second structure.
26
+ backend: The backend to use for the RMSD calculation. Can be 'rdkit'.
27
+ **kwargs: Backend-specific additional keywords to pass to the RMSD calculation
28
+ function. This can include options like 'symmetry' for symmetry-based RMSD
29
+ calculations. The specific options depend on the backend used. See
30
+ [qcinf._backends.<backend>._rmsd_<backend>] for details.
31
+
32
+ Returns:
33
+ The RMSD value between the two structures.
34
+
35
+ Raises:
36
+ ValueError: If the backend is not one of the supported options.
37
+ """
38
+ try:
39
+ fn = _RMSD_BACKEND_MAP[backend.lower()]
40
+ except KeyError as e:
41
+ raise ValueError(
42
+ f"Unknown backend '{backend}'. Known: {list(_RMSD_BACKEND_MAP)}"
43
+ ) from e
44
+ return fn(struct1, struct2, **kwargs)
45
+
46
+
47
+ _ALIGN_BACKEND_MAP: dict[str, Callable[..., tuple[Structure, float]]] = {
48
+ "rdkit": rdkit._align_rdkit,
49
+ }
50
+
51
+
52
+ def align(
53
+ struct: Structure,
54
+ refstruct: Structure,
55
+ *,
56
+ backend: str = "rdkit",
57
+ symmetry: bool = False,
58
+ **kwargs,
59
+ ) -> tuple[Structure, float]:
60
+ """Align a structure to a reference structure.
61
+
62
+ Args:
63
+ struct: The structure to align.
64
+ refstruct: The reference structure to align against.
65
+ backend: The backend to use for the alignment. Can be 'rdkit'.
66
+ symmetry: Whether to use symmetry in the alignment. Defaults to False.
67
+ **kwargs: Additional keyword arguments to pass to the alignment function.
68
+
69
+ Returns:
70
+ A tuple containing the RMSD and the aligned structure.
71
+ """
72
+ try:
73
+ fn = _ALIGN_BACKEND_MAP[backend.lower()]
74
+ except KeyError as e:
75
+ raise ValueError(
76
+ f"Unknown backend '{backend}'. Known: {list(_ALIGN_BACKEND_MAP)}"
77
+ ) from e
78
+ return fn(struct, refstruct, symmetry=symmetry, **kwargs)
79
+
80
+
81
+ def filter_conformers(
82
+ csr: ConformerSearchResults,
83
+ *,
84
+ backend: str = "rdkit",
85
+ threshold: float = 1.0,
86
+ **rmsd_kwargs,
87
+ ) -> ConformerSearchResults:
88
+ """Filter conformers based on RMSD threshold.
89
+
90
+ Args:
91
+ csr: The ConformerSearchResults object to filter.
92
+ backend: The backend to use for the RMSD calculation. Can be 'rdkit'.
93
+ threshold: The RMSD threshold for filtering in Bohr. Defaults to 1.0 Bohr
94
+ (0.53 Angstrom).
95
+ **rmsd_kwargs: Additional keyword arguments to pass to the RMSD calculation
96
+ function. This can include options like 'symmetry' for symmetry-based RMSD
97
+ calculations. The specific options depend on the backend used. See
98
+ [qcinf._backends.<backend>._rmsd_<backend>] for details.
99
+
100
+ Returns:
101
+ A new ConformerSearchResults object containing only the conformers that
102
+ meet the RMSD threshold.
103
+ """
104
+ filtered = set()
105
+ for i in range(len(csr.conformers)):
106
+ if i not in filtered:
107
+ for j in range(i + 1, len(csr.conformers)):
108
+ if (
109
+ rmsd(
110
+ csr.conformers[i],
111
+ csr.conformers[j],
112
+ backend=backend,
113
+ **rmsd_kwargs,
114
+ )
115
+ < threshold
116
+ ):
117
+ filtered.add(j)
118
+
119
+ keep_indices = [i for i in range(len(csr.conformers)) if i not in filtered]
120
+ return ConformerSearchResults(
121
+ conformers=[csr.conformers[i] for i in keep_indices],
122
+ conformer_energies=csr.conformer_energies_relative[keep_indices],
123
+ )
qcinf/py.typed ADDED
File without changes
qcinf/utils.py ADDED
@@ -0,0 +1,48 @@
1
+
2
+ import numpy as np
3
+ from qcio import Structure
4
+
5
+
6
+ def rotation_matrix(axis: str, angle_deg: float) -> np.ndarray:
7
+ """
8
+ Create a 3x3 rotation matrix for a rotation about a given axis by angle in degrees.
9
+
10
+ Parameters:
11
+ axis (str): 'x', 'y', or 'z' specifying the rotation axis.
12
+ angle_deg (float): Rotation angle in degrees.
13
+
14
+ Returns:
15
+ np.ndarray: 3x3 rotation matrix.
16
+ """
17
+ theta = np.radians(angle_deg)
18
+ c, s = np.cos(theta), np.sin(theta)
19
+
20
+ if axis.lower() == "x":
21
+ return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
22
+ elif axis.lower() == "y":
23
+ return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
24
+ elif axis.lower() == "z":
25
+ return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
26
+ else:
27
+ raise ValueError("Axis must be 'x', 'y', or 'z'.")
28
+
29
+
30
+ def rotate_structure(struct: Structure, axis: str, angle_deg: float) -> Structure:
31
+ """
32
+ Return a new Structure with its coordinates rotated by angle_deg about the given axis.
33
+
34
+ Parameters:
35
+ struct (Structure): Input structure with a .geometry attribute (an N x 3 numpy array).
36
+ axis (str): Axis to rotate about ('x', 'y', or 'z').
37
+ angle_deg (float): Rotation angle in degrees.
38
+
39
+ Returns:
40
+ Structure: New structure with rotated coordinates.
41
+ """
42
+ R = rotation_matrix(axis, angle_deg)
43
+ # Dump the structure to a dictionary and modify the geometry.
44
+ new_struct = struct.model_dump()
45
+ # Apply rotation: for each coordinate, multiply with the rotation matrix.
46
+ # We use R.T because our coordinates are row vectors.
47
+ new_struct["geometry"] = np.dot(struct.geometry, R.T)
48
+ return Structure.model_validate(new_struct)
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: qcinf
3
+ Version: 0.1.0
4
+ Summary: Cheminformatics algorithms and structure utilities using standardized qcio data structures.
5
+ Project-URL: Homepage, https://github.com/coltonbh/qcinf
6
+ Project-URL: Source, https://github.com/coltonbh/qcinf
7
+ Project-URL: Changelog, https://github.com/coltonbh/qcinf/blob/master/CHANGELOG.md
8
+ Project-URL: Bug Tracker, https://github.com/coltonbh/qcinf/issues
9
+ Project-URL: repository, https://github.com/coltonbh/qcinf
10
+ Author-email: Colton Hicks <github@coltonhicks.com>
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Natural Language :: English
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: pydantic!=2.0.1,!=2.1.0,~=2.0
25
+ Requires-Dist: qcconst>=0.2.1
26
+ Requires-Dist: qcio>=0.14.0
27
+ Requires-Dist: typing-extensions>=4.12.2
28
+ Provides-Extra: all
29
+ Requires-Dist: openbabel-wheel>=3.1.1.21; extra == 'all'
30
+ Requires-Dist: rdkit>=2024.9.6; extra == 'all'
31
+ Provides-Extra: openbabel
32
+ Provides-Extra: rdkit
33
+ Requires-Dist: rdkit>=2024.9.6; extra == 'rdkit'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # Quantum Chemistry Informatics (qcinf)
37
+
38
+ [![image](https://img.shields.io/pypi/v/qcinf.svg)](https://pypi.python.org/pypi/qcinf)
39
+ [![image](https://img.shields.io/pypi/l/qcinf.svg)](https://pypi.python.org/pypi/qcinf)
40
+ [![image](https://img.shields.io/pypi/pyversions/qcinf.svg)](https://pypi.python.org/pypi/qcinf)
41
+ [![Actions status](https://github.com/coltonbh/qcinf/workflows/Tests/badge.svg)](https://github.com/coltonbh/qcinf/actions)
42
+ [![Actions status](https://github.com/coltonbh/qcinf/workflows/Basic%20Code%20Quality/badge.svg)](https://github.com/coltonbh/qcinf/actions)
43
+
44
+ Cheminformatics algorithms and structure utilities using standardized [qcio](https://qcio.coltonhicks.com/) data structures.
45
+
46
+ ## The QC Suite of Programs
47
+
48
+ `qcinf` works in harmony with a suite of other quantum chemistry tools for fast, structured, and interoperable quantum chemistry.
49
+
50
+ - [qcconst](https://github.com/coltonbh/qcconst) - Physical constants, conversion factors, and a periodic table with clear source information for every value.
51
+ - [qcio](https://github.com/coltonbh/qcio) - Elegant and intuitive data structures for quantum chemistry, featuring seamless Jupyter Notebook visualizations. [Documentation](https://qcio.coltonhicks.com)
52
+ - [qcinf](https://github.com/coltonbh/qcinf) - Cheminformatics algorithms and structure utilities using standardized [qcio](https://qcio.coltonhicks.com/) data structures.
53
+ - [qccodec](https://github.com/coltonbh/qccodec) - A package for translating between standardized [qcio](https://github.com/coltonbh/qcio) data structures and native QC program inputs and outputs.
54
+ - [qcop](https://github.com/coltonbh/qcop) - A package for operating quantum chemistry programs using standardized [qcio](https://qcio.coltonhicks.com/) data structures. Compatible with `TeraChem`, `psi4`, `QChem`, `NWChem`, `ORCA`, `Molpro`, `geomeTRIC` and many more.
55
+ - [BigChem](https://github.com/mtzgroup/bigchem) - A distributed application for running quantum chemistry calculations at scale across clusters of computers or the cloud. Bring multi-node scaling to your favorite quantum chemistry program.
56
+ - `ChemCloud` - A [web application](https://github.com/mtzgroup/chemcloud-server) and associated [Python client](https://github.com/mtzgroup/chemcloud-client) for exposing a BigChem cluster securely over the internet.
57
+
58
+ ## Installation
59
+
60
+ ```bash
61
+ python -m pip install qcinf
62
+ ```
63
+
64
+ ## Support
65
+
66
+ If you have any issues with `qcinf` or would like to request a feature, please open an [issue](https://github.com/coltonbh/qcinf/issues).
@@ -0,0 +1,14 @@
1
+ qcinf/__init__.py,sha256=oGGkxh5Uo9JUqdNe2N93q29BHNx0pZ0D4J-oJ5GVlb0,325
2
+ qcinf/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ qcinf/utils.py,sha256=22JN81gF7QTwpnPR3N3iTfS9c_EZskmJFNLvINzR8C0,1700
4
+ qcinf/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ qcinf/_backends/openbabel.py,sha256=c_KowfFK7y9ulCVoqkTZQ7h5qVbxRev_MtJakR_avaA,5088
6
+ qcinf/_backends/qcutils.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ qcinf/_backends/rdkit.py,sha256=g58lWqGDxh6syx1-ZO2KOeN_AZlno69r2Tw8qwTSe2A,21473
8
+ qcinf/_backends/utils.py,sha256=FrclCCgBzIBXU9m8gSfmJlJZGJy9Pnx571pn9G_zAN4,1116
9
+ qcinf/algorithms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ qcinf/algorithms/conversion.py,sha256=0e4lDHTTaA_5RQKzkDntMA26ZPvlSFUQY3y5zPFwXYY,2647
11
+ qcinf/algorithms/geometry.py,sha256=NU-ri4sJ0Cw9FIyZHUvOewzfkTknfaljTs_HDIi6yfg,4044
12
+ qcinf-0.1.0.dist-info/METADATA,sha256=NycTdMr1M5i5TyNQWjkQFFWfwgxijhcczaWxEflqyN0,4069
13
+ qcinf-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
14
+ qcinf-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any