Loading...
Searching...
No Matches
ChemfilesIO.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/ChemfilesIO.h"
13#include "eon/EonLogger.h"
14#include "eon/Matter.h"
15#include "eon/fpe_handler.h"
16
17#include <algorithm>
18#include <cctype>
19#include <filesystem>
20#include <format>
21#include <mutex>
22#include <sstream>
23#include <stdexcept>
24#include <string>
25#include <vector>
26
27#ifdef WITH_CHEMFILES
28#include <chemfiles.hpp>
29#endif
30
31namespace eonc::io {
32namespace {
33
34namespace fs = std::filesystem;
35
36std::string lower(std::string s) {
37 std::transform(s.begin(), s.end(), s.begin(),
38 [](unsigned char c) { return std::tolower(c); });
39 return s;
40}
41
42std::mutex &format_mutex() {
43 static std::mutex mu;
44 return mu;
45}
46std::string &input_fmt() {
47 static std::string s;
48 return s;
49}
50thread_local std::string g_last_cell_warning;
51
52struct ConfigCell {
53 std::vector<double> values; // empty, 3 or 9
54 bool pbc{true};
55 double vacuum{10.0};
56};
57ConfigCell &config_cell() {
58 static ConfigCell c;
59 return c;
60}
61
63Matrix3d matrix_from_values(const std::vector<double> &v) {
64 Matrix3d box = Matrix3d::Zero();
65 if (v.size() == 3) {
66 box(0, 0) = v[0];
67 box(1, 1) = v[1];
68 box(2, 2) = v[2];
69 } else {
70 for (int i = 0; i < 9; ++i) {
71 box(i / 3, i % 3) = v[static_cast<size_t>(i)];
72 }
73 }
74 return box;
75}
76
77#ifdef WITH_CHEMFILES
79std::string chemfiles_format(const std::string &fmt) {
80 const auto f = lower(fmt);
81 if (f.empty()) {
82 return "";
83 }
84 if (f == "xyz" || f == "extxyz") {
85 return "XYZ";
86 }
87 if (f == "pdb") {
88 return "PDB";
89 }
90 if (f == "cif") {
91 return "CIF";
92 }
93 if (f == "gro") {
94 return "GRO";
95 }
96 if (f == "data" || f == "lammps" || f == "lammps-data" || f == "lmp") {
97 return "LAMMPS Data";
98 }
99 if (f == "mol2") {
100 return "MOL2";
101 }
102 if (f == "sdf") {
103 return "SDF";
104 }
105 if (f == "poscar" || f == "vasp") {
106 return "POSCAR";
107 }
108 return fmt; // a chemfiles format name, passed through
109}
110
112std::string format_for_path(const std::string &filename,
113 const std::string &format) {
114 if (!format.empty()) {
115 return chemfiles_format(format);
116 }
117 const auto ext = lower(fs::path(filename).extension().string());
118 if (ext == ".extxyz") {
119 return "XYZ";
120 }
121 if (ext == ".data" || ext == ".lmp") {
122 return "LAMMPS Data";
123 }
124 const auto name = lower(fs::path(filename).filename().string());
125 if (name == "poscar" || name == "contcar" || ext == ".vasp") {
126 return "POSCAR";
127 }
128 return "";
129}
130
133bool mask_from_property(const chemfiles::Property &p, bool frozen_when_true,
134 std::array<bool, 3> &mask) {
135 auto flip = [&](bool v) { return frozen_when_true ? v : !v; };
136 switch (p.kind()) {
137 case chemfiles::Property::BOOL: {
138 const bool v = flip(p.as_bool());
139 mask = {v, v, v};
140 return true;
141 }
142 case chemfiles::Property::DOUBLE: {
143 const bool v = flip(p.as_double() != 0.0);
144 mask = {v, v, v};
145 return true;
146 }
147 case chemfiles::Property::VECTOR3D: {
148 const auto v = p.as_vector3d();
149 mask = {flip(v[0] != 0.0), flip(v[1] != 0.0), flip(v[2] != 0.0)};
150 return true;
151 }
152 default:
153 return false;
154 }
155}
156
157void quiet_chemfiles() {
158 static std::once_flag once;
159 std::call_once(once, [] {
160 chemfiles::set_warning_callback(
161 [](const std::string &msg) { EONC_LOG_DEBUG("chemfiles: {}", msg); });
162 });
163}
164#endif
165
166} // namespace
167
168bool chemfiles_available() noexcept {
169#ifdef WITH_CHEMFILES
170 return true;
171#else
172 return false;
173#endif
174}
175
176bool is_readcon_path(std::string_view filename) {
177 const auto name = lower(fs::path(std::string(filename)).filename().string());
178 for (const char *ext : {".con", ".convel"}) {
179 const std::string e(ext);
180 if (name.ends_with(e) || name.ends_with(e + ".gz") ||
181 name.ends_with(e + ".zst")) {
182 return true;
183 }
184 }
185 return false;
186}
187
188bool is_chemfiles_path(std::string_view filename) {
189 const fs::path path{std::string(filename)};
190 const auto name = lower(path.filename().string());
191 if (name == "poscar" || name == "contcar") {
192 return true;
193 }
194 static const char *const kExt[] = {
195 ".xyz", ".extxyz", ".pdb", ".cif", ".mmcif", ".gro", ".data",
196 ".lmp", ".mol2", ".sdf", ".vasp", ".xtc", ".trr", ".dcd",
197 ".nc", ".arc", ".cml", ".cssr", ".mmtf", ".tng"};
198 const auto ext = lower(path.extension().string());
199 return std::find(std::begin(kExt), std::end(kExt), ext) != std::end(kExt);
200}
201
202void set_structure_input_format(std::string fmt) {
203 fmt = lower(std::move(fmt));
204 const std::lock_guard<std::mutex> g(format_mutex());
205 input_fmt() = (fmt == "con") ? std::string() : fmt;
206}
207
208const std::string &structure_input_format() noexcept { return input_fmt(); }
209
210std::vector<double> parse_cell_values(const std::string &text) {
211 std::vector<double> out;
212 std::istringstream in(text);
213 std::string tok;
214 while (in >> tok) {
215 try {
216 size_t used = 0;
217 out.push_back(std::stod(tok, &used));
218 if (used != tok.size()) {
219 throw std::invalid_argument(tok);
220 }
221 } catch (const std::exception &) {
222 throw std::invalid_argument("[Main] cell: '" + tok + "' is not a number");
223 }
224 }
225 if (!out.empty() && out.size() != 3 && out.size() != 9) {
226 throw std::invalid_argument(
227 "[Main] cell takes 3 numbers (a b c) or 9 (a 3x3 lattice), got " +
228 std::to_string(out.size()));
229 }
230 return out;
231}
232
233void set_config_cell(const std::vector<double> &values, bool pbc) {
234 if (!values.empty() && values.size() != 3 && values.size() != 9) {
235 throw std::invalid_argument("[Main] cell takes 3 or 9 numbers");
236 }
237 const std::lock_guard<std::mutex> g(format_mutex());
238 config_cell().values = values;
239 config_cell().pbc = pbc;
240}
241
242void set_default_vacuum(double angstrom) {
243 if (!(angstrom >= 0.0)) {
244 throw std::invalid_argument("[Main] default_vacuum must be >= 0");
245 }
246 const std::lock_guard<std::mutex> g(format_mutex());
247 config_cell().vacuum = angstrom;
248}
249
250double default_vacuum() noexcept { return config_cell().vacuum; }
251
252void publish_structure_input(std::string format, const std::string &cell,
253 bool pbc, double vacuum) {
254 const auto values = parse_cell_values(cell);
255 if (!(vacuum >= 0.0)) {
256 throw std::invalid_argument("[Main] default_vacuum must be >= 0");
257 }
258 set_structure_input_format(std::move(format));
259 set_config_cell(values, pbc);
260 set_default_vacuum(vacuum);
261}
262
263const std::string &last_cell_warning() noexcept { return g_last_cell_warning; }
264
265IoStatus inp2matter(Matter &m, const std::string &filename) {
266 if (is_chemfiles_path(filename)) {
267 return chemfiles2matter(m, filename);
268 }
269 const auto name = lower(fs::path(filename).filename().string());
270 if (name.ends_with(".convel") || name.ends_with(".convel.gz") ||
271 name.ends_with(".convel.zst")) {
272 return convel2matter(m, filename);
273 }
274 return con2matter(m, filename);
275}
276
277#ifdef WITH_CHEMFILES
278
279IoStatus chemfiles2matter(Matter &m, const std::string &filename,
280 const std::string &format) {
281 quiet_chemfiles();
282 try {
283 // chemfiles' cell-angle math divides by a zero length while building the
284 // default UnitCell (calc_angles_from_cell_matrix). eonclient arms FP
285 // traps; that invalid op is a continuable SIGFPE on Linux and a fatal
286 // SIGILL on Apple Silicon. External libraries run with soft IEEE, the
287 // same contract as LAMMPS and ASE.
288 const eonc::FPEGuard fpe;
289 chemfiles::Trajectory traj(filename, 'r',
290 format_for_path(filename, format));
291 if (traj.nsteps() == 0) {
292 EONC_LOG_ERROR("{} holds no frames", filename);
293 return IoStatus::ReadError;
294 }
295 const chemfiles::Frame frame = traj.read();
296
297 g_last_cell_warning.clear();
298 const auto &cell = frame.cell();
299 const bool file_has_cell = cell.shape() != chemfiles::UnitCell::INFINITE;
300 const auto n = static_cast<Eigen::Index>(frame.size());
301 m.resize(static_cast<long>(n));
302
303 AtomMatrix positions(n, 3);
304 VectorXd masses(n);
305 VectorXi atomic_nrs(n);
306 const auto &pos = frame.positions();
307 for (Eigen::Index i = 0; i < n; ++i) {
308 const auto &atom = frame[static_cast<size_t>(i)];
309 const auto z = atom.atomic_number();
310 if (!z) {
311 EONC_LOG_ERROR("{}: atom {} has type '{}', which is not an element",
312 filename, i, atom.type());
314 }
315 atomic_nrs(i) = static_cast<int>(*z);
316 masses(i) = atom.mass();
317 for (int k = 0; k < 3; ++k) {
318 positions(i, k) = pos[static_cast<size_t>(i)][k];
319 }
320 std::array<bool, 3> mask{false, false, false};
321 if (auto p = atom.get("fixed")) {
322 mask_from_property(*p, /*frozen_when_true=*/true, mask);
323 } else if (auto p = atom.get("move_mask")) {
324 mask_from_property(*p, /*frozen_when_true=*/false, mask);
325 }
326 m.setFixedMask(static_cast<long>(i), mask);
327 m.setAtomIndex(static_cast<long>(i), static_cast<std::int64_t>(i));
328 }
329 // chemfiles keeps file order, so the file-to-Matter map is the identity.
330 std::vector<long> identity(static_cast<size_t>(n));
331 for (Eigen::Index i = 0; i < n; ++i) {
332 identity[static_cast<size_t>(i)] = static_cast<long>(i);
333 }
334 m.setFileToMatter(std::move(identity));
335
336 Matrix3d box = Matrix3d::Zero();
337 bool periodic = true;
338 const ConfigCell cfg = [] {
339 const std::lock_guard<std::mutex> g(format_mutex());
340 return config_cell();
341 }();
342 if (file_has_cell) {
343 // chemfiles stores cell vectors as columns; Matter stores rows.
344 const auto cm = cell.matrix();
345 for (int i = 0; i < 3; ++i) {
346 for (int j = 0; j < 3; ++j) {
347 box(i, j) = cm[j][i];
348 }
349 }
350 } else if (!cfg.values.empty()) {
351 box = matrix_from_values(cfg.values);
352 periodic = cfg.pbc;
353 } else {
354 // Bounding box plus vacuum, shifted so every atom sits inside.
355 Eigen::RowVector3d lo = Eigen::RowVector3d::Zero();
356 Eigen::RowVector3d hi = Eigen::RowVector3d::Zero();
357 if (n > 0) {
358 lo = positions.colwise().minCoeff();
359 hi = positions.colwise().maxCoeff();
360 }
361 for (int k = 0; k < 3; ++k) {
362 box(k, k) = (hi(k) - lo(k)) + 2.0 * cfg.vacuum;
363 // A flat or single-atom axis still gets a positive length.
364 if (box(k, k) <= 0.0) {
365 box(k, k) = 1.0;
366 }
367 }
368 positions.rowwise() -= (lo - Eigen::RowVector3d::Constant(cfg.vacuum));
369 periodic = false;
370 g_last_cell_warning = std::format(
371 "WARNING: {} has no unit cell and [Main] cell is not set. Using a "
372 "non-periodic orthorhombic box of {:.3f} x {:.3f} x {:.3f} A "
373 "(atom bounding box plus {} A vacuum per side, [Main] "
374 "default_vacuum); atoms were shifted into it. Set [Main] cell and "
375 "[Main] pbc, or add a cell to the file, for a periodic system.",
376 filename, box(0, 0), box(1, 1), box(2, 2), cfg.vacuum);
377 EONC_LOG_WARNING("{}", g_last_cell_warning);
378 }
379 m.setCell(box);
380 if (!periodic) {
381 m.setPeriodic(false); // never force PBC onto an isolated-layout pot
382 }
383 m.setMasses(masses);
384 m.setAtomicNrs(atomic_nrs);
385 m.setPositions(positions);
386
387 // Frame::velocities() is set by formats that store velocities as a
388 // trajectory array. The XYZ reader does not (FormatMetadata::velocities
389 // is false): an extxyz `velo` column is an atom property of kind
390 // VECTOR3D, so read that when the frame has no velocity array.
391 AtomMatrix v(n, 3);
392 bool have_velocities = false;
393 if (const auto vel = frame.velocities()) {
394 have_velocities = true;
395 for (Eigen::Index i = 0; i < n; ++i) {
396 for (int k = 0; k < 3; ++k) {
397 v(i, k) = (*vel)[static_cast<size_t>(i)][k];
398 }
399 }
400 } else {
401 v.setZero();
402 for (Eigen::Index i = 0; i < n; ++i) {
403 const auto &atom = frame[static_cast<size_t>(i)];
404 const auto prop = atom.get("velo");
405 if (!prop || prop->kind() != chemfiles::Property::VECTOR3D) {
406 continue;
407 }
408 have_velocities = true;
409 const auto vec = prop->as_vector3d();
410 for (int k = 0; k < 3; ++k) {
411 v(i, k) = vec[static_cast<size_t>(k)];
412 }
413 }
414 }
415 if (have_velocities) {
416 m.setVelocities(v);
417 }
418 // resize/setPositions leave the potential dirty; no file forces here.
419 return IoStatus::Ok;
420 } catch (const std::exception &e) {
421 EONC_LOG_ERROR("Failed to read {} with chemfiles: {}", filename, e.what());
422 return IoStatus::ReadError;
423 }
424}
425
426#else // !WITH_CHEMFILES
427
428IoStatus chemfiles2matter(Matter &, const std::string &filename,
429 const std::string &) {
430 EONC_LOG_ERROR("Cannot read {}: this eonclient was built without chemfiles. "
431 "Install chemfiles-lib and reconfigure with "
432 "-Dwith_chemfiles=enabled, or convert the file to .con.",
433 filename);
435}
436
437#endif
438
439} // namespace eonc::io
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_DEBUG(...)
Definition EonLogger.h:310
#define EONC_LOG_ERROR(...)
Definition EonLogger.h:328
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322
void setFixedMask(long int atom, std::array< bool, 3 > mask)
Definition Matter.cpp:615
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
void setCell(const Matrix3d &newCell)
Definition Matter.cpp:347
void setPeriodic(bool periodic)
Definition Matter.h:341
void setAtomicNrs(const VectorXi &atmnrs)
Definition Matter.cpp:788
void setVelocities(const AtomMatrix &v)
Definition Matter.cpp:823
void setAtomIndex(long int atom, std::int64_t index)
Definition Matter.cpp:963
void resize(long int nAtoms)
Definition Matter.cpp:297
void setMasses(const VectorXd &massesIn)
Definition Matter.cpp:558
void setFileToMatter(std::vector< long > map)
Definition Matter.h:325
void set_structure_input_format(std::string fmt)
[Main] input_format: empty or "con" keeps readcon only.
IoStatus convel2matter(Matter &m, std::string filename)
IoStatus chemfiles2matter(Matter &, const std::string &filename, const std::string &)
IoStatus con2matter(Matter &m, std::string filename)
bool is_chemfiles_path(std::string_view filename)
True for structure paths routed to chemfiles: a known extension (xyz, extxyz, pdb,...
IoStatus inp2matter(Matter &m, const std::string &filename)
Input entry point: .con/.convel (and .gz/.zst) go to readcon, everything else goes to chemfiles.
std::vector< double > parse_cell_values(const std::string &text)
Parse "a b c" or nine numbers; throws std::invalid_argument.
const std::string & last_cell_warning() noexcept
Read the first frame of any chemfiles-supported file into Matter.
bool chemfiles_available() noexcept
True when this build links chemfiles (-Dwith_chemfiles found it).
void publish_structure_input(std::string format, const std::string &cell, bool pbc, double vacuum)
Publish [Main] input_format, cell, pbc, and default_vacuum to the process-wide readers.
IoStatus
Structured I/O result for the client surface (nanobind-friendly).
Definition ConFileIO.h:29
double default_vacuum() noexcept
const std::string & structure_input_format() noexcept
void set_config_cell(const std::vector< double > &values, bool pbc)
Fallback cell for foreign files that carry none ([Main] cell / pbc).
bool is_readcon_path(std::string_view filename)
True for paths readcon owns: .con, .convel and their .gz/.zst forms.
void set_default_vacuum(double angstrom)
Vacuum padding per side (Angstrom) for the bounding-box default cell.