Loading...
Searching...
No Matches
Hessian.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/Hessian.h"
13#include "eon/AtomicFile.h"
14#include "eon/CutoffNeighbors.h"
15#include "eon/EonLogger.h"
16#include "eon/HelperFunctions.h"
17#include "eon/PotentialOwner.h"
18#include "eon/SafeMath.h"
19#include "eon/Tunneling.h"
20#include "eon/VesinNeighbors.h"
21
22#include <algorithm>
23#include <cmath>
24#include <fstream>
25#include <iomanip>
26#include <limits>
27#include <locale>
28#include <sstream>
29#include <stdexcept>
30#include <string>
31#include <vector>
32
33namespace eonc {
34
35namespace {
36
37// phva_atoms entries are *mobile / displaced* atoms for FD (hybrid/PHVA-class
38// active set). Intersect with non-fixed atoms in HessianJob.
39
40// Checkpoint: first line "eon_hess_ckpt <size> <next_col>", then size*size
41// doubles in row-major order matching MatrixXd storage.
42bool loadColumnCheckpoint(const std::string &path, int size, int &nextCol,
43 MatrixXd &H, const std::string &context) {
44 eonc::log::Scoped log;
45 std::ifstream in(path);
46 if (!in) {
47 return false;
48 }
49 std::string tag;
50 int fileSize = 0;
51 in >> tag >> fileSize >> nextCol;
52 if (!in || tag != "eon_hess_ckpt" || fileSize != size || nextCol < 0 ||
53 nextCol > size) {
54 return false;
55 }
56 H.resize(size, size);
57 for (int i = 0; i < size; ++i) {
58 for (int j = 0; j < size; ++j) {
59 double v = 0.0;
60 in >> v;
61 if (!in) {
62 return false;
63 }
64 H(i, j) = v;
65 }
66 }
67 std::string marker;
68 if (!(in >> marker)) {
69 QUILL_LOG_WARNING(log, "[Hessian] legacy checkpoint has no geometry or "
70 "displacement identity; resume is unverified");
71 return true;
72 }
73 std::string stored;
74 if (marker != "eon_hess_context_v1" || !(in >> std::quoted(stored)) ||
75 stored != context) {
76 QUILL_LOG_WARNING(log, "[Hessian] checkpoint context mismatch; "
77 "recomputing all finite-difference columns");
78 return false;
79 }
80 return true;
81}
82
83// The context binds completed columns to their geometry and FD recipe.
84// External potential files require independent provenance checks.
85std::string columnCheckpointContext(const Matter &matter, const VectorXi &atoms,
86 double dr, FdScheme scheme,
87 const Parameters &parameters) {
88 std::ostringstream out;
89 out.imbue(std::locale::classic());
90 out << std::setprecision(std::numeric_limits<double>::max_digits10);
91 out << dr << ' ' << static_cast<int>(scheme) << ' '
92 << parameters.main_options().removeNetForce << ' '
93 << static_cast<int>(parameters.potential_options().potential) << ' '
94 << matter.getPeriodic() << ' ' << matter.numberOfAtoms();
95 const auto positions = matter.getPositions();
96 const auto numbers = matter.getAtomicNrs();
97 for (int i = 0; i < matter.numberOfAtoms(); ++i) {
98 out << ' ' << numbers(i) << ' ' << matter.getMass(i);
99 for (int j = 0; j < 3; ++j) {
100 out << ' ' << positions(i, j) << ' ' << matter.getFixed(i, j);
101 }
102 }
103 const auto cell = matter.getCell();
104 for (int i = 0; i < 3; ++i) {
105 for (int j = 0; j < 3; ++j) {
106 out << ' ' << cell(i, j);
107 }
108 }
109 out << ' ' << atoms.size();
110 for (int i = 0; i < atoms.size(); ++i) {
111 out << ' ' << atoms(i);
112 }
113 return out.str();
114}
115
116bool saveColumnCheckpoint(const std::string &path, int size, int nextCol,
117 const MatrixXd &H, const std::string &context) {
118 return helpers::atomicWriteFile(path, [&](FILE *out) {
119 if (std::fprintf(out, "eon_hess_ckpt %d %d\n", size, nextCol) < 0) {
120 return false;
121 }
122 for (int i = 0; i < size; ++i) {
123 for (int j = 0; j < size; ++j) {
124 if (std::fprintf(out, "%.*g%c",
125 std::numeric_limits<double>::max_digits10, H(i, j),
126 j + 1 == size ? '\n' : ' ') < 0) {
127 return false;
128 }
129 }
130 }
131 std::ostringstream footer;
132 footer << "eon_hess_context_v1 " << std::quoted(context) << '\n';
133 return std::fputs(footer.str().c_str(), out) >= 0;
134 });
135}
136
137} // namespace
138
140 : matter{matter},
141 parameters{params} {
142 hessian.resize(0, 0);
143 freqs.resize(0);
144}
145
146MatrixXd Hessian::getHessian(Matter *matterIn, const VectorXi &atomsIn) {
147 if ((matter != matterIn) || (atoms.size() != atomsIn.size()) ||
148 (atoms != atomsIn) || (hessian.rows() == 0)) {
149 hessian.resize(0, 0);
150 matter = matterIn;
151 atoms = atomsIn;
152
153 if (!calculate()) {
154 hessian.resize(0, 0);
155 }
156 }
157 return hessian;
158}
159
160VectorXd Hessian::getFreqs(Matter *matterIn, const VectorXi &atomsIn) {
161 if ((matter != matterIn) || (atoms.size() != atomsIn.size()) ||
162 (atoms != atomsIn) || (hessian.rows() == 0)) {
163 hessian.resize(0, 0);
164 matter = matterIn;
165 atoms = atomsIn;
166
167 if (!calculate()) {
168 freqs.resize(0);
169 hessian.resize(0, 0);
170 }
171 }
172 return freqs;
173}
174
175namespace {
176
177struct MobileColoring {
178 std::vector<int> color;
179 // closed[ia] = local mobile indices in the closed cutoff neighborhood of ia
180 std::vector<std::vector<int>> closed;
181};
182
183MobileColoring buildMobileColoring(const Matter &matter, const VectorXi &atoms,
184 double cutoff) {
185 MobileColoring out;
186 const int nAtoms = static_cast<int>(matter.numberOfAtoms());
187 const int nMobile = static_cast<int>(atoms.rows());
188 if (nAtoms <= 0 || nMobile <= 0 || !(cutoff > 0.0) ||
189 !std::isfinite(cutoff)) {
190 return out;
191 }
192 const Matrix3d cell = matter.getCell();
193 if (!(std::abs(cell.determinant()) > 1e-18)) {
194 return out;
195 }
196 for (int a = 0; a < nMobile; ++a) {
197 const long idx = atoms(a);
198 if (idx < 0 || idx >= nAtoms) {
199 return {};
200 }
201 }
202
203 const AtomMatrix &pos = matter.getPositions();
204 std::vector<std::vector<int>> nbs(static_cast<std::size_t>(nAtoms));
205 auto add = [&](int i, int j) {
206 if (i != j && i >= 0 && j >= 0 && i < nAtoms && j < nAtoms)
207 nbs[static_cast<std::size_t>(i)].push_back(j);
208 };
209 try {
210 if (matter.getPeriodic()) {
211 for (const auto &pair :
212 periodicCutoffNeighbors(pos.data(), static_cast<std::size_t>(nAtoms),
213 cell.data(), cutoff))
214 add(pair.first, pair.second);
215 } else {
218 opt.cutoff = cutoff;
219 opt.full = true;
220 opt.return_distances = false;
221 opt.return_vectors = false;
222 opt.periodic = {false, false, false};
223 nl.compute(pos.data(), static_cast<std::size_t>(nAtoms), cell.data(),
224 opt);
225 for (size_t p = 0; p < nl.size(); ++p)
226 add(static_cast<int>(nl.i(p)), static_cast<int>(nl.j(p)));
227 }
228 } catch (const std::exception &) {
229 return {};
230 }
231 for (auto &row : nbs) {
232 std::sort(row.begin(), row.end());
233 row.erase(std::unique(row.begin(), row.end()), row.end());
234 }
235
236 std::vector<int> local(static_cast<std::size_t>(nAtoms), -1);
237 for (int a = 0; a < nMobile; ++a) {
238 local[static_cast<std::size_t>(atoms(a))] = a;
239 }
240
241 out.closed.assign(static_cast<std::size_t>(nMobile), {});
242 for (int ia = 0; ia < nMobile; ++ia) {
243 auto &nbhd = out.closed[static_cast<std::size_t>(ia)];
244 nbhd.push_back(ia);
245 const int g = static_cast<int>(atoms(ia));
246 for (int nb : nbs[static_cast<std::size_t>(g)]) {
247 const int lb = local[static_cast<std::size_t>(nb)];
248 if (lb >= 0) {
249 nbhd.push_back(lb);
250 }
251 }
252 std::sort(nbhd.begin(), nbhd.end());
253 nbhd.erase(std::unique(nbhd.begin(), nbhd.end()), nbhd.end());
254 }
255
256 // Square of the cutoff graph on the mobile set: atoms whose closed
257 // neighborhoods intersect cannot move in the same finite-difference.
258 // Each adjacency row is deduplicated as it is filled. Pushing every
259 // toucher pair and sorting afterwards stores O(sum t_k^2) integers,
260 // which is the whole cell at a many-body range.
261 std::vector<std::vector<int>> touchers(static_cast<std::size_t>(nMobile));
262 for (int ia = 0; ia < nMobile; ++ia) {
263 for (int k : out.closed[static_cast<std::size_t>(ia)]) {
264 touchers[static_cast<std::size_t>(k)].push_back(ia);
265 }
266 }
267 std::vector<std::vector<int>> adj(static_cast<std::size_t>(nMobile));
268 std::vector<int> seen(static_cast<std::size_t>(nMobile), 0);
269 int epoch = 0;
270 for (int ia = 0; ia < nMobile; ++ia) {
271 ++epoch;
272 auto &row = adj[static_cast<std::size_t>(ia)];
273 for (int k : out.closed[static_cast<std::size_t>(ia)]) {
274 for (int j : touchers[static_cast<std::size_t>(k)]) {
275 if (j == ia) {
276 continue;
277 }
278 if (seen[static_cast<std::size_t>(j)] == epoch) {
279 continue;
280 }
281 seen[static_cast<std::size_t>(j)] = epoch;
282 row.push_back(j);
283 }
284 }
285 }
286 out.color = greedyColorCutoffGraph(adj);
287 return out;
288}
289
290void writeMassWeighted(MatrixXd &hessian, const Matter &matter,
291 const VectorXi &atoms, int col, int atomI,
292 const AtomMatrix &forceA, const AtomMatrix &forceB,
293 double denom, const std::vector<int> &owner, int ia) {
294 const int size = static_cast<int>(atoms.rows()) * 3;
295 const double massI = matter.getMass(atomI);
296 for (int j = 0; j < size; ++j) {
297 const long atomJ = atoms(j / 3);
298 double dF = 0.0;
299 if (owner[static_cast<std::size_t>(j / 3)] == ia) {
300 dF = forceA(atomJ, j % 3) - forceB(atomJ, j % 3);
301 }
302 hessian(col, j) = -dF / denom;
303 const double effMass = std::sqrt(matter.getMass(atomJ) * massI);
304 hessian(col, j) = eonc::safemath::safe_div(hessian(col, j), effMass, 0.0);
305 }
306}
307
308} // namespace
309
310std::vector<int>
311greedyColorCutoffGraph(const std::vector<std::vector<int>> &adj) {
312 const int n = static_cast<int>(adj.size());
313 std::vector<int> color(static_cast<std::size_t>(n), -1);
314 std::vector<int> used(static_cast<std::size_t>(std::max(n, 0)), 0);
315 int epoch = 0;
316 for (int v = 0; v < n; ++v) {
317 ++epoch;
318 for (int u : adj[static_cast<std::size_t>(v)]) {
319 if (u < 0 || u >= n || u == v) {
320 continue;
321 }
322 const int cu = color[static_cast<std::size_t>(u)];
323 if (cu >= 0 && cu < n) {
324 used[static_cast<std::size_t>(cu)] = epoch;
325 }
326 }
327 int c = 0;
328 while (c < n && used[static_cast<std::size_t>(c)] == epoch) {
329 ++c;
330 }
331 color[static_cast<std::size_t>(v)] = c;
332 }
333 return color;
334}
335
336std::vector<int> colorMobileCutoffGraph(const Matter &matter,
337 const VectorXi &atoms, double cutoff) {
338 return buildMobileColoring(matter, atoms, cutoff).color;
339}
340
342 int nAtoms = matter->numberOfAtoms();
343
344 int size = static_cast<int>(atoms.rows()) * 3;
345 QUILL_LOG_DEBUG(log, "[Hessian] Hessian size: {}\n", size);
346 if (size == 0) {
347 return false;
348 }
349
350 // Mobile-atom polarity: indices in `atoms` are FD-displaced DOF owners.
351 for (int a = 0; a < atoms.rows(); ++a) {
352 const long idx = atoms(a);
353 if (idx < 0 || idx >= nAtoms) {
354 QUILL_LOG_ERROR(log,
355 "[Hessian] atom index {} out of range [0, {}) at list "
356 "entry {}; aborting FD Hessian",
357 idx, nAtoms, a);
358 return false;
359 }
360 }
361
362 double dr = parameters.main_options().finiteDifference;
363 if (!(dr > 0.0) || !std::isfinite(dr)) {
364 QUILL_LOG_ERROR(log, "[Hessian] invalid finiteDifference dr={}\n", dr);
365 return false;
366 }
367
368 const FdScheme scheme = parseFdScheme(parameters.hessian_options().fd_scheme);
369 const std::string &ckptPath = parameters.hessian_options().checkpoint_path;
370
371 hessian.resize(size, size);
372 hessian.setZero();
373
374 // Net-force removal adds the same shift to every atom, so columns are
375 // no longer confined to the cutoff neighborhood. A column checkpoint is
376 // also stored one coordinate at a time.
377 bool anyFixed = false;
378 for (int i = 0; i < nAtoms; ++i) {
379 if (matter->getFixed(i)) {
380 anyFixed = true;
381 break;
382 }
383 }
384 const bool netCoupled =
385 parameters.main_options().removeNetForce && nAtoms > 1 && !anyFixed;
386 // hessianRange is the distance past which every block is exactly
387 // zero. An interaction cutoff is not that distance.
388 double range = 0.0;
389 if (matter->getPotential()) {
390 range = matter->getPotential()->hessianRange();
391 }
392 if (!netCoupled && ckptPath.empty() && range > 0.0 && std::isfinite(range)) {
393 if (calculateColored(range, dr, scheme)) {
394 return true;
395 }
396 hessian.setZero();
397 }
398 // A potential that evaluates batches (calculator groups, GPU models)
399 // takes the displaced structures together; the column checkpoint stays
400 // on the one-column-at-a-time path.
401 if (ckptPath.empty() && matter->getPotential() &&
402 matter->getPotential()->supportsBatchEvaluation() && size > 1) {
403 return calculateBatched(dr, scheme);
404 }
405 return calculateSerial(dr, scheme);
406}
407
408bool Hessian::calculateBatched(double dr, FdScheme scheme) {
409 const int size = static_cast<int>(atoms.rows()) * 3;
410 const AtomMatrix pos = matter->getPositions();
411 auto pot = matter->getPotential();
412
413 Matter base(*matter);
414 const AtomMatrix force0 = base.getForces();
415 if (!force0.allFinite()) {
416 QUILL_LOG_ERROR(log, "[Hessian] non-finite forces at undisplaced geometry; "
417 "aborting FD Hessian");
418 return false;
419 }
420
421 // Stencil points per column, in the order fdForceDerivative takes them.
422 std::vector<double> steps{1.0};
423 if (scheme != FdScheme::OneSided) {
424 steps.push_back(-1.0);
425 }
426 if (scheme == FdScheme::Fourth) {
427 steps.push_back(2.0);
428 steps.push_back(-2.0);
429 }
430 const int perColumn = static_cast<int>(steps.size());
431 const long nAtoms = matter->numberOfAtoms();
432 const VectorXi nrs = matter->getAtomicNrs();
433 const Matrix3d box =
434 matter->getPeriodic() ? matter->getCell() : Matrix3d::Zero().eval();
435
436 // Columns in chunks, so memory stays bounded for large mobile sets.
437 constexpr int kChunkColumns = 32;
438 std::vector<Matter> displaced;
439 for (int c0 = 0; c0 < size; c0 += kChunkColumns) {
440 const int c1 = std::min(size, c0 + kChunkColumns);
441 const long n = static_cast<long>(c1 - c0) * perColumn;
442 displaced.assign(static_cast<size_t>(n), base);
443 std::vector<const double *> posPtr, boxPtr;
444 std::vector<const int *> nrsPtr;
445 std::vector<double *> frcPtr;
446 for (int i = c0; i < c1; ++i) {
447 for (int k = 0; k < perColumn; ++k) {
448 Matter &m = displaced[static_cast<size_t>((i - c0) * perColumn + k)];
449 AtomMatrix p = pos;
450 p(atoms(i / 3), i % 3) += steps[static_cast<size_t>(k)] * dr;
451 m.setPositions(p);
452 }
453 }
454 for (auto &m : displaced) {
455 posPtr.push_back(m.getPositions().data());
456 nrsPtr.push_back(nrs.data());
457 frcPtr.push_back(m.forcesData());
458 boxPtr.push_back(box.data());
459 }
460 std::vector<double> energies(static_cast<size_t>(n)),
461 variances(static_cast<size_t>(n));
462 const std::vector<long> owners(static_cast<size_t>(n),
464 pot->forceBatchOwned(n, nAtoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
465 energies.data(), variances.data(), boxPtr.data(),
466 owners.data());
467 for (long j = 0; j < n; ++j) {
468 displaced[static_cast<size_t>(j)].setComputedPotential(
469 energies[static_cast<size_t>(j)], variances[static_cast<size_t>(j)]);
470 }
471 for (int i = c0; i < c1; ++i) {
472 auto forces = [&](int k) -> const AtomMatrix & {
473 return displaced[static_cast<size_t>((i - c0) * perColumn + k)]
474 .getForces();
475 };
476 const AtomMatrix &fPlus = forces(0);
477 const AtomMatrix &fMinus = perColumn > 1 ? forces(1) : force0;
478 const AtomMatrix &fPlus2 = perColumn > 2 ? forces(2) : force0;
479 const AtomMatrix &fMinus2 = perColumn > 3 ? forces(3) : force0;
480 if (!fPlus.allFinite() || !fMinus.allFinite() || !fPlus2.allFinite() ||
481 !fMinus2.allFinite()) {
482 QUILL_LOG_ERROR(log,
483 "[Hessian] non-finite forces for FD column {}; "
484 "aborting FD Hessian",
485 i);
486 return false;
487 }
488 const AtomMatrix slope =
489 fdForceDerivative(scheme, dr, force0, fPlus, fMinus, fPlus2, fMinus2);
490 for (int j = 0; j < size; j++) {
491 const double effMass = std::sqrt(matter->getMass(atoms(j / 3)) *
492 matter->getMass(atoms(i / 3)));
493 hessian(i, j) =
494 eonc::safemath::safe_div(-slope(atoms(j / 3), j % 3), effMass, 0.0);
495 }
496 }
497 }
498 return finalizeHessian(size);
499}
500
501bool Hessian::calculateColored(double range, double dr, FdScheme scheme) {
502 const int nAtoms = static_cast<int>(matter->numberOfAtoms());
503 const int nMobile = static_cast<int>(atoms.rows());
504 const int size = nMobile * 3;
505 const MobileColoring coloring = buildMobileColoring(*matter, atoms, range);
506 if (static_cast<int>(coloring.color.size()) != nMobile ||
507 static_cast<int>(coloring.closed.size()) != nMobile) {
508 return false;
509 }
510
511 int nColors = 0;
512 for (int c : coloring.color) {
513 if (c < 0) {
514 return false;
515 }
516 nColors = std::max(nColors, c + 1);
517 }
518 if (nColors <= 0) {
519 return false;
520 }
521 // One color per mobile atom does not reduce the force count, and this
522 // loop does not batch. Leave the matrix to the column path.
523 if (nColors >= nMobile) {
524 return false;
525 }
526 QUILL_LOG_DEBUG(log,
527 "[Hessian] hessian-range coloring: {} colors for {} mobile "
528 "atoms\n",
529 nColors, nMobile);
530
531 std::vector<std::vector<int>> members(static_cast<std::size_t>(nColors));
532 for (int ia = 0; ia < nMobile; ++ia) {
533 members[static_cast<std::size_t>(
534 coloring.color[static_cast<std::size_t>(ia)])]
535 .push_back(ia);
536 }
537 std::vector<std::vector<int>> owner(
538 static_cast<std::size_t>(nColors),
539 std::vector<int>(static_cast<std::size_t>(nMobile), -1));
540 for (int c = 0; c < nColors; ++c) {
541 for (int ia : members[static_cast<std::size_t>(c)]) {
542 for (int k : coloring.closed[static_cast<std::size_t>(ia)]) {
543 int &slot =
544 owner[static_cast<std::size_t>(c)][static_cast<std::size_t>(k)];
545 if (slot >= 0 && slot != ia) {
546 return false;
547 }
548 slot = ia;
549 }
550 }
551 }
552
553 Matter matterTemp(*matter);
554 const AtomMatrix pos = matter->getPositions();
555 AtomMatrix posDisplace(nAtoms, 3);
556 AtomMatrix force0 = matterTemp.getForces();
557 if (!force0.allFinite()) {
558 QUILL_LOG_ERROR(log, "[Hessian] non-finite forces at undisplaced geometry; "
559 "aborting FD Hessian");
560 return false;
561 }
562
563 for (int dir = 0; dir < 3; ++dir) {
564 for (int c = 0; c < nColors; ++c) {
565 const auto &group = members[static_cast<std::size_t>(c)];
566 if (group.empty()) {
567 continue;
568 }
569 auto shifted = [&](double scale, const char *side) -> AtomMatrix {
570 posDisplace.setZero();
571 for (int ia : group) {
572 posDisplace(atoms(ia), dir) = scale * dr;
573 }
574 matterTemp.setPositions(pos + posDisplace);
575 AtomMatrix force = matterTemp.getForces();
576 if (!force.allFinite()) {
577 QUILL_LOG_ERROR(log,
578 "[Hessian] non-finite forces for color {} dir {} "
579 "({}); aborting FD Hessian",
580 c, dir, side);
581 return AtomMatrix();
582 }
583 return force;
584 };
585 const AtomMatrix forcePlus = shifted(1.0, "+");
586 if (forcePlus.size() == 0) {
587 return false;
588 }
589 AtomMatrix forceMinus = force0;
590 AtomMatrix forcePlus2 = force0;
591 AtomMatrix forceMinus2 = force0;
592 if (scheme != FdScheme::OneSided) {
593 forceMinus = shifted(-1.0, "-");
594 if (forceMinus.size() == 0) {
595 return false;
596 }
597 }
598 if (scheme == FdScheme::Fourth) {
599 forcePlus2 = shifted(2.0, "+2");
600 if (forcePlus2.size() == 0) {
601 return false;
602 }
603 forceMinus2 = shifted(-2.0, "-2");
604 if (forceMinus2.size() == 0) {
605 return false;
606 }
607 }
608 const AtomMatrix slope = fdForceDerivative(
609 scheme, dr, force0, forcePlus, forceMinus, forcePlus2, forceMinus2);
610 const AtomMatrix zero = AtomMatrix::Zero(nAtoms, 3);
611 for (int ia : group) {
612 const int col = ia * 3 + dir;
613 writeMassWeighted(hessian, *matter, atoms, col,
614 static_cast<int>(atoms(ia)), slope, zero, 1.0,
615 owner[static_cast<std::size_t>(c)], ia);
616 }
617 }
618 }
619 return finalizeHessian(size);
620}
621
622bool Hessian::calculateSerial(double dr, FdScheme scheme) {
623 const int nAtoms = static_cast<int>(matter->numberOfAtoms());
624 const int size = static_cast<int>(atoms.rows()) * 3;
625 const std::string &ckptPath = parameters.hessian_options().checkpoint_path;
626 const bool wantResume =
627 parameters.hessian_options().resume && !ckptPath.empty();
628
629 AtomMatrix pos = matter->getPositions();
630 AtomMatrix posDisplace(nAtoms, 3);
631 AtomMatrix posTemp(nAtoms, 3);
632 AtomMatrix forcePlus(nAtoms, 3);
633 AtomMatrix forceMinus(nAtoms, 3);
634
635 const std::string context =
636 columnCheckpointContext(*matter, atoms, dr, scheme, parameters);
637 int startCol = 0;
638 if (wantResume &&
639 loadColumnCheckpoint(ckptPath, size, startCol, hessian, context)) {
640 QUILL_LOG_DEBUG(log, "[Hessian] resume from column {} / {}\n", startCol,
641 size);
642 } else {
643 startCol = 0;
644 hessian.setZero();
645 }
646
647 Matter matterTemp(*matter);
648 AtomMatrix force0 = matterTemp.getForces();
649 if (!force0.allFinite()) {
650 QUILL_LOG_ERROR(log, "[Hessian] non-finite forces at undisplaced geometry; "
651 "aborting FD Hessian");
652 return false;
653 }
654
655 for (int i = startCol; i < size; i++) {
656 posDisplace.setZero();
657 posDisplace(atoms(i / 3), i % 3) = dr;
658
659 posTemp = pos + posDisplace;
660 matterTemp.setPositions(posTemp);
661 forcePlus = matterTemp.getForces();
662 if (!forcePlus.allFinite()) {
663 QUILL_LOG_ERROR(log,
664 "[Hessian] non-finite forces for FD column {} (+); "
665 "aborting FD Hessian",
666 i);
667 return false;
668 }
669
670 if (scheme != FdScheme::OneSided) {
671 posTemp = pos - posDisplace;
672 matterTemp.setPositions(posTemp);
673 forceMinus = matterTemp.getForces();
674 if (!forceMinus.allFinite()) {
675 QUILL_LOG_ERROR(log,
676 "[Hessian] non-finite forces for FD column {} (-); "
677 "aborting FD Hessian",
678 i);
679 return false;
680 }
681 }
682 AtomMatrix forcePlus2 = force0;
683 AtomMatrix forceMinus2 = force0;
684 if (scheme == FdScheme::Fourth) {
685 posDisplace(atoms(i / 3), i % 3) = 2.0 * dr;
686 matterTemp.setPositions(pos + posDisplace);
687 forcePlus2 = matterTemp.getForces();
688 if (!forcePlus2.allFinite()) {
689 QUILL_LOG_ERROR(log,
690 "[Hessian] non-finite forces for FD column {} (+2); "
691 "aborting FD Hessian",
692 i);
693 return false;
694 }
695 matterTemp.setPositions(pos - posDisplace);
696 forceMinus2 = matterTemp.getForces();
697 if (!forceMinus2.allFinite()) {
698 QUILL_LOG_ERROR(log,
699 "[Hessian] non-finite forces for FD column {} (-2); "
700 "aborting FD Hessian",
701 i);
702 return false;
703 }
704 }
705 // H ≈ -dF, mass-weighted. dF is the selected real stencil.
706 const AtomMatrix slope = fdForceDerivative(
707 scheme, dr, force0, forcePlus, forceMinus, forcePlus2, forceMinus2);
708 for (int j = 0; j < size; j++) {
709 hessian(i, j) = -slope(atoms(j / 3), j % 3);
710 const double effMass = std::sqrt(matter->getMass(atoms(j / 3)) *
711 matter->getMass(atoms(i / 3)));
712 hessian(i, j) = eonc::safemath::safe_div(hessian(i, j), effMass, 0.0);
713 }
714
715 if (!ckptPath.empty()) {
716 // next column to compute after a clean interrupt
717 if (!saveColumnCheckpoint(ckptPath, size, i + 1, hessian, context)) {
718 QUILL_LOG_WARNING(log,
719 "[Hessian] failed to replace checkpoint {} at "
720 "column {}; retaining the last complete file",
721 ckptPath, i + 1);
722 }
723 }
724 }
725 return finalizeHessian(size);
726}
727
729 const std::string &ckptPath = parameters.hessian_options().checkpoint_path;
730
731 // Symmetrize (FD noise breaks H=H^T; required for vib analysis)
732 for (int i = 0; i < size; i++) {
733 for (int j = 0; j < i; j++) {
734 hessian(i, j) = (hessian(i, j) + hessian(j, i)) / 2;
735 hessian(j, i) = hessian(i, j);
736 }
737 }
738
739 if (!hessian.allFinite()) {
740 QUILL_LOG_ERROR(log, "[Hessian] non-finite entries after FD assembly; "
741 "aborting eigen solve");
742 return false;
743 }
744
745 if (writeFile) {
746 if (!parameters.main_options().quiet) {
747 QUILL_LOG_DEBUG(log, "[Hessian] writing hessian\n");
748 }
749 // A previous case in the same process can still hold hessian.dat on
750 // Windows. Replace it, and try once more after removing the old file.
751 std::ofstream hessfile("hessian.dat", std::ios::out | std::ios::trunc);
752 if (!hessfile) {
753 std::remove("hessian.dat");
754 hessfile.clear();
755 hessfile.open("hessian.dat", std::ios::out | std::ios::trunc);
756 }
757 if (!hessfile) {
758 QUILL_LOG_ERROR(log, "[Hessian] failed to open hessian.dat");
759 return false;
760 }
761 hessfile << std::setprecision(std::numeric_limits<double>::max_digits10)
762 << hessian;
763 hessfile.close();
764 if (!hessfile) {
765 QUILL_LOG_ERROR(log, "[Hessian] failed to write hessian.dat");
766 return false;
767 }
768 }
769
770 // Completed run: remove checkpoint so a later job does not resume stale cols
771 if (!ckptPath.empty()) {
772 std::remove(ckptPath.c_str());
773 }
774
775 double t0, t1;
776 eonc::helpers::getTime(&t0, nullptr, nullptr);
777 QUILL_LOG_DEBUG(log, "[Hessian] calculating eigen values of the hessian\n");
778 // ColMajor copy for SelfAdjointEigenSolver (eOn MatrixXd is RowMajor)
779 using ColMajorXd =
780 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;
781 ColMajorXd hessianCol = hessian;
782 const bool withModes = parameters.hessian_options().write_modes;
783 Eigen::SelfAdjointEigenSolver<ColMajorXd> es(
784 hessianCol,
785 withModes ? Eigen::ComputeEigenvectors : Eigen::EigenvaluesOnly);
786 eonc::helpers::getTime(&t1, nullptr, nullptr);
787 QUILL_LOG_DEBUG(log, "[Hessian] eigenvalue problem took {:.4e} seconds\n",
788 t1 - t0);
789 if (es.info() != Eigen::Success) {
790 QUILL_LOG_ERROR(log,
791 "[Hessian] SelfAdjointEigenSolver failed (info={}); "
792 "aborting",
793 static_cast<int>(es.info()));
794 return false;
795 }
796 freqs = es.eigenvalues();
797 if (!freqs.allFinite()) {
798 QUILL_LOG_ERROR(log, "[Hessian] non-finite eigenvalues; aborting");
799 return false;
800 }
801 if (withModes) {
802 modes = es.eigenvectors();
803 } else {
804 modes.resize(0, 0);
805 }
806
807 return true;
808}
809
810VectorXd Hessian::removeZeroFreqs(const VectorXd &freqs) {
811 QUILL_LOG_DEBUG(log, "[Hessian] removing zero frequency modes");
812 int size = freqs.size();
813 if (size != 3 * matter->numberOfAtoms()) {
814 return freqs;
815 }
816 VectorXd newfreqs;
817 newfreqs.resize(size);
818 int nremoved = 0;
819 for (int i = 0; i < size; i++) {
820 if (std::abs(freqs(i)) > parameters.hessian_options().zero_freq_value) {
821 newfreqs(i - nremoved) = freqs(i);
822 } else {
823 nremoved++;
824 }
825 }
826
827 if (!trivialModeCountIsPhysical(nremoved, matter->numberOfFixedAtoms())) {
828 QUILL_LOG_WARNING(log,
829 "[Hessian] found {} trivial eigenmodes; a free cluster "
830 "has 6 (5 if linear), a periodic cell 3, and a "
831 "structure with fixed atoms none",
832 nremoved);
833 }
834 return newfreqs.head(size - nremoved);
835}
836
837std::vector<double> cartesianMode(const Matter &matter, const VectorXi &atoms,
838 const Eigen::Ref<const VectorXd> &mode) {
839 const long n = matter.numberOfAtoms();
840 std::vector<double> out(static_cast<size_t>(3 * n), 0.0);
841 if (mode.size() != 3 * atoms.size()) {
842 throw std::invalid_argument("cartesianMode: mode length is not 3 x atoms");
843 }
844 double norm2 = 0.0;
845 for (long j = 0; j < mode.size(); ++j) {
846 const long atom = atoms(j / 3);
847 const double mass = matter.getMass(atom);
848 if (!(mass > 0.0)) {
849 throw std::invalid_argument("cartesianMode: atom without a mass");
850 }
851 const double x = mode(j) / std::sqrt(mass);
852 out[static_cast<size_t>(3 * atom + j % 3)] = x;
853 norm2 += x * x;
854 }
855 if (norm2 > 0.0) {
856 const double scale = 1.0 / std::sqrt(norm2);
857 for (double &x : out) {
858 x *= scale;
859 }
860 }
861 return out;
862}
863
864bool writeNormalModes(Matter &matter, const VectorXi &atoms,
865 const VectorXd &eigenvalues, const MatrixXd &modes,
866 const std::string &path) {
867 if (modes.cols() != eigenvalues.size() || modes.rows() != 3 * atoms.size()) {
868 return false;
869 }
870 for (long k = 0; k < eigenvalues.size(); ++k) {
871 const double lambda = eigenvalues(k);
872 const double hw =
873 std::copysign(tunneling::kHbar * std::sqrt(std::abs(lambda)), lambda);
875 meta.frame_index = static_cast<uint64_t>(k);
876 meta.scalars = {{"mode_eigenvalue", lambda},
877 {"hbar_omega", hw},
878 {"wavenumber", hw * kEvToWavenumber}};
879 meta.displacements = cartesianMode(matter, atoms, modes.col(k));
880 if (!io::io_ok(matter.matter2con(path, k > 0, &meta))) {
881 return false;
882 }
883 }
884 return true;
885}
886
887bool trivialModeCountIsPhysical(long removed, long fixedAtoms) {
888 if (fixedAtoms > 0) {
889 return removed == 0;
890 }
891 return removed == 3 || removed == 5 || removed == 6;
892}
893
894} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, eOnStorageOrder > MatrixXd
Definition Eigen.h:33
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
VectorXi getAtomicNrs() const
Definition Matter.cpp:786
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
bool getPeriodic() const noexcept
Definition Matter.h:338
Matrix3d getCell() const
Definition Matter.cpp:345
long int numberOfAtoms() const
Definition Matter.cpp:343
double getMass(long int atom) const
Definition Matter.cpp:548
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
const potential_options_t & potential_options() const
const main_options_t & main_options() const
bool writeFile
Definition Hessian.h:70
eonc::log::Scoped log
Definition Hessian.h:78
Matter * matter
Definition Hessian.h:64
MatrixXd modes
Definition Hessian.h:69
VectorXd freqs
Definition Hessian.h:68
Hessian(const Parameters &params, Matter *matter)
Definition Hessian.cpp:139
MatrixXd getHessian(Matter *matterIn, const VectorXi &atomsIn)
Definition Hessian.cpp:146
bool calculateSerial(double dr, FdScheme scheme)
Definition Hessian.cpp:622
VectorXd removeZeroFreqs(const VectorXd &freqs)
Definition Hessian.cpp:810
VectorXi atoms
Definition Hessian.h:72
bool calculate()
Definition Hessian.cpp:341
bool calculateBatched(double dr, FdScheme scheme)
Definition Hessian.cpp:408
const Parameters & parameters
Definition Hessian.h:65
bool finalizeHessian(int size)
Definition Hessian.cpp:728
bool calculateColored(double range, double dr, FdScheme scheme)
Definition Hessian.cpp:501
MatrixXd hessian
Definition Hessian.h:67
VectorXd getFreqs(Matter *matterIn, const VectorXi &atomsIn)
Definition Hessian.cpp:160
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
long int numberOfAtoms() const
Definition Matter.cpp:343
double getMass(long int atom) const
Definition Matter.cpp:548
const AtomMatrix & getForces() const
Definition Matter.cpp:482
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
RAII wrapper around vesin_neighbors for Matter-style boxes (double[9] row-major 3×3 cell,...
bool atomicWriteFile(const std::string &path, Writer writer)
Definition AtomicFile.h:26
void getTime(double *real, double *user, double *sys)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
constexpr long derivative
constexpr double safe_div(double num, double denom, double fallback=0.0)
Definition SafeMath.h:21
constexpr double kHbar
hbar in eV^0.5 amu^0.5 Angstrom, correctly rounded from the exact SI values (h = 6....
Definition Tunneling.h:39
RAII resource manager for the ARTn C library with global synchronization.
FdScheme
Real finite-difference scheme for the assembled Hessian and for Lanczos/Davidson Hessian-vector produ...
M fdForceDerivative(FdScheme scheme, double dr, const M &f0, const M &fPlus, const M &fMinus, const M &fPlus2, const M &fMinus2)
Derivative of a sampled force map along one real step of length dr.
constexpr double kEvToWavenumber
1 eV in cm^-1, e / (h c) from the exact SI values.
Definition Hessian.h:31
FdScheme parseFdScheme(std::string_view scheme)
bool writeNormalModes(Matter &matter, const VectorXi &atoms, const VectorXd &eigenvalues, const MatrixXd &modes, const std::string &path)
Writes one frame of matter per mode to path, the mode as the displacements section and mode_eigenvalu...
Definition Hessian.cpp:864
std::vector< CutoffPair > periodicCutoffNeighbors(const double *positions, size_t atoms, const double *cell, double cutoff, bool full)
bool trivialModeCountIsPhysical(long removed, long fixedAtoms)
Whether removed zero-frequency modes are what the structure's symmetries give: 6 for a free cluster (...
Definition Hessian.cpp:887
std::vector< int > greedyColorCutoffGraph(const std::vector< std::vector< int > > &adj)
Greedy coloring of an undirected graph.
Definition Hessian.cpp:311
std::vector< int > colorMobileCutoffGraph(const Matter &matter, const VectorXi &atoms, double cutoff)
Conflict graph on atoms: two mobile atoms share an edge when their closed cutoff neighborhoods inters...
Definition Hessian.cpp:336
std::vector< double > cartesianMode(const Matter &matter, const VectorXi &atoms, const Eigen::Ref< const VectorXd > &mode)
Cartesian displacement of every atom along one mass-weighted mode over the mobile degrees of freedom ...
Definition Hessian.cpp:837
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::vector< ConMetadataValue > scalars
Definition ConFileIO.h:79
std::vector< double > displacements
Per-atom displacement, row-major N x 3 in Angstrom (a normal mode, a dimer direction).
Definition ConFileIO.h:85