From 1135e4d8e9f9cbd70d0a02fbe06bde47fb6b173b Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Thu, 5 Nov 2026 14:06:53 +0000 Subject: [PATCH] Backport fixes from PR #520. [ci skip] --- corelib/src/libs/SireCAS/lambdaschedule.cpp | 14 +- src/sire/morph/_xml.py | 114 ++++++---- tests/conftest.py | 10 + tests/convert/test_openmm_constraints.py | 110 ++++++++-- tests/convert/test_openmm_lambda.py | 136 ++++++++++++ tests/convert/test_openmm_lever_values.py | 27 +++ tests/convert/test_openmm_minimise.py | 22 ++ tests/convert/test_openmm_rest2.py | 18 +- tests/morph/test_decouple.py | 73 +++++++ wrapper/Convert/SireOpenMM/_perturbablemol.py | 7 +- wrapper/Convert/SireOpenMM/lambdalever.cpp | 160 +++++++++++++- wrapper/Convert/SireOpenMM/lambdalever.h | 6 + wrapper/Convert/SireOpenMM/openmmminimise.cpp | 92 ++++++-- wrapper/Convert/SireOpenMM/openmmmolecule.cpp | 201 ++++++++++++++++-- wrapper/Convert/SireOpenMM/openmmmolecule.h | 23 ++ .../SireOpenMM/sire_to_openmm_system.cpp | 201 ++++++++++++++++-- 16 files changed, 1094 insertions(+), 120 deletions(-) create mode 100644 tests/convert/test_openmm_lever_values.py diff --git a/corelib/src/libs/SireCAS/lambdaschedule.cpp b/corelib/src/libs/SireCAS/lambdaschedule.cpp index 9d22dc6ae..cde8ac4c7 100644 --- a/corelib/src/libs/SireCAS/lambdaschedule.cpp +++ b/corelib/src/libs/SireCAS/lambdaschedule.cpp @@ -759,18 +759,20 @@ void LambdaSchedule::addDecoupleStage(const QString &name, bool perturbed_is_dec this->setEquation(name, "ghost/ghost", "*", this->initial()); this->setEquation(name, "ghost-14", "*", this->initial()); - // kappa is fixed to 1.0 - this->setEquation(name, "ghost/ghost", "kappa", 1.0); - this->setEquation(name, "ghost-14", "kappa", 1.0); + // stop subtracting the hard Coulomb as the charges in the + // NonbondedForce go to zero, so the intramolecular terms are kept + this->setEquation(name, "ghost/ghost", "kappa", 1.0 - this->lam()); + this->setEquation(name, "ghost-14", "kappa", 1.0 - this->lam()); } else { this->setEquation(name, "ghost/ghost", "*", this->final()); this->setEquation(name, "ghost-14", "*", this->final()); - // kappa is fixed to 1.0 - this->setEquation(name, "ghost/ghost", "kappa", 1.0); - this->setEquation(name, "ghost-14", "kappa", 1.0); + // stop subtracting the hard Coulomb as the charges in the + // NonbondedForce go to zero, so the intramolecular terms are kept + this->setEquation(name, "ghost/ghost", "kappa", this->lam()); + this->setEquation(name, "ghost-14", "kappa", this->lam()); } } diff --git a/src/sire/morph/_xml.py b/src/sire/morph/_xml.py index 29bee2a1d..51d39fe89 100644 --- a/src/sire/morph/_xml.py +++ b/src/sire/morph/_xml.py @@ -113,6 +113,63 @@ def evaluate_xml_force(mols, xml, force): nrg_coul_list = [] nrg_lj_list = [] + def evaluate_bonds(bond_force): + """Evaluate the energy of each bond in a CustomBondForce.""" + + # Get the energy terms. + terms = list(reversed(bond_force.get("energy").split(";")[1:-1])) + + # The LJ term may be cut off, e.g. "coul_nrg+step(0.9-r)*lj_nrg". + import re + + match = re.search(r"step\(([^-]+)-r\)", bond_force.get("energy").split(";")[0]) + lj_cutoff = float(match.group(1)) if match else None + + # Get the parameters for this force. + parameters = [p.get("name") for p in bond_force.find("PerBondParameters")] + + # Get all the bond parameters. + bonds = bond_force.find("Bonds").findall("Bond") + + # Get the list of atoms. + atoms = mols.atoms() + + # Loop over all bonds. + for bond in bonds: + # Get the atoms involved in the bond. + atom_i = atoms[int(bond.get("p1"))] + atom_j = atoms[int(bond.get("p2"))] + + # Set the parameters for this bond. + for k, param in enumerate(parameters): + setattr(module, param, float(bond.get(f"param{k + 1}"))) + + # Get the distance between the particles. + r = measure(atom_i, atom_j).to(nanometer) + + # Evaluate the energy term by term. + for term in terms: + # Replace any instances of ^ with **. + term = term.replace("^", "**") + + # Split the term into the result and the expression. + result, expression = term.split("=") + + # Evaluate the expression. + setattr(module, result, eval(expression)) + + # Give energies units. + coul_nrg = module.coul_nrg * kJ_per_mol + lj_nrg = module.lj_nrg * kJ_per_mol + + if lj_cutoff is not None and r > lj_cutoff: + lj_nrg = 0.0 * kJ_per_mol + + # Append the results for this bond. + pairs.append((atom_i, atom_j)) + nrg_coul_list.append(coul_nrg) + nrg_lj_list.append(lj_nrg) + # CustomNonbondedForce: ghost-ghost or ghost-nonghost. if name != "Ghost14BondForce": # Get the parameters for this force. @@ -135,6 +192,8 @@ def evaluate_xml_force(mols, xml, force): .find("Set2") ] + is_same_set = set(set1) == set(set2) + # Get the exclusions. exclusions = [ (int(e.get("p1")), int(e.get("p2"))) @@ -171,8 +230,9 @@ def evaluate_xml_force(mols, xml, force): # Get the index from set2. j = set2[y] - # Ignore self-interaction. - if i == j: + # Ignore self-interaction, and count each pair once when + # the two sets are the same. + if i == j or (is_same_set and j < i): continue # Check if this pair is excluded. @@ -215,49 +275,17 @@ def evaluate_xml_force(mols, xml, force): nrg_coul_list.append(coul_nrg) nrg_lj_list.append(lj_nrg) + # Intramolecular ghost/ghost pairs are computed without a cutoff + # in a separate CustomBondForce. + if name == "GhostGhostNonbondedForce": + for bond_force in tree.find("Forces"): + if bond_force.get("name") == "GhostGhostBondForce": + evaluate_bonds(bond_force) + break + # CustomBondForce: ghost-14. else: - # Get the parameters for this force. - parameters = [p.get("name") for p in force.find("PerBondParameters")] - - # Get all the bond parameters. - bonds = force.find("Bonds").findall("Bond") - - # Get the list of atoms. - atoms = mols.atoms() - - # Loop over all bonds. - for bond in bonds: - # Get the atoms involved in the bond. - atom_i = atoms[int(bond.get("p1"))] - atom_j = atoms[int(bond.get("p2"))] - - # Set the parameters for this bond. - for k, param in enumerate(parameters): - setattr(module, param, float(bond.get(f"param{k + 1}"))) - - # Get the distance between the particles. - r = measure(atom_i, atom_j).to(nanometer) - - # Evaluate the energy term by term. - for term in terms: - # Replace any instances of ^ with **. - term = term.replace("^", "**") - - # Split the term into the result and the expression. - result, expression = term.split("=") - - # Evaluate the expression. - setattr(module, result, eval(expression)) - - # Give energies units. - coul_nrg = module.coul_nrg * kJ_per_mol - lj_nrg = module.lj_nrg * kJ_per_mol - - # Append the results for this bond. - pairs.append((atom_i, atom_j)) - nrg_coul_list.append(coul_nrg) - nrg_lj_list.append(lj_nrg) + evaluate_bonds(force) # Return the results. return pairs, nrg_coul_list, nrg_lj_list diff --git a/tests/conftest.py b/tests/conftest.py index 816684d5e..e20c8ad49 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -238,6 +238,16 @@ def cyclopropyl_constraint_bug(): return sr.load_test_files("ejm_31_jmc_28.bss") +@pytest.fixture(scope="session") +def macrocycle_ghost_constraints(): + return sr.load_test_files("macrocycle_ghost_constraints.bss") + + +@pytest.fixture(scope="session") +def ring_break_constraints(): + return sr.load_test_files("ring_break_constraints.bss") + + @pytest.fixture(scope="session") def zero_lj_mols(): return sr.load_test_files("zero_lj.prm7", "zero_lj.rst7") diff --git a/tests/convert/test_openmm_constraints.py b/tests/convert/test_openmm_constraints.py index e856864e2..98b835146 100644 --- a/tests/convert/test_openmm_constraints.py +++ b/tests/convert/test_openmm_constraints.py @@ -462,9 +462,9 @@ def test_cyclopropyl_anchor_bond_constraint( cyclopropyl_constraint_bug, openmm_platform ): """ - Regression test for an unperturbed anchor bond (to two alternate - heavy-atom substituents) not being constrained under - "h-bonds-not-heavy-perturbed", unlike SOMD1. + Heavy-atom bonds at the alchemical junction aren't constrained under + "h-bonds-not-heavy-perturbed", since constraining them destabilises + perturbable molecules with large ghost regions. (SOMD1 constrains them.) """ mols = sr.morph.link_to_reference(cyclopropyl_constraint_bug) mol = mols[0] @@ -503,21 +503,49 @@ def get_anchor_constraints(d): return found - found = get_anchor_constraints(d) + assert get_anchor_constraints(d) == {} - assert set(found.keys()) == substituent_idxs + d.set_lambda(1.0) - # both anchor bonds should have the same, static length, matching - # SOMD1's value for this generic aromatic-C/sp3-C bond - for length in found.values(): - assert length == pytest.approx(1.51234, abs=1e-3) + assert get_anchor_constraints(d) == {} - # the constraint should remain static (not lambda-dependent), since the - # bond's own parameters don't change between end states - d.set_lambda(1.0) - found_at_1 = get_anchor_constraints(d) - assert found_at_1 == found +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +@pytest.mark.slow +@pytest.mark.parametrize("lambda_value", [0.0, 1.0]) +def test_macrocycle_ghost_constraints( + macrocycle_ghost_constraints, openmm_platform, lambda_value +): + """ + A partially mapped macrocycle (OpenFE bayer_macrocycles brd4, 61a~25e), + solvated, with large ghost regions. This blew up within a few steps when + heavy-atom bonds at the alchemical junction were constrained. + """ + if lambda_value == 0.0: + mols = sr.morph.link_to_reference(macrocycle_ghost_constraints) + else: + mols = sr.morph.link_to_perturbed(macrocycle_ghost_constraints) + + mols = ( + mols.minimisation(lambda_value=lambda_value, platform=openmm_platform) + .run() + .commit() + ) + + d = mols.dynamics( + timestep="2 fs", + lambda_value=lambda_value, + constraint="h-bonds", + perturbable_constraint="h-bonds-not-heavy-perturbed", + platform=openmm_platform, + ) + + d.run("1 ps", save_frequency=0, auto_fix_minimise=False) + + assert d.current_potential_energy().value() < 0 @pytest.mark.skipif( @@ -591,3 +619,57 @@ def test_asymmetric_constraints(merged_ethane_methanol): # Check the minimised potential energies are the same. (Post constraint projection.) assert isclose(nrg_forwards, nrg_backwards, rel_tol=1e-4) + + +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +@pytest.mark.slow +@pytest.mark.parametrize("lambda_value", [0.0, 1.0]) +def test_ring_break_constraints(ring_break_constraints, openmm_platform, lambda_value): + """ + The bond broken by a ring-breaking perturbation (OpenFE scaffold_hopping + chk1, 1~17) is never constrained. One of its atoms becomes a hydrogen, so it + used to be constrained at lambda = 1, where it no longer exists, which blew up. + """ + pert = ring_break_constraints.molecules("property is_perturbable")[0] + + bonds = [ + { + tuple(sorted((b.atom0().value(), b.atom1().value()))) + for b in pert.property(f"connectivity{i}").get_bonds() + } + for i in (0, 1) + ] + broken = bonds[0] ^ bonds[1] + assert len(broken) == 1 + + if lambda_value == 0.0: + mols = sr.morph.link_to_reference(ring_break_constraints) + else: + mols = sr.morph.link_to_perturbed(ring_break_constraints) + + mols = ( + mols.minimisation(lambda_value=lambda_value, platform=openmm_platform) + .run() + .commit() + ) + + d = mols.dynamics( + timestep="1 fs", + lambda_value=lambda_value, + constraint="h-bonds", + perturbable_constraint="h-bonds-not-heavy-perturbed", + platform=openmm_platform, + ) + + constrained = { + tuple(sorted((c[0][0].index().value(), c[0][1].index().value()))) + for c in d.get_constraints() + if c[0][0].molecule().number() == pert.number() + } + + assert not (broken & constrained) + + d.run("1 ps", save_frequency=0, auto_fix_minimise=False) diff --git a/tests/convert/test_openmm_lambda.py b/tests/convert/test_openmm_lambda.py index 6e22457e0..40feeef9a 100644 --- a/tests/convert/test_openmm_lambda.py +++ b/tests/convert/test_openmm_lambda.py @@ -722,3 +722,139 @@ def test_neopentane_methane_no_charge(neopentane_methane, openmm_platform): d.set_lambda(lam_val) calc = d.current_potential_energy().value() assert calc == pytest.approx(nrg, abs=1e-4) + + +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +@pytest.mark.parametrize( + "cutoff, cutoff_type, periodic", + [ + ("none", None, False), + ("7.5 A", "RF", False), + ("10 A", "RF", True), + ("10 A", "PME", True), + ], +) +@pytest.mark.parametrize("swap_end_states", [False, True]) +@pytest.mark.parametrize("softening", ["zacharias", "taylor", "beutler"]) +def test_ring_break_end_state( + ring_break_constraints, + openmm_platform, + cutoff, + cutoff_type, + periodic, + swap_end_states, + softening, +): + """ + The energies at the end states of a ring-breaking perturbation match the + plain end-state molecules for any cutoff type and soft-core form: the + broken pair doesn't interact while it is bonded, and the pairs across the + broken bond are normal non-bonded pairs once it is broken. Swapping the + end states tests the ring-making case. + """ + merge = ring_break_constraints.molecules("property is_perturbable")[0] + + c = merge.cursor() + c["coordinates"] = c["coordinates0"] + c["coordinates1"] = c["coordinates0"] + merge = c.commit() + + def get_end_state(state, remove_state): + c = merge.cursor() + for key in c.keys(): + if key.endswith(state): + c[key.removesuffix(state)] = c[key] + del c[key] + elif key.endswith(remove_state): + del c[key] + c["is_perturbable"] = False + return c.commit() + + space = ring_break_constraints.space() if periodic else sr.vol.Cartesian() + + m = { + "platform": openmm_platform, + "constraint": "none", + "cutoff": cutoff, + "space": space, + } + + if cutoff_type is not None: + m["cutoff_type"] = cutoff_type + + nrg0 = sr.convert.to(get_end_state("0", "1"), "openmm", map=m).get_energy().value() + nrg1 = sr.convert.to(get_end_state("1", "0"), "openmm", map=m).get_energy().value() + + if swap_end_states: + nrg0, nrg1 = nrg1, nrg0 + + m["swap_end_states"] = swap_end_states + + if softening == "taylor": + m["use_taylor_softening"] = True + elif softening == "beutler": + m["use_beutler_softening"] = True + + omm = sr.convert.to(merge, "openmm", map=m) + + omm.set_lambda(0.0) + assert omm.get_energy().value() == pytest.approx(nrg0, abs=1e-2) + + omm.set_lambda(1.0) + assert omm.get_energy().value() == pytest.approx(nrg1, abs=1e-2) + + +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +def test_unscaled_14_coulomb_end_state(merged_ethane_methanol, openmm_platform): + """ + 1-4 pairs with an unscaled Coulomb term but a scaled LJ term are still + exceptions, so the end states match the plain molecules with reaction + field. + """ + from sire.legacy.MM import CLJNBPairs, CLJScaleFactor + + merge = merged_ethane_methanol[0] + + c = merge.cursor() + c["coordinates"] = c["coordinates0"] + c["coordinates1"] = c["coordinates0"] + nbpairs = CLJNBPairs(merge.property("connectivity"), CLJScaleFactor(1.0, 0.5)) + c["intrascale0"] = nbpairs + c["intrascale1"] = nbpairs + merge = c.commit() + + def get_end_state(state, remove_state): + c = merge.cursor() + for key in c.keys(): + if key.endswith(state): + c[key.removesuffix(state)] = c[key] + del c[key] + elif key.endswith(remove_state): + del c[key] + c["is_perturbable"] = False + return c.commit() + + m = { + "platform": openmm_platform, + "constraint": "none", + "cutoff": "7.5 A", + "cutoff_type": "RF", + "space": sr.vol.Cartesian(), + } + + nrg0 = sr.convert.to(get_end_state("0", "1"), "openmm", map=m).get_energy().value() + nrg1 = sr.convert.to(get_end_state("1", "0"), "openmm", map=m).get_energy().value() + + omm = sr.convert.to(merge, "openmm", map=m) + + omm.set_lambda(0.0) + assert omm.get_energy().value() == pytest.approx(nrg0, abs=1e-3) + + omm.set_lambda(1.0) + assert omm.get_energy().value() == pytest.approx(nrg1, abs=1e-3) diff --git a/tests/convert/test_openmm_lever_values.py b/tests/convert/test_openmm_lever_values.py new file mode 100644 index 000000000..8078249cc --- /dev/null +++ b/tests/convert/test_openmm_lever_values.py @@ -0,0 +1,27 @@ +import sire as sr + +import pytest + + +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +def test_unchanged_levers_not_reported(): + """ + Levers that don't change, apart from round-off, aren't reported. + """ + mols = sr.load_test_files("benzene.prm7", "benzene.rst") + benzene = sr.morph.decouple(mols[0], as_new_molecule=False) + + p = benzene.perturbation().to_openmm() + df = p.get_lever_values(schedule=benzene.property("schedule")) + + assert list(df.columns) == [ + "clj-charge-1", + "clj-charge-7", + "clj-epsilon-1", + "clj-epsilon-7", + "clj-alpha-1", + "ghost/ghost-kappa-1", + ] diff --git a/tests/convert/test_openmm_minimise.py b/tests/convert/test_openmm_minimise.py index 9f7dc2045..a125b763d 100644 --- a/tests/convert/test_openmm_minimise.py +++ b/tests/convert/test_openmm_minimise.py @@ -90,3 +90,25 @@ def test_openmm_minimise_vacuum(kigaki_mols, openmm_platform): mols = mols.minimisation(platform=openmm_platform, vacuum=True).run(10).commit() assert not mols.property("space").is_periodic() + + +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +def test_openmm_minimise_invalid_energy(ala_mols, openmm_platform): + # A NaN position makes the minimiser fail. It should raise an exception + # rather than crash the interpreter. (The message depends on the platform.) + import math + + from openmm import Vec3, unit + + m = ala_mols.minimisation(platform=openmm_platform) + + context = m._d._omm_mols + positions = context.getState(getPositions=True).getPositions() + positions[0] = Vec3(math.nan, math.nan, math.nan) * unit.nanometer + context.setPositions(positions) + + with pytest.raises(Exception): + m.run(10) diff --git a/tests/convert/test_openmm_rest2.py b/tests/convert/test_openmm_rest2.py index 67d767a38..1c3f4cfe0 100644 --- a/tests/convert/test_openmm_rest2.py +++ b/tests/convert/test_openmm_rest2.py @@ -204,12 +204,22 @@ def test_rest2(mols, rest2_selection, excluded_atoms, request): excluded_nonbonded_indices.append(i) exception_params_initial = [] excluded_exceptions = [] + exception_atoms = [] for i in range(force.getNumExceptions()): x, y, chargeProd, sigma, epsilon = force.getExceptionParameters(i) exception_params_initial.append((chargeProd, epsilon)) + exception_atoms.append((x, y)) if x in excluded_atoms or y in excluded_atoms: excluded_exceptions.append(i) + # Intramolecular ghost/ghost pairs keep the per-particle REST2 scaling. + ghost_pairs = set() + for f in omm_system.getForces(): + if f.getName() == "GhostGhostBondForce": + for i in range(f.getNumBonds()): + x, y, _ = f.getBondParameters(i) + ghost_pairs.add((x, y)) + # Handle custom forces for pertubable molecules. if is_perturbable: # Find the ghost/ghost nonbonded interaction. @@ -342,7 +352,13 @@ def test_rest2(mols, rest2_selection, excluded_atoms, request): for i in range(len(exception_params_initial)): charge, epsilon = exception_params_initial[i] charge_modified, epsilon_modified = exception_params_modified[i] - if i in excluded_exceptions: + if exception_atoms[i] in ghost_pairs: + x, y = exception_atoms[i] + factor = (1.0 if x in excluded_atoms else scale**0.5) * ( + 1.0 if y in excluded_atoms else scale**0.5 + ) + assert isclose(charge_modified._value, charge._value * factor) + elif i in excluded_exceptions: # This exception is not in the REST2 region so is unchanged. assert isclose(charge_modified._value, charge._value) assert isclose(epsilon_modified._value, epsilon._value) diff --git a/tests/morph/test_decouple.py b/tests/morph/test_decouple.py index 8c0dc68c3..bac6fb7aa 100644 --- a/tests/morph/test_decouple.py +++ b/tests/morph/test_decouple.py @@ -87,6 +87,79 @@ def test_decouple(ala_mols, openmm_platform): assert bwds.empty +@pytest.mark.skipif( + "openmm" not in sr.convert.supported_formats(), + reason="openmm support is not available", +) +@pytest.mark.parametrize("cutoff_type", ["PME", "RF"]) +def test_decouple_intramolecular_cutoff(ala_mols, openmm_platform, cutoff_type): + """ + The decouple schedule keeps the intramolecular interactions, and their + electrostatics aren't cut off, so the decoupled molecule matches the + molecule in vacuum, apart from the LJ beyond the cutoff. + """ + import math + + from openmm import unit + + mol = ala_mols[0] + + dmol = sr.morph.decouple(mol) + + # The cutoff is shorter than the molecule. + cutoff = 0.4 + d = dmol.dynamics( + platform=openmm_platform, + cutoff=f"{10 * cutoff} A", + cutoff_type=cutoff_type, + schedule=dmol.property("schedule"), + lambda_value=1.0, + map={"space": ala_mols.space()}, + ) + + d_vac = mol.dynamics(platform=openmm_platform, vacuum=True, cutoff="none") + + # The LJ energy of the non-excluded, non-1-4 pairs beyond the cutoff. + context = d_vac.context() + nbforce = [ + f for f in context.getSystem().getForces() if f.getName() == "NonbondedForce" + ][0] + positions = context.getState(getPositions=True).getPositions(asNumpy=True) + positions = positions.value_in_unit(unit.nanometer) + + exceptions = set() + for i in range(nbforce.getNumExceptions()): + p1, p2, *_ = nbforce.getExceptionParameters(i) + exceptions.add((min(p1, p2), max(p1, p2))) + + params = [ + nbforce.getParticleParameters(i) for i in range(nbforce.getNumParticles()) + ] + + lj_tail = 0.0 + for i in range(len(params)): + for j in range(i + 1, len(params)): + r = math.dist(positions[i], positions[j]) + if r <= cutoff or (i, j) in exceptions: + continue + sigma = 0.5 * (params[i][1] + params[j][1]).value_in_unit(unit.nanometer) + epsilon = math.sqrt( + params[i][2].value_in_unit(unit.kilojoule_per_mole) + * params[j][2].value_in_unit(unit.kilojoule_per_mole) + ) + sr6 = (sigma / r) ** 6 + lj_tail += 4.0 * epsilon * (sr6 * sr6 - sr6) + + # Convert from kJ/mol to kcal/mol. + lj_tail /= 4.184 + + assert lj_tail != pytest.approx(0.0, abs=1e-2) + + assert d.current_potential_energy().value() == pytest.approx( + d_vac.current_potential_energy().value() - lj_tail, abs=1e-2 + ) + + @pytest.mark.skipif( "openmm" not in sr.convert.supported_formats(), reason="openmm support is not available", diff --git a/wrapper/Convert/SireOpenMM/_perturbablemol.py b/wrapper/Convert/SireOpenMM/_perturbablemol.py index 135e44cdc..fbc2d8bff 100644 --- a/wrapper/Convert/SireOpenMM/_perturbablemol.py +++ b/wrapper/Convert/SireOpenMM/_perturbablemol.py @@ -145,7 +145,10 @@ def _get_lever_values( merged = {} - # only add in columns that change values + from math import isclose + + # only add in columns that change values, ignoring round-off from + # morphing between identical end states for i in range(len(colnames)): column = columns[i] @@ -153,7 +156,7 @@ def _get_lever_values( changed = False for j in range(1, len(column)): - if column[j] != column[j - 1]: + if not isclose(column[j], column[0], rel_tol=1e-12, abs_tol=1e-12): changed = True break diff --git a/wrapper/Convert/SireOpenMM/lambdalever.cpp b/wrapper/Convert/SireOpenMM/lambdalever.cpp index 3aa75bddf..53deb03d5 100644 --- a/wrapper/Convert/SireOpenMM/lambdalever.cpp +++ b/wrapper/Convert/SireOpenMM/lambdalever.cpp @@ -1302,6 +1302,11 @@ double LambdaLever::setLambda(OpenMM::Context &context, auto ghost_ghostff = this->getForce("ghost/ghost", system); auto ghost_nonghostff = this->getForce("ghost/non-ghost", system); auto ghost_14ff = this->getForce("ghost-14", system); + auto ghost_pairff = this->getForce("ghost/ghost-pairs", system); + auto ghost_pair_rff = this->getForce("clj-ghost-pairs", system); + auto ring_breaking_rff = this->getForce("clj-ring-break", system); + auto ring_making_rff = this->getForce("clj-ring-make", system); + auto exception_rff = this->getForce("clj-exceptions", system); auto ring_breaking_ff = this->getForce("ring-break", system); auto ring_making_ff = this->getForce("ring-make", system); auto bondff = this->getForce("bond", system); @@ -1761,11 +1766,103 @@ double LambdaLever::setLambda(OpenMM::Context &context, } } } + + // Exceptions that are normal pairs in an end state need the reaction + // field correction there, interpolated with the charge scale lever. + const auto rf_exception_idxs = perturbable_mol.getRFExceptionIndicies(); + + if (exception_rff != 0 and not rf_exception_idxs.isEmpty()) + { + const auto exception_atoms = perturbable_mol.getExceptionAtoms(); + const auto charge_scales0 = perturbable_mol.getChargeScales0(); + const auto charge_scales1 = perturbable_mol.getChargeScales1(); + const auto lj_scales0 = perturbable_mol.getLJScales0(); + const auto lj_scales1 = perturbable_mol.getLJScales1(); + + for (const auto &rf_idx : rf_exception_idxs) + { + const int j = boost::get<0>(rf_idx); + const auto atom0 = boost::get<0>(exception_atoms[j]); + const auto atom1 = boost::get<1>(exception_atoms[j]); + + // a pair is only a normal pair if neither scale is applied + const bool is_normal0 = charge_scales0[j] == 1.0 and lj_scales0[j] == 1.0; + const bool is_normal1 = charge_scales1[j] == 1.0 and lj_scales1[j] == 1.0; + + const double is_normal = schedule.morph("clj", "charge_scale", + is_normal0 ? 1.0 : 0.0, + is_normal1 ? 1.0 : 0.0, + lambda_value); + + // match the REST2 scaling of the exception + const double scale = (perturbable_mol.isRest2(atom0) and perturbable_mol.isRest2(atom1)) + ? rest2_scale + : 1.0; + + exception_rff->setBondParameters( + boost::get<1>(rf_idx), atom0 + start_index, atom1 + start_index, + {is_normal * scale * morphed_charges[atom0] * morphed_charges[atom1]}); + } + } + + // The hard Coulomb for the intramolecular ghost/ghost pairs is an + // exception, and the soft-core terms use the ghost/ghost levers. + const auto ghost_pair_idxs = perturbable_mol.getGhostPairIndicies(); + + if (not ghost_pair_idxs.isEmpty()) + { + const auto ghost_pair_atoms = perturbable_mol.getGhostPairAtoms(); + + for (int j = 0; j < ghost_pair_atoms.count(); ++j) + { + const auto atom0 = boost::get<0>(ghost_pair_atoms[j]); + const auto atom1 = boost::get<1>(ghost_pair_atoms[j]); + + // match the per-particle REST2 scaling of the non-bonded forces + const double scale = (perturbable_mol.isRest2(atom0) ? sqrt_rest2_scale : 1.0) * + (perturbable_mol.isRest2(atom1) ? sqrt_rest2_scale : 1.0); + + const double charge = scale * morphed_charges[atom0] * morphed_charges[atom1]; + + cljff->setExceptionParameters( + boost::get<0>(ghost_pair_idxs[j]), + atom0 + start_index, atom1 + start_index, + charge, 1e-9, 1e-9); + + if (ghost_pair_rff != 0) + ghost_pair_rff->setBondParameters(boost::get<1>(ghost_pair_idxs[j]), + atom0 + start_index, atom1 + start_index, + {charge}); + + if (ghost_pairff != 0) + { + const auto p = get_exception(atom0, atom1, + start_index, 1.0, 1.0, + morphed_ghost_charges, + morphed_ghost_sigmas, + morphed_ghost_epsilons, + morphed_ghost_alphas, + morphed_ghost_kappas); + + std::vector params = { + boost::get<2>(p) * scale, + boost::get<3>(p), + 4.0 * boost::get<4>(p) * scale, + boost::get<5>(p), + boost::get<6>(p)}; + + ghost_pairff->setBondParameters(boost::get<1>(ghost_pair_idxs[j]), + boost::get<0>(p), + boost::get<1>(p), + params); + } + } + } } // Update CLJ exceptions for ring-breaking pairs. - // The CLJ exception carries coul_kappa*q_a0*q_a1 for the hard Coulomb - // (including RF/PME long-range). coul_kappa is zero during + // The CLJ exception carries coul_kappa*q_a0*q_a1 for the hard Coulomb, + // with a separate correction for reaction field. coul_kappa is zero during // potential_swap/restraints_off/ring_open and ramps 0→1 in morph only, // so Coulomb only activates once the LJ softcore has already separated // the atoms. The CustomBondForce handles softcore LJ only (no q param). @@ -1790,6 +1887,11 @@ double LambdaLever::setLambda(OpenMM::Context &context, { cljff->setExceptionParameters(clj_idx, rb_ea0, rb_ea1, rb_new_charge, 1e-9, 1e-9); + + if (ring_breaking_rff != nullptr) + ring_breaking_rff->setBondParameters(boost::get<1>(rb_exc[j]), + rb_ea0, rb_ea1, {rb_new_charge}); + has_changed_cljff = true; } } @@ -1816,6 +1918,11 @@ double LambdaLever::setLambda(OpenMM::Context &context, { cljff->setExceptionParameters(clj_idx, rm_ea0, rm_ea1, rm_new_charge, 1e-9, 1e-9); + + if (ring_making_rff != nullptr) + ring_making_rff->setBondParameters(boost::get<1>(rm_exc[j]), + rm_ea0, rm_ea1, {rm_new_charge}); + has_changed_cljff = true; } } @@ -2095,12 +2202,26 @@ double LambdaLever::setLambda(OpenMM::Context &context, if (has_changed_cljff and cljff) cljff->updateParametersInContext(context); + if (has_changed_cljff) + { + if (ghost_pair_rff) + ghost_pair_rff->updateParametersInContext(context); + if (ring_breaking_rff) + ring_breaking_rff->updateParametersInContext(context); + if (ring_making_rff) + ring_making_rff->updateParametersInContext(context); + if (exception_rff) + exception_rff->updateParametersInContext(context); + } + if (has_changed_ghostff) { if (ghost_ghostff) ghost_ghostff->updateParametersInContext(context); if (ghost_nonghostff) ghost_nonghostff->updateParametersInContext(context); + if (ghost_pairff) + ghost_pairff->updateParametersInContext(context); } #ifdef SIRE_USE_CUSTOMVOLUMEFORCE @@ -2652,6 +2773,21 @@ void LambdaLever::setForceIndex(const QString &force, this->lambda_schedule.addForce(force); } +/** Set the index of a force that is driven by the levers of another force, + * so isn't added to the schedule. + */ +void LambdaLever::setDependentForceIndex(const QString &force, int index) +{ + if (index < 0) + throw SireError::invalid_index(QObject::tr( + "This looks like an invalid index for force '%1' : %2") + .arg(force) + .arg(index), + CODELOC); + + this->name_to_ffidx.insert(force, index); +} + /** Add the index of a restraint force called 'restraint' in the * OpenMM System. There can be multiple restraint forces with * the same name @@ -2717,6 +2853,26 @@ void LambdaLever::setExceptionIndicies(int mol_idx, this->perturbable_mols[mol_idx].setExceptionIndicies(name, exception_idxs); } +/** Set the indicies of the ghost/ghost pairs for the perturbable + * molecule at index 'mol_idx' + */ +void LambdaLever::setGhostPairIndicies(int mol_idx, + const QVector> &ghost_pair_idxs) +{ + mol_idx = SireID::Index(mol_idx).map(this->perturbable_mols.count()); + this->perturbable_mols[mol_idx].setGhostPairIndicies(ghost_pair_idxs); +} + +/** Set the exceptions that need a reaction field correction for the + * perturbable molecule at index 'mol_idx' + */ +void LambdaLever::setRFExceptionIndicies(int mol_idx, + const QVector> &rf_exception_idxs) +{ + mol_idx = SireID::Index(mol_idx).map(this->perturbable_mols.count()); + this->perturbable_mols[mol_idx].setRFExceptionIndicies(rf_exception_idxs); +} + /** Set the constraint indicies for the perturbable molecule at * index 'mol_idx' */ diff --git a/wrapper/Convert/SireOpenMM/lambdalever.h b/wrapper/Convert/SireOpenMM/lambdalever.h index bea447220..d3709d5cf 100644 --- a/wrapper/Convert/SireOpenMM/lambdalever.h +++ b/wrapper/Convert/SireOpenMM/lambdalever.h @@ -128,6 +128,8 @@ namespace SireOpenMM void setForceIndex(const QString &force, int index); + void setDependentForceIndex(const QString &force, int index); + void addRestraintIndex(const QString &force, int index); int addPerturbableMolecule(const OpenMMMolecule &molecule, @@ -137,6 +139,10 @@ namespace SireOpenMM void setExceptionIndicies(int idx, const QString &ff, const QVector> &exception_idxs); + void setGhostPairIndicies(int idx, const QVector> &ghost_pair_idxs); + + void setRFExceptionIndicies(int idx, const QVector> &rf_exception_idxs); + void setConstraintIndicies(int idx, const QVector &constraint_idxs); void setQMExceptionIndicies(const QVector &exception_idxs); diff --git a/wrapper/Convert/SireOpenMM/openmmminimise.cpp b/wrapper/Convert/SireOpenMM/openmmminimise.cpp index d42a038ed..9f1ad4c63 100644 --- a/wrapper/Convert/SireOpenMM/openmmminimise.cpp +++ b/wrapper/Convert/SireOpenMM/openmmminimise.cpp @@ -42,15 +42,16 @@ // COPIED FROM SO POST - https://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c +#include #include -#include // std::isnan, std::fpclassify -#include +#include // std::isnan, std::fpclassify #include // std::setw -#include +#include #include // CHAR_BIT +#include +#include #include #include // uint64_t -#include inline auto is_ieee754_nan(double const x) -> bool @@ -81,15 +82,17 @@ inline auto is_ieee754_nan(double const x) return (bits & exp_mask) == exp_mask and (bits & mantissa_mask) != 0; } +#include "Helpers/scoped_gil_release.hpp" + +#include "lbgfs/lbfgs.h" #include "openmm/OpenMMException.h" #include "openmm/Platform.h" #include "openmm/VerletIntegrator.h" -#include "lbgfs/lbfgs.h" +#include #include #include #include #include -#include #include "SireError/errors.h" @@ -619,7 +622,9 @@ namespace SireOpenMM double starting_k, double ratchet_scale, double max_constraint_error, double timeout) { - PyThreadState *_save = PyEval_SaveThread(); + // Restored on scope exit, so that exceptions reach Python with the GIL. + std::optional gil; + gil.emplace(); if (max_iterations < 0) { @@ -675,16 +680,22 @@ namespace SireOpenMM // Get the initial positions before any minimisation, so that // we can reset to these in case anything goes majorly wrong auto starting_pos = context.getState(OpenMM::State::Positions).getPositions(); + const double starting_energy = context.getState(OpenMM::State::Energy).getPotentialEnergy(); // flag for if we've done a hard reset bool have_hard_reset = false; - std::vector initial_pos; + // Start from the initial positions, so that a reset is possible even if + // the first energy evaluation fails. + std::vector initial_pos = starting_pos; double energy_before = 1e10; bool is_success = true; + bool is_invalid_energy = false; + bool is_timed_out = false; int max_linesearch = 100; const int max_linesearch_delta = 100; + const int max_linesearch_limit = 1000; // Store the starting time. auto start_time = std::chrono::high_resolution_clock::now(); @@ -703,6 +714,7 @@ namespace SireOpenMM if (elapsed_time > timeout) { data.addLog("Minimisation timed out!"); + is_timed_out = true; break; } @@ -729,7 +741,6 @@ namespace SireOpenMM } } - data.addLog(QString("Minimisation loop - %1 steps from %2").arg(data.getIteration()).arg(data.getMaxIterations())); try @@ -741,6 +752,7 @@ namespace SireOpenMM { // something has gone wrong, so we need to restart data.addLog("Infinite or NaN energy detected!"); + is_invalid_energy = true; is_success = false; throw std::exception(); } @@ -791,6 +803,7 @@ namespace SireOpenMM { data.addLog("Minimisation timed out!"); is_success = false; + is_timed_out = true; break; } @@ -808,6 +821,7 @@ namespace SireOpenMM { // something has gone wrong, so we need to restart data.addLog("Infinite or NaN energy detected!"); + is_invalid_energy = true; is_success = false; throw std::exception(); } @@ -816,6 +830,13 @@ namespace SireOpenMM data.aboutToStart(); auto result = lbfgs(num_particles * 3, x, &fx, evaluate, progress, &data, ¶m); + // the context and fx hold the last trial point, which L-BFGS may + // have rejected, so re-evaluate at the accepted point + { + std::vector g(num_particles * 3); + fx = evaluate(&data, x, g.data(), num_particles * 3, 0.0); + } + data.addLog(QString("...completed %1 iterations").arg(data.getIteration() - last_it)); bool should_break = false; @@ -828,11 +849,21 @@ namespace SireOpenMM if (result == LBFGSERR_MAXIMUMLINESEARCH) { - // increase the max line by max_linesearch_delta and try again - max_linesearch += max_linesearch_delta; - data.addLog(QString("Increasing the maximum line search to %1").arg(max_linesearch)); - // immediately try again - should_continue = true; + if (max_linesearch >= max_linesearch_limit) + { + // the energy surface is likely discontinuous + data.addLog("Reached the line search limit!"); + should_break = true; + } + else + { + // increase the max line by max_linesearch_delta and try again + max_linesearch += max_linesearch_delta; + param.max_linesearch = max_linesearch; + data.addLog(QString("Increasing the maximum line search to %1").arg(max_linesearch)); + // immediately try again + should_continue = true; + } } else if (result == LBFGSERR_INVALIDPARAMETERS) { @@ -864,6 +895,7 @@ namespace SireOpenMM { // we've hit a singularity, so we need to restart data.addLog("Infinite or NaN energy detected!"); + is_invalid_energy = true; throw std::exception(); } @@ -1016,6 +1048,7 @@ namespace SireOpenMM { // something has gone wrong, so we need to restart data.addLog("Infinite or NaN energy detected!"); + is_invalid_energy = true; throw std::exception(); } @@ -1090,7 +1123,7 @@ namespace SireOpenMM } } - PyEval_RestoreThread(_save); + gil.reset(); if (is_success) { @@ -1100,6 +1133,35 @@ namespace SireOpenMM else { data.addLog("Minimisation failed!"); + + // keep the last accepted positions, unless they are no better than the start + const auto final_energy = context.getState(OpenMM::State::Energy).getPotentialEnergy(); + + if (std::isinf(final_energy) or std::isnan(final_energy) or is_ieee754_nan(final_energy) or + final_energy >= starting_energy) + { + data.addLog("Restoring the starting positions."); + context.setPositions(starting_pos); + } + + if (is_timed_out) + { + bar.failure("Minimisation failed! Timed out!"); + throw SireError::invalid_state(QObject::tr( + "The minimiser did not converge within the timeout of %1 seconds.") + .arg(timeout), + CODELOC); + } + + if (is_invalid_energy) + { + bar.failure("Minimisation failed! Infinite or NaN energy!"); + throw SireError::invalid_state(QObject::tr( + "The minimiser could not minimise the system, since its energy " + "is infinite or NaN. Check for overlapping atoms."), + CODELOC); + } + bar.failure("Minimisation failed! Could not satisfy constraints!"); throw SireError::invalid_state(QObject::tr( "Despite repeated attempts, the minimiser could not minimise the system " diff --git a/wrapper/Convert/SireOpenMM/openmmmolecule.cpp b/wrapper/Convert/SireOpenMM/openmmmolecule.cpp index 8d2d66f84..4b06d25db 100644 --- a/wrapper/Convert/SireOpenMM/openmmmolecule.cpp +++ b/wrapper/Convert/SireOpenMM/openmmmolecule.cpp @@ -913,19 +913,6 @@ void OpenMMMolecule::constructFromAmber(const Molecule &mol, auto bonds = params.bonds(); - // Whether an atom's amber type changes between end states - used below - // to identify bonds that are part of the alchemical junction. Amber - // type, not charge, since charges can be redistributed across the whole - // ligand without affecting bonded parameters. - const auto params1_ambertypes = params1.amberTypes(); - - auto is_perturbing_atom = [&](int atom_idx) -> bool - { - const auto &cgatomidx = idx_to_cgatomidx_data[atom_idx]; - - return ambertypes.at(cgatomidx) != params1_ambertypes.at(cgatomidx); - }; - if (is_perturbable) { // add in any bonds that exist only in the other state @@ -986,11 +973,8 @@ void OpenMMMolecule::constructFromAmber(const Molecule &mol, // Whether the bond's own k/r0 change between end states. bool bond_is_perturbing = false; - // Whether the bond is part of the alchemical junction (touches a - // ghost or transmuting atom). SOMD1 constrains an unperturbing bond - // unconditionally only if it's part of the perturbation; ordinary - // unperturbed bonds elsewhere in the molecule are not affected. - bool bond_is_ghost_junction = false; + // Whether the bond exists at only one end state, i.e. it is broken or formed. + bool bond_is_broken_or_formed = false; if (is_perturbable) { @@ -1008,7 +992,7 @@ void OpenMMMolecule::constructFromAmber(const Molecule &mol, } bond_is_perturbing = (std::abs(k_1 - k) > 1e-3 or std::abs(r0_1 - r0) > 1e-3); - bond_is_ghost_junction = is_perturbing_atom(atom0) or is_perturbing_atom(atom1); + bond_is_broken_or_formed = (k == 0 or k_1 == 0); } if (this_constraint_type == CONSTRAIN_AUTO_BONDS) @@ -1032,10 +1016,7 @@ void OpenMMMolecule::constructFromAmber(const Molecule &mol, should_constrain_bond = vibrational_period < auto_constraints_factor * timestep_in_fs; } else if ((not has_massless_atom) and ((this_constraint_type & CONSTRAIN_BONDS) or - (has_light_atom and (this_constraint_type & CONSTRAIN_HBONDS)) or - (is_perturbable and not bond_is_perturbing and - bond_is_ghost_junction and - (this_constraint_type & CONSTRAIN_HBONDS)))) + (has_light_atom and (this_constraint_type & CONSTRAIN_HBONDS)))) { should_constrain_bond = true; @@ -1061,6 +1042,13 @@ void OpenMMMolecule::constructFromAmber(const Molecule &mol, } } + // Never constrain a bond that is absent at one end state, since its atoms + // are unbonded there. + if (bond_is_broken_or_formed) + { + should_constrain_bond = false; + } + if (should_constrain_bond) { if (dynamic_constraints and (std::abs(r0 - r0_1) > 1e-4)) // match to somd1 @@ -2634,6 +2622,107 @@ QVector> OpenMMMolecule::getExceptionAtoms() const return exception_atoms; } +/** Return the pairs of ghost atoms in this molecule that interact but are + * not exceptions, in molecule-local indexes. These are computed without a + * cutoff, since they are intramolecular. + */ +QVector> OpenMMMolecule::getGhostPairs() const +{ + QVector> pairs; + + QSet ghost_set = from_ghost_idxs; + ghost_set.unite(to_ghost_idxs); + + if (ghost_set.count() < 2) + return pairs; + + QSet> exceptions; + + for (const auto ¶m : exception_params) + { + const auto atom0 = boost::get<0>(param); + const auto atom1 = boost::get<1>(param); + exceptions.insert(qMakePair(std::min(atom0, atom1), std::max(atom0, atom1))); + } + + // virtual sites are excluded from their parent atom and its other sites + QHash vs_parent; + + if (has_vs) + { + for (int i = 0; i < this->nAtoms(); ++i) + { + const auto atom_vs = vs_parents.property(std::to_string(i).c_str()).asAnArray(); + + for (int j = 0; j < atom_vs.size(); ++j) + { + vs_parent.insert(this->nAtoms() + atom_vs.at(j).asAnInteger(), i); + } + } + } + + // pairs in different bonded fragments keep using the minimum image + // convention, so stay in the cutoff forces + QVector fragment(this->nAtoms()); + + for (int i = 0; i < this->nAtoms(); ++i) + fragment[i] = i; + + auto find_fragment = [&](qint32 atom) + { + while (fragment[atom] != atom) + { + fragment[atom] = fragment[fragment[atom]]; + atom = fragment[atom]; + } + + return atom; + }; + + for (const auto &bond : bond_params) + { + const auto root0 = find_fragment(boost::get<0>(bond)); + const auto root1 = find_fragment(boost::get<1>(bond)); + + if (root0 != root1) + fragment[root0] = root1; + } + + auto ghosts = ghost_set.values(); + std::sort(ghosts.begin(), ghosts.end()); + + for (int i = 0; i < ghosts.count(); ++i) + { + const auto atom0 = ghosts[i]; + + for (int j = i + 1; j < ghosts.count(); ++j) + { + const auto atom1 = ghosts[j]; + + // to and from ghosts never interact + if ((from_ghost_idxs.contains(atom0) and to_ghost_idxs.contains(atom1)) or + (to_ghost_idxs.contains(atom0) and from_ghost_idxs.contains(atom1))) + continue; + + if (exceptions.contains(qMakePair(atom0, atom1))) + continue; + + const auto parent0 = vs_parent.value(atom0, atom0); + const auto parent1 = vs_parent.value(atom1, atom1); + + if (parent0 == parent1) + continue; + + if (find_fragment(parent0) != find_fragment(parent1)) + continue; + + pairs.append(boost::make_tuple(atom0, atom1)); + } + } + + return pairs; +} + /** Return all of the coulomb intramolecular scale factors (nbscl) * in exception order for this molecule */ @@ -2788,6 +2877,7 @@ PerturbableOpenMMMolecule::PerturbableOpenMMMolecule(const OpenMMMolecule &mol, charge_scl1 = mol.perturbed->getChargeScales(); exception_atoms = mol.getExceptionAtoms(); + ghost_pair_atoms = mol.getGhostPairs(); lj_scl0 = mol.getLJScales(); lj_scl1 = mol.perturbed->getLJScales(); @@ -2876,6 +2966,8 @@ PerturbableOpenMMMolecule::PerturbableOpenMMMolecule(const PerturbableOpenMMMole lj_scl0(other.lj_scl0), lj_scl1(other.lj_scl1), to_ghost_idxs(other.to_ghost_idxs), from_ghost_idxs(other.from_ghost_idxs), exception_atoms(other.exception_atoms), exception_idxs(other.exception_idxs), + ghost_pair_atoms(other.ghost_pair_atoms), ghost_pair_idxs(other.ghost_pair_idxs), + rf_exception_idxs(other.rf_exception_idxs), perturbable_constraints(other.perturbable_constraints), constraint_idxs(other.constraint_idxs), start_atom_idx(other.start_atom_idx), @@ -2912,6 +3004,8 @@ bool PerturbableOpenMMMolecule::operator==(const PerturbableOpenMMMolecule &othe lj_scl0 == other.lj_scl0 and lj_scl1 == other.lj_scl1 and to_ghost_idxs == other.to_ghost_idxs and from_ghost_idxs == other.from_ghost_idxs and exception_atoms == other.exception_atoms and exception_idxs == other.exception_idxs and + ghost_pair_atoms == other.ghost_pair_atoms and ghost_pair_idxs == other.ghost_pair_idxs and + rf_exception_idxs == other.rf_exception_idxs and perturbable_constraints == other.perturbable_constraints and constraint_idxs == other.constraint_idxs and cmap_grid0 == other.cmap_grid0 and cmap_grid1 == other.cmap_grid1 and cmap_grid_sizes == other.cmap_grid_sizes and cmap_atoms == other.cmap_atoms; @@ -2980,6 +3074,10 @@ PerturbableOpenMMMolecule &PerturbableOpenMMMolecule::operator=(const Perturbabl exception_atoms = other.exception_atoms; exception_idxs = other.exception_idxs; + ghost_pair_atoms = other.ghost_pair_atoms; + ghost_pair_idxs = other.ghost_pair_idxs; + rf_exception_idxs = other.rf_exception_idxs; + perturbable_constraints = other.perturbable_constraints; constraint_idxs = other.constraint_idxs; @@ -3235,6 +3333,63 @@ void PerturbableOpenMMMolecule::setExceptionIndicies(const QString &name, this->exception_idxs.insert(name, exception_idxs); } +/** Return the molecule-local indices of the interacting ghost/ghost + * pairs that aren't exceptions + */ +QVector> PerturbableOpenMMMolecule::getGhostPairAtoms() const +{ + return this->ghost_pair_atoms; +} + +/** Return the global indexes of the ghost/ghost pairs in the non-bonded + * and ghost/ghost bond forces + */ +QVector> PerturbableOpenMMMolecule::getGhostPairIndicies() const +{ + return this->ghost_pair_idxs; +} + +/** Set the global indexes of the ghost/ghost pairs in the non-bonded + * and ghost/ghost bond forces + */ +void PerturbableOpenMMMolecule::setGhostPairIndicies(const QVector> &idxs) +{ + if (idxs.count() != this->ghost_pair_atoms.count()) + throw SireError::incompatible_error(QObject::tr( + "The number of ghost pair indicies (%1) does not match the number of ghost pairs (%2)") + .arg(idxs.count()) + .arg(this->ghost_pair_atoms.count()), + CODELOC); + + this->ghost_pair_idxs = idxs; +} + +/** Return the exceptions that are normal pairs in either end state, as + * their index in the exceptions and in the exception reaction field force + */ +QVector> PerturbableOpenMMMolecule::getRFExceptionIndicies() const +{ + return this->rf_exception_idxs; +} + +/** Set the exceptions that are normal pairs in either end state, as + * their index in the exceptions and in the exception reaction field force + */ +void PerturbableOpenMMMolecule::setRFExceptionIndicies(const QVector> &idxs) +{ + for (const auto &idx : idxs) + { + if (boost::get<0>(idx) < 0 or boost::get<0>(idx) >= this->exception_atoms.count()) + throw SireError::invalid_index(QObject::tr( + "Invalid exception index %1 for a molecule with %2 exceptions") + .arg(boost::get<0>(idx)) + .arg(this->exception_atoms.count()), + CODELOC); + } + + this->rf_exception_idxs = idxs; +} + /** Set the indexes of perturbable constraints in the System */ void PerturbableOpenMMMolecule::setConstraintIndicies(const QVector &idxs) { diff --git a/wrapper/Convert/SireOpenMM/openmmmolecule.h b/wrapper/Convert/SireOpenMM/openmmmolecule.h index 39a1e2621..fc0b5fcb7 100644 --- a/wrapper/Convert/SireOpenMM/openmmmolecule.h +++ b/wrapper/Convert/SireOpenMM/openmmmolecule.h @@ -100,6 +100,8 @@ namespace SireOpenMM QVector> getExceptionAtoms() const; + QVector> getGhostPairs() const; + QVector getChargeScales() const; QVector getLJScales() const; @@ -352,6 +354,16 @@ namespace SireOpenMM void setExceptionIndicies(const QString &name, const QVector> &exception_idxs); + QVector> getGhostPairAtoms() const; + + QVector> getGhostPairIndicies() const; + + void setGhostPairIndicies(const QVector> &ghost_pair_idxs); + + QVector> getRFExceptionIndicies() const; + + void setRFExceptionIndicies(const QVector> &rf_exception_idxs); + void setConstraintIndicies(const QVector &constraint_idxs); QVector getConstraintIndicies() const; @@ -433,6 +445,17 @@ namespace SireOpenMM * if this is a peturbable molecule */ QHash>> exception_idxs; + /** The interacting ghost/ghost pairs that aren't exceptions */ + QVector> ghost_pair_atoms; + + /** The indicies of each ghost/ghost pair in the non-bonded + * and ghost/ghost bond forces */ + QVector> ghost_pair_idxs; + + /** The exceptions that are normal pairs in either end state, with the + * index of each in the exception reaction field force */ + QVector> rf_exception_idxs; + /** All of the perturbable constraints - these include the r0 values * for both end states */ diff --git a/wrapper/Convert/SireOpenMM/sire_to_openmm_system.cpp b/wrapper/Convert/SireOpenMM/sire_to_openmm_system.cpp index 0ef55c83f..139d2f066 100644 --- a/wrapper/Convert/SireOpenMM/sire_to_openmm_system.cpp +++ b/wrapper/Convert/SireOpenMM/sire_to_openmm_system.cpp @@ -1448,6 +1448,11 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, /// OpenMM::CustomBondForce *ghost_14ff = 0; + OpenMM::CustomBondForce *ghost_pairff = 0; + OpenMM::CustomBondForce *ghost_pair_rff = 0; + OpenMM::CustomBondForce *ring_breaking_rff = 0; + OpenMM::CustomBondForce *ring_making_rff = 0; + OpenMM::CustomBondForce *exception_rff = 0; OpenMM::CustomBondForce *ring_breaking_ff = 0; OpenMM::CustomBondForce *ring_making_ff = 0; OpenMM::CustomNonbondedForce *ghost_ghostff = 0; @@ -1627,14 +1632,14 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, { rb_expression = QString( "lj_nrg;" - "lj_nrg=four_epsilon*sig6*(sig6-1);" + "lj_nrg=(1-ring_break_alpha)*four_epsilon*sig6*(sig6-1);" "sig6=(sigma^6)/(%1*sigma^6 + r_safe^6);" "r_safe=max(r, 0.001);") .arg(taylor_power_expression("ring_break_alpha", taylor_power)) .toStdString(); rm_expression = QString( "lj_nrg;" - "lj_nrg=four_epsilon*sig6*(sig6-1);" + "lj_nrg=(1-ring_make_alpha)*four_epsilon*sig6*(sig6-1);" "sig6=(sigma^6)/(%1*sigma^6 + r_safe^6);" "r_safe=max(r, 0.001);") .arg(taylor_power_expression("ring_make_alpha", taylor_power)) @@ -1644,7 +1649,7 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, { rb_expression = QString( "lj_nrg;" - "lj_nrg=four_epsilon*sig6*(sig6-1);" + "lj_nrg=(1-ring_break_alpha)*four_epsilon*sig6*(sig6-1);" "sig6=(sigma^6)/(((sigma*delta)+r_safe^2)^3);" "r_safe=max(r, 0.001);" "delta=%1*ring_break_alpha;") @@ -1652,7 +1657,7 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, .toStdString(); rm_expression = QString( "lj_nrg;" - "lj_nrg=four_epsilon*sig6*(sig6-1);" + "lj_nrg=(1-ring_make_alpha)*four_epsilon*sig6*(sig6-1);" "sig6=(sigma^6)/(((sigma*delta)+r_safe^2)^3);" "r_safe=max(r, 0.001);" "delta=%1*ring_make_alpha;") @@ -1699,6 +1704,73 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, // periodic boundaries or cutoffs ghost_14ff->setUsesPeriodicBoundaryConditions(false); + // intramolecular ghost/ghost pairs, which have the same form as the + // ghost/ghost interaction, but with the Coulomb term not cut off + auto ghost_pair_expression = nb14_expression; + + if (cljff->getNonbondedMethod() != OpenMM::NonbondedForce::NoCutoff) + { + const auto lj_start = ghost_pair_expression.find(';'); + + ghost_pair_expression = QString("coul_nrg+step(%1-r)*lj_nrg;") + .arg(cljff->getCutoffDistance(), 0, 'g', 17) + .toStdString() + + ghost_pair_expression.substr(lj_start + 1); + } + + ghost_pairff = new OpenMM::CustomBondForce(ghost_pair_expression); + ghost_pairff->setName("GhostGhostBondForce"); + + ghost_pairff->addPerBondParameter("q"); + ghost_pairff->addPerBondParameter("sigma"); + ghost_pairff->addPerBondParameter("four_epsilon"); + ghost_pairff->addPerBondParameter("alpha"); + ghost_pairff->addPerBondParameter("kappa"); + + ghost_pairff->setUsesPeriodicBoundaryConditions(false); + + // the hard Coulomb for intramolecular ghost/ghost and ring-breaking/making + // pairs is a NonbondedForce exception, which has no reaction field, so + // add the difference from a normal pair + const auto nbmethod = cljff->getNonbondedMethod(); + + if (nbmethod == OpenMM::NonbondedForce::CutoffPeriodic or + nbmethod == OpenMM::NonbondedForce::CutoffNonPeriodic) + { + const double rc = cljff->getCutoffDistance(); + const double eps = cljff->getReactionFieldDielectric(); + const double krf = (eps - 1.0) / ((2.0 * eps + 1.0) * rc * rc * rc); + const double crf = (3.0 * eps) / ((2.0 * eps + 1.0) * rc); + + const auto rf_expression = + QString("138.9354558466661*q*select(step(r-%1), -1/r, %2*r^2-%3)") + .arg(rc, 0, 'g', 17) + .arg(krf, 0, 'g', 17) + .arg(crf, 0, 'g', 17) + .toStdString(); + + auto create_rf_force = [&](const char *name) + { + auto ff = new OpenMM::CustomBondForce(rf_expression); + ff->setName(name); + ff->addPerBondParameter("q"); + ff->setUsesPeriodicBoundaryConditions(false); + return ff; + }; + + ghost_pair_rff = create_rf_force("GhostGhostReactionFieldForce"); + + // exceptions that are normal pairs in an end state, e.g. pairs + // across a bond that is broken by a ring-breaking perturbation + exception_rff = create_rf_force("ExceptionReactionFieldForce"); + + if (ring_breaking_ff != 0) + ring_breaking_rff = create_rf_force("RingBreakingReactionFieldForce"); + + if (ring_making_ff != 0) + ring_making_rff = create_rf_force("RingMakingReactionFieldForce"); + } + if (use_beutler_softening) { // Beutler et al., Chem. Phys. Lett., 1994 @@ -1841,7 +1913,18 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, ghost_ghostff->setForceGroup(force_group_counter); lambda_lever.setForceIndex("ghost/ghost", system.addForce(ghost_ghostff)); - lambda_lever.setForceGroup("ghost/ghost", force_group_counter++); + lambda_lever.setForceGroup("ghost/ghost", force_group_counter); + + // the intramolecular pairs are part of the ghost/ghost interaction + ghost_pairff->setForceGroup(force_group_counter++); + lambda_lever.setDependentForceIndex("ghost/ghost-pairs", system.addForce(ghost_pairff)); + + // the reaction field correction is part of the hard Coulomb + if (ghost_pair_rff != 0) + { + ghost_pair_rff->setForceGroup(lambda_lever.getForceGroup("clj")); + lambda_lever.setDependentForceIndex("clj-ghost-pairs", system.addForce(ghost_pair_rff)); + } ghost_nonghostff->setForceGroup(force_group_counter); lambda_lever.setForceIndex("ghost/non-ghost", system.addForce(ghost_nonghostff)); @@ -1879,6 +1962,24 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, lambda_lever.setForceIndex("ring-make", system.addForce(ring_making_ff)); lambda_lever.setForceGroup("ring-make", force_group_counter++); } + + if (exception_rff != 0) + { + exception_rff->setForceGroup(lambda_lever.getForceGroup("clj")); + lambda_lever.setDependentForceIndex("clj-exceptions", system.addForce(exception_rff)); + } + + if (ring_breaking_rff != 0) + { + ring_breaking_rff->setForceGroup(lambda_lever.getForceGroup("clj")); + lambda_lever.setDependentForceIndex("clj-ring-break", system.addForce(ring_breaking_rff)); + } + + if (ring_making_rff != 0) + { + ring_making_rff->setForceGroup(lambda_lever.getForceGroup("clj")); + lambda_lever.setDependentForceIndex("clj-ring-make", system.addForce(ring_making_rff)); + } } #ifdef SIRE_USE_CUSTOMVOLUMEFORCE @@ -2681,6 +2782,7 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, // Filled alongside exception_idxs; (-1,-1) for non-ring pairs. QVector> rb_exception_idxs; QVector> rm_exception_idxs; + QVector> rf_exception_idxs; int rb_bond_count = 0; int rm_bond_count = 0; if (is_perturbable) @@ -2823,7 +2925,8 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, // LJ stays at 1e-9 throughout: the ring-break/make CustomBondForce // provides the full softcore LJ. The Coulomb charge is initialised // to the correct value for each direction so the NonbondedForce - // carries the right hard Coulomb (including RF/PME) from the start. + // carries the right hard Coulomb from the start (with a separate + // reaction field correction). // nbidx stays -1 (no ghost-14 bond for ring-break/make pairs). if (is_ring_breaking and ring_breaking_ff != 0) @@ -2844,10 +2947,13 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, // Use 1e-9 to prevent OpenMM from pruning the exception. idx = cljff->addException(boost::get<0>(p), boost::get<1>(p), 1e-9, 1e-9, 1e-9, true); - ring_breaking_ff->addBond(boost::get<0>(p), - boost::get<1>(p), - params_rb); - rb_exception_idxs[j] = boost::make_tuple(idx, rb_bond_count); + const int rb_idx = ring_breaking_ff->addBond(boost::get<0>(p), + boost::get<1>(p), + params_rb); + // the reaction field correction shares the bond index + if (ring_breaking_rff != 0) + ring_breaking_rff->addBond(boost::get<0>(p), boost::get<1>(p), {1e-9}); + rb_exception_idxs[j] = boost::make_tuple(idx, rb_idx); ++rb_bond_count; } else if (is_ring_making and ring_making_ff != 0) @@ -2870,10 +2976,13 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, init_charge = 1e-9; idx = cljff->addException(boost::get<0>(p), boost::get<1>(p), init_charge, 1e-9, 1e-9, true); - ring_making_ff->addBond(boost::get<0>(p), - boost::get<1>(p), - params_rm); - rm_exception_idxs[j] = boost::make_tuple(idx, rm_bond_count); + const int rm_idx = ring_making_ff->addBond(boost::get<0>(p), + boost::get<1>(p), + params_rm); + // the reaction field correction shares the bond index + if (ring_making_rff != 0) + ring_making_rff->addBond(boost::get<0>(p), boost::get<1>(p), {init_charge}); + rm_exception_idxs[j] = boost::make_tuple(idx, rm_idx); ++rm_bond_count; } else @@ -2897,6 +3006,18 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, // these are the indexes of the exception in the // non-bonded forcefields and also the ghost-14 forcefield exception_idxs[j] = boost::make_tuple(idx, nbidx); + + // an exception that is a normal pair in an end state needs the + // reaction field correction there + const auto ¶m1 = mol.perturbed->exception_params[j]; + + if (exception_rff != 0 and idx >= 0 and + ((coul_14_scale == 1.0 and lj_14_scale == 1.0) or + (boost::get<2>(param1) == 1.0 and boost::get<3>(param1) == 1.0))) + { + const int rf_idx = exception_rff->addBond(boost::get<0>(p), boost::get<1>(p), {0.0}); + rf_exception_idxs.append(boost::make_tuple(j, rf_idx)); + } } else { @@ -2917,8 +3038,60 @@ OpenMMMetaData SireOpenMM::sire_to_openmm_system(OpenMM::System &system, if (is_perturbable) { auto pert_idx = idx_to_pert_idx.value(i, openmm_mols.count() + 1); + + // Intramolecular ghost/ghost pairs are excluded from the cutoff + // ghost forces. The hard Coulomb is an exception, corrected for + // reaction field, and the soft-core terms are in the ghost/ghost + // bond force. + const auto ghost_pairs = mol.getGhostPairs(); + + if (not ghost_pairs.isEmpty() and ghost_pairff != 0) + { + QVector> ghost_pair_idxs(ghost_pairs.count()); + + for (int j = 0; j < ghost_pairs.count(); ++j) + { + const auto atom0 = boost::get<0>(ghost_pairs[j]); + const auto atom1 = boost::get<1>(ghost_pairs[j]); + + const auto &clj0 = mol.cljs.at(atom0); + const auto &clj1 = mol.cljs.at(atom1); + + const double charge = boost::get<0>(clj0) * boost::get<0>(clj1); + double sigma = 0.5 * (boost::get<1>(clj0) + boost::get<1>(clj1)); + double four_epsilon = 4.0 * std::sqrt(boost::get<2>(clj0) * boost::get<2>(clj1)); + + // cannot use zero params in case they are eagerly removed + if (sigma == 0) + sigma = 1e-9; + + const int idx = cljff->addException(atom0 + start_index, atom1 + start_index, + charge, 1e-9, 1e-9, false); + + std::vector params = {charge, sigma, four_epsilon, + std::max(mol.alphas.at(atom0), mol.alphas.at(atom1)), + std::max(mol.kappas.at(atom0), mol.kappas.at(atom1))}; + + const int nbidx = ghost_pairff->addBond(atom0 + start_index, atom1 + start_index, params); + + // both bond forces hold the same pairs, so share the index + if (ghost_pair_rff != 0) + ghost_pair_rff->addBond(atom0 + start_index, atom1 + start_index, {charge}); + + ghost_ghostff->addExclusion(atom0 + start_index, atom1 + start_index); + ghost_nonghostff->addExclusion(atom0 + start_index, atom1 + start_index); + + ghost_pair_idxs[j] = boost::make_tuple(idx, nbidx); + } + + lambda_lever.setGhostPairIndicies(pert_idx, ghost_pair_idxs); + } + lambda_lever.setExceptionIndicies(pert_idx, "clj", exception_idxs); + + if (not rf_exception_idxs.isEmpty()) + lambda_lever.setRFExceptionIndicies(pert_idx, rf_exception_idxs); if (rb_bond_count > 0) lambda_lever.setExceptionIndicies(pert_idx, "ring-break", rb_exception_idxs);