Skip to content
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

Cache some charge increment calculations #1126

Merged
merged 5 commits into from
Jan 23, 2025
Merged
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
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
Loading