Reading the engine#

Binding the engine followed sim.run() as far as the bridge, and the browser page showed the same path running on these pages: Python builds the engine’s objects, then makes one call, runSimulation, and the whole run happens in C++. This page continues on the C++ side. It walks the real engine in the order a run uses it, one class at a time, matching each class to its part of the loop in A simple molecular dynamics loop, and names the C++ idea each excerpt relies on, with a link to the chapter that explains it.

The excerpts are copied from the source files when this site is built, so they always match the code.

The classes and who holds whom#

Four classes do the work (Fig. 24). A MolecularDynamics object runs the loop. It keeps its own copy of the Geometry (the atoms and the box) and shares a ForceCalculator with whoever created it. The ForceCalculator keeps a list of energy functions, each one a Potential; LJPotential and DFTPotential are two kinds of Potential.

../_images/engine_classes.svg

Fig. 24 The classes of a running simulation. Arrows between boxes show what one object holds; “is a” marks the two energy functions that fit the Potential socket (dashed).#

Putting a run together#

The Python method System.from_yaml, read in Binding the engine, is the clearest map of how the pieces connect. In order: the parser reads the simulation file; in lj_particle_box mode LJParticleBoxBuilder.createCubicLattice builds the Geometry; each potential file becomes a Potential, added to a ForceCalculator; and a MolecularDynamics object receives the geometry, the force calculator, the parameters and the trajectory file. The command line program run_simulation does the same steps in C++, in the main function of src/tools/run_simulation.cpp. The sections below take these objects one at a time, starting with the atoms.

The system: Geometry#

Geometry holds the state of the simulation except the velocities: the type and position of every atom, and the box.

class Geometry {
public:
    Geometry();
    
    // Atom methods
    void addAtom(const std::string& atomType, const std::array<double, 3>& coordinates);
    size_t getNumberOfAtoms() const;
    const std::vector<std::string>& getAtoms() const { return atomTypes; }
    const std::vector<std::array<double, 3>>& getPositions() const { return atomCoordinates; }
    const std::string& getAtomType(size_t index) const;
    const std::array<double, 3>& getCoordinates(size_t index) const;
    void setCoordinates(size_t index, const std::array<double, 3>& newCoordinates);
    
    // Box methods
    void setBoxDimensions(const std::array<double, 3>& dimensions);
    const std::array<double, 3>& getBoxDimensions() const { return boxDimensions; }
    
private:
    std::vector<std::string> atomTypes;
    std::vector<std::array<double, 3>> atomCoordinates;
    std::array<double, 3> boxDimensions = {0.0, 0.0, 0.0};
};
  • A class groups data with the functions that work on it; the data is private, so other code reaches it only through the public functions (Classes).

  • Positions are a std::vector of std::array<double, 3>: a list with one entry per atom, each entry three numbers \(x, y, z\) (Vectors and loops).

  • getPositions returns const std::vector<...>&: a read-only reference to the stored list, so the caller sees the positions without copying them. Functions showed that an ordinary argument or result is copied; a reference is how C++ avoids that copy.

The atoms are placed by LJParticleBoxBuilder::createCubicLattice, in src/builder/lj_particle_box_builder.cpp. Its heart is three nested loops, one per direction:

// Place particles on cubic lattice with small random offsets
std::size_t particlesAdded = 0;
for (int i = 0; i < particlesPerDim && particlesAdded < config.numParticles; ++i) {
    for (int j = 0; j < particlesPerDim && particlesAdded < config.numParticles; ++j) {
        for (int k = 0; k < particlesPerDim && particlesAdded < config.numParticles; ++k) {
            // Position on lattice, centered in box
            double x = (i + 0.5) * spacing - boxLength / 2.0 + smallDisp(rng);
            double y = (j + 0.5) * spacing - boxLength / 2.0 + smallDisp(rng);
            double z = (k + 0.5) * spacing - boxLength / 2.0 + smallDisp(rng);
            
            geometry.addAtom("LJ", {x, y, z});
            ++particlesAdded;
        }
    }
}

