Where we are. 01 gave you the map: geometry → potentials → force calculator → MD driver. This doc zooms into the potentials layer, where the LJ energy and forces are computed.
The force on atom
Now let's see every piece of that in src/engine/potentials/lj_potential.cpp.
LJPotential inherits from the abstract Potential base class defined in src/engine/force_calculator.h. The two methods it must implement are:
double calculateEnergy(const Geometry& geometry);
void calculateForces(const Geometry& geometry, std::vector<std::array<double,3>>& forces);It also overrides the optional calculateForcesAndEnergy(), which returns the energy and fills the forces from one pass over the pairs; the MD loop calls that one every step.
The class stores per-atom-type parameters:
struct AtomParameters { double epsilon; double sigma; };
std::map<std::string, AtomParameters> atomParameters;
double cutoff = 10.0; // default, overridden by config
std::string mixingRule = "geometric";For the LJ-bulk run those are loaded from data/potentials/lj_bulk.yaml:
components:
- type: "lennard_jones"
cutoff: 2.5 # Cutoff radius in reduced units
atom_parameters:
"LJ": { epsilon: 1.0, sigma: 1.0 }
mixing_rule: "geometric"This is the direct translation of the LJ equation:
double LJPotential::calculatePairEnergy(double epsilon, double sigma, double distance) {
if (distance <= 0.0) return 0.0;
double sigma_r = sigma / distance;
double sigma_r6 = std::pow(sigma_r, 6);
double sigma_r12 = sigma_r6 * sigma_r6;
return 4.0 * epsilon * (sigma_r12 - sigma_r6);
}sigma_r6 is sigma_r12 is
void LJPotential::calculatePairForce(double epsilon, double sigma, double distance,
const std::array<double, 3>& direction,
std::array<double, 3>& force1,
std::array<double, 3>& force2) {
if (distance <= 0.0) return;
double sigma_r = sigma / distance;
double sigma_r6 = std::pow(sigma_r, 6);
double sigma_r12 = sigma_r6 * sigma_r6;
double forceMagnitude = 24.0 * epsilon * (2.0 * sigma_r12 - sigma_r6) / distance;
for (int i = 0; i < 3; ++i) {
force1[i] -= forceMagnitude * direction[i];
force2[i] += forceMagnitude * direction[i];
}
}direction is the unit vector forceMagnitude is
Newton's third law is applied in the same call: force2[i] += ... is the opposite of force1[i] -= .... This means the double-loop only needs to run over
Every pair loop starts with:
if (distance > cutoff || distance < 1e-10) continue;cutoff = 2.5 in reduced units. Pairs beyond that distance contribute nothing. The 1e-10 guard prevents division by zero if two particles overlap.
The potential is not shifted to zero at the cutoff in the current implementation (shift_potential: false in the config). This means there is a small discontinuity in energy at
In a simulation box with PBC you don't want to compare
if (boxDim[0] > 0.0) dx = dx - boxDim[0] * std::round(dx / boxDim[0]);
if (boxDim[1] > 0.0) dy = dy - boxDim[1] * std::round(dy / boxDim[1]);
if (boxDim[2] > 0.0) dz = dz - boxDim[2] * std::round(dz / boxDim[2]);std::round(dx / L) gives the nearest integer, i.e. which box image is closest. Subtracting n * L folds the displacement back into
This block appears identically in both calculateEnergyReference() and calculateForcesReference(), the original pair loops kept as the correctness baseline. The kernels in lj_kernels.cpp, which a real run calls, do the same fold. If boxDim is zero (no PBC), the if guards skip it entirely.
When two different atom types interact, you need combined getMixedParameters() handles this:
// geometric (default):
epsilon_mix = sqrt(eps_i * eps_j);
sigma_mix = sqrt(sig_i * sig_j);
// arithmetic (Lorentz-Berthelot):
epsilon_mix = sqrt(eps_i * eps_j);
sigma_mix = 0.5 * (sig_i + sig_j);"Arithmetic" names how
For the LJ-bulk simulation there is only one atom type ("LJ") with
Everything above is the reference code: calculateEnergyReference() and
calculateForcesReference() loop over pairs and call the two pair functions.
They are kept because they read line by line like the equation, and because
tests/unit/test_lj_kernels.cpp checks every faster version against them.
An MD step does not call them. calculateForcesAndEnergy() copies positions
into flat arrays and hands them to ljComputeGather() in
src/engine/potentials/lj_kernels.cpp.
With the default backend (LJBackend::Serial) the work is done by
computeRange(), and its inner loop is the same pair force written differently:
const double r2 = dx * dx + dy * dy + dz * dz;
if (r2 > v.cutoff2 || r2 < 1e-20) continue; // cutoff test in r^2
const double eps4 = eps4row[tj]; // 4*eps_ij, pre-mixed
const double sig2 = sig2row[tj]; // sigma_ij^2, pre-mixed
const double sr2 = sig2 / r2;
const double sr6 = sr2 * sr2 * sr2; // no std::pow
const double sr12 = sr6 * sr6;
ei += eps4 * (sr12 - sr6);
const double fOverR = 6.0 * eps4 * (2.0 * sr12 - sr6) / r2;
fxi -= fOverR * dx; // F/r times the displacement:
// no unit vector, no sqrtThree things changed from the reference, none of them physics:
| Reference | Kernel | Why |
|---|---|---|
distance = sqrt(r2), then sigma / distance
|
stays in |
|
std::pow(sigma_r, 6) |
two multiplies | same number, cheaper (the compiler often does this already) |
std::map lookup by type name, mixing per pair |
flat eps4 / sigma2 tables, mixed once in buildView()
|
an array index instead of a string lookup |
The kernel also does not use Newton's third law: each atom i loops over
every j and writes only its own force (the "gather" form). That doubles the
arithmetic but means no two atoms ever write the same slot, which is what lets
the Threads and OpenMP backends split the atoms across cores. The energy is
counted twice and halved by the caller.
How much each change buys, and why gather vs. scatter matters, is measured in
learn-parallel lesson 02 (the
Looking at the YAML config and the code comments:
-
Neighbor lists — the config mentions
neighbor_list_radiusandupdate_frequencybut the code still uses an$O(N^2)$ pair loop -
Potential shift —
shift_potential: false; adding this would eliminate the energy discontinuity at cutoff
These are the natural next performance/accuracy improvements flagged in the codebase.
The tail correction (the energy of all pairs beyond the cutoff, assuming a
uniform fluid out there) is implemented, and off by default. Turn it on with
tail_correction: true in the potential YAML or LJPotential.setTailCorrection(True).
It changes the energy and the pressure but adds no force, so trajectories are
unchanged; learn-parallel lesson 08
derives it.
| File | Role |
|---|---|
| src/engine/potentials/lj_potential.h | Class declaration, public API |
| src/engine/potentials/lj_potential.cpp | Pair functions, reference loops, mixing tables, tail correction |
| src/engine/potentials/lj_kernels.cpp | The kernels a real run calls, and the parallel backends |
| src/engine/force_calculator.h | Potential base class |
| data/potentials/lj_bulk.yaml | LJ params for bulk run |
Next: 03_integrator_and_md.md — you can now compute energy and forces for one frozen configuration; the next doc answers how those forces get turned into motion, step after step.