Multi Resolution Molecular Dynamics 0.4.0
Multi Resolution Molecular Dynamics
Loading...
Searching...
No Matches
07_LennardJones_ThermodynamicForce
Note
This page is generated from examples/07_LennardJones_ThermoForce/07_LennardJones_ThermodynamicForce.cpp. Build and run it with cmake --build mrmd-build --target 07_LennardJones_ThermodynamicForce followed by ./mrmd-build/examples/07_LennardJones_ThermoForce/07_LennardJones_ThermodynamicForce. Pass --help to see the available command line options.

Thermodynamic force iteration run for the Lennard-Jones fluid coupled to a tracer gas of non-interacting particles and starting with zero thermodynamic force. The final thermodynamic force is dumped into a TXT file.

Configuration for the thermodynamic force iteration simulation.

struct Config
{
// time parameters
idx_t nsteps = 5000000 * 10 + 1;
real_t dt = 0.002_r;
// input file parameters
std::string fileRestoreH5MD =
"equilibrateLangevin_final.h5md";
// interaction parameters
static constexpr real_t sigma =
1_r;
static constexpr real_t epsilon = 1_r;
static constexpr real_t mass = 1_r;
static constexpr real_t r_cut = 2.5_r * sigma;
real_t r_cap = 0.82417464_r * sigma;
// neighbor list parameters
static constexpr real_t skin = 0.3_r * sigma;
static constexpr real_t neighborCutoff = r_cut + skin;
static constexpr real_t cell_ratio =
1_r;
static constexpr idx_t estimatedMaxNeighbors =
60;
// thermostat parameters
real_t temperature = 1.5_r;
real_t friction = 0.04_r / dt;
// thermodynamic force parameters
idx_t densitySamplingInterval = 200;
idx_t densityUpdateInterval = 10000;
real_t densityBinWidth = 0.2_r * sigma;
real_t smoothingDamping = 1_r;
real_t smoothingInverseDamping = 1_r / smoothingDamping;
idx_t smoothingNeighbors =
0;
real_t smoothingRange = real_c(smoothingNeighbors) * densityBinWidth *
smoothingDamping;
real_t thermodynamicForceModulation = 2_r;
const bool enforceSymmetry = true;
// application regions
real_t intRegionMin = 0_r;
real_t intRegionMax = 10_r * sigma + r_cut;
real_t thermoForceRegionMin =
10_r * sigma;
real_t thermoForceRegionMax =
14.5_r * sigma;
// output parameters
bool bOutput = true;
idx_t outputInterval = -1;
const std::string resName = "Argon";
const std::vector<std::string> typeNames = {"Ar"};
std::string fileOut = "thermodynamicForce";
std::string fileOutH5MD;
std::string fileOutFinalGRO;
std::string fileOutFinalH5MD;
std::string fileOutTF;
std::string fileOutDens;
std::string fileOutFinalTF;
};
int64_t idx_t
Definition datatypes.hpp:91
double real_t
Definition datatypes.hpp:99
KOKKOS_INLINE_FUNCTION constexpr real_t real_c(T t)
Definition datatypes.hpp:114

Simulation logic goes here