Each atom sits at the centre of its grid cell, plus a small random nudge (smallDisp, up to 5% of the spacing). The - boxLength / 2.0 shifts the grid so that it is centred on the origin: its coordinates run from \(-L/2\) to \(L/2\), while the box the engine wraps atoms into runs from 0 to \(L\). The first time step resolves this (see the integrator below).

The socket: Potential#

The Potential class is the socket of the plug picture:

// Base class for all interaction potentials
class Potential {
public:
    virtual ~Potential() = default;
    
    // Calculate energy for a given geometry
    virtual double calculateEnergy(const Geometry& geometry) = 0;
    
    // Calculate forces for a given geometry
    virtual void calculateForces(const Geometry& geometry, 
                                std::vector<std::array<double, 3>>& forces) = 0;
    
    // Forces and energy together. The default makes two calls; a potential whose
    // kernel yields both in one pass (LJ) overrides this to halve the cost.
    virtual double calculateForcesAndEnergy(const Geometry& geometry,
                                            std::vector<std::array<double, 3>>& forces) {
        calculateForces(geometry, forces);
        return calculateEnergy(geometry);
    }

    // Get the name of the potential
    virtual std::string getName() const = 0;
};

virtual ... = 0 declares a function without a body: every kind of Potential must provide its own. Code that holds a Potential can call calculateForces without knowing which energy function it is talking to (The plug).

calculateForcesAndEnergy is virtual too, but it has a body: a default that calls the other two. A kind of Potential may replace it. LJPotential does, because its pair loop yields the forces and the energy in one pass, and the default would run that loop twice.

LJPotential is one such kind. Its declaration starts:

class LJPotential : public Potential {
public:
    LJPotential();
    ~LJPotential() override;

    // Potential interface implementation.
    // These dispatch to lj_kernels via the currently selected backend.
    double calculateEnergy(const Geometry& geometry) override;
    void calculateForces(const Geometry& geometry, std::vector<std::array<double, 3>>& forces) override;
    double calculateForcesAndEnergy(const Geometry& geometry,
                                    std::vector<std::array<double, 3>>& forces) override;
    std::string getName() const override { return "Lennard-Jones"; }

: public Potential says that an LJPotential is a Potential; override marks each function that fills one of the socket’s slots, and the compiler checks that it really does.

The pair loop#

The work of LJPotential is the loop over pairs of atoms, in src/engine/potentials/lj_kernels.cpp. The part for one pair \(i, j\):

double dx = v.x[j] - xi;
double dy = v.y[j] - yi;
double dz = v.z[j] - zi;

// Minimum image convention.
dx -= v.bx * std::round(dx * invbx);
dy -= v.by * std::round(dy * invby);
dz -= v.bz * std::round(dz * invbz);

const double r2 = dx * dx + dy * dy + dz * dz;

// Cutoff test in r^2. No sqrt is ever taken in this kernel:
// both the energy and the force can be written in terms of r^2.
if (r2 > v.cutoff2 || r2 < 1e-20) continue;

const int tj = v.type[j];
const double eps4 = eps4row[tj];    // 4 * epsilon_ij, pre-mixed
const double sig2 = sig2row[tj];    // sigma_ij^2,     pre-mixed

const double sr2 = sig2 / r2;
const double sr6 = sr2 * sr2 * sr2;      // (sigma/r)^6 with 2 multiplies
const double sr12 = sr6 * sr6;           // instead of std::pow(x, 6)

// E = 4*eps*(sr12 - sr6)
ei += eps4 * (sr12 - sr6);

// F/r = 24*eps*(2*sr12 - sr6)/r^2, and 24*eps == 6*eps4.
// Multiplying this by the displacement vector gives the force
// directly -- no normalisation, hence no sqrt.
const double fOverR = 6.0 * eps4 * (2.0 * sr12 - sr6) / r2;

fxi -= fOverR * dx;
fyi -= fOverR * dy;
fzi -= fOverR * dz;

Line by line, this is the energy function of the loop:

  • dx, dy, dz are the separation of the pair. The three “minimum image” lines replace each by the separation to the nearest copy in the periodic box.

  • Pairs beyond the cutoff are skipped. The test compares \(r^2\) with \(r_c^2\), so no square root is needed.

  • sr6 is \((\sigma/r)^6\) and sr12 is \((\sigma/r)^{12}\); eps4 is \(4\varepsilon\). The energy line is the LJ formula.

