Skip to content

Commit

Permalink
Merge pull request #1126 from openforcefield/fix-charge-summing
Browse files Browse the repository at this point in the history
Cache some charge increment calculations
  • Loading branch information
mattwthompson authored Jan 23, 2025
2 parents ea24a5f + fe8f88f commit 4edb63a
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions openff/interchange/smirnoff/_nonbonded.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
LibraryChargeHandler,
]

_ZERO_CHARGE = Quantity(0.0, unit.elementary_charge)
_ZERO_CHARGE = Quantity(0.0, "elementary_charge")


@functools.lru_cache(None)
Expand Down Expand Up @@ -352,7 +352,10 @@ def _get_charges(
for i, increment in enumerate(parameter_value):
orientation_atom_index = topology_key.orientation_atom_indices[i]

charges[orientation_atom_index] = charges.get(orientation_atom_index, 0.0) + increment.m
charges[orientation_atom_index] = _add_charges(
charges.get(orientation_atom_index, _ZERO_CHARGE).m,
increment.m,
)

elif parameter_key == "charge":
assert len(topology_key.atom_indices) == 1
Expand All @@ -365,15 +368,22 @@ def _get_charges(
"molecules_with_preset_charges",
"ExternalSource",
):
charges[atom_index] = charges.get(atom_index, 0.0) + parameter_value.m
charges[atom_index] = _add_charges(
charges.get(atom_index, _ZERO_CHARGE).m,
parameter_value.m,
)

elif potential_key.associated_handler in ( # type: ignore[operator]
"ChargeIncrementModelHandler"
):
# the "charge" and "charge_increment" keys may not appear in that order, so
# we "add" the charge whether or not the increment was already applied.
# There should be a better way to do this.
charges[atom_index] = charges.get(atom_index, 0.0) + parameter_value.m

charges[atom_index] = _add_charges(
charges.get(atom_index, _ZERO_CHARGE).m,
parameter_value.m,
)

else:
raise RuntimeError(
Expand All @@ -385,7 +395,10 @@ def _get_charges(

atom_index = topology_key.atom_indices[0]

charges[atom_index] = charges.get(atom_index, 0.0) + parameter_value.m
charges[atom_index] = _add_charges(
charges.get(atom_index, _ZERO_CHARGE).m,
parameter_value.m,
)

logger.info(
"Charge section ChargeIncrementModel, applying charge increment from atom " # type: ignore[union-attr]
Expand Down

0 comments on commit 4edb63a

Please sign in to comment.