void thermodynamicForce(Config& config)
{
// initialize
data::Subdomain initialSubdomain;
auto atoms = data::Atoms(0);
// load data from file
auto io = io::RestoreH5MD();
io.restore(config.fileRestoreH5MD, initialSubdomain, atoms);
// reinitialize subdomain with no ghost layer in x-direction
data::Subdomain subdomain(
{
initialSubdomain.minCorner[0],
initialSubdomain.minCorner[1],
initialSubdomain.minCorner[2],
},
{
initialSubdomain.maxCorner[0],
initialSubdomain.maxCorner[1],
initialSubdomain.maxCorner[2],
},
{0_r, initialSubdomain.ghostLayerThickness[1], initialSubdomain.ghostLayerThickness[1]});
// calculate volume of the simulation domain
const auto volume = subdomain.getVolume();
// calculate and print initial density
auto rho = real_c(atoms.numLocalAtoms) / volume;
std::cout << "rho: " << rho << std::endl;
// set up ghost layer for periodic boundary conditions
// set up neighbor list
HalfVerletList verletList;
real_t maxAtomDisplacement = std::numeric_limits<real_t>::max();
idx_t rebuildCounter = 0;
// set up interaction potential and force calculation and application
action::LennardJones lennardJones(config.r_cut, config.sigma, config.epsilon, config.r_cap);
// calculate and print box center coordinates
const auto boxCenter = subdomain.getCenter();
std::cout << "x center: " << boxCenter[0] << std::endl;
std::cout << "y center: " << boxCenter[1] << std::endl;
std::cout << "z center: " << boxCenter[2] << std::endl;
// set up different regions
util::IsInSymmetricSlab isInIntRegion(
{boxCenter[0], boxCenter[1], boxCenter[2]}, config.intRegionMin, config.intRegionMax);
util::IsInSymmetricSlab isInThermoForceRegion({boxCenter[0], boxCenter[1], boxCenter[2]},
config.thermoForceRegionMin,
config.thermoForceRegionMax,
-std::numeric_limits<real_t>::epsilon());
// set up thermostat for temperature control during equilibration
action::VelocityVerletLangevinThermostat langevinIntegrator(config.friction,
config.temperature);
// set up thermodynamic force for density control
action::ThermodynamicForce thermodynamicForce({rho},
subdomain,
config.densityBinWidth,
{config.thermodynamicForceModulation},
config.enforceSymmetry,
false);
// set up timer for runtime measurement
Kokkos::Timer timer;
// set up mean square displacement analysis
analysis::MeanSquareDisplacement meanSquareDisplacement;
meanSquareDisplacement.reset(atoms);
auto msd = 0_r;
// output management
io::DumpProfile dumpDens;
real_t densityBinVolume =
subdomain.diameter[1] * subdomain.diameter[2] * config.densityBinWidth;
auto dumpH5MD = io::DumpH5MD("J-Hizzle");
std::ofstream fStat("statistics.txt");
if (config.bOutput)
{
// print table header for simulation statistics
util::printTable("step", "time", "T", "Ek", "E0", "E", "p", "msd", "Nlocal", "Nghost");
util::printTableSep("step", "time", "T", "Ek", "E0", "E", "p", "msd", "Nlocal", "Nghost");
dumpDens.open(config.fileOutDens);
dumpDens.dumpScalarView(Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), data::createGrid(thermodynamicForce.getDensityProfile())));
// thermodynamic force
dumpThermoForce.open(config.fileOutTF);
dumpThermoForce.dumpScalarView(Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), data::createGrid(thermodynamicForce.getForce())));
// microstate
dumpH5MD.open(config.fileOutH5MD, subdomain, atoms);
}
// main simulation loop
for (auto step = 0; step < config.nsteps; ++step)
{
// integrate equations of motion with Langevin thermostat
maxAtomDisplacement += langevinIntegrator.preForceIntegrate(atoms, config.dt);
// check if neighbor list needs to be rebuilt
if (maxAtomDisplacement >=
config.skin *
0.5_r) // the condition is on half the skin thickness because in principle two
// atoms may both move half the skin thickness towards each other
{
// reset displacement
maxAtomDisplacement = 0_r;
// reinsert atoms that left the domain according to periodic boundary conditions
ghostLayer.exchangeRealAtoms(atoms, subdomain);
// create ghost atoms in the ghost layer beyond the periodic boundaries
ghostLayer.createGhostAtoms(atoms, subdomain);
// rebuild neighbor list
verletList.build(atoms.getPos(),
0,
atoms.numLocalAtoms,
config.neighborCutoff,
config.cell_ratio,
subdomain.minGhostCorner.data(),
subdomain.maxGhostCorner.data(),
config.estimatedMaxNeighbors);
++rebuildCounter;
}
else
{
// update ghost atom positions in the ghost layer according to periodic boundary
// conditions
ghostLayer.updateGhostAtoms(atoms, subdomain);
}
if (step % config.densitySamplingInterval == 0)
{
thermodynamicForce.sample(atoms);
}
if (config.bOutput && (step % config.outputInterval == 0))
{
// density profile output
auto numberOfDensityProfileSamples =
thermodynamicForce.getNumberOfDensityProfileSamples();
real_t normalizationFactor = 1_r / densityBinVolume;
if (numberOfDensityProfileSamples > 0)
{
normalizationFactor =
1_r / (densityBinVolume * real_c(numberOfDensityProfileSamples));
}
auto densityProfile = Kokkos::create_mirror_view_and_copy(
Kokkos::HostSpace(), thermodynamicForce.getDensityProfile(0));
dumpDens.dumpScalarView(densityProfile, normalizationFactor);
}
if (step % config.densityUpdateInterval == 0 && step > 0)
{
// update thermodynamic force in the update region based on the sampled density profile
thermodynamicForce.update_if(
config.smoothingInverseDamping, config.smoothingRange, isInThermoForceRegion);
}
// reset forces to zero
auto force = atoms.getForce();
Cabana::deep_copy(force, 0_r);
// apply thermodynamic force to atoms in the thermodynamic force region
thermodynamicForce.applyInterpolated_if(atoms, isInThermoForceRegion);
// compute forces and potential energy for atoms in the interaction region
lennardJones.apply_if(
atoms,
verletList,
KOKKOS_LAMBDA(const real_t x1,
const real_t y1,
const real_t z1,
const real_t x2,
const real_t y2,
const real_t z2) {
return (isInIntRegion(x1, y1, z1) && isInIntRegion(x2, y2, z2));
});
// contribute forces calculated on ghost atoms back to real atoms
ghostLayer.contributeBackGhostToReal(atoms);
// integrate equations of motion after force calculation
langevinIntegrator.postForceIntegrate(atoms, config.dt);
// handle output and statistics
if (config.bOutput && (step % config.outputInterval == 0))
{
// calculate statistics
auto E0 = (lennardJones.getEnergy()) / real_c(atoms.numLocalAtoms);
auto systemMomentum = analysis::getSystemMomentum(atoms);
auto T = (2_r / 3_r) * Ek;
auto p = analysis::getPressure(atoms, subdomain);
msd = meanSquareDisplacement.calc(atoms, subdomain) /
(real_c(config.outputInterval) * config.dt);
meanSquareDisplacement.reset(atoms);
// print statistics to console
timer.seconds(),
T,
Ek,
E0,
E0 + Ek,
p,
msd,
atoms.numLocalAtoms,
atoms.numGhostAtoms);
// dump statistics to file
fStat << step << " " << timer.seconds() << " " << T << " " << Ek << " " << E0 << " "
<< E0 + Ek << " " << p << " " << msd << " " << atoms.numLocalAtoms << " "
<< atoms.numGhostAtoms << " " << std::endl;
// thermodynamic force output
auto thermoForce = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(),
thermodynamicForce.getForce(0));
dumpThermoForce.dumpScalarView(thermoForce);
io::dumpThermoForce(format("{0}_i{1:02}_tf.txt",
config.fileOut,
idx_c(std::floor(step / config.densityUpdateInterval))),
thermodynamicForce,
0);
// phase point output
dumpH5MD.dumpStep(subdomain, atoms, step, config.dt);
}
}
if (config.bOutput)
{
dumpDens.close();
dumpThermoForce.close();
dumpH5MD.close();
// final phase point output
dumpH5MD.dump(config.fileOutFinalH5MD, subdomain, atoms);
// close statistics file
fStat.close();
io::dumpGRO(config.fileOutFinalGRO,
atoms,
subdomain,
0,
config.resName,
config.resName,
config.typeNames,
false,
true);
// final thermodynamic force output
io::dumpThermoForce(config.fileOutFinalTF, thermodynamicForce, 0);
}
// write performance data to file
auto time = timer.seconds();
std::cout << time << std::endl;
auto cores = util::getEnvironmentVariable("OMP_NUM_THREADS");
std::ofstream fout("ecab.perf", std::ofstream::app);
fout << cores << ", " << time << ", " << atoms.numLocalAtoms << ", " << config.nsteps
<< std::endl;
fout.close();
}
High-level interface for the application of the Lennard-Jones potential to given atoms.
Definition LennardJones.hpp:118
High-level interface for calculating and applying the one-body thermodynamic force of AdResS.
Definition ThermodynamicForce.hpp:39
Integrator that updates the positions and velocities of atoms using the BAOAB Langevin dynamics algor...
Definition VelocityVerletLangevinThermostat.hpp:36
Calculates the mean square displacement of particles over time.
Definition MeanSquareDisplacement.hpp:31
void reset(data::Atoms &atoms)
Store current positions as a starting point.
Definition MeanSquareDisplacement.cpp:24
real_t calc(data::Atoms &atoms, const data::Subdomain &subdomain)
Compare current positions against the starting point.
Definition MeanSquareDisplacement.cpp:60
High-level interface for managing ghost atoms at the periodic boundaries.
Definition GhostLayer.hpp:33
void createGhostAtoms(data::Atoms &atoms, const data::Subdomain &subdomain)
Definition GhostLayer.hpp:44
void updateGhostAtoms(data::Atoms &atoms, const data::Subdomain &subdomain)
Definition GhostLayer.hpp:49
void exchangeRealAtoms(data::Atoms &atoms, const data::Subdomain &subdomain)
Definition GhostLayer.hpp:39
void contributeBackGhostToReal(data::Atoms &atoms)
Definition GhostLayer.hpp:56
Handles dumping trajectory data in H5MD format.
Definition DumpH5MD.hpp:41
Handles dumping profile data to a file.
Definition DumpProfile.hpp:30
void close()
Definition DumpProfile.cpp:24
void open(const std::string &filename)
Definition DumpProfile.cpp:22
void dumpScalarView(const ScalarView::HostMirror &dataProfile, const real_t &normalizationFactor=1_r)
Definition DumpProfile.cpp:26
Handles restoring trajectory data from H5MD format.
Definition RestoreH5MD.hpp:33
Predicate to check if a point is within an axis-aligned slab.
Definition IsInSymmetricSlab.hpp:26
real_t getMeanKineticEnergy(data::Atoms &atoms)
Definition KineticEnergy.hpp:44
Vector3D getSystemMomentum(data::Atoms &atoms)
Definition SystemMomentum.cpp:21
real_t getPressure(data::Atoms &atoms, const data::Subdomain &subdomain)
Definition Pressure.cpp:23
ScalarView createGrid(const MultiHistogram &input)
Definition MultiHistogram.cpp:214
DeviceAtoms Atoms
Definition Atoms.hpp:177
Save and load simulation data.
void dumpGRO(const std::string &filename, data::Atoms &atoms, const data::Subdomain &subdomain, const real_t &timestamp, const std::string &title, const std::string &resName, const std::vector< std::string > &typeNames, bool dumpGhosts, bool dumpVelocities)
format specification https://manual.gromacs.org/current/reference-manual/file-formats....
Definition DumpGRO.cpp:26
void dumpThermoForce(const std::string &filename, const action::ThermodynamicForce &thermodynamicForce, const idx_t &typeId)
Definition DumpThermoForce.cpp:24
void printTableSep(HEAD)
Definition PrintTable.hpp:40
std::string getEnvironmentVariable(const std::string &variable)
Definition EnvironmentVariables.hpp:23
void printTable(HEAD head)
Definition PrintTable.hpp:27
Cabana::VerletList< Kokkos::DefaultExecutionSpace::memory_space, Cabana::HalfNeighborTag, Cabana::VerletLayout2D, Cabana::TeamOpTag > HalfVerletList
Definition datatypes.hpp:184
KOKKOS_INLINE_FUNCTION constexpr idx_t idx_c(const T &val)
Definition datatypes.hpp:93
@ X
index of the x coordinate in vector views
Definition datatypes.hpp:142
Axis-aligned simulation box with a surrounding ghost layer.
Definition Subdomain.hpp:46
Point3D minCorner
Definition Subdomain.hpp:86
Point3D maxCorner
Definition Subdomain.hpp:89
Point3D ghostLayerThickness
Definition Subdomain.hpp:93
real_t getVolume() const
Definition Subdomain.cpp:57

