Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion openmmforcefields/generators/template_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,25 @@ def generate_residue_template(self, molecule):
* This method preserves stereochemistry during AM1-BCC charge parameterization.
* Atom names in molecules will be assigned Tripos atom names if any are blank or not unique.
"""
import shutil

missing = [exe for exe in ("antechamber", "parmchk2") if shutil.which(exe) is None]

if missing:
raise RuntimeError(
f"AmberTools is required for GAFF parameter assignment "
f"(missing from PATH: {', '.join(missing)}).\n"
"Install it with: conda install -c conda-forge 'ambertools>=22'"
)

try:
import parmed
except ModuleNotFoundError as exc:
if exc.name != "parmed":
raise
raise RuntimeError(
"ParmEd is required for GAFF parameter assignment. Install it with: pip install parmed"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about the explicit recommendation to install with pip here, since users might still install OpenMMForceFields with conda (in which case it is probably better to avoid creating an environment in which packages have been installed with both conda and pip).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thinking here is that if the package is installed with conda, then they will have parmed and ambertools, if the install it via pip, then they could be missing parmed but have ambertools in their path, so it felt like the only edge case here is solved with a pip install.

) from exc

from openff.units import unit

Expand Down Expand Up @@ -631,7 +650,6 @@ def generate_residue_template(self, molecule):
from io import StringIO

leaprc = StringIO(f"parm = loadamberparams {frcmod_filename}")
import parmed

params = parmed.amber.AmberParameterSet.from_leaprc(leaprc)
kwargs = {}
Expand Down
42 changes: 42 additions & 0 deletions openmmforcefields/tests/test_optional_parmed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Exercise the optional GAFF-only ParmEd dependency."""

import shutil
import subprocess
import sys

import pytest

from openmmforcefields.generators import GAFFTemplateGenerator


def test_generators_import_without_parmed():
"""Normal imports must not require the optional ParmEd dependency for GAFF."""
subprocess.run(
[
sys.executable,
"-c",
"import sys; sys.modules['parmed'] = None; "
"from openmmforcefields.generators import "
"GAFFTemplateGenerator, SMIRNOFFTemplateGenerator, SystemGenerator",
],
check=True,
capture_output=True,
text=True,
)


def test_gaff_missing_parmed(monkeypatch):
"""Report the missing dependency before starting parameter assignment."""
monkeypatch.setattr(shutil, "which", lambda _: "/usr/bin/mock-ambertools")
monkeypatch.setitem(sys.modules, "parmed", None)
generator = GAFFTemplateGenerator(forcefield="gaff-2.2.20")
with pytest.raises(RuntimeError, match="ParmEd is required for GAFF"):
generator.generate_residue_template(object())


