From 7424fc4a4107a69bf5cc6e9e6926888f1f91a215 Mon Sep 17 00:00:00 2001 From: Samiha Sharlin <70553929+ssharlin@users.noreply.github.com> Date: Tue, 18 Aug 2026 09:12:02 -0400 Subject: [PATCH] feat: canonical identity-switch move (MCCCS-MN swatch) Single-box, composition-conserving pair exchange: one molecule of component A and one of component B swap identities in place. Complements the semi-grand IdentityChangeCBMC; conserves N of every component and needs no fugacities. Input keys: IdentitySwitches, IdentitySwitchProbability. Tests: tests/raspa3-tests/mc_identity_switch_drift.cpp --- src/raspakit/component.cpp | 6 + src/raspakit/component.ixx | 3 +- src/raspakit/input_reader.cpp | 26 ++ .../mc_moves/component/identity_switch.cpp | 332 ++++++++++++++++++ .../mc_moves/component/identity_switch.ixx | 43 +++ src/raspakit/mc_moves/mc_moves.cpp | 48 +++ src/raspakit/mc_moves/move_types.cpp | 7 +- src/raspakit/mc_moves/move_types.ixx | 6 +- src/raspakit/mc_moves/probabilities.cpp | 1 + src/raspakit/mc_moves/statistics.ixx | 1 + tests/raspa3-tests/CMakeLists.txt | 1 + .../raspa3-tests/mc_identity_switch_drift.cpp | 168 +++++++++ 12 files changed, 637 insertions(+), 5 deletions(-) create mode 100644 src/raspakit/mc_moves/component/identity_switch.cpp create mode 100644 src/raspakit/mc_moves/component/identity_switch.ixx create mode 100644 tests/raspa3-tests/mc_identity_switch_drift.cpp diff --git a/src/raspakit/component.cpp b/src/raspakit/component.cpp index 2ee0b60b9..872cea53b 100644 --- a/src/raspakit/component.cpp +++ b/src/raspakit/component.cpp @@ -2141,6 +2141,7 @@ Archive &operator<<(Archive &archive, const Compon archive << c.partialReinsertionFixedAtoms; archive << c.identityChanges; archive << c.gibbsIdentityChanges; + archive << c.identitySwitches; archive << c.initialNumberOfMolecules; @@ -2239,6 +2240,11 @@ Archive &operator>>(Archive &archive, Component &c archive >> c.partialReinsertionFixedAtoms; archive >> c.identityChanges; archive >> c.gibbsIdentityChanges; + // 'identitySwitches' was added in version 2; older restart files do not contain it. + if (versionNumber >= 2) + { + archive >> c.identitySwitches; + } archive >> c.initialNumberOfMolecules; diff --git a/src/raspakit/component.ixx b/src/raspakit/component.ixx index 257e61803..9d954a7ee 100644 --- a/src/raspakit/component.ixx +++ b/src/raspakit/component.ixx @@ -142,7 +142,7 @@ export struct Component std::optional fugacityCoefficient = std::nullopt, bool thermodynamicIntegration = false, std::vector blockingPockets = {}) noexcept(false); - std::uint64_t versionNumber{1}; ///< Version number for serialization. + std::uint64_t versionNumber{2}; ///< Version number for serialization. Type type{0}; ///< Type of the component (Adsorbate or Cation). @@ -236,6 +236,7 @@ export struct Component mutable std::map, std::vector> growthPlanCache{}; std::vector identityChanges{}; std::vector gibbsIdentityChanges{}; + std::vector identitySwitches{}; ///< Partner components for the canonical identity-switch move. std::size_t initialNumberOfMolecules{0}; ///< Initial number of molecules in the component. diff --git a/src/raspakit/input_reader.cpp b/src/raspakit/input_reader.cpp index ba47d9431..3e745b8af 100644 --- a/src/raspakit/input_reader.cpp +++ b/src/raspakit/input_reader.cpp @@ -843,6 +843,15 @@ void InputReader::parseMolecularSimulations(const nlohmann::basic_json(); + for (std::size_t i = 0; i < move_probabilities.size(); ++i) + { + move_probabilities[i].setProbability(Move::Types::IdentitySwitchCBMC, identity_switch_CBMC_probability); + } + } + if (item.contains("SwapConventionalProbability") && item["SwapConventionalProbability"].is_number_float()) { double swapProbability = item["SwapConventionalProbability"].get(); @@ -1200,6 +1209,21 @@ void InputReader::parseMolecularSimulations(const nlohmann::basic_json identity_switches = item["IdentitySwitches"].get>(); + if (std::ranges::contains(identity_switches, componentId)) + { + throw std::runtime_error( + std::format("[Input reader]: component '{}' (id {}) cannot list itself in 'IdentitySwitches'\n", + jsonComponentName, componentId)); + } + for (std::size_t i = 0; i != jsonNumberOfSystems; ++i) + { + jsonComponents[i][componentId].identitySwitches = identity_switches; + } + } + if (item.contains("GibbsIdentityChanges") && item["GibbsIdentityChanges"].is_array()) { std::vector gibbs_identity_changes = item["GibbsIdentityChanges"].get>(); @@ -3376,6 +3400,7 @@ const std::set InputReader::compon "ReinsertionProbability", "PartialReinsertionProbability", "IdentityChangeProbability", + "IdentitySwitchProbability", "SwapConventionalProbability", "SwapProbability", "PairSwapConventionalProbability", @@ -3409,6 +3434,7 @@ const std::set InputReader::compon "IdealGasRosenbluthWeight", "MolFraction", "IdentityChanges", + "IdentitySwitches", "GibbsIdentityChanges", "ThermodynamicIntegration", "LambdaBinIndex", diff --git a/src/raspakit/mc_moves/component/identity_switch.cpp b/src/raspakit/mc_moves/component/identity_switch.cpp new file mode 100644 index 000000000..3937008bc --- /dev/null +++ b/src/raspakit/mc_moves/component/identity_switch.cpp @@ -0,0 +1,332 @@ +module; + +module mc_moves_identity_switch; + +import std; + +import component; +import atom; +import molecule; +import double3; +import simd_quatd; +import simulationbox; +import cbmc; +import cbmc_chain_data; +import cbmc_growth_context; +import cbmc_interactions; +import cbmc_interactions_intermolecular; +import randomnumbers; +import system; +import running_energy; +import forcefield; +import interactions_framework_molecule; +import interactions_ewald; +import interactions_polarization; +import mc_moves_move_types; + +std::optional MC_Moves::identitySwitchMove(RandomNumber &random, System &system, + std::size_t selectedComponent) +{ + std::chrono::steady_clock::time_point time_begin, time_end; + const Move::Types move = Move::Types::IdentitySwitchCBMC; + + Component &componentAData = system.components[selectedComponent]; + if (componentAData.identitySwitches.empty()) + { + return std::nullopt; + } + + const std::size_t componentA = selectedComponent; + const std::size_t componentB = + componentAData.identitySwitches[random.uniform_integer(0, componentAData.identitySwitches.size() - 1)]; + + if (componentB >= system.components.size() || componentB == componentA) + { + return std::nullopt; + } + + Component &componentBData = system.components[componentB]; + if (componentBData.type != componentAData.type) + { + return std::nullopt; + } + + // Composition is conserved (one A and one B are exchanged), so picking one molecule of each + // uniformly gives identical proposal probabilities for the forward and reverse moves; no + // 50/50 role swap is needed for detailed balance. + if (system.numberOfIntegerMoleculesPerComponent[componentA] == 0 || + system.numberOfIntegerMoleculesPerComponent[componentB] == 0) + { + return std::nullopt; + } + + componentAData.mc_moves_statistics.addTrial(move); + componentBData.mc_moves_statistics.addTrial(move); + + const std::size_t moleculeA = system.randomIntegerMoleculeOfComponent(random, componentA); + const std::size_t moleculeB = system.randomIntegerMoleculeOfComponent(random, componentB); + + std::span atomsA = system.spanOfMolecule(componentA, moleculeA); + std::span atomsB = system.spanOfMolecule(componentB, moleculeB); + + // copies: pristine old configurations (taken before any relabeling below) + std::vector oldA(atomsA.begin(), atomsA.end()); + std::vector oldB(atomsB.begin(), atomsB.end()); + const Atom startingBeadA = oldA[componentAData.startingBead]; + const Atom startingBeadB = oldB[componentBData.startingBead]; + + const std::size_t globalA = system.moleculeIndexOfComponent(componentA, moleculeA); + const std::size_t globalB = system.moleculeIndexOfComponent(componentB, moleculeB); + const std::make_signed_t skipBothMolecules = static_cast>(globalA); + + // Determine cutoff distances based on whether dual cutoff is used. + const double cutOffFrameworkVDW = + system.forceField.useDualCutOff ? system.forceField.dualCutOff : system.forceField.cutOffFrameworkVDW; + const double cutOffMoleculeVDW = + system.forceField.useDualCutOff ? system.forceField.dualCutOff : system.forceField.cutOffMoleculeVDW; + const double cutOffCoulomb = + system.forceField.useDualCutOff ? system.forceField.dualCutOff : system.forceField.cutOffCoulomb; + + // Distinct trial ids that cannot collide with any existing molecule (global ids are 0..N-1). + const std::size_t trialIdNewB = system.numberOfMolecules(); + const std::size_t trialIdNewA = system.numberOfMolecules() + 1; + + const CBMC::GrowContext growContext{system.hasExternalField, + system.forceField, + system.simulationBox, + system.interpolationGrids, + system.externalFieldInterpolationGrid, + system.framework, + system.spanOfFrameworkAtoms(), + system.spanOfMoleculeAtoms(), + system.beta, + cutOffFrameworkVDW, + cutOffMoleculeVDW, + cutOffCoulomb}; + + struct CBMCResult + { + ChainGrowData growNewB; // new B grown at A's site + ChainGrowData growNewA; // new A grown at B's site + ChainRetraceData retraceA; // old A retraced at its site + ChainRetraceData retraceB; // old B retraced at its site + }; + + // Both molecules must be invisible to all four CBMC operations (grown/retraced against the + // background "system minus {A, B}"). The CBMC helpers exclude molecules by global moleculeId: + // the retraces self-exclude by id-matching and the grows take one skip id. We therefore + // temporarily relabel molecule B's atoms with molecule A's global id so that a single skip id + // (and a single self-match) covers both molecules. The relabeling is undone unconditionally + // right after the CBMC phase; nothing inside the window reads moleculeId for any other purpose. + for (Atom &atom : atomsB) + { + atom.moleculeId = static_cast(globalA); + } + + time_begin = std::chrono::steady_clock::now(); + std::optional cbmc = [&]() -> std::optional + { + std::optional growNewB = CBMC::growMoleculeIdentityChangeInsertion( + random, growContext, componentBData, componentB, trialIdNewB, startingBeadA, 1.0, 0, false, skipBothMolecules); + if (!growNewB) + { + return std::nullopt; + } + if (system.insideBlockedPockets(componentBData, + std::span(growNewB->atoms.begin(), growNewB->atoms.end()))) + { + return std::nullopt; + } + + std::optional growNewA = CBMC::growMoleculeIdentityChangeInsertion( + random, growContext, componentAData, componentA, trialIdNewA, startingBeadB, 1.0, 0, false, skipBothMolecules); + if (!growNewA) + { + return std::nullopt; + } + if (system.insideBlockedPockets(componentAData, + std::span(growNewA->atoms.begin(), growNewA->atoms.end()))) + { + return std::nullopt; + } + + // Retraces self-exclude by moleculeId; because of the relabeling both molecules are excluded. + ChainRetraceData retraceA = + CBMC::retraceMoleculeIdentityChangeDeletion(random, growContext, componentAData, atomsA); + ChainRetraceData retraceB = + CBMC::retraceMoleculeIdentityChangeDeletion(random, growContext, componentBData, atomsB); + + return CBMCResult{std::move(*growNewB), std::move(*growNewA), std::move(retraceA), std::move(retraceB)}; + }(); + + // restore molecule B's global id unconditionally before anything else touches the system + for (Atom &atom : atomsB) + { + atom.moleculeId = static_cast(globalB); + } + time_end = std::chrono::steady_clock::now(); + componentAData.mc_moves_cputime[move][Move::Timing::NonEwald] += (time_end - time_begin); + system.mc_moves_cputime[move][Move::Timing::NonEwald] += (time_end - time_begin); + + if (!cbmc) + { + return std::nullopt; + } + + if (system.forceField.useDualCutOff) + { + // Dual cut-off scheme: correct both grown configurations from the inner cut-off to the full + // cut-offs, using the same background (both exchanged molecules excluded) as the growth. + std::optional correctionNewB = + CBMC::computeDualCutOffCorrection(growContext, componentBData, cbmc->growNewB.atoms, skipBothMolecules); + std::optional correctionNewA = + CBMC::computeDualCutOffCorrection(growContext, componentAData, cbmc->growNewA.atoms, skipBothMolecules); + if (!correctionNewB.has_value() || !correctionNewA.has_value()) + { + return std::nullopt; + } + + cbmc->growNewB.energies += correctionNewB.value(); + cbmc->growNewB.RosenbluthWeight *= std::exp(-system.beta * correctionNewB->potentialEnergy()); + cbmc->growNewA.energies += correctionNewA.value(); + cbmc->growNewA.RosenbluthWeight *= std::exp(-system.beta * correctionNewA->potentialEnergy()); + } + + componentAData.mc_moves_statistics.addConstructed(move); + componentBData.mc_moves_statistics.addConstructed(move); + + // The direct A-B pair interaction is absent from all four CBMC weights (both molecules were + // excluded from the background), so it enters the acceptance explicitly: new pair minus old pair. + std::optional newPairEnergy = CBMC::computeInterMolecularEnergy( + system.forceField, system.simulationBox, + std::span(cbmc->growNewA.atoms.begin(), cbmc->growNewA.atoms.end()), cutOffMoleculeVDW, cutOffCoulomb, + std::span(cbmc->growNewB.atoms.begin(), cbmc->growNewB.atoms.end()), -1, -1); + if (!newPairEnergy) + { + return std::nullopt; + } + std::optional oldPairEnergy = CBMC::computeInterMolecularEnergy( + system.forceField, system.simulationBox, std::span(oldA.begin(), oldA.end()), cutOffMoleculeVDW, + cutOffCoulomb, std::span(oldB.begin(), oldB.end()), -1, -1); + if (!oldPairEnergy) + { + // an existing configuration should never register as an overlap; reject defensively + return std::nullopt; + } + + // Combined Ewald Fourier difference for the simultaneous change of both molecules + // (single call so the cross terms between the two exchanged molecules are handled exactly). + std::vector newAtoms; + newAtoms.reserve(cbmc->growNewB.atoms.size() + cbmc->growNewA.atoms.size()); + newAtoms.insert(newAtoms.end(), cbmc->growNewB.atoms.begin(), cbmc->growNewB.atoms.end()); + newAtoms.insert(newAtoms.end(), cbmc->growNewA.atoms.begin(), cbmc->growNewA.atoms.end()); + + std::vector oldAtoms; + oldAtoms.reserve(oldA.size() + oldB.size()); + oldAtoms.insert(oldAtoms.end(), oldA.begin(), oldA.end()); + oldAtoms.insert(oldAtoms.end(), oldB.begin(), oldB.end()); + + time_begin = std::chrono::steady_clock::now(); + RunningEnergy energyFourierDifference = Interactions::energyDifferenceEwaldFourier( + system.eik_x, system.eik_y, system.eik_z, system.eik_xy, system.storedEik, system.trialEik, system.forceField, + system.simulationBox, newAtoms, oldAtoms, system.netCharge); + time_end = std::chrono::steady_clock::now(); + componentAData.mc_moves_cputime[move][Move::Timing::Ewald] += (time_end - time_begin); + system.mc_moves_cputime[move][Move::Timing::Ewald] += (time_end - time_begin); + + // Tail corrections cancel exactly: the multiset of atom types in the box is unchanged + // (one A and one B on both sides of the move), for both molecule-molecule and + // framework-molecule contributions. Likewise the Ewald net-charge correction vanishes. + + RunningEnergy polarizationDifference; + std::vector new_electric_field(newAtoms.size()); + std::vector old_electric_field(oldAtoms.size()); + if (system.forceField.computePolarization) + { + Interactions::computeFrameworkMoleculeElectricFieldDifference(system.forceField, system.simulationBox, + system.spanOfFrameworkAtoms(), new_electric_field, + old_electric_field, newAtoms, oldAtoms); + + Interactions::computeEwaldFourierElectricFieldDifference( + system.eik_x, system.eik_y, system.eik_z, system.eik_xy, system.fixedFrameworkStoredEik, system.storedEik, + system.trialEik, system.forceField, system.simulationBox, new_electric_field, old_electric_field, newAtoms, + oldAtoms); + + polarizationDifference = Interactions::computePolarizationEnergyDifference(system.forceField, new_electric_field, + old_electric_field, newAtoms, oldAtoms); + } + + const RunningEnergy pairEnergyDifference = newPairEnergy.value() - oldPairEnergy.value(); + + // Canonical acceptance: composition is conserved, so fugacities, ideal-gas Rosenbluth weights and + // the N_old/(N_new+1) factors of the semi-grand move all cancel identically. What remains is the + // Rosenbluth ratio of the two grows over the two retraces, corrected for the energy terms that the + // CBMC weights do not contain (Fourier-space Ewald, polarization, and the explicit pair term). + const double correctionFactor = + std::exp(-system.beta * (energyFourierDifference.potentialEnergy() + polarizationDifference.potentialEnergy() + + pairEnergyDifference.potentialEnergy())); + + const double acceptanceProbability = correctionFactor * + (cbmc->growNewB.RosenbluthWeight * cbmc->growNewA.RosenbluthWeight) / + (cbmc->retraceA.RosenbluthWeight * cbmc->retraceB.RosenbluthWeight); + + if (random.uniform() < acceptanceProbability) + { + componentAData.mc_moves_statistics.addAccepted(move); + componentBData.mc_moves_statistics.addAccepted(move); + + Interactions::acceptEwaldMove(system.forceField, system.storedEik, system.trialEik); + + std::vector acceptedAtomsNewB(cbmc->growNewB.atoms.begin(), cbmc->growNewB.atoms.end()); + for (Atom &atom : acceptedAtomsNewB) + { + atom.componentId = static_cast(componentB); + } + Molecule acceptedMoleculeNewB = cbmc->growNewB.molecule; + acceptedMoleculeNewB.componentId = componentB; + + std::vector acceptedAtomsNewA(cbmc->growNewA.atoms.begin(), cbmc->growNewA.atoms.end()); + for (Atom &atom : acceptedAtomsNewA) + { + atom.componentId = static_cast(componentA); + } + Molecule acceptedMoleculeNewA = cbmc->growNewA.molecule; + acceptedMoleculeNewA.componentId = componentA; + + // Replace A first, then B. Deleting a molecule of component A shifts atom storage but leaves + // component B's per-component molecule index unchanged (insertions append at the end of a + // component's block), so 'moleculeB' still refers to the original molecule; its span, however, + // must be re-fetched because the underlying atom vector has been modified. + if (system.forceField.computePolarization) + { + std::span electricFieldNewB = std::span(new_electric_field.begin(), cbmc->growNewB.atoms.size()); + std::span electricFieldNewA = std::span( + new_electric_field.begin() + static_cast::difference_type>(cbmc->growNewB.atoms.size()), + cbmc->growNewA.atoms.size()); + + system.deleteMolecule(componentA, moleculeA, atomsA); + system.insertMoleculePolarization(componentB, acceptedMoleculeNewB, acceptedAtomsNewB, electricFieldNewB); + + std::span refetchedAtomsB = system.spanOfMolecule(componentB, moleculeB); + system.deleteMolecule(componentB, moleculeB, refetchedAtomsB); + system.insertMoleculePolarization(componentA, acceptedMoleculeNewA, acceptedAtomsNewA, electricFieldNewA); + } + else + { + system.deleteMolecule(componentA, moleculeA, atomsA); + system.insertMolecule(componentB, acceptedMoleculeNewB, acceptedAtomsNewB); + + std::span refetchedAtomsB = system.spanOfMolecule(componentB, moleculeB); + system.deleteMolecule(componentB, moleculeB, refetchedAtomsB); + system.insertMolecule(componentA, acceptedMoleculeNewA, acceptedAtomsNewA); + } + + const RunningEnergy energyDifference = (cbmc->growNewB.energies + cbmc->growNewA.energies) - + (cbmc->retraceA.energies + cbmc->retraceB.energies) + + energyFourierDifference + pairEnergyDifference + polarizationDifference; + + return energyDifference; + } + + return std::nullopt; +} diff --git a/src/raspakit/mc_moves/component/identity_switch.ixx b/src/raspakit/mc_moves/component/identity_switch.ixx new file mode 100644 index 000000000..821458684 --- /dev/null +++ b/src/raspakit/mc_moves/component/identity_switch.ixx @@ -0,0 +1,43 @@ +module; + +export module mc_moves_identity_switch; + +import std; + +import randomnumbers; +import running_energy; +import system; + +export namespace MC_Moves +{ +/** + * \brief Performs a canonical CBMC identity-switch move (the MCCCS-MN "swatch" move). + * + * Selects one molecule of \p selectedComponent and one molecule of a partner component (drawn + * from \c Component::identitySwitches) in the same box and exchanges their identities: a molecule + * of the partner type is grown with CBMC at the first molecule's starting-bead position and vice + * versa, while both old molecules are retraced. + * + * In contrast to \c MC_Moves::identityChangeMove (the semi-grand "swotch" move, which converts a + * single molecule and is driven by the imposed fugacity ratio), this move exchanges a *pair* and + * therefore conserves the number of molecules of every component. Fugacities, ideal-gas + * Rosenbluth weights and the number-of-molecules factors cancel identically, so the acceptance + * rule contains only the Rosenbluth ratio of the two grows over the two retraces, corrected for + * the terms the CBMC weights do not contain (Fourier-space Ewald, polarization, and the direct + * interaction between the two exchanged molecules). Tail corrections cancel exactly because the + * multiset of pseudo-atom types in the box is unchanged. + * + * Because composition is conserved, the move imposes no thermodynamic constraint of its own: it + * leaves every equilibrium average untouched and serves purely to accelerate sampling in dense + * multicomponent systems, where insertion and deletion of whole molecules is inefficient. + * + * Requires \c Component::identitySwitches to be populated with the partner component indices. + * + * \param random Random number generator instance. + * \param system The simulation system. + * \param selectedComponent Index of the component selected for the move attempt. + * + * \return Energy difference if the move is accepted; \c std::nullopt otherwise. + */ +std::optional identitySwitchMove(RandomNumber &random, System &system, std::size_t selectedComponent); +} // namespace MC_Moves diff --git a/src/raspakit/mc_moves/mc_moves.cpp b/src/raspakit/mc_moves/mc_moves.cpp index 8a7ea675c..cb6829879 100644 --- a/src/raspakit/mc_moves/mc_moves.cpp +++ b/src/raspakit/mc_moves/mc_moves.cpp @@ -54,6 +54,7 @@ import mc_moves_gibbs_swap_cbmc; import mc_moves_volume; import mc_moves_gibbs_volume; import mc_moves_identity_change; +import mc_moves_identity_switch; import mc_moves_swap_cfcmc; import mc_moves_swap_cfcmc_cbmc; import mc_moves_gibbs_swap_cbmc; @@ -501,6 +502,22 @@ Move::Types MC_Moves::performRandomMoveInitialization(RandomNumber& random, Syst } break; } + case Move::Types::IdentitySwitchCBMC: + { + if (!selectedSystem.components[selectedComponent].identitySwitches.empty()) + { + std::optional energyDifference = + MC_Moves::identitySwitchMove(random, selectedSystem, selectedComponent); + + if (energyDifference) + { + selectedSystem.runningEnergies += energyDifference.value(); + } + + selectedSystem.tmmc.updateMatrix(double3(0.0, 1.0, 0.0), oldN); + } + break; + } case Move::Types::Swap: { if (random.uniform() < 0.5) @@ -1219,6 +1236,22 @@ Move::Types MC_Moves::performRandomMoveEquilibration(RandomNumber& random, Syste } break; } + case Move::Types::IdentitySwitchCBMC: + { + if (!selectedSystem.components[selectedComponent].identitySwitches.empty()) + { + std::optional energyDifference = + MC_Moves::identitySwitchMove(random, selectedSystem, selectedComponent); + + if (energyDifference) + { + selectedSystem.runningEnergies += energyDifference.value(); + } + + selectedSystem.tmmc.updateMatrix(double3(0.0, 1.0, 0.0), oldN); + } + break; + } case Move::Types::Swap: { if (random.uniform() < 0.5) @@ -1913,6 +1946,21 @@ Move::Types MC_Moves::performRandomMoveProduction(RandomNumber& random, System& } break; } + case Move::Types::IdentitySwitchCBMC: + { + if (!selectedSystem.components[selectedComponent].identitySwitches.empty()) + { + std::optional energyDifference = + MC_Moves::identitySwitchMove(random, selectedSystem, selectedComponent); + + if (energyDifference) + { + selectedSystem.runningEnergies += energyDifference.value(); + } + selectedSystem.tmmc.updateMatrix(double3(0.0, 1.0, 0.0), oldN); + } + break; + } case Move::Types::Swap: { if (random.uniform() < 0.5) diff --git a/src/raspakit/mc_moves/move_types.cpp b/src/raspakit/mc_moves/move_types.cpp index 7a3d248ff..180590e66 100644 --- a/src/raspakit/mc_moves/move_types.cpp +++ b/src/raspakit/mc_moves/move_types.cpp @@ -48,7 +48,8 @@ std::array Move::moveNames "Group swap (CBMC)", "Group swap (CFCMC)", "Group swap (CB/CFCMC)", - "Tethered proton hop" + "Tethered proton hop", + "Identity switch (CBMC)" }; std::array Move::timingNames = @@ -228,6 +229,8 @@ std::array, std::to_underlying(Move::Types::Count)> Mo Move::Timing::LambdaNonEwald, Move::Timing::LambdaEwald, Move::Timing::LambdaTail}, // TetheredProtonHop std::vector{Move::Timing::ExternalFieldMolecule, Move::Timing::FrameworkMolecule, - Move::Timing::MoleculeMolecule, Move::Timing::Ewald} + Move::Timing::MoleculeMolecule, Move::Timing::Ewald}, + // IdentitySwitchCBMC + std::vector{Move::Timing::NonEwald, Move::Timing::Ewald} }; diff --git a/src/raspakit/mc_moves/move_types.ixx b/src/raspakit/mc_moves/move_types.ixx index 41bce07e7..d0eea0bf2 100644 --- a/src/raspakit/mc_moves/move_types.ixx +++ b/src/raspakit/mc_moves/move_types.ixx @@ -52,7 +52,8 @@ export struct Move GroupSwapCFCMC = 41, // CFCMC insertion/deletion of a neutral group of molecules GroupSwapCBCFCMC = 42, // CB/CFCMC insertion/deletion of a neutral group of molecules TetheredProtonHop = 43, // relocation of a tethered proton among its discrete candidate sites - Count = 44 + IdentitySwitchCBMC = 44, // canonical pair identity exchange (MCCCS-MN 'swatch') + Count = 45 }; /** @@ -125,7 +126,8 @@ export inline std::unordered_set componentMoves = {Move::Types::Tra Move::Types::RotationSmartMC, Move::Types::TranslationRotationSmartMC, Move::Types::ReinsertionCBMC, Move::Types::PartialReinsertionCBMC, - Move::Types::IdentityChangeCBMC, Move::Types::Swap, + Move::Types::IdentityChangeCBMC, + Move::Types::IdentitySwitchCBMC, Move::Types::Swap, Move::Types::SwapCBMC, Move::Types::PairSwapCBMC, Move::Types::PairSwap, Move::Types::GroupSwap, Move::Types::GroupSwapCBMC, diff --git a/src/raspakit/mc_moves/probabilities.cpp b/src/raspakit/mc_moves/probabilities.cpp index 1c7ead37d..ac80eecd4 100644 --- a/src/raspakit/mc_moves/probabilities.cpp +++ b/src/raspakit/mc_moves/probabilities.cpp @@ -121,6 +121,7 @@ std::string MCMoveProbabilities::repr() std::print(stream, "reinsertionCBMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::ReinsertionCBMC)]); std::print(stream, "partialReinsertionCBMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::PartialReinsertionCBMC)]); std::print(stream, "identityChangeCBMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::IdentityChangeCBMC)]); + std::print(stream, "identitySwitchCBMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::IdentitySwitchCBMC)]); std::print(stream, "swapProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::Swap)]); std::print(stream, "swapCBMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::SwapCBMC)]); std::print(stream, "swapCFCMCProbability: {}\n", normalized_probabilities[std::to_underlying(Move::Types::SwapCFCMC)]); diff --git a/src/raspakit/mc_moves/statistics.ixx b/src/raspakit/mc_moves/statistics.ixx index 6c55f712a..7b9cf948f 100644 --- a/src/raspakit/mc_moves/statistics.ixx +++ b/src/raspakit/mc_moves/statistics.ixx @@ -68,6 +68,7 @@ export struct MCMoveStatistics stats[std::to_underlying(Move::Types::ReinsertionCBMC)] = MoveStatistics{}; stats[std::to_underlying(Move::Types::PartialReinsertionCBMC)] = MoveStatistics{}; stats[std::to_underlying(Move::Types::IdentityChangeCBMC)] = MoveStatistics{}; + stats[std::to_underlying(Move::Types::IdentitySwitchCBMC)] = MoveStatistics{}; stats[std::to_underlying(Move::Types::GibbsVolume)] = MoveStatistics{.maxChange = 0.1, .lowerLimit = 0.01, .upperLimit = 1.5}; stats[std::to_underlying(Move::Types::GibbsSwapCBMC)] = MoveStatistics{}; diff --git a/tests/raspa3-tests/CMakeLists.txt b/tests/raspa3-tests/CMakeLists.txt index da78981d2..8ba464c90 100644 --- a/tests/raspa3-tests/CMakeLists.txt +++ b/tests/raspa3-tests/CMakeLists.txt @@ -2,6 +2,7 @@ add_executable(unit_tests_raspa3 mc_component_moves.cpp mc_fractional_molecule_order.cpp mc_gibbs_drift.cpp + mc_identity_switch_drift.cpp mc_thermodynamic_integration_drift.cpp mc_muvt_drift.cpp mc_muvt_grids_drift.cpp diff --git a/tests/raspa3-tests/mc_identity_switch_drift.cpp b/tests/raspa3-tests/mc_identity_switch_drift.cpp new file mode 100644 index 000000000..f11b63035 --- /dev/null +++ b/tests/raspa3-tests/mc_identity_switch_drift.cpp @@ -0,0 +1,168 @@ +#include + +import std; + +import int3; +import double3; +import randomnumbers; +import units; +import atom; +import pseudo_atom; +import vdwparameters; +import forcefield; +import framework; +import component; +import system; +import monte_carlo; +import simulationbox; +import running_energy; +import move_statistics; +import mc_moves_statistics; +import mc_moves_move_types; +import mc_moves_probabilities; + +// The identity-switch move exchanges the identities of one molecule of component A and one +// molecule of component B in the same box (the MCCCS-MN "swatch"). Because a pair is exchanged, +// the number of molecules of every component is conserved and the acceptance rule contains no +// fugacities: only the Rosenbluth ratio of the two grows over the two retraces, corrected for +// the Fourier-space Ewald difference, the polarization difference and the direct interaction +// between the two exchanged molecules. + +// Two components built from the same pseudo-atom are physically identical and differ only in +// their label, so every factor in the acceptance rule cancels exactly and the move is always +// accepted. The composition must stay exactly where it started: unlike the semi-grand identity +// change, this move cannot convert one component into the other. +TEST(MC_IDENTITY_SWITCH_DRIFT, identical_components_are_always_accepted) +{ + const ForceField forceField = ForceField::makeZeoliteForceField(12.0, true, false, false); + + const std::optional typeCH4 = forceField.findPseudoAtom("CH4"); + ASSERT_TRUE(typeCH4.has_value()); + + MCMoveProbabilities probabilities = MCMoveProbabilities(); + probabilities.setProbability(Move::Types::Translation, 1.0); + probabilities.setProbability(Move::Types::IdentitySwitchCBMC, 1.0); + + Component beadA = Component::makeIon(forceField, 0, "beadA", typeCH4.value(), 0.0); + beadA.mc_moves_probabilities = probabilities; + beadA.identitySwitches = {1}; + + Component beadB = Component::makeIon(forceField, 1, "beadB", typeCH4.value(), 0.0); + beadB.mc_moves_probabilities = probabilities; + beadB.identitySwitches = {0}; + + SimulationBox box = SimulationBox(30.0, 30.0, 30.0); + + const std::size_t initialA{30}; + const std::size_t initialB{10}; + + System system = System(forceField, box, false, 300.0, 1e4, 1.0, {}, {beadA, beadB}, {}, {initialA, initialB}, 5, + MCMoveProbabilities()); + + std::vector systems{system}; + std::size_t numberOfProductionCycles{200}; + std::size_t numberOfInitializationCycles{50}; + std::size_t numberOfEquilibrationCycles{50}; + std::size_t printEvery{1000}; + std::size_t writeBinaryRestartEvery{10000}; + std::size_t rescaleWangLandauEvery{5000}; + std::size_t optimizeMCMovesEvery{5000}; + std::size_t numberOfBlocks{5}; + bool outputToFiles{false}; + + MonteCarlo mc = MonteCarlo({numberOfProductionCycles, 0, numberOfInitializationCycles, numberOfEquilibrationCycles, + printEvery, writeBinaryRestartEvery, rescaleWangLandauEvery, optimizeMCMovesEvery}, + systems, 42uz, numberOfBlocks, outputToFiles); + + mc.run(); + + for (System &s : mc.systems) + { + // the move conserves the number of molecules of each component + EXPECT_EQ(s.numberOfIntegerMoleculesPerComponent[0], initialA); + EXPECT_EQ(s.numberOfIntegerMoleculesPerComponent[1], initialB); + + for (std::size_t componentId = 0; componentId != 2; ++componentId) + { + const MoveStatistics &statistics = std::get>( + s.components[componentId].mc_moves_statistics[Move::Types::IdentitySwitchCBMC]); + + // the move must actually have run, otherwise the check below is vacuous + EXPECT_GT(statistics.totalConstructed, 0.0); + + // identical components: all Rosenbluth weights and energy differences cancel, so every + // constructed trial is accepted + EXPECT_DOUBLE_EQ(statistics.totalAccepted, statistics.totalConstructed); + } + + RunningEnergy recomputedEnergies = s.computeTotalEnergies(); + RunningEnergy drift = s.runningEnergies - recomputedEnergies; + + EXPECT_NEAR(drift.potentialEnergy(), 0.0, 1e-6); + } +} + +// Charged, multi-site molecules of different sizes. Both molecules change at the same time, so +// the Ewald difference is evaluated for a span covering two molecules at once: the intramolecular +// exclusion terms must be matched per molecule and the cross terms between the two exchanged +// molecules must not be counted as exclusions. This is the case that a single-molecule move never +// exercises; an error in it shows up as accumulating energy drift rather than as a wrong average. +TEST(MC_IDENTITY_SWITCH_DRIFT, charged_multisite_components_energy_drift) +{ + const ForceField forceField = ForceField::makeZeoliteForceField(12.0, true, false, true); + + MCMoveProbabilities probabilities = MCMoveProbabilities(); + probabilities.setProbability(Move::Types::Translation, 1.0); + probabilities.setProbability(Move::Types::IdentitySwitchCBMC, 1.0); + + Component co2 = Component::makeCO2(forceField, 0, true); + co2.mc_moves_probabilities = probabilities; + co2.identitySwitches = {1}; + + Component water = Component::makeWater(forceField, 1, true); + water.mc_moves_probabilities = probabilities; + water.identitySwitches = {0}; + + SimulationBox box = SimulationBox(30.0, 30.0, 30.0); + + const std::size_t initialCO2{20}; + const std::size_t initialWater{20}; + + System system = System(forceField, box, false, 300.0, 1e4, 1.0, {}, {co2, water}, {}, {initialCO2, initialWater}, 5, + MCMoveProbabilities()); + + std::vector systems{system}; + std::size_t numberOfProductionCycles{200}; + std::size_t numberOfInitializationCycles{50}; + std::size_t numberOfEquilibrationCycles{50}; + std::size_t printEvery{1000}; + std::size_t writeBinaryRestartEvery{10000}; + std::size_t rescaleWangLandauEvery{5000}; + std::size_t optimizeMCMovesEvery{5000}; + std::size_t numberOfBlocks{5}; + bool outputToFiles{false}; + + MonteCarlo mc = MonteCarlo({numberOfProductionCycles, 0, numberOfInitializationCycles, numberOfEquilibrationCycles, + printEvery, writeBinaryRestartEvery, rescaleWangLandauEvery, optimizeMCMovesEvery}, + systems, 42uz, numberOfBlocks, outputToFiles); + + mc.run(); + + for (System &s : mc.systems) + { + EXPECT_EQ(s.numberOfIntegerMoleculesPerComponent[0], initialCO2); + EXPECT_EQ(s.numberOfIntegerMoleculesPerComponent[1], initialWater); + + RunningEnergy recomputedEnergies = s.computeTotalEnergies(); + RunningEnergy drift = s.runningEnergies - recomputedEnergies; + + EXPECT_NEAR(drift.potentialEnergy(), 0.0, 1e-6); + EXPECT_NEAR(drift.moleculeMoleculeVDW, 0.0, 1e-6); + EXPECT_NEAR(drift.moleculeMoleculeCharge, 0.0, 1e-6); + EXPECT_NEAR(drift.ewald_fourier, 0.0, 1e-6); + EXPECT_NEAR(drift.ewald_self, 0.0, 1e-6); + EXPECT_NEAR(drift.ewald_exclusion, 0.0, 1e-6); + EXPECT_NEAR(drift.tail, 0.0, 1e-6); + EXPECT_NEAR(drift.polarization, 0.0, 1e-6); + } +}