Main function for the simulation

int main(int argc, char* argv[])
{
// initialize Kokkos environment
Kokkos::ScopeGuard scope_guard(argc, argv);
// print Kokkos execution space
std::cout << "execution space: " << typeid(Kokkos::DefaultExecutionSpace).name() << std::endl;
// initialize simulation configuration with command line interface
Config config;
CLI::App app{"Lennard-Jones Thermodynamic Force Simulation"};
app.add_option("-n,--nsteps", config.nsteps, "number of simulation steps");
app.add_option("-d,--tstep", config.dt, "time step");
app.add_option("-o,--outint", config.outputInterval, "output interval");
app.add_option("-i,--inpfile", config.fileRestoreH5MD, "input file name");
app.add_option("-f,--outfile", config.fileOut, "output file name");
app.add_option("-T,--temperature", config.temperature, "thermostat target temperature");
app.add_option("--friction", config.friction, "friction coefficient for thermostat");
app.add_option("--sampling", config.densitySamplingInterval, "density sampling interval");
app.add_option("--update", config.densityUpdateInterval, "density update interval");
app.add_option("--densbinwidth", config.densityBinWidth, "density bin width");
app.add_option("--damping", config.smoothingDamping, "density smoothing damping factor");
app.add_option("--neighbors", config.smoothingNeighbors, "density smoothing neighbors");
app.add_option(
"--forcemod", config.thermodynamicForceModulation, "thermodynamic force modulation");
app.add_option("--rcap", config.r_cap, "capping radius for inner Lennard-Jones potential");
app.add_option("--intmin", config.intRegionMin, "interacting region minimum coordinate");
app.add_option("--intmax", config.intRegionMax, "interacting region maximum coordinate");
app.add_option("--thermoforcemin",
config.thermoForceRegionMin,
"thermodynamic force region minimum coordinate");
app.add_option("--thermoforcemax",
config.thermoForceRegionMax,
"thermodynamic force region maximum coordinate");
CLI11_PARSE(app, argc, argv);
config.fileOutH5MD = format("{0}.h5md", config.fileOut);
config.fileOutTF = format("{0}_tf.txt", config.fileOut);
config.fileOutDens = format("{0}_dens.txt", config.fileOut);
config.fileOutFinalGRO = format("{0}_final.gro", config.fileOut);
config.fileOutFinalH5MD = format("{0}_final.h5md", config.fileOut);
config.fileOutFinalTF = format("{0}_final_tf.txt", config.fileOut);
config.smoothingRange =
real_c(config.smoothingNeighbors) * config.densityBinWidth * config.smoothingDamping;
if (config.outputInterval < 0) config.bOutput = false;
thermodynamicForce(config);
return EXIT_SUCCESS;
}