def test_gaff_missing_ambertools_still_reports_ambertools(monkeypatch):
monkeypatch.setattr(shutil, "which", lambda _: None)
monkeypatch.setitem(sys.modules, "parmed", None)
generator = GAFFTemplateGenerator(forcefield="gaff-2.2.20")
with pytest.raises(RuntimeError, match="AmberTools is required for GAFF"):
generator.generate_residue_template(object())
14 changes: 7 additions & 7 deletions openmmforcefields/tests/test_system_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def test_barostat(self, barostat_class, args):
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down Expand Up @@ -259,7 +259,7 @@ def test_create_with_template_generator(self, small_molecule_forcefield):
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down Expand Up @@ -306,7 +306,7 @@ def test_forcefield_default_kwargs(self, small_molecule_forcefield, test_systems
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down Expand Up @@ -361,7 +361,7 @@ def test_forcefield_kwargs(self, small_molecule_forcefield, test_systems):
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down Expand Up @@ -394,7 +394,7 @@ def test_parameterize_molecules_from_creation(self, test_systems, small_molecule
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand All @@ -419,7 +419,7 @@ def test_parameterize_molecules_specified_during_create_system(self, test_system
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down Expand Up @@ -454,7 +454,7 @@ def test_add_molecules(self, test_systems, small_molecule_forcefield):
"small_molecule_forcefield",
[
pytest.param("gaff-2.2.20", marks=pytest.mark.gaff),
"openff-2.0.0",
"openff-2.3.0",
pytest.param("espaloma-0.3.2", marks=pytest.mark.espaloma),
],
)
Expand Down
38 changes: 26 additions & 12 deletions openmmforcefields/tests/test_template_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import openmm
import pytest
from openff.toolkit import Molecule, Topology, ForceField as OFFForceField
from openff.toolkit import AmberToolsToolkitWrapper, OpenEyeToolkitWrapper
from openff.units import unit as OFFUnit
from openmm.app import PME, ForceField, Modeller, NoCutoff, PDBFile

Expand Down Expand Up @@ -76,9 +77,13 @@ def filter_molecules(

def _filter_openff(self, force_field: str) -> bool:
"""
Return True only for Parsley and force fields among SMIRNOFF force fields.
Return whether a force field should be included in parameterization tests.

Skips over (returns False) smirnoff99Frosst, ff14SB, water models, and 2.0.0rc1.
Skip protein and solvent force fields, smirnoff99Frosst, and OpenFF
2.0.0-rc.1. Also skip SMIRNOFF force fields requiring ToolkitAM1BCC
when neither AmberTools nor OpenEye is available.

GAFF force fields are accepted without SMIRNOFF validation.
"""

if "ff14sb" in force_field:
Expand All @@ -101,6 +106,15 @@ def _filter_openff(self, force_field: str) -> bool:
if "smirnoff99" in force_field:
return False

# GAFF is not a SMIRNOFF force field.
if force_field.startswith("gaff-"):
return True

# Older force fields require AM1-BCC, which NAGL cannot provide by name.
if "ToolkitAM1BCC" in OFFForceField(force_field).registered_parameter_handlers:
if not (AmberToolsToolkitWrapper.is_available() or OpenEyeToolkitWrapper.is_available()):
return False

return True

def setUp(self):
Expand Down Expand Up @@ -1144,11 +1158,11 @@ def test_forcefield_multiple(self):
"""Test loading multiple force field components together"""

generator = SMIRNOFFTemplateGenerator(
forcefield=["openff-2.0.0.offxml", "tip3p.offxml", OFFForceField().to_string()]
forcefield=["openff-2.3.0.offxml", "tip3p.offxml", OFFForceField().to_string()]
)
assert generator.forcefield
assert len(generator.smirnoff_filenames) == 3
assert generator.smirnoff_filenames[0].endswith("openff-2.0.0.offxml")
assert generator.smirnoff_filenames[0].endswith("openff-2.3.0.offxml")
assert generator.smirnoff_filenames[1].endswith("tip3p.offxml")
assert generator.smirnoff_filenames[2] is None
assert os.path.exists(generator.smirnoff_filenames[0])
Expand All @@ -1158,21 +1172,21 @@ def test_forcefield_unconstrained(self):
"""Test that forcefield names resolve to unconstrained versions correctly"""

# Should redirect to the unconstrained version
generator = SMIRNOFFTemplateGenerator(forcefield="openff-2.0.0")
assert generator.forcefield == "openff-2.0.0"
generator = SMIRNOFFTemplateGenerator(forcefield="openff-2.3.0")
assert generator.forcefield == "openff-2.3.0"
assert len(generator.smirnoff_filenames) == 1
assert generator.smirnoff_filenames[0].endswith("openff_unconstrained-2.0.0.offxml")
assert generator.smirnoff_filenames[0].endswith("openff_unconstrained-2.3.0.offxml")
assert os.path.exists(generator.smirnoff_filenames[0])

# Should not point to any valid force field
with pytest.raises(ValueError, match="Can't load or parse specified SMIRNOFF"):
SMIRNOFFTemplateGenerator(forcefield="openff_unconstrained-2.0.0")
SMIRNOFFTemplateGenerator(forcefield="openff_unconstrained-2.3.0")

# Specifying a name with .offxml should never get modified
generator = SMIRNOFFTemplateGenerator(forcefield="openff-2.0.0.offxml")
generator = SMIRNOFFTemplateGenerator(forcefield="openff-2.3.0.offxml")
assert generator.forcefield
assert len(generator.smirnoff_filenames) == 1
assert generator.smirnoff_filenames[0].endswith("openff-2.0.0.offxml")
assert generator.smirnoff_filenames[0].endswith("openff-2.3.0.offxml")
assert os.path.exists(generator.smirnoff_filenames[0])

generator = SMIRNOFFTemplateGenerator(forcefield="openff_unconstrained-2.0.0.offxml")
Expand Down Expand Up @@ -1620,7 +1634,7 @@ def test_bespoke_force_field(self):
the template generator.
"""

custom_sage = OFFForceField("openff-2.0.0.offxml")
custom_sage = OFFForceField("openff-2.3.0.offxml")
# Create a simple molecule with one bond type
ethane = Molecule.from_smiles("CC")
# Label ethane to get the bond type (not hard coded incase this changes in future)
Expand Down Expand Up @@ -1658,7 +1672,7 @@ def test_14_scaling_from_offxml(self):

from openmm import unit

custom_sage = OFFForceField("openff-2.0.0.offxml")
custom_sage = OFFForceField("openff-2.3.0.offxml")
custom_sage.get_parameter_handler("vdW").scale14 = 0.7
custom_sage.get_parameter_handler("Electrostatics").scale14 = 0.3

Expand Down
Loading