Algorithm Search⌘K

Algorithmadvanced

Dissipative particle dynamics

Also called DPD.

Moves soft mesoscale beads with conservative, dissipative and random pairwise forces that conserve momentum, so the beads show hydrodynamics.

Time
O(S N^2) worst
Space
O(N) extra
Where
N = the number of beads; S = the number of time steps
Properties
randomizediterativemomentum-conservingrandomizednot symplectic
Origin
P. J. Hoogerbrugge, J. M. V. A. Koelman, 1992

Dissipative particle dynamics (DPD) is a particle method for soft matter at scales between atoms and continua. Each bead stands for a cluster of molecules. Pairs of beads within a cutoff feel three forces along the line between them: a soft repulsion, a friction that acts on the relative velocity, and a random force. The friction and the random force are tied by a fluctuation-dissipation relation, so the beads sample the canonical ensemble at a set temperature (a theorem for the continuous-time dynamics). Every force acts in equal and opposite pairs, so the total momentum is conserved and the beads show hydrodynamic flow at large scales. This is the difference from Langevin dynamics, whose friction acts against a fixed background and destroys momentum. The method sits between molecular dynamics and continuum solvers such as smoothed particle hydrodynamics and the lattice Boltzmann method.

In plain words

Imagine a liquid made of soft balls instead of hard molecules. Each ball is a small blob of many molecules. When two balls come close, they push each other away gently, so they can even overlap a little. They also rub against each other: if they move apart or together, a friction slows down their difference in speed. And they get random kicks, one kick per pair, equal and opposite on the two balls.

The friction takes energy out and the kicks put energy in. If the two are set in the right ratio, the balls settle at the temperature you want. Because every push, rub and kick acts on both balls of a pair with opposite signs, the liquid as a whole never gains or loses momentum. That is why the balls flow like a real liquid, with waves and vortices.

The problem

The input is a set of NN beads of mass 11 with positions xix_i and velocities viv_i in a periodic box of side LL in two dimensions, a cutoff rcr_c, a repulsion strength aa, a friction γ\gamma, a noise amplitude σ\sigma and a time step hh. For a pair with rij=∣xi−xj∣<rcr_{ij} = |x_i - x_j| < r_c (with the minimum image), let eij=(xi−xj)/rije_{ij} = (x_i - x_j) / r_{ij}, vij=vi−vjv_{ij} = v_i - v_j and w(r)=1−r/rcw(r) = 1 - r / r_c. The force on bead ii from bead jj is Fij=(FijC+FijD+FijR)eijF_{ij} = (F^C_{ij} + F^D_{ij} + F^R_{ij}) e_{ij} with

FijC=a w(rij),FijD=−γ wD(rij) (eij⋅vij),FijR=σ wR(rij) θij/h,F^C_{ij} = a\, w(r_{ij}), \qquad F^D_{ij} = -\gamma\, w^D(r_{ij})\, (e_{ij} \cdot v_{ij}), \qquad F^R_{ij} = \sigma\, w^R(r_{ij})\, \theta_{ij} / \sqrt{h},

where θij=θji\theta_{ij} = \theta_{ji} is a standard normal number drawn once per pair and step. The conservative force comes from the soft pair potential arc2w(r)2\frac{a r_c}{2} w(r)^2. The goal is a trajectory whose positions and velocities sample the canonical distribution ∝exp⁡(−H/kBT)\propto \exp(-H / k_B T), H=∑i∣vi∣2/2+UH = \sum_i |v_i|^2 / 2 + U, on the surface of fixed total momentum. The fluctuation-dissipation relation of Espanol and Warren (1995) gives this for the continuous-time dynamics:

wD=(wR)2,σ2=2γkBT.w^D = (w^R)^2, \qquad \sigma^2 = 2 \gamma k_B T .

The page uses wR=ww^R = w and wD=w2w^D = w^2. With σ\sigma and γ\gamma fixed, the temperature is kBT=σ2/(2γ)k_B T = \sigma^2 / (2 \gamma). The kinetic temperature of a run is ∑i∣vi∣2/Nf\sum_i |v_i|^2 / N_f with Nf=2N−2N_f = 2N - 2, because the two components of the total momentum are fixed.

