Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
cd183a8
try to get charges from the force field
jthorton Aug 12, 2026
d1ecb40
Merge branch 'main' into charge_from_ff
jthorton Aug 19, 2026
46c5bbf
add forcefield option for charge assignment
jthorton Aug 19, 2026
f372a16
remove import
jthorton Aug 19, 2026
7c0575e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 19, 2026
00692ec
fix rename, update error message
jthorton Aug 19, 2026
ebf4e78
Merge remote-tracking branch 'origin/charge_from_ff' into charge_from_ff
jthorton Aug 19, 2026
3eb3600
update cli option, add readme
jthorton Aug 20, 2026
d700702
finish CLI support and test, file extension handling
jthorton Aug 21, 2026
5083dd0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Aug 21, 2026
38ff7c6
fix whitespace
jthorton Aug 21, 2026
5fbd1ce
Merge branch 'main' into charge_from_ff
jthorton Aug 24, 2026
aec1d35
use the toolkits in the input settings
jthorton Aug 26, 2026
5616dc1
fix whitespace
jthorton Aug 26, 2026
b9a332f
Merge branch 'main' into charge_from_ff
jthorton Sep 2, 2026
8c4421f
PR feedback, update toolkit backends with nagl, add extra force field…
jthorton Sep 2, 2026
76924a4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 2, 2026
5610478
fix mypy
jthorton Sep 2, 2026
0e50422
Merge branch 'main' into charge_from_ff
jthorton Sep 7, 2026
6038475
Merge branch 'main' into charge_from_ff
jthorton Sep 9, 2026
44102d9
catch forcefields is empty list
jthorton Sep 9, 2026
4cb249d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 9, 2026
cb3fa7b
use new charge settings class for the cli
jthorton Sep 14, 2026
617f07f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 14, 2026
85af2be
Merge branch 'main' into charge_from_ff
jthorton Sep 14, 2026
25d3928
remove whitespace
jthorton Sep 14, 2026
870f030
Merge remote-tracking branch 'origin/charge_from_ff' into charge_from_ff
jthorton Sep 14, 2026
998df08
Update src/openfe/protocols/openmm_utils/charge_generation.py
jthorton Sep 16, 2026
289f674
Update src/openfe/protocols/openmm_utils/charge_generation.py
jthorton Sep 16, 2026
9ef5b92
support vsite force fields, fix mypy
jthorton Sep 16, 2026
e53786f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 16, 2026
d6cd80a
Merge branch 'main' into charge_from_ff
IAlibay Sep 17, 2026
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
23 changes: 23 additions & 0 deletions news/charge_from_ff.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
**Added:**

* The ``assign_offmol_partial_charges`` and ``bulk_assign_partial_charges`` functions can assign charges from a list of OpenFF SMIRNOFF style force fields. Set method=``forcefield`` and provide a list of force field files via the new keyword argument ``forcefields``. This is also supported in the ``charge-molecules`` CLI command and is set by using a yaml settings file.

**Changed:**

* <news item>

**Deprecated:**

* <news item>

**Removed:**

* <news item>

**Fixed:**

* <news item>

**Security:**

* <news item>
107 changes: 90 additions & 17 deletions src/openfe/protocols/openmm_utils/charge_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@

import copy
import sys
import typing
import warnings
from typing import Callable, Literal

import numpy as np
from gufe import SmallMoleculeComponent
from openff.toolkit import ForceField
from openff.toolkit import Molecule as OFFMol
from openff.toolkit.typing.engines.smirnoff import ParameterHandler, VirtualSiteHandler
from openff.toolkit.utils.base_wrapper import ToolkitWrapper
from openff.toolkit.utils.toolkit_registry import ToolkitRegistry
from openff.toolkit.utils.toolkits import (
Expand Down Expand Up @@ -69,6 +72,12 @@
"openeye": [OpenEyeToolkitWrapper],
"rdkit": [RDKitToolkitWrapper],
}
# If the user wants to use NAGL to assign charges via the force field option
# then we need to add it to the backend options if it is available
if HAS_NAGL:
BACKEND_OPTIONS["ambertools"].append(NAGLToolkitWrapper)
BACKEND_OPTIONS["openeye"].append(NAGLToolkitWrapper)
BACKEND_OPTIONS["rdkit"].append(NAGLToolkitWrapper)


