Loading...
Searching...
No Matches
NwchemGradientOracle.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#pragma once
3#include <fcntl.h>
4#include <sys/wait.h>
5#include <unistd.h>
6
7#include <atomic>
8#include <cerrno>
9#include <cstdlib>
10#include <filesystem>
11#include <fstream>
12#include <iomanip>
13#include <sstream>
14#include <utility>
15
18
19namespace gpr::potentials {
20// Explicit numerical profiles retain the same molecular Hamiltonian while
21// separating quadrature and electronic convergence in reproducibility checks.
23 enum class Grid { Huge, Medium };
24 enum class Scf { Strict, Author2025 };
27 void validate() const
28 {
29 if ((grid != Grid::Huge && grid != Grid::Medium) ||
31 throw std::invalid_argument("Unsupported NWChem numerical profile");
32 }
33 const char* gridName() const
34 {
35 validate();
36 return grid == Grid::Huge ? "huge" : "medium";
37 }
38 const char* scfName() const
39 {
40 validate();
41 return scf == Scf::Strict ? "strict" : "author2025";
42 }
43};
44// File-backed native NWChem energy/gradient calls in atomic units. A unique
45// directory retains every input, output and failed call. No shell interprets
46// the executable or its arguments, and the coordinate frame is preserved.
48 std::filesystem::path executable_, root_;
49 std::vector<std::string> elements_;
50 bool dispersion_;
51 const NwchemNumericalSettings settings_;
52 std::atomic<std::size_t> calls_{};
53 std::atomic<std::size_t> hessianCalls_{};
54
55public:
56 NwchemGradientOracle(std::filesystem::path executable,
57 std::filesystem::path root,
58 std::vector<std::string> elements,
59 bool dispersion = false,
60 NwchemNumericalSettings settings = {})
61 : executable_(std::filesystem::absolute(executable)),
62 root_(std::filesystem::absolute(root)),
63 elements_(std::move(elements)),
64 dispersion_(dispersion),
65 settings_(settings)
66 {
67 settings_.validate();
68 if (elements_.empty() ||
69 !std::filesystem::is_regular_file(executable_) ||
70 !std::filesystem::create_directory(root_))
71 throw std::invalid_argument(
72 "Native NWChem executable and new oracle directory required");
73 for (const auto& element: elements_)
74 if (element != "H" && element != "C" && element != "N" &&
75 element != "O")
76 throw std::invalid_argument(
77 "Unsupported JCTC benchmark element");
78 }
79 // Canonical input text is the coordinate, Hamiltonian and
80 // numerical-settings contract shared by fresh calls and retained native
81 // observations.
82 std::string inputText(const Eigen::VectorXd& positions,
83 bool curvature) const
84 {
85 if (positions.size() !=
86 static_cast<Eigen::Index>(3 * elements_.size()) ||
87 !positions.allFinite())
88 throw std::invalid_argument(
89 "Finite native NWChem molecular coordinates required");
90 std::ostringstream input;
91 input
92 << "start point\necce_print point.ecce\nmemory total 1500 "
93 "mb\ncharge 0\ngeometry units bohr nocenter noautosym noautoz\n"
94 << std::setprecision(17);
95 for (std::size_t atom = 0; atom < elements_.size(); ++atom)
96 input << elements_[atom] << ' ' << positions[3 * atom] << ' '
97 << positions[3 * atom + 1] << ' ' << positions[3 * atom + 2]
98 << '\n';
99 input << "end\nbasis spherical\n * library 6-31g*\nend\ndft\n xc "
100 "b3lyp\n mult 1\n iterations 500\n direct\n grid "
101 << settings_.gridName() << " nodisk\n";
102 if (settings_.scf == NwchemNumericalSettings::Scf::Strict)
103 input << " convergence energy 1e-11 density 1e-10 gradient 1e-10\n";
104 else
105 input << " convergence energy 1e-6 density 1e-5 gradient 5e-4\n";
106 if (dispersion_) input << " disp vdw 3\n";
107 input << "end\n";
108 if (curvature) input << "hessian\n thresh 1e-10\nend\n";
109 input << "task dft gradient\n";
110 if (curvature) input << "task dft frequencies\n";
111 return input.str();
112 }
113 // Orbitals change the initial guess while all native task settings match
114 // the canonical cold input.
115 std::string orbitalInputText(const Eigen::VectorXd& positions,
116 bool curvature) const
117 {
118 auto text = inputText(positions, curvature);
119 const auto end = text.find("end\n", text.find("\ndft\n"));
120 text.insert(end, " vectors input seed.movecs output point.movecs\n");
121 return text;
122 }
123
124private:
125 static std::string verifyOrbitalSeed(const std::filesystem::path& directory,
126 const std::string& expectedDigest = {})
127 {
128 const auto digest =
129 gpr::sha256File((directory / "seed.movecs").string());
130 if (digest.empty() ||
131 (!expectedDigest.empty() && digest != expectedDigest))
132 throw std::runtime_error(
133 "Retained NWChem orbital seed hash differs");
134 std::ifstream manifest(directory / "seed.sha256", std::ios::binary);
135 if (!manifest)
136 throw std::runtime_error(
137 "Retained NWChem orbital seed hash is absent");
138 const std::string recorded((std::istreambuf_iterator<char>(manifest)),
139 {});
140 if (recorded != digest + "\n")
141 throw std::runtime_error(
142 "Retained NWChem orbital seed hash differs");
143 return digest;
144 }
145
146 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> computeInput(
147 const Eigen::VectorXd& positions, bool curvature,
148 const std::filesystem::path* orbitalSeed)
149 {
150 if (positions.size() !=
151 static_cast<Eigen::Index>(3 * elements_.size()) ||
152 !positions.allFinite())
153 throw std::invalid_argument(
154 "Finite native NWChem molecular coordinates required");
155 const auto directory = root_ / ("point-" + std::to_string(calls_++));
156 if (!std::filesystem::create_directory(directory))
157 throw std::runtime_error("NWChem point directory must be new");
158 std::string orbitalDigest;
159 if (orbitalSeed) {
160 if (!std::filesystem::is_regular_file(*orbitalSeed))
161 throw std::invalid_argument(
162 "NWChem orbital seed must be a regular file");
163 const auto digest = gpr::sha256File(orbitalSeed->string());
164 if (digest.empty())
165 throw std::runtime_error("Cannot hash NWChem orbital seed");
166 orbitalDigest = digest;
167 std::filesystem::copy_file(*orbitalSeed, directory / "seed.movecs");
168 if (gpr::sha256File(orbitalSeed->string()) != digest ||
169 gpr::sha256File((directory / "seed.movecs").string()) != digest)
170 throw std::runtime_error(
171 "NWChem orbital seed changed during retention");
172 std::ofstream manifest(directory / "seed.sha256", std::ios::binary);
173 manifest << digest << '\n';
174 if (!manifest)
175 throw std::runtime_error(
176 "Cannot retain NWChem orbital seed hash");
177 }
178 {
179 std::ofstream input(directory / "point.nw");
180 input << (orbitalSeed ? orbitalInputText(positions, curvature)
181 : inputText(positions, curvature));
182 if (!input)
183 throw std::runtime_error("Cannot write native NWChem input");
184 if (curvature) ++hessianCalls_;
185 }
186 if (orbitalSeed) verifyOrbitalSeed(directory, orbitalDigest);
187 std::vector<std::string> environment;
188 for (char** entry = ::environ; entry && *entry; ++entry)
189 environment.emplace_back(*entry);
190 if (!std::getenv("NWCHEM_BASIS_LIBRARY")) {
191 const auto basis = executable_.parent_path().parent_path() /
192 "share/nwchem/libraries";
193 if (!std::filesystem::is_directory(basis))
194 throw std::runtime_error(
195 "Native NWChem basis directory is absent");
196 environment.push_back("NWCHEM_BASIS_LIBRARY=" + basis.string() +
197 "/");
198 }
199 std::vector<char*> env;
200 for (auto& item: environment)
201 env.push_back(item.data());
202 env.push_back(nullptr);
203 char* arguments[] = {const_cast<char*>(executable_.c_str()),
204 const_cast<char*>("point.nw"), nullptr};
205 const pid_t child = fork();
206 if (child < 0) throw std::runtime_error("Cannot start native NWChem");
207 if (child == 0) {
208 if (chdir(directory.c_str()) != 0) _exit(125);
209 const int output =
210 open("point.out", O_CREAT | O_EXCL | O_WRONLY, 0600);
211 if (output < 0 || dup2(output, STDOUT_FILENO) < 0 ||
212 dup2(output, STDERR_FILENO) < 0)
213 _exit(125);
214 close(output);
215 execve(executable_.c_str(), arguments, env.data());
216 _exit(127);
217 }
218 int status = 0;
219 pid_t waited;
220 do {
221 waited = waitpid(child, &status, 0);
222 } while (waited < 0 && errno == EINTR);
223 if (orbitalSeed) verifyOrbitalSeed(directory, orbitalDigest);
224 if (waited != child || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
225 throw std::runtime_error(
226 "Native NWChem failed; retained point output identifies the "
227 "calculation");
228 return orbitalSeed
229 ? readRetainedWithOrbitals(directory, positions, curvature)
230 : readRetained(directory, positions, curvature);
231 }
232
233public:
234 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> compute(
235 const Eigen::VectorXd& positions, bool curvature)
236 {
237 return computeInput(positions, curvature, nullptr);
238 }
239 // The source guess stays outside the task's input and output files.
240 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd>
241 computeWithOrbitals(const Eigen::VectorXd& positions, bool curvature,
242 const std::filesystem::path& seedFile)
243 {
244 return computeInput(positions, curvature, &seedFile);
245 }
246 // The caller owns proof that the retained task returned successfully.
247 // Reparse the same full-precision records used by fresh evaluations.
248private:
249 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> readRetainedInput(
250 const std::filesystem::path& directory,
251 const Eigen::VectorXd& positions, bool curvature, bool orbitals) const
252 {
253 std::ifstream input(directory / "point.nw", std::ios::binary);
254 if (!input)
255 throw std::runtime_error("Retained native NWChem input is absent");
256 const std::string text((std::istreambuf_iterator<char>(input)), {});
257 if (text != (orbitals ? orbitalInputText(positions, curvature)
258 : inputText(positions, curvature)))
259 throw std::invalid_argument(
260 "Retained NWChem coordinates or input settings differ");
261 std::ifstream output(directory / "point.out");
262 std::string line;
264 result.gradient = Eigen::VectorXd::Zero(positions.size());
265 bool energy = false, gradient = false;
266 while (std::getline(output, line)) {
267 const auto marker = line.find("Total DFT energy =");
268 if (marker != std::string::npos) {
269 std::istringstream value(line.substr(marker + 18));
270 if (!(value >> result.energy))
271 throw std::runtime_error("Invalid NWChem energy record");
272 energy = true;
273 }
274 if (line.find("DFT ENERGY GRADIENTS") != std::string::npos) {
275 std::size_t found = 0;
276 while (found < elements_.size() && std::getline(output, line)) {
277 std::istringstream row(line);
278 int index;
279 std::string element;
280 double x, y, z, gx, gy, gz;
281 if (!(row >> index >> element >> x >> y >> z >> gx >> gy >>
282 gz))
283 continue;
284 if (index != static_cast<int>(found + 1) ||
285 element != elements_[found])
286 throw std::runtime_error(
287 "NWChem gradient atom identity differs");
288 result.gradient.segment<3>(3 * found) =
289 Eigen::Vector3d(gx, gy, gz);
290 ++found;
291 }
292 if (found != elements_.size())
293 throw std::runtime_error(
294 "Incomplete NWChem gradient table");
295 gradient = true;
296 }
297 }
298 // The display table rounds gradients to six decimal places. The
299 // native task record retains the force precision required by Newton.
300 std::ifstream machine(directory / "point.ecce");
301 bool preciseEnergy = false, preciseGradient = false;
302 while (std::getline(machine, line)) {
303 if (line.rfind("task_gradient%", 0) != 0) continue;
304 const std::string gradientKey = "%begin%total gradient%",
305 energyKey = "%begin%total energy%";
306 const auto gradientAt = line.find(gradientKey),
307 energyAt = line.find(energyKey);
308 if (energyAt != std::string::npos) {
309 if (!(machine >> result.energy))
310 throw std::runtime_error(
311 "Invalid full-precision NWChem energy");
312 preciseEnergy = true;
313 }
314 if (gradientAt != std::string::npos) {
315 const auto begin = gradientAt + gradientKey.size(),
316 end = line.find('%', begin);
317 if (end == std::string::npos)
318 throw std::runtime_error(
319 "Missing native NWChem gradient dimensions");
320 std::istringstream dimensions(line.substr(begin, end - begin));
321 std::size_t rows, atoms;
322 if (!(dimensions >> rows >> atoms) || rows != 3 ||
323 atoms != elements_.size())
324 throw std::runtime_error(
325 "Native NWChem gradient dimensions differ");
326 for (Eigen::Index k = 0; k < positions.size(); ++k)
327 if (!(machine >> result.gradient[k]))
328 throw std::runtime_error(
329 "Incomplete full-precision NWChem gradient");
330 machine >> std::ws;
331 std::string finish;
332 std::getline(machine, finish);
333 if (finish.find("%end%total gradient%") == std::string::npos)
334 throw std::runtime_error(
335 "Invalid native NWChem gradient termination");
336 preciseGradient = true;
337 }
338 }
339 if (!preciseEnergy || !preciseGradient)
340 throw std::runtime_error(
341 "Full-precision native NWChem task output required");
342 if (!energy || !gradient || !std::isfinite(result.energy) ||
343 !result.gradient.allFinite())
344 throw std::runtime_error(
345 "Native NWChem energy/gradient result is incomplete");
346 Eigen::MatrixXd hessian;
347 if (curvature) {
348 std::ifstream file(directory / "point.hess");
349 hessian.resize(positions.size(), positions.size());
350 for (Eigen::Index i = 0; i < positions.size(); ++i)
351 for (Eigen::Index j = 0; j <= i; ++j) {
352 std::string token;
353 if (!(file >> token))
354 throw std::runtime_error(
355 "Incomplete native NWChem Hessian");
356 for (auto& c: token)
357 if (c == 'D' || c == 'd') c = 'E';
358 std::size_t consumed = 0;
359 const double value = std::stod(token, &consumed);
360 if (consumed != token.size() || !std::isfinite(value))
361 throw std::runtime_error(
362 "Invalid native NWChem Hessian value");
363 hessian(i, j) = hessian(j, i) = value;
364 }
365 std::string extra;
366 if (file >> extra)
367 throw std::runtime_error("Extra native NWChem Hessian records");
368 }
369 return {std::move(result), std::move(hessian)};
370 }
371
372public:
373 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> readRetained(
374 const std::filesystem::path& directory,
375 const Eigen::VectorXd& positions, bool curvature) const
376 {
377 return readRetainedInput(directory, positions, curvature, false);
378 }
379 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd>
380 readRetainedWithOrbitals(const std::filesystem::path& directory,
381 const Eigen::VectorXd& positions,
382 bool curvature) const
383 {
384 const auto digest = verifyOrbitalSeed(directory);
385 auto result = readRetainedInput(directory, positions, curvature, true);
386 verifyOrbitalSeed(directory, digest);
387 return result;
388 }
389 quantum::PotentialEvaluation evaluate(const Eigen::VectorXd& positions)
390 {
391 return compute(positions, false).first;
392 }
393 Eigen::MatrixXd hessian(const Eigen::VectorXd& positions)
394 {
395 return compute(positions, true).second;
396 }
397 auto evaluateWithHessian(const Eigen::VectorXd& positions)
398 {
399 return compute(positions, true);
400 }
401 std::size_t calls() const noexcept
402 {
403 return calls_.load();
404 }
405 std::size_t hessianCalls() const noexcept
406 {
407 return hessianCalls_.load();
408 }
409};
410} // namespace gpr::potentials
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
auto evaluateWithHessian(const Eigen::VectorXd &positions)
std::pair< quantum::PotentialEvaluation, Eigen::MatrixXd > readRetainedWithOrbitals(const std::filesystem::path &directory, const Eigen::VectorXd &positions, bool curvature) const
quantum::PotentialEvaluation evaluate(const Eigen::VectorXd &positions)
std::string orbitalInputText(const Eigen::VectorXd &positions, bool curvature) const
std::pair< quantum::PotentialEvaluation, Eigen::MatrixXd > computeWithOrbitals(const Eigen::VectorXd &positions, bool curvature, const std::filesystem::path &seedFile)
std::pair< quantum::PotentialEvaluation, Eigen::MatrixXd > readRetained(const std::filesystem::path &directory, const Eigen::VectorXd &positions, bool curvature) const
Eigen::MatrixXd hessian(const Eigen::VectorXd &positions)
NwchemGradientOracle(std::filesystem::path executable, std::filesystem::path root, std::vector< std::string > elements, bool dispersion=false, NwchemNumericalSettings settings={})
std::string inputText(const Eigen::VectorXd &positions, bool curvature) const
std::pair< quantum::PotentialEvaluation, Eigen::MatrixXd > compute(const Eigen::VectorXd &positions, bool curvature)
std::size_t hessianCalls() const noexcept
int status
Analytical test potentials and potentials built from a fitted GP.
std::string line(const std::string &topic, const std::vector< Field > &fields)
std::string sha256File(const std::string &path)
Digest of a file's contents; empty when the file cannot be read.
Definition Sha256.cpp:134
Panel finish(Real left, Real right, const Value &k, const Value &g, const Value &absolute)
STL namespace.