48 std::filesystem::path executable_, root_;
49 std::vector<std::string> elements_;
52 std::atomic<std::size_t> calls_{};
53 std::atomic<std::size_t> hessianCalls_{};
57 std::filesystem::path root,
58 std::vector<std::string> elements,
59 bool dispersion =
false,
61 : executable_(
std::filesystem::absolute(executable)),
62 root_(
std::filesystem::absolute(root)),
63 elements_(
std::move(elements)),
64 dispersion_(dispersion),
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" &&
76 throw std::invalid_argument(
77 "Unsupported JCTC benchmark element");
82 std::string
inputText(
const Eigen::VectorXd& positions,
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;
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]
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";
103 input <<
" convergence energy 1e-11 density 1e-10 gradient 1e-10\n";
105 input <<
" convergence energy 1e-6 density 1e-5 gradient 5e-4\n";
106 if (dispersion_) input <<
" disp vdw 3\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";
116 bool curvature)
const
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");
125 static std::string verifyOrbitalSeed(
const std::filesystem::path& directory,
126 const std::string& expectedDigest = {})
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);
136 throw std::runtime_error(
137 "Retained NWChem orbital seed hash is absent");
138 const std::string recorded((std::istreambuf_iterator<char>(manifest)),
140 if (recorded != digest +
"\n")
141 throw std::runtime_error(
142 "Retained NWChem orbital seed hash differs");
146 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> computeInput(
147 const Eigen::VectorXd& positions,
bool curvature,
148 const std::filesystem::path* orbitalSeed)
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;
160 if (!std::filesystem::is_regular_file(*orbitalSeed))
161 throw std::invalid_argument(
162 "NWChem orbital seed must be a regular file");
165 throw std::runtime_error(
"Cannot hash NWChem orbital seed");
166 orbitalDigest = digest;
167 std::filesystem::copy_file(*orbitalSeed, directory /
"seed.movecs");
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';
175 throw std::runtime_error(
176 "Cannot retain NWChem orbital seed hash");
179 std::ofstream input(directory /
"point.nw");
183 throw std::runtime_error(
"Cannot write native NWChem input");
184 if (curvature) ++hessianCalls_;
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() +
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");
208 if (chdir(directory.c_str()) != 0) _exit(125);
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)
215 execve(executable_.c_str(), arguments, env.data());
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 "
234 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd>
compute(
235 const Eigen::VectorXd& positions,
bool curvature)
237 return computeInput(positions, curvature,
nullptr);
240 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd>
242 const std::filesystem::path& seedFile)
244 return computeInput(positions, curvature, &seedFile);
249 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd> readRetainedInput(
250 const std::filesystem::path& directory,
251 const Eigen::VectorXd& positions,
bool curvature,
bool orbitals)
const
253 std::ifstream input(directory /
"point.nw", std::ios::binary);
255 throw std::runtime_error(
"Retained native NWChem input is absent");
256 const std::string text((std::istreambuf_iterator<char>(input)), {});
259 throw std::invalid_argument(
260 "Retained NWChem coordinates or input settings differ");
261 std::ifstream output(directory /
"point.out");
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");
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);
280 double x,
y,
z, gx, gy, gz;
281 if (!(row >> index >> element >>
x >>
y >>
z >> gx >> gy >>
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);
292 if (found != elements_.size())
293 throw std::runtime_error(
294 "Incomplete NWChem gradient table");
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;
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");
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;
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) ||
344 throw std::runtime_error(
345 "Native NWChem energy/gradient result is incomplete");
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) {
353 if (!(file >> token))
354 throw std::runtime_error(
355 "Incomplete native NWChem Hessian");
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");
367 throw std::runtime_error(
"Extra native NWChem Hessian records");
369 return {std::move(result), std::move(
hessian)};
374 const std::filesystem::path& directory,
375 const Eigen::VectorXd& positions,
bool curvature)
const
377 return readRetainedInput(directory, positions, curvature,
false);
379 std::pair<quantum::PotentialEvaluation, Eigen::MatrixXd>
381 const Eigen::VectorXd& positions,
382 bool curvature)
const
384 const auto digest = verifyOrbitalSeed(directory);
385 auto result = readRetainedInput(directory, positions, curvature,
true);
386 verifyOrbitalSeed(directory, digest);
391 return compute(positions,
false).first;
393 Eigen::MatrixXd
hessian(
const Eigen::VectorXd& positions)
395 return compute(positions,
true).second;
399 return compute(positions,
true);
403 return calls_.load();
407 return hessianCalls_.load();