def assign_offmol_espaloma_charges(offmol: OFFMol, toolkit_registry: ToolkitRegistry) -> None:
Expand Down Expand Up @@ -286,10 +295,11 @@ def _generate_offmol_conformers(
def assign_offmol_partial_charges(
offmol: OFFMol,
overwrite: bool,
method: Literal["am1bcc", "am1bccelf10", "nagl", "espaloma"],
method: Literal["am1bcc", "am1bccelf10", "nagl", "espaloma", "forcefield"],
Comment thread
IAlibay marked this conversation as resolved.
Resolved
toolkit_backend: Literal["ambertools", "openeye", "rdkit"],
generate_n_conformers: int | None,
nagl_model: str | None,
forcefields: list[str] | None = None,
) -> OFFMol:
"""
Assign partial charges to an OpenFF Molecule based on a selected method.
Expand All @@ -299,11 +309,11 @@ def assign_offmol_partial_charges(
offmol : openff.toolkit.Molecule
The Molecule to assign partial charges to.
overwrite : bool
Whether or not to overwrite any existing non-zero partial charges.
Whether to overwrite any existing non-zero partial charges.
Note that zeroed charges will always be overwritten.
method : Literal['am1bcc', 'am1bccelf10', 'nagl', 'espaloma']
method : Literal['am1bcc', 'am1bccelf10', 'nagl', 'espaloma', 'forcefield']
Partial charge assignment method.
Supported methods include; am1bcc, am1bccelf10, nagl, and espaloma.
Supported methods include; am1bcc, am1bccelf10, nagl, espaloma and forcefield.
toolkit_backend : Literal['ambertools', 'openeye', 'rdkit']
OpenFF toolkit backend employed for charge generation.
Supported options:
Expand All @@ -319,6 +329,14 @@ def assign_offmol_partial_charges(
nagl_model : str | None
The NAGL model to use for charge assignment if method is ``nagl``.
If ``None``, the latest am1bcc NAGL charge model is used.
forcefields : list[str] | None, default None
An optional list of SMIRNOFF style force field offxml paths or strings which should be used to assign partial charges.

Notes
-----
Charges are applied based on the following source preferences:
- Charges already present on the ligand are retained if overwrite is ``False``.
- Charges are applied using the input method and settings.

Raises
------
Expand All @@ -333,12 +351,63 @@ def assign_offmol_partial_charges(
-------
The Molecule with partial charges assigned.
"""
method_name = method.lower()
toolkit_name = toolkit_backend.lower()

# validate the input combination first
if method_name == "forcefield":
if forcefields is None or not forcefields:
errmsg = (
"The forcefield method requires a force field or list of force fields' to be provided "
"via `forcefields`."
)
raise ValueError(errmsg)
elif forcefields is not None and forcefields:
errmsg = f"The `forcefields` option is only valid with the `forcefield` charge method, but got {method_name}."
raise ValueError(errmsg)

# If you have non-zero charges and not overwriting, just return
if offmol.partial_charges is not None and np.any(offmol.partial_charges):
if not overwrite:
return offmol

if method_name == "forcefield":
# mypy can't tell we have already validated that forcefields is not None
forcefields = typing.cast(list[str], forcefields)
try:
# try to parse what the user has provided, due to supporting dropping the offxml extension,
# we need to try and catch the OSError and add the extension if needed
ff = ForceField(*forcefields)
except OSError:
# try adding the offxml extension if not present and it's a possible file path
forcefields_with_ext = []
for _ff in forcefields:
# if the string of the force field is passed it should start with the xml header
if not _ff.endswith(".offxml") and not _ff.startswith("<?xml"):
ff_with_ext = f"{_ff}.offxml"
forcefields_with_ext.append(ff_with_ext)
else:
forcefields_with_ext.append(_ff)

# try again to load the force field with the added extension, if we fail let it raise the error
ff = ForceField(*forcefields_with_ext)

# strip out any VirtualSiteHandler from the force field since we don't want to add virtual sites to the molecule
for handler_name in ff.registered_parameter_handlers:
handler = ff.get_parameter_handler(handler_name)
if issubclass(handler.__class__, VirtualSiteHandler):
warnings.warn(
f"Found a VirtualSiteHandler: {handler_name} in the force field, base charges before applying the virtual site handler will be assigned to the molecule.",
)
ff.deregister_parameter_handler(handler_name)

# make the toolkit registry based on the selected backend
toolkits = ToolkitRegistry([i() for i in BACKEND_OPTIONS[toolkit_name]])
# let the force field resolve the partial charge assignment method
charges = ff.get_partial_charges(offmol, toolkit_registry=toolkits)
offmol.partial_charges = charges
return offmol

# Dictionary for each available charge method
# The idea of this pattern is to allow for maximum flexibility by
# allowing for swapping out method calls as necessary.
Expand Down Expand Up @@ -384,13 +453,13 @@ def assign_offmol_partial_charges(

# Grab the backends and also check our method
try:
backends = CHARGE_METHODS[method.lower()]["backends"]
backends = CHARGE_METHODS[method_name]["backends"]
except KeyError:
errmsg = f"Unknown partial charge method {method}"
raise ValueError(errmsg)

# Check our method actually supports the toolkit backend selected
if toolkit_backend.lower() not in backends: # type: ignore
if toolkit_name not in backends: # type: ignore
errmsg = (
f"Selected toolkit_backend ({toolkit_backend}) cannot "
f"be used with the selected method ({method}). "
Expand All @@ -399,26 +468,26 @@ def assign_offmol_partial_charges(
raise ValueError(errmsg)

# OpenEye is the only optional dependency in the toolkit backends
if toolkit_backend.lower() == "openeye" and not HAS_OPENEYE:
if toolkit_name == "openeye" and not HAS_OPENEYE:
errmsg = "OpenEye is not available and cannot be selected as a backend"
raise ImportError(errmsg)

# Issue 1760
if HAS_OPENEYE and method.lower() == "nagl":
if toolkit_backend.lower() != "openeye":
if HAS_OPENEYE and method_name == "nagl":
if toolkit_name != "openeye":
errmsg = "OpenEye toolkit is installed but not used in the OpenFF toolkit registry backend. This is not possible with NAGL charges."
raise ValueError(errmsg)

toolkits = ToolkitRegistry([i() for i in BACKEND_OPTIONS[toolkit_backend.lower()]])
toolkits = ToolkitRegistry([i() for i in BACKEND_OPTIONS[toolkit_name]])

# We make a copy of the molecule since we're going to modify conformers
offmol_copy = copy.deepcopy(offmol)

# Generate conformers - note this method may differ based on the partial
# charge method employed
CHARGE_METHODS[method.lower()]["confgen_func"](
CHARGE_METHODS[method_name]["confgen_func"](
offmol=offmol_copy,
max_conf=CHARGE_METHODS[method.lower()]["max_conf"],
max_conf=CHARGE_METHODS[method_name]["max_conf"],
toolkit_registry=toolkits,
generate_n_conformers=generate_n_conformers,
) # type: ignore
Expand All @@ -427,10 +496,10 @@ def assign_offmol_partial_charges(
# <https://github.com/openforcefield/openff-toolkit/issues/1831>
with threadpool_limits(limits=1):
# Call selected method to assign partial charges
CHARGE_METHODS[method.lower()]["charge_func"](
CHARGE_METHODS[method_name]["charge_func"](
offmol=offmol_copy,
toolkit_registry=toolkits,
**CHARGE_METHODS[method.lower()]["charge_extra_kwargs"],
**CHARGE_METHODS[method_name]["charge_extra_kwargs"],
) # type: ignore

# Copy partial charges back
Expand All @@ -441,11 +510,12 @@ def assign_offmol_partial_charges(
def bulk_assign_partial_charges(
molecules: list[SmallMoleculeComponent],
overwrite: bool,
method: Literal["am1bcc", "am1bccelf10", "nagl", "espaloma"],
method: Literal["am1bcc", "am1bccelf10", "nagl", "espaloma", "forcefield"],
toolkit_backend: Literal["ambertools", "openeye", "rdkit"],
generate_n_conformers: int | None,
nagl_model: str | None,
processors: int = 1,
forcefields: list[str] | None = None,
) -> list[SmallMoleculeComponent]:
"""
Assign partial charges to a list of SmallMoleculeComponents using multiprocessing.
Expand All @@ -457,9 +527,9 @@ def bulk_assign_partial_charges(
overwrite : bool
Whether or not to overwrite any existing non-zero partial charges.
Note that zeroed charges will always be overwritten.
method : Literal['am1bcc', 'am1bccelf10', 'nagl', 'espaloma']
method : Literal['am1bcc', 'am1bccelf10', 'nagl', 'espaloma', 'forcefield']
Partial charge assignment method.
Supported methods include; am1bcc, am1bccelf10, nagl, and espaloma.
Supported methods include; am1bcc, am1bccelf10, nagl, espaloma and forcefield.
toolkit_backend : Literal['ambertools', 'openeye', 'rdkit']
OpenFF toolkit backend employed for charge generation.
Supported options:
Expand All @@ -477,6 +547,8 @@ def bulk_assign_partial_charges(
If ``None``, the latest am1bcc NAGL charge model is used.
processors: int, default 1
The number of processors which should be used to generate the charges.
forcefields : list[str] | None, default None
An optional list of SMIRNOFF style force field offxml paths or strings which should be used to assign partial charges.

Raises
------
Expand All @@ -499,6 +571,7 @@ def bulk_assign_partial_charges(
"toolkit_backend": toolkit_backend,
"generate_n_conformers": generate_n_conformers,
"nagl_model": nagl_model,
"forcefields": forcefields,
}

if processors > 1:
Expand Down
Loading
Loading