  • fOverR is the size of the force divided by \(r\), \(24\varepsilon\left[2(\sigma/r)^{12} - (\sigma/r)^6\right]/r^2\). Multiplying it by the separation gives the force vector on atom \(i\), again without a square root.

This loop visits every pair, so its cost grows as \(N^2\); how it is split across processor cores is the subject of the parallel programming module.

The force step: ForceCalculator#

ForceCalculator holds the list of potentials and adds up their forces and energies:

void ForceCalculator::calculateForces(const Geometry& geometry, 
                                   std::vector<std::array<double, 3>>& forces) {
    calculateForcesAndEnergy(geometry, forces);
}

double ForceCalculator::calculateForcesAndEnergy(const Geometry& geometry,
                                                 std::vector<std::array<double, 3>>& forces) {
    // Initialize forces to zero
    size_t numAtoms = geometry.getNumberOfAtoms();
    forces.resize(numAtoms, {0.0, 0.0, 0.0});
    for (auto& force : forces) {
        force = {0.0, 0.0, 0.0};
    }
    
    double totalEnergy = 0.0;

    // Calculate forces from each potential
    for (const auto& potential : potentials) {
        // Create a temporary forces vector for this potential
        std::vector<std::array<double, 3>> potentialForces(numAtoms, {0.0, 0.0, 0.0});
        
        // Calculate forces (and energy) for this potential
        totalEnergy += potential->calculateForcesAndEnergy(geometry, potentialForces);
        
        // Add to total forces
        for (size_t i = 0; i < numAtoms; ++i) {
            for (int d = 0; d < 3; ++d) {
                forces[i][d] += potentialForces[i][d];
            }
        }
    }
    return totalEnergy;
}

The list is a std::vector<std::shared_ptr<Potential>>. A shared_ptr is a pointer that several objects can share, and that deletes the object when the last one lets go; here it lets the list hold different kinds of potential side by side, each reached through the Potential socket (The plug). With one potential in the list, as in every run on these pages, the sum has one term.

The loop: MolecularDynamics#

MolecularDynamics owns the loop. initialize gives every atom a random velocity at the target temperature and computes the first forces:

void MolecularDynamics::initialize() {
    // Validate that necessary components are set
    if (!forceCalculator) {
        throw std::runtime_error("Force calculator not set before initialization");
    }
    
    if (geometry.getNumberOfAtoms() == 0) {
        throw std::runtime_error("No atoms in geometry before initialization");
    }
    
    // Initialize velocities using Maxwell-Boltzmann distribution
    initializeVelocities(params.temperature);
    
    // Initialize forces array
    size_t numAtoms = geometry.getNumberOfAtoms();
    forces.resize(numAtoms, {0.0, 0.0, 0.0});
    
    // Calculate initial energy and forces
    calculateForces();
    currentEnergy = potentialEnergy;
    
    currentStep = 0;
}

runSimulation then repeats one step per pass. The heart of the loop is three calls: the thermostat before the step, the integrator, and the thermostat after it:

for (currentStep = 0; currentStep < totalSteps; ++currentStep) {
    const bool inProduction = usePhases && currentStep >= equilibrationSteps;
    // Temperature is held except in NVE production
    Thermostat* activeThermostat = inProduction ? nullptr : thermostat.get();
    
    if (activeThermostat) {
        activeThermostat->beforeStep(state, params.timeStep, params.temperature);
    }
    
    // Advance one step with the plugged-in integrator; it leaves the forces
    // and potential energy at the new positions
    integrator->step(state, params.timeStep);
    
    if (activeThermostat) {
        activeThermostat->afterStep(state, params.timeStep, params.temperature);
    }
    

The rest of the pass adds the kinetic energy to the potential energy, which the force step inside the integrator has already computed, prints a line every 10 steps, and writes a frame of the trajectory.

The integrator and the thermostat are plugs, like the potential. The loop holds an Integrator and a Thermostat, and calls them without knowing which kind it holds:

class Integrator {
public:
    virtual ~Integrator() = default;

    // Advance positions and velocities by one time step dt.
    virtual void step(MDState& state, double dt) = 0;

    // Name used in YAML and in Python, e.g. "velocity_verlet".
    virtual std::string getName() const = 0;
};

Each plug gets an MDState: a view of the positions, velocities and forces it may change. The YAML key integrator: picks velocity_verlet (the default) or leapfrog; thermostat: picks velocity_rescale (the default), berendsen, langevin or none. Every run on these pages uses the defaults.

The integrator is the Velocity-Verlet step of the loop, with every mass equal to 1:

void VelocityVerletIntegrator::step(MDState& state, double dt) {
    Geometry& geometry = state.geometry;
    auto& velocities = state.velocities;
    auto& forces = state.forces;
    const double dtSquaredHalf = 0.5 * dt * dt;

    // First half: new positions from f(t), velocities half-kicked by f(t)
    for (size_t i = 0; i < geometry.getNumberOfAtoms(); ++i) {
        // r(t+dt) = r(t) + v(t)*dt + 0.5*f(t)*dt^2
        std::array<double, 3> pos = geometry.getCoordinates(i);
        std::array<double, 3> newPos = {
            pos[0] + velocities[i][0] * dt + forces[i][0] * dtSquaredHalf,
            pos[1] + velocities[i][1] * dt + forces[i][1] * dtSquaredHalf,
            pos[2] + velocities[i][2] * dt + forces[i][2] * dtSquaredHalf
        };
        geometry.setCoordinates(i, newPos);

        // v(t+dt/2) = v(t) + 0.5*f(t)*dt
        velocities[i][0] += forces[i][0] * 0.5 * dt;
        velocities[i][1] += forces[i][1] * 0.5 * dt;
        velocities[i][2] += forces[i][2] * 0.5 * dt;
    }

    state.wrapPositions();

    // f(t+dt) at the new positions
    state.computeForces();

    // Second half: v(t+dt) = v(t+dt/2) + 0.5*f(t+dt)*dt
    for (size_t i = 0; i < geometry.getNumberOfAtoms(); ++i) {
        velocities[i][0] += forces[i][0] * 0.5 * dt;
        velocities[i][1] += forces[i][1] * 0.5 * dt;
        velocities[i][2] += forces[i][2] * 0.5 * dt;
    }
}

The first loop moves each position by \(v\,\Delta t + \tfrac12 F\,\Delta t^2\) and adds half a step of force to each velocity; then the forces are recomputed at the new positions; the second loop adds the other half. In between, wrapPositions moves any atom with a coordinate below 0 or at least \(L\) back in, by one box length. On the first step that wraps every negative coordinate of the centred grid into the box (−2.12 becomes 3.26 for \(L = 5.39\)), so from then on positions stay between 0 and \(L\); only the Initial configuration frame of the trajectory shows the centred grid.

The other integrator, leapfrog, is written as kick, drift, kick. In exact arithmetic it gives the same trajectory as velocity Verlet, so its numbers match to rounding; it is there to show a second plug, not a different result.

Fig. 25 draws one pass of runSimulation this way. Compared with the loop of A simple molecular dynamics loop (Fig. 2), the Integrator box has opened up: it is one function, VelocityVerletIntegrator::step, whose two loops sit on either side of the force step, because the velocities can only be finished with the forces at the new positions.

../_images/engine_loop.svg

Fig. 25 One pass of runSimulation, one time step. Each box names the engine function that does that part; both halves of the velocity update happen inside the integrator’s step, with the forces computed between them.#

The thermostat by default rescales every velocity by one factor, so that the temperature is exactly the target. With a time constant tau it becomes Berendsen and moves only part of the way:

void VelocityRescaleThermostat::afterStep(MDState& state, double dt, double targetTemperature) {
    // Current temperature (kB = 1, mass = 1)
    const double currentTemp = state.temperature();
    if (currentTemp <= 1e-10) {
        return;  // Nothing to scale; avoids dividing by zero
    }

    double scaleFactor;
    if (tau > 0.0) {
        // Berendsen: relax towards the target with time constant tau. Clamp at
        // zero so a huge dt/tau cannot ask for the square root of a negative.
        const double lambdaSquared = 1.0 + (dt / tau) * (targetTemperature / currentTemp - 1.0);
        scaleFactor = std::sqrt(std::max(0.0, lambdaSquared));
    } else {
        // Rescale exactly onto the target
        scaleFactor = std::sqrt(targetTemperature / currentTemp);
    }

    for (auto& v : state.velocities) {
        v[0] *= scaleFactor;
        v[1] *= scaleFactor;
        v[2] *= scaleFactor;
    }
}

The temperature here is computed as in the thermal energy section, \(T = 2K / (3N)\) with \(k_B = 1\).

Reading the configuration: YAMLParser#

YAMLParser turns the YAML files into the objects above. It does not read YAML itself: it runs a small Python script, yaml_parser.py, that converts the file to JSON, and reads the JSON with the nlohmann/json library. So a run needs Python with the PyYAML package, and that script where the engine looks for it (the repository’s src/utils/, or the folder the run starts in).

For a classical potential file, the LJ branch builds the plug:

if (componentType == "lennard_jones") {
    // Create a new LJ potential
    auto ljPotential = std::make_shared<LJPotential>();
    
    // Set the cutoff
    double cutoff = component["cutoff"];
    ljPotential->setCutoff(cutoff);
    
    // Parse atom parameters
    for (auto it = component["atom_parameters"].begin(); it != component["atom_parameters"].end(); ++it) {
        std::string atomType = it.key();
        double epsilon = it.value()["epsilon"];
        double sigma = it.value()["sigma"];
        
        ljPotential->addAtomParameters(atomType, epsilon, sigma);
    }
    
    // Set mixing rule if available
    if (component.contains("mixing_rule")) {
        ljPotential->setMixingRule(component["mixing_rule"]);
    }

    // Long-range dispersion correction (energy and pressure only;
    // it adds no force). Off unless the file asks for it.
    if (component.contains("tail_correction")) {
        ljPotential->setTailCorrection(component["tail_correction"].get<bool>());
    }
    
    return ljPotential;

It reads the cutoff, ε and σ for each atom type, and the mixing rule, which sets ε and σ for a pair of two different types. std::make_shared creates the LJPotential and the shared_ptr that will hold it in the list.

What the engine leaves out#

The engine is small on purpose. These limits are known and stay as they are on these pages:

  • Every pair is checked on every step, so the work grows as \(N^2\); there is no neighbour list yet that would skip far pairs cheaply.

  • The LJ energy is cut, not shifted, at the cutoff, and no tail correction is added by default. The tail correction is opt-in (tail_correction: true in the potential YAML, or setTailCorrection), but the YAML key shift_potential is not read by the parser.

  • Every atom has mass 1.

  • The default thermostat is the simplest kind: an exact rescaling after every step, which holds the temperature fixed but does not let it fluctuate as it would in a real system at that temperature. The langevin thermostat lets it fluctuate, but no run on these pages uses it.

  • The run length is total_steps, unless the file sets equilibration_steps or production_steps. Those two then replace it: the temperature is held during equilibration, and production runs with no thermostat (NVE) and prints its energy drift. data/lj_nve_simulation.yaml is such a file.

Check yourself#

1. You write a new energy function, MorsePotential. Which class must it derive from, and which functions must it provide?

It must derive from Potential and provide calculateEnergy, calculateForces and getName, the three functions declared = 0. Nothing in ForceCalculator or MolecularDynamics changes.

2. In the pair loop, why is the cutoff tested on r2 and not on r?

Comparing squared distances gives the same answer and avoids a square root for every pair; the energy and force formulas also need only \(r^2\).

3. How many times does one step visit each pair of atoms?

Twice, with the default serial loop. The force call in the integrator’s step runs the pair loop once, and that loop visits pair \((i, j)\) once from atom \(i\) and once from atom \(j\). The potential energy that runSimulation reports comes out of the same pass, through calculateForcesAndEnergy, so it costs no second loop.

4. A run’s YAML says shift_potential: true. Is the potential shifted?

No. The parser does not read that key, so the run uses the default: the energy is cut at the cutoff, not shifted.

Next#

The pair loop visits every pair of atoms, so its cost grows as \(N^2\), and so far it runs on one core. The parallel programming module first measures how much of a step that loop takes, then splits it across the cores of the processor.