The algorithm

  1. DPD-STEP(x, v, F, h, λ) ▷ F holds the forces of the last step
  2. 1x_i ← x_i + h v_i + (h²/2) F_i (mod L) for every bead i
  3. 2ṽ_i ← v_i + λ h F_i ▷ predicted velocity for the friction
  4. 3F' ← DPD-FORCES(x, ṽ)
  5. 4v_i ← v_i + (h/2) (F_i + F'_i) for every bead i
  6. 5return F'
  7. DPD-FORCES(x, v)
  8. 6for each pair i < j with r_ij < r_c, starting from F_i = 0 for all i
  9. 7w ← 1 - r_ij / r_c
  10. 8s ← a w - γ w² (e_ij · v_ij) + σ w θ_ij / √h ▷ θ_ij standard normal, one per pair
  11. 9F_i ← F_i + s e_ij, F_j ← F_j - s e_ij

Lines L1 to L5 are the modified velocity Verlet scheme of Groot and Warren (1997). The friction depends on the velocities, so the new forces need the new velocities, which in turn need the new forces. Line L2 breaks this loop with a predicted velocity; λ=1/2\lambda = 1/2 is the natural choice for Verlet integration, and Groot and Warren tuned λ\lambda as a free parameter. The noise term has the factor 1/h1 / \sqrt{h} because the impulse of a Wiener process over a step of length hh has standard deviation h\sqrt{h}, and the force is the impulse divided by hh. Line L9 adds the pair force to bead ii and subtracts it from bead jj; the random number is shared by the two beads.

Example

Two beads by hand. Put two beads on the xx axis at distance 0.50.5, closing at relative speed 11, with a=25a = 25, γ=4.5\gamma = 4.5, σ=0\sigma = 0 and rc=1r_c = 1. Then w=0.5w = 0.5 and e01⋅v01=−1e_{01} \cdot v_{01} = -1, so line L8 gives s=25⋅0.5−4.5⋅0.25⋅(−1)=12.5+1.125=13.625s = 25 \cdot 0.5 - 4.5 \cdot 0.25 \cdot (-1) = 12.5 + 1.125 = 13.625. The repulsion and the friction both push the beads apart, with force 13.62513.625 on each bead in opposite directions. At distance 11, w=0w = 0 and the force is zero.

Temperature. A fluid of N=48N = 48 beads in a box of side 44 (density 33) with a=25a = 25, γ=4.5\gamma = 4.5 and σ=3\sigma = 3 has the target kBT=9/9=1k_B T = 9 / 9 = 1; with γ=9\gamma = 9 it has kBT=1/2k_B T = 1/2. These parameters are choices of the page. The mean kinetic temperature over 4 runs of 30 time units with λ=1/2\lambda = 1/2 is 1.00421.0042 at h=0.01h = 0.01, 1.00771.0077 at h=0.02h = 0.02, 1.03371.0337 at h=0.04h = 0.04 and 1.06981.0698 at h=0.06h = 0.06, with Nf=2N−2=94N_f = 2N - 2 = 94. The noise of one run is about ±0.025\pm 0.025. So the temperature is right to within the noise at small steps, and the step size error grows quickly above h=0.02h = 0.02. These are measurements.

Energy without the thermostat. With γ=σ=0\gamma = \sigma = 0 the scheme is velocity Verlet for the soft potential. Over 3 time units, the largest error in the energy per bead is 0.05940.0594, 0.01250.0125 and 0.002470.00247 for h=0.02h = 0.02, 0.010.01 and 0.0050.005, against an energy of about 10.1310.13 per bead. Each halving of hh divides the error by about 55, which is second order or a bit better (measurement).

Correctness

The proof in the proofs file has two parts. First, the pair force of line L8 is the same scalar for (i,j)(i, j) and (j,i)(j, i), because eij⋅vije_{ij} \cdot v_{ij} and θij\theta_{ij} are symmetric, and eji=−eije_{ji} = -e_{ij}. So the forces are equal and opposite, the total force is zero, and line L4 keeps the total momentum exactly in exact arithmetic (a theorem; the tests find drift at the level of rounding, below 10−1110^{-11} over 200 steps). The conservative part is the negative gradient of U=∑i<jarc2w(rij)2U = \sum_{i < j} \frac{a r_c}{2} w(r_{ij})^2.

Second, for the stochastic differential equations of DPD, the limit h→0h \to 0 of the scheme, the Gibbs density ρ∝exp⁡(−H/kBT)\rho \propto \exp(-H / k_B T) is stationary if wD=(wR)2w^D = (w^R)^2 and σ2=2γkBT\sigma^2 = 2 \gamma k_B T. The proof applies the Fokker-Planck operator to ρ\rho: the Hamiltonian part gives zero, and the part of each pair is proportional to γwD−σ2(wR)2/(2kBT)\gamma w^D - \sigma^2 (w^R)^2 / (2 k_B T), which the relation makes zero. Stationarity does not prove ergodicity, and the scheme at finite hh samples a slightly different distribution; that error is measured above, not bounded.

Proof: DPD conserves momentum, and its fluctuation-dissipation relation makes the Gibbs distribution stationaryfull

Setup. NN beads of mass 11 with positions xix_i and velocities viv_i in a periodic box, the cutoff rcr_c, rij=∣xi−xj∣r_{ij} = |x_i - x_j| with the minimum image, eij=(xi−xj)/rije_{ij} = (x_i - x_j) / r_{ij}, vij=vi−vjv_{ij} = v_i - v_j, the weight w(r)=1−r/rcw(r) = 1 - r / r_c for r<rcr < r_c and w=0w = 0 otherwise. The pair force on bead ii from bead jj is Fij=sijeijF_{ij} = s_{ij} e_{ij} with the scalar

sij=a w(rij)−γ wD(rij)(eij⋅vij)+σ wR(rij) θij/h,s_{ij} = a\, w(r_{ij}) - \gamma\, w^D(r_{ij}) (e_{ij} \cdot v_{ij}) + \sigma\, w^R(r_{ij})\, \theta_{ij} / \sqrt{h},

where the code uses wR=ww^R = w and wD=w2w^D = w^2, and θij=θji\theta_{ij} = \theta_{ji} is one standard normal number per pair and step.

Lemma 1 (Newton's third law). Fji=−FijF_{ji} = -F_{ij} for every pair, so ∑iFi=0\sum_i F_i = 0 for the forces Fi=∑j≠iFijF_i = \sum_{j \ne i} F_{ij} of lines L6 to L9.

Proof. rji=rijr_{ji} = r_{ij}, eji=−eije_{ji} = -e_{ij} and vji=−vijv_{ji} = -v_{ij}, so eji⋅vji=eij⋅vije_{ji} \cdot v_{ji} = e_{ij} \cdot v_{ij}, and θji=θij\theta_{ji} = \theta_{ij} because the code draws one number per unordered pair. So sji=sijs_{ji} = s_{ij} and Fji=sijeji=−FijF_{ji} = s_{ij} e_{ji} = -F_{ij}. Line L9 adds FijF_{ij} to bead ii and −Fij-F_{ij} to bead jj, and the sum over all beads cancels pair by pair. □\square

Lemma 2 (momentum). In exact arithmetic, a step of lines L1 to L5 keeps the total momentum P=∑iviP = \sum_i v_i.

Proof. Line L4 changes PP by (h/2)(∑iFi+∑iFinew)(h / 2) (\sum_i F_i + \sum_i F^{\text{new}}_i). Both sums are zero by Lemma 1, for any positions and any predicted velocities. □\square

Lemma 3 (the conservative part). With U=∑i<j(arc/2) w(rij)2U = \sum_{i < j} (a r_c / 2)\, w(r_{ij})^2, the conservative part of FiF_i is −∇xiU-\nabla_{x_i} U.

Proof. ddrarc2(1−r/rc)2=−a(1−r/rc)=−a w(r)\frac{d}{dr} \frac{a r_c}{2} (1 - r / r_c)^2 = -a (1 - r / r_c) = -a\, w(r) for r<rcr < r_c, and ∇xirij=eij\nabla_{x_i} r_{ij} = e_{ij}. So −∇xi-\nabla_{x_i} of the pair term is a w(rij)eija\, w(r_{ij}) e_{ij}. The pair term and its derivative are 00 at r=rcr = r_c, so UU is continuously differentiable across the cutoff. □\square

Theorem (fluctuation-dissipation, Espanol and Warren 1995). Consider the stochastic differential equations of DPD as h→0h \to 0:

dxi=vi dt,dvi=(−∇xiU−γ∑j≠iwD(rij)(eij⋅vij)eij)dt+σ∑j≠iwR(rij) eij dWij,dx_i = v_i\, dt, \qquad dv_i = \Big( -\nabla_{x_i} U - \gamma \sum_{j \ne i} w^D(r_{ij}) (e_{ij} \cdot v_{ij}) e_{ij} \Big) dt + \sigma \sum_{j \ne i} w^R(r_{ij})\, e_{ij}\, dW_{ij},

with independent Wiener processes Wij=WjiW_{ij} = W_{ji} per pair. The noise coefficient depends on positions only and the positions carry no noise, so the Ito and Stratonovich forms agree. Let ρ=Z−1exp⁡(−βH)\rho = Z^{-1} \exp(-\beta H) with H=∑i∣vi∣2/2+UH = \sum_i |v_i|^2 / 2 + U. Then ρ\rho is a stationary solution of the Fokker-Planck equation if wD=(wR)2w^D = (w^R)^2 and σ2=2γkBT\sigma^2 = 2 \gamma k_B T. Conversely, if ρ\rho is stationary for every β\beta-independent choice of the potential and wR≠0w^R \ne 0 on (0,rc)(0, r_c), then γ wD=(βσ2/2)(wR)2\gamma\, w^D = (\beta \sigma^2 / 2) (w^R)^2.

Proof. The Fokker-Planck operator splits into the Liouville part of HH and one part per pair. The Liouville part is −{ρ,H}-\{\rho, H\}, which is zero for any function of HH. For a pair (i,j)(i, j), write Dij=eij⋅(∇vi−∇vj)D_{ij} = e_{ij} \cdot (\nabla_{v_i} - \nabla_{v_j}). The drift of the pair is −γwD(eij⋅vij)-\gamma w^D (e_{ij} \cdot v_{ij}) times the vector (eij,−eij)(e_{ij}, -e_{ij}) in the variables (vi,vj)(v_i, v_j), and the noise vector is σwR(eij,−eij)\sigma w^R (e_{ij}, -e_{ij}). Since wDw^D and wRw^R do not depend on the velocities, the pair part of the operator applied to ρ\rho is

Lijρ=Dij[γ wD(eij⋅vij) ρ+12σ2(wR)2 Dijρ].L_{ij} \rho = D_{ij} \Big[ \gamma\, w^D (e_{ij} \cdot v_{ij})\, \rho + \tfrac{1}{2} \sigma^2 (w^R)^2\, D_{ij} \rho \Big].

For the Gibbs density, ∇viρ=−βviρ\nabla_{v_i} \rho = -\beta v_i \rho, so Dijρ=−β(eij⋅vij)ρD_{ij} \rho = -\beta (e_{ij} \cdot v_{ij}) \rho, and the bracket is (eij⋅vij) ρ [γwD−βσ2(wR)2/2](e_{ij} \cdot v_{ij})\, \rho\, [\gamma w^D - \beta \sigma^2 (w^R)^2 / 2]. With wD=(wR)2w^D = (w^R)^2 and σ2=2γkBT\sigma^2 = 2 \gamma k_B T, the factor in square brackets is zero for every rr, so Lijρ=0L_{ij} \rho = 0 for every pair, and ρ\rho is stationary. Conversely, the bracket is zero for all states only if γwD(r)=(βσ2/2)(wR(r))2\gamma w^D(r) = (\beta \sigma^2 / 2) (w^R(r))^2 for every rr; if the bracket is not zero, LijρL_{ij} \rho is a function of the state that is not identically zero (take one pair in range, all others out of range), and ρ\rho is not stationary. □\square

Remarks. The theorem gives stationarity of the Gibbs distribution on each surface of fixed total momentum; it does not prove that the dynamics are ergodic or that the distribution is reached from every start. With the total momentum fixed, the kinetic temperature is kBT=∑i∣vi∣2/Nfk_B T = \sum_i |v_i|^2 / N_f with Nf=2N−2N_f = 2N - 2 in two dimensions. The scheme of lines L1 to L5 has a step size error, so the sampled temperature differs from kBTk_B T by an amount that grows with hh; this error is measured on the page, not bounded here. The code meets both conditions of the theorem: wR=ww^R = w, wD=w2w^D = w^2, and the tests choose σ2=2γkBT\sigma^2 = 2 \gamma k_B T. ■\blacksquare

Complexity

In the real RAM model, lines L6 to L9 visit all N(N−1)/2N (N - 1) / 2 pairs, so a step costs O(N2)O(N^2) and SS steps cost O(SN2)O(S N^2). With a linked cell list of cell side rcr_c, a step costs O(N)O(N) at fixed density, because each bead has a bounded number of neighbors. The memory is O(N)O(N) for positions, velocities and two force arrays. Each step needs one random number per interacting pair. The soft repulsion allows time steps much larger than in atomistic molecular dynamics, which is the main source of the speed of the method.

Properties

  • Momentum conservation. The total momentum is exact in exact arithmetic (theorem). Angular momentum is also conserved for an isolated system, because all pair forces are central; in a periodic box it is not defined.
  • Galilean invariance. The forces depend only on relative positions and relative velocities, so a uniform flow does not change the dynamics (theorem). A Langevin thermostat does not have this property.
  • Canonical sampling. The Gibbs distribution is stationary for the continuous-time dynamics under the fluctuation-dissipation relation (theorem); at finite hh the temperature has a step size error (measurement above).
  • Hydrodynamics. Momentum conservation and local interactions give flow governed at large scales by the Navier-Stokes equations, with a viscosity that depends on γ\gamma, rcr_c and the density (a known result of kinetic theory, not proved here).
  • Soft potential. The repulsion awa w is bounded, so beads can overlap and the fluid has no hard core. This gives large time steps but a fluid that is much more compressible than a real liquid.
  • Not symplectic. With friction and noise the scheme is stochastic and dissipative; without them it is velocity Verlet.

Variants and improvements

  • Splitting schemes. Shardlow (2003) splits each step into the conservative forces and the friction and noise of each pair, and solves the pair parts one after another. This removes most of the step size error in the temperature at a small extra cost.
  • Other thermostats with momentum conservation. The Lowe-Andersen scheme replaces friction and noise by pairwise velocity exchanges with a heat bath, in the spirit of the Andersen thermostat but on relative velocities.
  • Other weights. The relation only needs wD=(wR)2w^D = (w^R)^2, so other choices of wRw^R, for example a power of 1−r/rc1 - r / r_c, keep the canonical distribution and change the transport coefficients such as the viscosity.
  • Energy-conserving and many-body DPD. Variants add an internal energy per bead, so that heat flows, or let the repulsion depend on the local density, so that the fluid can have a liquid-vapor interface.
  • Coarse-grained forces from atomistic data. The conservative force can come from force matching or iterative Boltzmann inversion, and the friction and noise from the Mori-Zwanzig formalism in its Markov approximation.

When to use it

Use DPD for complex fluids where flow matters at scales of tens of nanometers to microns: polymer solutions and melts, block copolymers, membranes, vesicles and colloids. Use Brownian dynamics or Langevin dynamics when hydrodynamic interactions do not matter, because they are simpler and give the right equilibrium. Use the lattice Boltzmann method or smoothed particle hydrodynamics when the fluid is a plain continuum and thermal noise is small. Use molecular dynamics when chemical detail matters.

Pitfalls

  • The wrong dissipative weight. Writing line L8 with γw(eij⋅vij)\gamma w (e_{ij} \cdot v_{ij}), the same weight as the noise, breaks the relation wD=(wR)2w^D = (w^R)^2. With γ=4.5\gamma = 4.5 and σ=3\sigma = 3, the target kBT=1k_B T = 1 becomes a kinetic temperature of about 0.360.36 in the example fluid at h=0.02h = 0.02 (measurement, 4 runs). Use γw2(eij⋅vij)\gamma w^2 (e_{ij} \cdot v_{ij}), as in line L8.
  • The wrong noise amplitude. Choosing σ2=γkBT\sigma^2 = \gamma k_B T halves the temperature, because the stationary temperature is σ2/(2γ)\sigma^2 / (2 \gamma) (theorem). Use σ=2γkBT\sigma = \sqrt{2 \gamma k_B T}.
  • No factor 1/h1 / \sqrt{h}. Writing line L8 as σwθij\sigma w \theta_{ij} makes the noise impulse of a step hσwθh \sigma w \theta instead of hσwθ\sqrt{h} \sigma w \theta, so the temperature falls with hh and goes to zero as h→0h \to 0. Keep θij/h\theta_{ij} / \sqrt{h}.
  • Two random numbers per pair. Drawing one θ\theta for bead ii and another for bead jj in line L9 makes the random forces unequal, and the total momentum drifts like a random walk. Draw one θij\theta_{ij} per pair and step, and use it for both beads.
  • The wrong count of degrees of freedom. With zero total momentum, the kinetic temperature is ∑i∣vi∣2/(2N−2)\sum_i |v_i|^2 / (2N - 2) in two dimensions. Dividing by 2N2N reports a temperature that is low by the factor (N−1)/N(N - 1) / N.
  • Too large a step. The temperature error grows from below 1%1\% at h=0.02h = 0.02 to 7%7\% at h=0.06h = 0.06 in the example. Check the kinetic temperature against σ2/(2γ)\sigma^2 / (2 \gamma) for each new set of parameters.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dissipative_particle_dynamics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dissipative-particle-dynamics/. The authors are listed in prov/9VVD0G.jsonl.
"""Dissipative particle dynamics (Hoogerbrugge and Koelman 1992; Espanol and Warren 1995).

N beads of mass 1 in a periodic square box of side box. Each pair i, j
closer than the cutoff rc feels three forces along e_ij = r_ij / |r_ij|,
with the weight w(r) = 1 - r / rc:

    conservative  F^C = a w(r) e_ij
    dissipative   F^D = -gamma w(r)^2 (e_ij . v_ij) e_ij
    random        F^R = sigma w(r) theta_ij e_ij / sqrt(h)

with v_ij = v_i - v_j, an independent standard normal theta_ij = theta_ji
per pair and per step, and the time step h. The fluctuation-dissipation
relation of Espanol and Warren, w^D = (w^R)^2 and sigma^2 = 2 gamma kT,
makes the Gibbs distribution with the soft potential stationary for the
stochastic dynamics (h -> 0). Each pair force acts with opposite signs on
i and j, so the total momentum is conserved.

The integrator is the modified velocity Verlet scheme of Groot and Warren
(1997) with the parameter lam; lam = 1/2 is plain velocity Verlet with the
velocity-dependent forces evaluated at a predicted velocity.
"""

import math
import random
from typing import Sequence

Vec = list[float]


def _wrap(d: float, box: float) -> float:
    return d - box * round(d / box)


def dpd_forces(x: Sequence[Vec], v: Sequence[Vec], box: float, a: float, gamma: float,
               sigma: float, h: float, rng: random.Random, rc: float = 1.0) -> list[Vec]:
    """The total DPD force on each bead for positions x and velocities v."""
    n = len(x)
    f = [[0.0, 0.0] for _ in range(n)]
    noise = sigma / math.sqrt(h)
    for i in range(n):                                                    # @line L6
        for j in range(i + 1, n):
            dx = _wrap(x[i][0] - x[j][0], box)
            dy = _wrap(x[i][1] - x[j][1], box)
            r2 = dx * dx + dy * dy
            if r2 >= rc * rc:
                continue
            r = math.sqrt(r2)
            ex, ey = dx / r, dy / r
            w = 1.0 - r / rc                                              # @line L7
            theta = rng.gauss(0.0, 1.0)
            ev = ex * (v[i][0] - v[j][0]) + ey * (v[i][1] - v[j][1])
            fij = a * w - gamma * w * w * ev + noise * w * theta          # @line L8
            f[i][0] += fij * ex                                           # @line L9
            f[i][1] += fij * ey
            f[j][0] -= fij * ex
            f[j][1] -= fij * ey
    return f


def dpd_step(x: list[Vec], v: list[Vec], f: list[Vec], box: float, a: float, gamma: float,
             sigma: float, h: float, rng: random.Random, lam: float = 0.5,
             rc: float = 1.0) -> list[Vec]:
    """One modified velocity Verlet step; x and v change in place, the new forces are returned."""
    n = len(x)
    for i in range(n):
        for k in range(2):
            x[i][k] = (x[i][k] + h * v[i][k] + 0.5 * h * h * f[i][k]) % box     # @line L1
    v_pred = [[v[i][k] + lam * h * f[i][k] for k in range(2)] for i in range(n)]  # @line L2
    f_new = dpd_forces(x, v_pred, box, a, gamma, sigma, h, rng, rc)              # @line L3
    for i in range(n):
        for k in range(2):
            v[i][k] += 0.5 * h * (f[i][k] + f_new[i][k])                         # @line L4
    return f_new                                                                 # @line L5


def conservative_energy(x: Sequence[Vec], box: float, a: float, rc: float = 1.0) -> float:
    """U = sum over pairs with r < rc of (a rc / 2) (1 - r / rc)^2, whose force is F^C."""
    u = 0.0
    n = len(x)
    for i in range(n):
        for j in range(i + 1, n):
            r = math.hypot(_wrap(x[i][0] - x[j][0], box), _wrap(x[i][1] - x[j][1], box))
            if r < rc:
                u += 0.5 * a * rc * (1.0 - r / rc) ** 2
    return u


def kinetic_temperature(v: Sequence[Vec]) -> float:
    """kT = 2 K / N_f with K = sum |v|^2 / 2 and N_f = 2N - 2 (2D, total momentum fixed)."""
    return sum(p[0] * p[0] + p[1] * p[1] for p in v) / (2 * len(v) - 2)


def initial_state(n: int, box: float, kt: float, rng: random.Random) -> tuple[list[Vec], list[Vec]]:
    """Uniform random positions and Gaussian velocities with zero total momentum."""
    x = [[rng.uniform(0.0, box), rng.uniform(0.0, box)] for _ in range(n)]
    v = [[rng.gauss(0.0, math.sqrt(kt)), rng.gauss(0.0, math.sqrt(kt))] for _ in range(n)]
    for k in range(2):
        mean = sum(p[k] for p in v) / n
        for p in v:
            p[k] -= mean
    return x, v


def run(n: int, box: float, a: float, gamma: float, sigma: float, h: float, steps: int,
        seed: int, lam: float = 0.5, kt0: float = 1.0) -> tuple[list[Vec], list[Vec], list[float]]:
    """Run a DPD simulation and return the final x, v and the kinetic temperature per step."""
    rng = random.Random(seed)
    x, v = initial_state(n, box, kt0, rng)
    f = dpd_forces(x, v, box, a, gamma, sigma, h, rng)
    temps = []
    for _ in range(steps):
        f = dpd_step(x, v, f, box, a, gamma, sigma, h, rng, lam)
        temps.append(kinetic_temperature(v))
    return x, v, temps
test_dissipative_particle_dynamics.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dissipative-particle-dynamics/. The authors are listed in prov/9VVD0G.jsonl.
import math
import random

import pytest

from dissipative_particle_dynamics import (conservative_energy, dpd_forces, dpd_step, initial_state,
                                           kinetic_temperature, run)

BOX = 4.0
N = 48  # density 3 in a 4 by 4 box


def test_two_beads_by_hand():
    # Beads at distance 0.5 on the x axis, closing at speed 1: w = 1/2, e.v = -1.
    x = [[1.5, 1.0], [1.0, 1.0]]
    v = [[-0.5, 0.0], [0.5, 0.0]]
    f = dpd_forces(x, v, BOX, 25.0, 4.5, 0.0, 0.01, random.Random(0))
    # a w - gamma w^2 (e.v) = 12.5 + 4.5 / 4 = 13.625, repulsive on bead 0
    assert f[0] == pytest.approx([13.625, 0.0], abs=1e-12)
    assert f[1] == pytest.approx([-13.625, 0.0], abs=1e-12)
    far = dpd_forces([[0.0, 0.0], [1.0, 0.0]], v, BOX, 25.0, 4.5, 3.0, 0.01, random.Random(0))
    assert far == [[0.0, 0.0], [0.0, 0.0]]


def test_periodic_image_is_used():
    x = [[0.1, 2.0], [3.9, 2.0]]  # distance 0.2 through the boundary
    f = dpd_forces(x, [[0.0, 0.0], [0.0, 0.0]], BOX, 25.0, 0.0, 0.0, 0.01, random.Random(0))
    assert f[0][0] == pytest.approx(25.0 * 0.8, abs=1e-12)
    assert f[1][0] == pytest.approx(-25.0 * 0.8, abs=1e-12)


def test_conservative_force_is_minus_gradient_of_energy():
    rng = random.Random(3)
    x, v = initial_state(12, 2.0, 1.0, rng)
    f = dpd_forces(x, v, 2.0, 25.0, 0.0, 0.0, 0.01, rng)
    eps = 1e-6
    for i in range(len(x)):
        for k in range(2):
            x[i][k] += eps
            up = conservative_energy(x, 2.0, 25.0)
            x[i][k] -= 2 * eps
            down = conservative_energy(x, 2.0, 25.0)
            x[i][k] += eps
            assert -(up - down) / (2 * eps) == pytest.approx(f[i][k], rel=1e-6, abs=1e-6)


def test_total_momentum_is_conserved_to_rounding():
    rng = random.Random(5)
    x, v = initial_state(N, BOX, 1.0, rng)
    f = dpd_forces(x, v, BOX, 25.0, 4.5, 3.0, 0.04, rng)
    for _ in range(200):
        f = dpd_step(x, v, f, BOX, 25.0, 4.5, 3.0, 0.04, rng)
        for k in range(2):
            assert abs(sum(p[k] for p in v)) < 1e-11
            assert abs(sum(q[k] for q in f)) < 1e-10


def max_energy_error(h, time=3.0):
    """Largest |H(t) - H(0)| / N over a run without thermostat (gamma = sigma = 0)."""
    rng = random.Random(6)
    x, v = initial_state(N, BOX, 1.0, rng)
    f = dpd_forces(x, v, BOX, 25.0, 0.0, 0.0, h, rng)

    def energy():
        return conservative_energy(x, BOX, 25.0) + 0.5 * sum(p[0] ** 2 + p[1] ** 2 for p in v)

    e0 = energy()
    worst = 0.0
    for _ in range(round(time / h)):
        f = dpd_step(x, v, f, BOX, 25.0, 0.0, 0.0, h, rng)
        worst = max(worst, abs(energy() - e0) / N)
    return worst


def test_without_thermostat_energy_error_is_second_order():
    coarse, fine = max_energy_error(0.01), max_energy_error(0.005)
    assert coarse < 0.02
    assert coarse / fine > 3.0


def test_temperature_follows_the_fluctuation_dissipation_relation():
    # sigma^2 = 2 gamma kT: sigma = 3 with gamma = 4.5 gives kT = 1, with gamma = 9 gives kT = 1/2.
    for gamma, kt in ((4.5, 1.0), (9.0, 0.5)):
        _, v, temps = run(N, BOX, 25.0, gamma, 3.0, 0.02, 800, seed=1)
        tail = temps[160:]
        mean = sum(tail) / len(tail)
        assert abs(mean - kt) < 0.1 * kt


def test_start_far_from_equilibrium_relaxes_to_kt():
    _, _, temps = run(N, BOX, 25.0, 4.5, 3.0, 0.02, 600, seed=2, kt0=4.0)
    assert temps[0] > 2.0
    tail = temps[200:]
    assert abs(sum(tail) / len(tail) - 1.0) < 0.1


def test_kinetic_temperature_counts_two_n_minus_two_degrees():
    v = [[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]]
    assert kinetic_temperature(v) == pytest.approx(4.0 / 6.0)
    assert math.isclose(sum(p[0] for p in v), 0.0)

History

Hoogerbrugge and Koelman introduced dissipative particle dynamics in 1992 to simulate hydrodynamics of complex fluids with soft particles that exchange momentum in pairs. Espanol and Warren wrote the method in 1995 as stochastic differential equations, derived its Fokker-Planck equation and found the fluctuation-dissipation relation between the weights and the amplitudes that makes the Gibbs distribution stationary. Groot and Warren made DPD a practical tool in 1997, with a choice of the conservative force and parameters for real fluids and the modified velocity Verlet scheme. Shardlow gave splitting integrators in 2003. Espanol and Warren reviewed the method in 2017.

References

  1. P. J. Hoogerbrugge and J. M. V. A. Koelman, Simulating microscopic hydrodynamic phenomena with dissipative particle dynamics, Europhysics Letters 19(3), 1992, 155-160, the original method, with soft particles that exchange momentum in pairs
  2. P. Espanol and P. Warren, Statistical mechanics of dissipative particle dynamics, Europhysics Letters 30(4), 1995, 191-196, the stochastic differential equations of DPD, the Fokker-Planck equation and the fluctuation-dissipation relation for the weight functions and the noise amplitude
  3. Robert D. Groot and Patrick B. Warren, Dissipative particle dynamics: Bridging the gap between atomistic and mesoscopic simulation, The Journal of Chemical Physics 107(11), 1997, 4423-4435, the choice of the conservative force and the parameters for practice, and the modified velocity Verlet scheme with the parameter lambda
  4. Tony Shardlow, Splitting for dissipative particle dynamics, SIAM Journal on Scientific Computing 24(4), 2003, 1267-1282, the splitting of the dynamics into conservative steps and pairwise friction and noise steps
  5. Pep Espanol and Patrick B. Warren, Perspective: Dissipative particle dynamics, The Journal of Chemical Physics 146(15), 2017, 150901, a review of the method, its variants and its links to coarse graining

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example