-
Notifications
You must be signed in to change notification settings - Fork 23
Uff python bindings #129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
scal444
wants to merge
3
commits into
NVIDIA-Digital-Bio:main
Choose a base branch
from
scal444:uff_python
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Uff python bindings #129
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| from typing import Any, List | ||
| from rdkit.Chem import Mol | ||
|
|
||
| def UFFOptimizeMoleculesConfs( | ||
| molecules: List[Mol], | ||
| maxIters: int = 1000, | ||
| vdwThresholds: Any = ..., | ||
| ignoreInterfragInteractions: Any = ..., | ||
| hardwareOptions: Any = ..., | ||
| ) -> List[List[float]]: ... | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,198 @@ | ||||||||||||||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||||||||||||||
| # SPDX-License-Identifier: Apache-2.0 | ||||||||||||||
| # | ||||||||||||||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||||||||||||||
| # you may not use this file except in compliance with the License. | ||||||||||||||
| # You may obtain a copy of the License at | ||||||||||||||
| # | ||||||||||||||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||||||||||||||
| # | ||||||||||||||
| # Unless required by applicable law or agreed to in writing, software | ||||||||||||||
| # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||||||||||||||
| # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||||||||||
| # See the License for the specific language governing permissions and | ||||||||||||||
| # limitations under the License. | ||||||||||||||
|
|
||||||||||||||
| import os | ||||||||||||||
|
|
||||||||||||||
| import pytest | ||||||||||||||
| from rdkit import Chem | ||||||||||||||
| from rdkit.Chem import rdDistGeom, rdForceFieldHelpers | ||||||||||||||
| from rdkit.ForceField import rdForceField as _rdForceField # noqa: F401 | ||||||||||||||
| from rdkit.Geometry import Point3D | ||||||||||||||
|
|
||||||||||||||
| import nvmolkit.uffOptimization as nvmolkit_uff | ||||||||||||||
| from nvmolkit.types import HardwareOptions | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| @pytest.fixture | ||||||||||||||
| def uff_test_mols(num_mols=5): | ||||||||||||||
| """Load a handful of UFF-valid molecules from the shared validation set.""" | ||||||||||||||
| sdf_path = os.path.join( | ||||||||||||||
| os.path.dirname(__file__), | ||||||||||||||
| "..", | ||||||||||||||
| "..", | ||||||||||||||
| "tests", | ||||||||||||||
| "test_data", | ||||||||||||||
| "MMFF94_dative.sdf", | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| if not os.path.exists(sdf_path): | ||||||||||||||
| pytest.skip(f"Test data file not found: {sdf_path}") | ||||||||||||||
|
|
||||||||||||||
| supplier = Chem.SDMolSupplier(sdf_path, removeHs=False, sanitize=True) | ||||||||||||||
| molecules = [] | ||||||||||||||
| for mol in supplier: | ||||||||||||||
| if mol is None: | ||||||||||||||
| continue | ||||||||||||||
| if not rdForceFieldHelpers.UFFHasAllMoleculeParams(mol): | ||||||||||||||
| continue | ||||||||||||||
| molecules.append(mol) | ||||||||||||||
| if len(molecules) >= num_mols: | ||||||||||||||
| break | ||||||||||||||
|
|
||||||||||||||
| if len(molecules) < num_mols: | ||||||||||||||
| pytest.skip(f"Expected {num_mols} UFF-valid molecules, found {len(molecules)}") | ||||||||||||||
|
|
||||||||||||||
| return molecules | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def create_hard_copy_mols(molecules): | ||||||||||||||
| return [Chem.Mol(mol) for mol in molecules] | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def make_fragmented_mol(): | ||||||||||||||
| mol = Chem.AddHs(Chem.MolFromSmiles("CC.CC")) | ||||||||||||||
| params = rdDistGeom.ETKDGv3() | ||||||||||||||
| params.useRandomCoords = True | ||||||||||||||
| params.randomSeed = 42 | ||||||||||||||
| rdDistGeom.EmbedMultipleConfs(mol, numConfs=1, params=params) | ||||||||||||||
| conf = mol.GetConformer() | ||||||||||||||
|
Comment on lines
+69
to
+70
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||
| fragments = Chem.GetMolFrags(mol) | ||||||||||||||
| if len(fragments) != 2: | ||||||||||||||
| raise AssertionError("Expected two fragments for interfragment interaction test") | ||||||||||||||
| anchor = conf.GetAtomPosition(fragments[0][0]) | ||||||||||||||
| moved = conf.GetAtomPosition(fragments[1][0]) | ||||||||||||||
| shift = Point3D(anchor.x - moved.x + 2.0, anchor.y - moved.y, anchor.z - moved.z) | ||||||||||||||
| for atom_idx in fragments[1]: | ||||||||||||||
| pos = conf.GetAtomPosition(atom_idx) | ||||||||||||||
| conf.SetAtomPosition(atom_idx, Point3D(pos.x + shift.x, pos.y + shift.y, pos.z + shift.z)) | ||||||||||||||
| return mol | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def calculate_rdkit_uff_energies( | ||||||||||||||
| molecules, | ||||||||||||||
| maxIters=1000, | ||||||||||||||
| vdwThreshold: float = 10.0, | ||||||||||||||
| ignoreInterfragInteractions: bool = True, | ||||||||||||||
| ): | ||||||||||||||
| all_energies = [] | ||||||||||||||
| for mol in molecules: | ||||||||||||||
| mol_energies = [] | ||||||||||||||
| for conf_id in range(mol.GetNumConformers()): | ||||||||||||||
| ff = rdForceFieldHelpers.UFFGetMoleculeForceField( | ||||||||||||||
| mol, | ||||||||||||||
| vdwThresh=vdwThreshold, | ||||||||||||||
| confId=conf_id, | ||||||||||||||
| ignoreInterfragInteractions=ignoreInterfragInteractions, | ||||||||||||||
| ) | ||||||||||||||
| ff.Initialize() | ||||||||||||||
| ff.Minimize(maxIts=maxIters) | ||||||||||||||
| mol_energies.append(ff.CalcEnergy()) | ||||||||||||||
| all_energies.append(mol_energies) | ||||||||||||||
| return all_energies | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def test_uff_optimization_serial_vs_rdkit(uff_test_mols): | ||||||||||||||
| rdkit_mols = create_hard_copy_mols(uff_test_mols) | ||||||||||||||
| nvmolkit_mols = create_hard_copy_mols(uff_test_mols) | ||||||||||||||
|
|
||||||||||||||
| rdkit_energies = calculate_rdkit_uff_energies(rdkit_mols, maxIters=200) | ||||||||||||||
|
|
||||||||||||||
| nvmolkit_energies = [] | ||||||||||||||
| for mol in nvmolkit_mols: | ||||||||||||||
| mol_energies = nvmolkit_uff.UFFOptimizeMoleculesConfs([mol], maxIters=200) | ||||||||||||||
| nvmolkit_energies.extend(mol_energies) | ||||||||||||||
|
|
||||||||||||||
| assert len(rdkit_energies) == len(nvmolkit_energies) | ||||||||||||||
| for mol_idx, (rdkit_mol_energies, nvmolkit_mol_energies) in enumerate(zip(rdkit_energies, nvmolkit_energies)): | ||||||||||||||
| assert len(rdkit_mol_energies) == len(nvmolkit_mol_energies) | ||||||||||||||
| for conf_idx, (rdkit_energy, nvmolkit_energy) in enumerate(zip(rdkit_mol_energies, nvmolkit_mol_energies)): | ||||||||||||||
| diff = abs(rdkit_energy - nvmolkit_energy) | ||||||||||||||
| rel = diff / abs(rdkit_energy) if abs(rdkit_energy) > 1e-10 else diff | ||||||||||||||
| assert rel < 1e-3, ( | ||||||||||||||
| f"Molecule {mol_idx}, conformer {conf_idx}: " | ||||||||||||||
| f"RDKit={rdkit_energy:.6f} nvMolKit={nvmolkit_energy:.6f} rel={rel:.6f}" | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def test_uff_optimization_batch_vs_rdkit(uff_test_mols): | ||||||||||||||
| rdkit_mols = create_hard_copy_mols(uff_test_mols) | ||||||||||||||
| nvmolkit_mols = create_hard_copy_mols(uff_test_mols) | ||||||||||||||
|
|
||||||||||||||
| rdkit_energies = calculate_rdkit_uff_energies(rdkit_mols, maxIters=200) | ||||||||||||||
| hardware_options = HardwareOptions(batchSize=2, batchesPerGpu=1) | ||||||||||||||
| nvmolkit_energies = nvmolkit_uff.UFFOptimizeMoleculesConfs( | ||||||||||||||
| nvmolkit_mols, | ||||||||||||||
| maxIters=200, | ||||||||||||||
| hardwareOptions=hardware_options, | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| assert len(rdkit_energies) == len(nvmolkit_energies) | ||||||||||||||
| for mol_idx, (rdkit_mol_energies, nvmolkit_mol_energies) in enumerate(zip(rdkit_energies, nvmolkit_energies)): | ||||||||||||||
| assert len(rdkit_mol_energies) == len(nvmolkit_mol_energies) | ||||||||||||||
| for conf_idx, (rdkit_energy, nvmolkit_energy) in enumerate(zip(rdkit_mol_energies, nvmolkit_mol_energies)): | ||||||||||||||
| diff = abs(rdkit_energy - nvmolkit_energy) | ||||||||||||||
| rel = diff / abs(rdkit_energy) if abs(rdkit_energy) > 1e-10 else diff | ||||||||||||||
| assert rel < 1e-3, ( | ||||||||||||||
| f"Molecule {mol_idx}, conformer {conf_idx}: " | ||||||||||||||
| f"RDKit={rdkit_energy:.6f} nvMolKit={nvmolkit_energy:.6f} rel={rel:.6f}" | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def test_uff_optimization_empty_input(): | ||||||||||||||
| assert nvmolkit_uff.UFFOptimizeMoleculesConfs([]) == [] | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def test_uff_optimization_invalid_input(): | ||||||||||||||
| unsupported = Chem.MolFromSmiles("*") | ||||||||||||||
| with pytest.raises(ValueError) as exc_info: | ||||||||||||||
| nvmolkit_uff.UFFOptimizeMoleculesConfs([None, unsupported]) | ||||||||||||||
| assert exc_info.value.args[1]["none"] == [0] | ||||||||||||||
| assert exc_info.value.args[1]["no_params"] == [1] | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| def test_uff_optimization_threshold_and_interfrag_vs_rdkit(): | ||||||||||||||
| mols = [make_fragmented_mol(), make_fragmented_mol()] | ||||||||||||||
| rdkit_mols = create_hard_copy_mols(mols) | ||||||||||||||
| nvmolkit_mols = create_hard_copy_mols(mols) | ||||||||||||||
|
|
||||||||||||||
| thresholds = [25.0, 100.0] | ||||||||||||||
| ignore_interfrag = [False, True] | ||||||||||||||
|
|
||||||||||||||
| rdkit_energies = [ | ||||||||||||||
| calculate_rdkit_uff_energies( | ||||||||||||||
| [mol], | ||||||||||||||
| maxIters=1000, | ||||||||||||||
| vdwThreshold=threshold, | ||||||||||||||
| ignoreInterfragInteractions=ignore, | ||||||||||||||
| )[0] | ||||||||||||||
| for mol, threshold, ignore in zip(rdkit_mols, thresholds, ignore_interfrag) | ||||||||||||||
| ] | ||||||||||||||
| nvmolkit_energies = nvmolkit_uff.UFFOptimizeMoleculesConfs( | ||||||||||||||
| nvmolkit_mols, | ||||||||||||||
| maxIters=1000, | ||||||||||||||
| vdwThreshold=thresholds, | ||||||||||||||
| ignoreInterfragInteractions=ignore_interfrag, | ||||||||||||||
| ) | ||||||||||||||
|
|
||||||||||||||
| assert len(rdkit_energies) == len(nvmolkit_energies) | ||||||||||||||
| for mol_idx, (rdkit_mol_energies, nvmolkit_mol_energies) in enumerate(zip(rdkit_energies, nvmolkit_energies)): | ||||||||||||||
| assert len(rdkit_mol_energies) == len(nvmolkit_mol_energies) | ||||||||||||||
| for conf_idx, (rdkit_energy, nvmolkit_energy) in enumerate(zip(rdkit_mol_energies, nvmolkit_mol_energies)): | ||||||||||||||
| diff = abs(rdkit_energy - nvmolkit_energy) | ||||||||||||||
| rel = diff / abs(rdkit_energy) if abs(rdkit_energy) > 1e-10 else diff | ||||||||||||||
| assert rel < 1e-3, ( | ||||||||||||||
| f"Molecule {mol_idx}, conformer {conf_idx}: " | ||||||||||||||
| f"RDKit={rdkit_energy:.6f} nvMolKit={nvmolkit_energy:.6f} rel={rel:.6f}" | ||||||||||||||
| ) | ||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #include <GraphMol/ROMol.h> | ||
|
|
||
| #include <boost/python.hpp> | ||
| #include <stdexcept> | ||
| #include <vector> | ||
|
|
||
| #include "bfgs_uff.h" | ||
|
|
||
| namespace bp = boost::python; | ||
|
|
||
| template <typename T> bp::list vectorToList(const std::vector<T>& vec) { | ||
| bp::list list; | ||
| for (const auto& value : vec) { | ||
| list.append(value); | ||
| } | ||
| return list; | ||
| } | ||
|
|
||
| template <typename T> bp::list vectorOfVectorsToList(const std::vector<std::vector<T>>& vecOfVecs) { | ||
| bp::list outerList; | ||
| for (const auto& innerVec : vecOfVecs) { | ||
| outerList.append(vectorToList(innerVec)); | ||
| } | ||
| return outerList; | ||
| } | ||
|
|
||
| static std::vector<RDKit::ROMol*> extractMolecules(const bp::list& molecules) { | ||
| const int n = bp::len(molecules); | ||
| std::vector<RDKit::ROMol*> mols; | ||
| mols.reserve(n); | ||
| for (int i = 0; i < n; ++i) { | ||
| auto* mol = bp::extract<RDKit::ROMol*>(bp::object(molecules[i]))(); | ||
| if (mol == nullptr) { | ||
| throw std::invalid_argument("Invalid molecule at index " + std::to_string(i)); | ||
| } | ||
| mols.push_back(mol); | ||
| } | ||
| return mols; | ||
| } | ||
|
|
||
| static std::vector<double> extractDoubleList(const bp::list& values, const int expectedSize, const std::string& name) { | ||
| if (bp::len(values) != expectedSize) { | ||
| throw std::invalid_argument("Expected " + std::to_string(expectedSize) + " values for " + name + ", got " + | ||
| std::to_string(bp::len(values))); | ||
| } | ||
| std::vector<double> result; | ||
| result.reserve(expectedSize); | ||
| for (int i = 0; i < expectedSize; ++i) { | ||
| result.push_back(bp::extract<double>(values[i])); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| static std::vector<bool> extractBoolList(const bp::list& values, const int expectedSize, const std::string& name) { | ||
| if (bp::len(values) != expectedSize) { | ||
| throw std::invalid_argument("Expected " + std::to_string(expectedSize) + " values for " + name + ", got " + | ||
| std::to_string(bp::len(values))); | ||
| } | ||
| std::vector<bool> result; | ||
| result.reserve(expectedSize); | ||
| for (int i = 0; i < expectedSize; ++i) { | ||
| result.push_back(bp::extract<bool>(values[i])); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| BOOST_PYTHON_MODULE(_uffOptimization) { | ||
| bp::def( | ||
| "UFFOptimizeMoleculesConfs", | ||
| +[](const bp::list& molecules, | ||
| int maxIters, | ||
| const bp::list& vdwThresholds, | ||
| const bp::list& ignoreInterfragInteractions, | ||
| const nvMolKit::BatchHardwareOptions& hardwareOptions) -> bp::list { | ||
| auto molsVec = extractMolecules(molecules); | ||
| const int numMols = static_cast<int>(molsVec.size()); | ||
| const auto thresholdVec = extractDoubleList(vdwThresholds, numMols, "vdwThreshold"); | ||
| const auto ignoreVec = extractBoolList(ignoreInterfragInteractions, numMols, "ignoreInterfragInteractions"); | ||
| const auto result = | ||
| nvMolKit::UFF::UFFOptimizeMoleculesConfsBfgs(molsVec, maxIters, thresholdVec, ignoreVec, hardwareOptions); | ||
| return vectorOfVectorsToList(result); | ||
| }, | ||
| (bp::arg("molecules"), | ||
| bp::arg("maxIters") = 1000, | ||
| bp::arg("vdwThresholds"), | ||
| bp::arg("ignoreInterfragInteractions"), | ||
| bp::arg("hardwareOptions") = nvMolKit::BatchHardwareOptions()), | ||
| "Optimize conformers for multiple molecules using UFF force field.\n" | ||
| "\n" | ||
| "Args:\n" | ||
| " molecules: List of RDKit molecules to optimize\n" | ||
| " maxIters: Maximum number of optimization iterations (default: 1000)\n" | ||
| " vdwThresholds: Per-molecule van der Waals thresholds\n" | ||
| " ignoreInterfragInteractions: Per-molecule interfragment interaction flags\n" | ||
| " hardwareOptions: BatchHardwareOptions object with hardware settings\n" | ||
| "\n" | ||
| "Returns:\n" | ||
| " List of lists of energies, where each inner list contains energies for conformers of one molecule"); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Anytypes reduce stub valueAll three non-trivial parameters are typed as
Any, eliminating IDE autocompletion and type-checker coverage for callers of the internal binding. The C++ layer already enforces concrete list types, so the stub can reflect them.