| 1 |
/****************************************************************************** |
| 2 |
This source file is part of the Avogadro project. |
| 3 |
This source code is released under the 3-Clause BSD License, (see "LICENSE"). |
| 4 |
|
| 5 |
CSVR Thermostat - Canonical Sampling through Velocity Rescaling |
| 6 |
Based on: Bussi, Donadio, Parrinello, J. Chem. Phys. 126, 014101 (2007) |
| 7 |
******************************************************************************/ |
| 8 |
|
| 9 |
#ifndef AVOGADRO_QTPLUGINS_CSVRTHERMOSTAT_H |
| 10 |
#define AVOGADRO_QTPLUGINS_CSVRTHERMOSTAT_H |
| 11 |
|
| 12 |
#include <cmath> |
| 13 |
#include <random> |
| 14 |
#include <iostream> |
| 15 |
#include <Eigen/Dense> |
| 16 |
|
| 17 |
namespace Avogadro::QtPlugins { |
| 18 |
|
| 19 |
// Unit conversion constants for MD with: |
| 20 |
// - positions in Angstroms (Å) |
| 21 |
// - time in femtoseconds (fs) |
| 22 |
// - mass in atomic mass units (amu) |
| 23 |
// - energy in kJ/mol (from force field) |
| 24 |
// - temperature in Kelvin (K) |
| 25 |
// |
| 26 |
// CRITICAL: The force field returns energy in kJ/mol, meaning the energy |
| 27 |
// for one mole of the ENTIRE SYSTEM (not per atom). The gradient is thus |
| 28 |
// in kJ/(mol·Å). For dynamics, we need accelerations that produce realistic |
| 29 |
// atomic velocities. |
| 30 |
// |
| 31 |
// Physical constants: |
| 32 |
// kB = 1.380649e-23 J/K (Boltzmann constant) |
| 33 |
// NA = 6.02214076e23 /mol (Avogadro's number) |
| 34 |
// 1 amu = 1.66054e-27 kg |
| 35 |
// 1 Å = 1e-10 m |
| 36 |
// 1 fs = 1e-15 s |
| 37 |
// |
| 38 |
namespace units { |
| 39 |
// For temperature calculation from kinetic energy: |
| 40 |
// T = 2 * KE / (n_dof * kB) |
| 41 |
// where KE is in kJ/mol and we want T in K. |
| 42 |
// Using R = kB * NA = 8.314 J/(mol·K) = 8.314e-3 kJ/(mol·K) |
| 43 |
constexpr double kB = 8.314462618e-3; // kJ/(mol*K) - this is R |
| 44 |
|
| 45 |
// Force/acceleration conversion: |
| 46 |
// The gradient from the force field is in kJ/(mol·Å). |
| 47 |
// We want acceleration in Å/fs². |
| 48 |
// |
| 49 |
// From F = ma: a = F/m = [kJ/(mol·Å)] / [amu] |
| 50 |
// |
| 51 |
// 1 kJ/(mol·Å·amu) = 1000 J / (6.022e23 · 1e-10 m · 1.66054e-27 kg) |
| 52 |
// = 1000 / (1e-13) m/s² = 1e16 m/s² |
| 53 |
// In Å/fs²: 1e16 m/s² · 1e10 Å/m · (1e-15)² s²/fs² = 1e-4 Å/fs² |
| 54 |
constexpr double FORCE_CONVERSION = 1e-4; // (kJ/mol/Å)/amu to Å/fs² |
| 55 |
} // namespace units |
| 56 |
|
| 57 |
class CSVRThermostat |
| 58 |
{ |
| 59 |
private: |
| 60 |
double target_temp; // Target temperature (K) |
| 61 |
double |
| 62 |
coupling_time; // Coupling time constant - MUST BE IN SAME UNITS AS dt (fs) |
| 63 |
double dt; // Timestep (fs) |
| 64 |
unsigned int n_dof; // Number of degrees of freedom |
| 65 |
bool auto_dof; // Automatically calculate DOF from atom count |
| 66 |
bool remove_com; // Remove COM motion during velocity initialization |
| 67 |
bool enable_diagnostics; // Enable diagnostic output |
| 68 |
|
| 69 |
std::mt19937 rng; |
| 70 |
std::normal_distribution<double> normal_dist; |
| 71 |
|
| 72 |
// Generate single Gaussian random number |
| 73 |
double gaussian_random() { return normal_dist(rng); } |
| 74 |
|
| 75 |
// Generate sum of squared Gaussian random numbers (chi-squared distribution) |
| 76 |
// For n degrees of freedom |
| 77 |
double sum_noises_squared(int n) |
| 78 |
{ |
| 79 |
if (n <= 0) |
| 80 |
return 0.0; |
| 81 |
// didn't realize there was a chi-squared distribution |
| 82 |
std::chi_squared_distribution<double> chi2(n); |
| 83 |
return chi2(rng); |
| 84 |
} |
| 85 |
|
| 86 |
public: |
| 87 |
CSVRThermostat(double T_target = 300.0, double timestep = 1.0, |
| 88 |
double tau = 100.0, int ndof = 3, unsigned seed = 12345) |
| 89 |
: target_temp(T_target), coupling_time(tau), dt(timestep), n_dof(ndof), |
| 90 |
auto_dof(true), remove_com(true), enable_diagnostics(false), rng(seed), |
| 91 |
normal_dist(0.0, 1.0) |
| 92 |
{ |
| 93 |
// IMPORTANT: Default coupling_time is now 100 fs (0.1 ps) |
| 94 |
// Previously was 10, which if interpreted as ps would be 10000 fs |
| 95 |
// Ensure coupling_time and dt are in the same units! |
| 96 |
} |
| 97 |
|
| 98 |
// Setters |
| 99 |
void setTargetTemperature(double T_target) { target_temp = T_target; } |
| 100 |
|
| 101 |
// IMPORTANT: tau must be in the same units as dt (femtoseconds) |
| 102 |
// Typical values: 100-1000 fs (0.1-1.0 ps) |
| 103 |
void setCouplingTime(double tau) { coupling_time = tau; } |
| 104 |
|
| 105 |
void setTimeStep(double timestep) { dt = timestep; } |
| 106 |
|
| 107 |
// Set number of degrees of freedom manually |
| 108 |
// For N atoms: 3N (periodic), 3N-3 (non-periodic, COM removed), |
| 109 |
// 3N-6 (non-periodic, COM and rotation removed) |
| 110 |
void setDegreesOfFreedom(int ndof) |
| 111 |
{ |
| 112 |
n_dof = ndof; |
| 113 |
auto_dof = false; // Disable automatic calculation |
| 114 |
} |
| 115 |
|
| 116 |
// Enable/disable automatic DOF calculation (default: enabled) |
| 117 |
// When enabled, DOF = 3*N_atoms - 3 (assumes COM motion removed) |
| 118 |
void setAutoDOF(bool enable) { auto_dof = enable; } |
| 119 |
|
| 120 |
// Enable/disable COM removal during velocity initialization |
| 121 |
void setRemoveCOM(bool enable) { remove_com = enable; } |
| 122 |
|
| 123 |
// Enable/disable diagnostic output |
| 124 |
void setDiagnostics(bool enable) { enable_diagnostics = enable; } |
| 125 |
|
| 126 |
// Getters for diagnostics |
| 127 |
double getTargetTemperature() const { return target_temp; } |
| 128 |
double getCouplingTime() const { return coupling_time; } |
| 129 |
double getTimeStep() const { return dt; } |
| 130 |
int getDegreesOfFreedom() const { return n_dof; } |
| 131 |
|
| 132 |
// Calculate current kinetic energy in Joules (SI) |
| 133 |
// This returns the kinetic energy for the entire system, not per mole. |
| 134 |
double compute_kinetic_energy(const Eigen::VectorXd& velocities, |
| 135 |
const Eigen::VectorXd& masses) |
| 136 |
{ |
| 137 |
constexpr double Apfs_to_mps = 1e5; // (m/s) / (Å/fs) |
| 138 |
constexpr double amu_to_kg = 1.66054e-27; // kg/amu |
| 139 |
|
| 140 |
double ke = 0.0; |
| 141 |
int n_atoms = masses.size() / 3; |
| 142 |
|
| 143 |
for (int i = 0; i < n_atoms; ++i) { |
| 144 |
Eigen::Vector3d v = velocities.segment<3>(3 * i); |
| 145 |
double v_mps_sq = v.squaredNorm() * Apfs_to_mps * Apfs_to_mps; |
| 146 |
double m_kg = masses[3 * i] * amu_to_kg; |
| 147 |
ke += 0.5 * m_kg * v_mps_sq; |
| 148 |
} |
| 149 |
return ke; // in Joules |
| 150 |
} |
| 151 |
|
| 152 |
// Calculate current temperature from kinetic energy |
| 153 |
double compute_temperature(const Eigen::VectorXd& velocities, |
| 154 |
const Eigen::VectorXd& masses) |
| 155 |
{ |
| 156 |
if (n_dof < 1) |
| 157 |
return 0.0; |
| 158 |
|
| 159 |
constexpr double kB_SI = 1.380649e-23; // J/K |
| 160 |
double ke = compute_kinetic_energy(velocities, masses); |
| 161 |
// T = 2 * KE / (n_dof * kB) |
| 162 |
return 2.0 * ke / (n_dof * kB_SI); |
| 163 |
} |
| 164 |
|
| 165 |
// Apply CSVR (Canonical Sampling through Velocity Rescaling) thermostat |
| 166 |
// Based on Bussi, Donadio, Parrinello, J. Chem. Phys. 126, 014101 (2007) |
| 167 |
// |
| 168 |
// This thermostat correctly samples the canonical ensemble by adding |
| 169 |
// stochastic terms to the velocity rescaling. Unlike Berendsen, it |
| 170 |
// produces correct fluctuations in kinetic energy. |
| 171 |
// |
| 172 |
// The algorithm implements Eq. (A7) from the paper: |
| 173 |
// K_new = K_old * c + K_target * (1-c) * (sum_i R_i^2) / n_dof |
| 174 |
// + 2 * sqrt(K_old * K_target * c * (1-c) / n_dof) * R_1 |
| 175 |
// |
| 176 |
// where c = exp(-dt/tau), R_i are independent Gaussian random numbers, |
| 177 |
// and the sum is over n_dof terms. |
| 178 |
void apply(Eigen::VectorXd& velocities, const Eigen::VectorXd& masses) |
| 179 |
{ |
| 180 |
constexpr double kB_SI = 1.380649e-23; // J/K |
| 181 |
|
| 182 |
// Update DOF if automatic mode is enabled |
| 183 |
if (auto_dof) { |
| 184 |
int n_atoms = masses.size() / 3; |
| 185 |
n_dof = 3 * n_atoms - 3; // Remove 3 DOF for COM translation |
| 186 |
if (n_dof < 1) |
| 187 |
n_dof = 1; |
| 188 |
} |
| 189 |
|
| 190 |
// Current kinetic energy in Joules |
| 191 |
double ke_current = compute_kinetic_energy(velocities, masses); |
| 192 |
|
| 193 |
if (ke_current < 1e-30) { |
| 194 |
if (enable_diagnostics) { |
| 195 |
std::cerr |
| 196 |
<< "CSVR Warning: Near-zero kinetic energy, skipping thermostat\n"; |
| 197 |
} |
| 198 |
return; |
| 199 |
} |
| 200 |
|
| 201 |
// Target kinetic energy from equipartition: KE = (n_dof/2) * kB * T |
| 202 |
double ke_target = 0.5 * n_dof * kB_SI * target_temp; |
| 203 |
|
| 204 |
// Exponential decay factor |
| 205 |
// CRITICAL: dt and coupling_time MUST be in the same units (both in fs) |
| 206 |
double c = std::exp(-dt / coupling_time); |
| 207 |
|
| 208 |
// Sanity check on c value |
| 209 |
if (c < 0.5 && enable_diagnostics) { |
| 210 |
std::cerr << "CSVR Warning: c=" << c << " is very small. " |
| 211 |
<< "Check that dt (" << dt << ") and coupling_time (" |
| 212 |
<< coupling_time << ") are in the same units (fs).\n"; |
| 213 |
} |
| 214 |
|
| 215 |
// CSVR formula from Bussi et al. Eq. (A7) |
| 216 |
// |
| 217 |
// K_new = c * K + (1-c) * K_target / Nf * (R1² + sum_{i=2}^{Nf} Ri²) |
| 218 |
// + 2 * sqrt(c * (1-c) * K * K_target / Nf) * R1 |
| 219 |
// |
| 220 |
// where R1 is the SAME Gaussian in both the linear and quadratic terms. |
| 221 |
// This is a non-central chi-squared variate and is always non-negative. |
| 222 |
// |
| 223 |
// CRITICAL: The previous implementation replaced R1² with E[R1²] = 1 |
| 224 |
// ("centering"), which broke the non-central chi-squared structure, |
| 225 |
// destroyed the R1/R1² correlation, and made ke_new occasionally negative. |
| 226 |
|
| 227 |
double R1 = gaussian_random(); |
| 228 |
|
| 229 |
// Sum of (n_dof - 1) independent squared Gaussians (for i = 2..Nf) |
| 230 |
double sum_Rsq_rest = sum_noises_squared(n_dof - 1); |
| 231 |
|
| 232 |
// Full chi-squared sum includes R1² from the same draw |
| 233 |
double chi_sq_sum = R1 * R1 + sum_Rsq_rest; |
| 234 |
|
| 235 |
// Compute new kinetic energy using correct CSVR formula (Eq. A7) |
| 236 |
double ke_new = |
| 237 |
c * ke_current + (1.0 - c) * ke_target / n_dof * chi_sq_sum + |
| 238 |
2.0 * std::sqrt(c * (1.0 - c) * ke_current * ke_target / n_dof) * R1; |
| 239 |
|
| 240 |
// Safety net: The correct CSVR formula is a non-central chi-squared |
| 241 |
// variate and should always be non-negative. This guard should essentially |
| 242 |
// never fire, but we keep it for numerical safety (e.g., extreme |
| 243 |
// floating-point edge cases). |
| 244 |
if (ke_new < 0.0) { |
| 245 |
ke_new = ke_target * 0.01; |
| 246 |
if (enable_diagnostics) { |
| 247 |
std::cerr |
| 248 |
<< "CSVR Warning: Negative KE computed (should be very rare " |
| 249 |
"with correct formula), clamping to small positive value\n"; |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
// Compute scaling factor |
| 254 |
double alpha = std::sqrt(ke_new / ke_current); |
| 255 |
|
| 256 |
// Rescale all velocities |
| 257 |
velocities *= alpha; |
| 258 |
|
| 259 |
// Diagnostic output |
| 260 |
if (enable_diagnostics) { |
| 261 |
double T_before = 2.0 * ke_current / (n_dof * kB_SI); |
| 262 |
double T_after = 2.0 * ke_new / (n_dof * kB_SI); |
| 263 |
std::cerr << "CSVR: T_before=" << T_before << " T_after=" << T_after |
| 264 |
<< " T_target=" << target_temp << " alpha=" << alpha |
| 265 |
<< " c=" << c << " n_dof=" << n_dof << "\n"; |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
// Initialize velocities to Maxwell-Boltzmann distribution at target |
| 270 |
// temperature velocities: 3N vector to be filled [vx0, vy0, vz0, vx1, vy1, |
| 271 |
// vz1, ...] masses: 3N vector [m0, m0, m0, m1, m1, m1, ...] |
| 272 |
void initializeVelocities(Eigen::VectorXd& velocities, |
| 273 |
const Eigen::VectorXd& masses) |
| 274 |
{ |
| 275 |
int n_atoms = masses.size() / 3; |
| 276 |
|
| 277 |
// Update DOF if automatic mode is enabled |
| 278 |
if (auto_dof) { |
| 279 |
n_dof = 3 * n_atoms - 3; |
| 280 |
if (n_dof < 1) |
| 281 |
n_dof = 1; |
| 282 |
} |
| 283 |
|
| 284 |
constexpr double kB_SI = 1.380649e-23; // J/K |
| 285 |
constexpr double amu_to_kg = 1.66054e-27; // kg/amu |
| 286 |
constexpr double mps_to_Apfs = 1e-5; // (Å/fs) / (m/s) |
| 287 |
|
| 288 |
// Generate Maxwell-Boltzmann distributed velocities |
| 289 |
for (int i = 0; i < n_atoms; ++i) { |
| 290 |
double mass_kg = masses[3 * i] * amu_to_kg; |
| 291 |
double sigma_mps = std::sqrt(kB_SI * target_temp / mass_kg); |
| 292 |
double sigma = sigma_mps * mps_to_Apfs; |
| 293 |
|
| 294 |
velocities[3 * i] = sigma * gaussian_random(); |
| 295 |
velocities[3 * i + 1] = sigma * gaussian_random(); |
| 296 |
velocities[3 * i + 2] = sigma * gaussian_random(); |
| 297 |
} |
| 298 |
|
| 299 |
// Remove center of mass motion if enabled |
| 300 |
if (remove_com) { |
| 301 |
Eigen::Vector3d total_momentum = Eigen::Vector3d::Zero(); |
| 302 |
double total_mass = 0.0; |
| 303 |
|
| 304 |
for (int i = 0; i < n_atoms; ++i) { |
| 305 |
double mass = masses[3 * i]; |
| 306 |
total_momentum += mass * velocities.segment<3>(3 * i); |
| 307 |
total_mass += mass; |
| 308 |
} |
| 309 |
|
| 310 |
Eigen::Vector3d com_velocity = total_momentum / total_mass; |
| 311 |
|
| 312 |
for (int i = 0; i < n_atoms; ++i) { |
| 313 |
velocities.segment<3>(3 * i) -= com_velocity; |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
// Rescale to exact target temperature |
| 318 |
double current_temp = compute_temperature(velocities, masses); |
| 319 |
if (current_temp > 0.0) { |
| 320 |
double scale = std::sqrt(target_temp / current_temp); |
| 321 |
velocities *= scale; |
| 322 |
} |
| 323 |
|
| 324 |
if (enable_diagnostics) { |
| 325 |
double final_temp = compute_temperature(velocities, masses); |
| 326 |
std::cerr << "CSVR: Initialized velocities at T=" << final_temp |
| 327 |
<< "K (target=" << target_temp << "K)\n"; |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
// Reseed the random number generator |
| 332 |
void reseed(unsigned seed) { rng.seed(seed); } |
| 333 |
}; |
| 334 |
|
| 335 |
} // namespace Avogadro::QtPlugins |
| 336 |
|
| 337 |
#endif |