Loading...
Searching...
No Matches
eonc::io Namespace Reference

Classes

struct  ConMetadataText
struct  ConMetadataValue

Enumerations

enum class  IoStatus : std::uint8_t {
  Ok = 0 , ReadError = 1 , WriteError = 2 , AppendError = 3 ,
  OpenError = 4 , InvalidArgument = 5
}
 Structured I/O result for the client surface (nanobind-friendly). More...

Functions

bool chemfiles_available () noexcept
 True when this build links chemfiles (-Dwith_chemfiles found it).
bool is_readcon_path (std::string_view filename)
 True for paths readcon owns: .con, .convel and their .gz/.zst forms.
bool is_chemfiles_path (std::string_view filename)
 True for structure paths routed to chemfiles: a known extension (xyz, extxyz, pdb, cif, mmcif, gro, data, lmp, mol2, sdf, vasp, xtc, trr, dcd, nc, arc, cml, cssr, mmtf, tng) or a POSCAR/CONTCAR name.
void set_structure_input_format (std::string fmt)
 [Main] input_format: empty or "con" keeps readcon only.
const std::string & structure_input_format () noexcept
std::vector< double > parse_cell_values (const std::string &text)
 Parse "a b c" or nine numbers; throws std::invalid_argument.
void set_config_cell (const std::vector< double > &values, bool pbc)
 Fallback cell for foreign files that carry none ([Main] cell / pbc).
void set_default_vacuum (double angstrom)
 Vacuum padding per side (Angstrom) for the bounding-box default cell.
double default_vacuum () noexcept
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.
const std::string & last_cell_warning () noexcept
 Read the first frame of any chemfiles-supported file into Matter.
IoStatus inp2matter (Matter &m, const std::string &filename)
 Input entry point: .con/.convel (and .gz/.zst) go to readcon, everything else goes to chemfiles.
IoStatus chemfiles2matter (Matter &, const std::string &filename, const std::string &)
readcon::ConFrame matterToConFrame (Matter &m, const ConFrameMetadata *metadata=nullptr)
 Build a single stamped ConFrame from Matter (same builder as matter2con).
void set_write_con_forces (bool enabled) noexcept
 Whether written .con frames carry "Forces of Component" sections.
bool write_con_forces () noexcept
ConFrameMetadata metadata_from_frame (const readcon::ConFrame &frame)
 Extract known frame-level fields from a parsed readcon frame.
std::pair< std::array< double, 3 >, std::array< double, 3 > > cell_to_lengths_angles (const Matter &m)
void resetConAppendState ()
 Drop the per-path bookkeeping that lets append-mode writes skip re-parsing frames this process wrote.
IoStatus matter2con (Matter &m, std::string filename, bool append=false, const ConFrameMetadata *metadata=nullptr)
 Append a frame to a .con, or truncate and write one frame.
IoStatus con2matter (Matter &m, std::string filename)
IoStatus con2matter (Matter &m, const readcon::ConFrame &frame, ConFrameMetadata *out_metadata)
IoStatus matter2convel (Matter &m, std::string filename)
IoStatus convel2matter (Matter &m, std::string filename)
IoStatus matter2xyz (Matter &m, std::string filename, bool append=false)
 Write one extended-XYZ frame: Lattice= cell and 17-digit coordinates.
IoStatus writeTibble (Matter &m, std::string filename)
 Debug table (positions, optional cached forces). Not a structure format.
std::vector< readcon::ConFrame > buildNebPathFrames (const std::vector< std::shared_ptr< Matter > > &path, const std::vector< ConFrameMetadata > &metadata_per_image)
 Build NEB band ConFrames without writing (clone builder path of writeNebPath).
IoStatus writeConFrames (std::string filename, const std::vector< readcon::ConFrame > &frames)
 Write already-built ConFrames to a multi-frame .con (temp or durable).
IoStatus writeNebPath (std::string filename, const std::vector< std::shared_ptr< Matter > > &path, const std::vector< ConFrameMetadata > &metadata_per_image)
 Write a full NEB path as one multi-frame .con using ConFrameBuilder::clone().
void mirror_con_corpus (const std::string &path)
 Copy a con file into the run readcon-db corpus when libreadcon_db loads.
bool readcon_db_mirror_ok ()
 True when the loaded rkrdb_open belongs to the linked readcon-db.
void readcon_db_mirror_reset ()
 Drop a cached load so a later call reads EON_READCON_DB_LIBRARY again.
const char * readcon_db_loaded_version ()
 Version of the loaded library. Empty when the load failed.
constexpr bool io_ok (IoStatus s) noexcept
constexpr const char * io_status_name (IoStatus s) noexcept
 Human-readable label for logging / bindings.

Enumeration Type Documentation

◆ IoStatus

enum class eonc::io::IoStatus : std::uint8_t
strong

Structured I/O result for the client surface (nanobind-friendly).

Prefer comparing to IoStatus::Ok rather than treating as bool.

Enumerator
Ok 
ReadError 
WriteError 
AppendError 
OpenError 
InvalidArgument 

Definition at line 29 of file ConFileIO.h.

29 : std::uint8_t {
30 Ok = 0,
31 ReadError = 1,
32 WriteError = 2,
33 AppendError = 3,
34 OpenError = 4,
36};

Function Documentation

◆ buildNebPathFrames()

std::vector< readcon::ConFrame > eonc::io::buildNebPathFrames ( const std::vector< std::shared_ptr< Matter > > & path,
const std::vector< ConFrameMetadata > & metadata_per_image )
nodiscard

Build NEB band ConFrames without writing (clone builder path of writeNebPath).

Empty vector on invalid input.

Parameters
pathimages, endpoints included
metadata_per_imageone record per image; length must equal path

Definition at line 894 of file ConFileIO.cpp.

895 {
896 std::vector<readcon::ConFrame> frames;
897 if (path.empty() || path.size() != metadata_per_image.size()) {
899 "buildNebPathFrames: path/metadata size mismatch (path={}, meta={})",
900 path.size(), metadata_per_image.size());
901 return frames;
902 }
903 for (const auto &img : path) {
904 if (!img) {
905 EONC_LOG_ERROR("buildNebPathFrames: null Matter in path");
906 return {};
907 }
908 }
909
910 Matter &template_m = *path.front();
912
913 std::vector<uint64_t> atom_ids;
914 std::array<std::string, 2> prebox;
915 std::array<std::string, 2> postbox;
916 collect_ids_headers(template_m, atom_ids, prebox, postbox);
917
918 frames.reserve(path.size());
919 try {
920 auto seed = seed_builder(template_m, prebox, postbox, atom_ids);
921 for (size_t i = 0; i < path.size(); ++i) {
922 Matter &img = *path[i];
924 if (img.numberOfAtoms() != template_m.numberOfAtoms()) {
926 "buildNebPathFrames: image {} atom count {} != template {}", i,
927 img.numberOfAtoms(), template_m.numberOfAtoms());
928 return {};
929 }
930 auto builder = seed.clone();
931 apply_frame_metadata(builder, &metadata_per_image[i]);
932 apply_geometry(builder, img, /*with_velocities=*/false,
933 &metadata_per_image[i]);
934 frames.push_back(builder.build());
935 }
936 } catch (const std::exception &e) {
937 EONC_LOG_ERROR("buildNebPathFrames failed: {}", e.what());
938 return {};
939 }
940 return frames;
941}
#define EONC_LOG_ERROR(...)
Definition EonLogger.h:328
void applyPeriodicBoundaryIfEnabled()
Apply MIC wrap when periodic boundaries are enabled (I/O path).
Definition Matter.h:351
long int numberOfAtoms() const
Definition Matter.cpp:343

◆ cell_to_lengths_angles()

std::pair< std::array< double, 3 >, std::array< double, 3 > > eonc::io::cell_to_lengths_angles ( const Matter & m)

Definition at line 512 of file ConFileIO.cpp.

512 {
513 const Matrix3d cell = m.getCell();
514 std::array<double, 3> lengths;
515 lengths[0] = cell.row(0).norm();
516 lengths[1] = cell.row(1).norm();
517 lengths[2] = cell.row(2).norm();
518 // CON header line 4 is alpha beta gamma:
519 // alpha = angle(b,c), beta = angle(a,c), gamma = angle(a,b).
520 std::array<double, 3> angles;
522 cell.row(1).dot(cell.row(2)), lengths[1] * lengths[2])) *
523 180.0 / eonc::helpers::pi;
525 cell.row(0).dot(cell.row(2)), lengths[0] * lengths[2])) *
526 180.0 / eonc::helpers::pi;
528 cell.row(0).dot(cell.row(1)), lengths[0] * lengths[1])) *
529 180.0 / eonc::helpers::pi;
530 return {lengths, angles};
531}
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Matrix3d getCell() const
Definition Matter.cpp:345
constexpr double pi
constexpr double safe_div(double num, double denom, double fallback=0.0)
Definition SafeMath.h:21
double safe_acos(double x)
Definition SafeMath.h:34

◆ chemfiles2matter()

IoStatus eonc::io::chemfiles2matter ( Matter & ,
const std::string & filename,
const std::string &  )
nodiscard

Definition at line 428 of file ChemfilesIO.cpp.

429 {
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}

◆ chemfiles_available()

bool eonc::io::chemfiles_available ( )
nodiscardnoexcept

True when this build links chemfiles (-Dwith_chemfiles found it).

Definition at line 168 of file ChemfilesIO.cpp.

168 {
169#ifdef WITH_CHEMFILES
170 return true;
171#else
172 return false;
173#endif
174}

◆ con2matter() [1/2]

IoStatus eonc::io::con2matter ( Matter & m,
const readcon::ConFrame & frame,
ConFrameMetadata * out_metadata )
nodiscard

Definition at line 621 of file ConFileIO.cpp.

622 {
623 try {
624 const auto &atoms = frame.atoms();
625 const auto &lengths = frame.cell();
626 const auto &angles_deg = frame.angles();
627 const auto &prebox = frame.prebox_header();
628 const auto &postbox = frame.postbox_header();
629
630 m.headerCon[0] = prebox[0] + "\n";
631 m.headerCon[1] = prebox[1] + "\n";
632 m.headerCon[3] = postbox[0] + "\n";
633 m.headerCon[4] = postbox[1] + "\n";
634
635 double angles[3] = {angles_deg[0], angles_deg[1], angles_deg[2]};
636 if (angles[0] == 90.0 && angles[1] == 90.0 && angles[2] == 90.0) {
637 Matrix3d cell = Matrix3d::Zero();
638 cell(0, 0) = lengths[0];
639 cell(1, 1) = lengths[1];
640 cell(2, 2) = lengths[2];
641 m.setCell(cell);
642 } else {
643 angles[0] *= eonc::helpers::pi / 180.0;
644 angles[1] *= eonc::helpers::pi / 180.0;
645 angles[2] *= eonc::helpers::pi / 180.0;
646 const double alpha = angles[0];
647 const double beta = angles[1];
648 const double gamma = angles[2];
649
650 Matrix3d cell = Matrix3d::Zero();
651 cell(0, 0) = 1.0;
652 cell(1, 0) = cos(gamma);
653 cell(1, 1) = sin(gamma);
654 cell(2, 0) = cos(beta);
655 cell(2, 1) = (cos(alpha) - cell(1, 0) * cell(2, 0)) / cell(1, 1);
656 cell(2, 2) = eonc::safemath::safe_sqrt(1.0 - pow(cell(2, 0), 2) -
657 pow(cell(2, 1), 2));
658
659 cell(0, 0) *= lengths[0];
660 cell(1, 0) *= lengths[1];
661 cell(1, 1) *= lengths[1];
662 cell(2, 0) *= lengths[2];
663 cell(2, 1) *= lengths[2];
664 cell(2, 2) *= lengths[2];
665 m.setCell(cell);
666 }
667 m.headerCon[2] =
668 std::format("{} {} {}\n", angles_deg[0], angles_deg[1], angles_deg[2]);
669
670 const auto n = static_cast<Eigen::Index>(atoms.size());
671 m.resize(static_cast<long>(atoms.size()));
672
673 // Undo the species grouping the .con format imposes, so an index into
674 // Matter addresses the same atom as the matching row of mode.dat.
675 const std::vector<size_t> order = matter_order(atoms);
676 std::vector<long> file_to_matter(static_cast<size_t>(n));
677 for (Eigen::Index i = 0; i < n; ++i) {
678 file_to_matter[order[static_cast<size_t>(i)]] = static_cast<long>(i);
679 }
680 m.setFileToMatter(std::move(file_to_matter));
681
682 AtomMatrix positions = AtomMatrix::Zero(n, 3);
683 AtomMatrix forces = AtomMatrix::Zero(n, 3);
684 AtomMatrix velocities = AtomMatrix::Zero(n, 3);
685 VectorXd masses = VectorXd::Zero(n);
686 VectorXi atomic_nrs = VectorXi::Zero(n);
687 bool any_force = false;
688 bool any_velocity = false;
689
690 for (Eigen::Index i = 0; i < n; ++i) {
691 const auto &atom = atoms[order[static_cast<size_t>(i)]];
692 positions(i, 0) = atom.x;
693 positions(i, 1) = atom.y;
694 positions(i, 2) = atom.z;
695 masses(i) = atom.mass;
696 atomic_nrs(i) = static_cast<int>(atom.atomic_number);
697 const auto fixed = atom.fixed_mask();
698 m.setFixedMask(static_cast<long>(i), {fixed[0], fixed[1], fixed[2]});
699 m.setAtomIndex(static_cast<long>(i),
700 static_cast<std::int64_t>(atom.atom_id));
701
702 if (auto vel = atom.velocity()) {
703 any_velocity = true;
704 velocities(i, 0) = (*vel)[0];
705 velocities(i, 1) = (*vel)[1];
706 velocities(i, 2) = (*vel)[2];
707 }
708 if (auto force = atom.force()) {
709 any_force = true;
710 forces(i, 0) = (*force)[0];
711 forces(i, 1) = (*force)[1];
712 forces(i, 2) = (*force)[2];
713 }
714 }
715
716 m.setMasses(masses);
717 m.setAtomicNrs(atomic_nrs);
718 m.setPositions(positions);
719
720 if (any_velocity || frame.has_velocities()) {
721 m.setVelocities(velocities);
722 }
723
724 const auto meta = metadata_from_frame(frame);
725 if (out_metadata != nullptr) {
726 *out_metadata = meta;
727 }
728
729 // Trust file energy+forces only when both are present. Energy-only must not
730 // mark the pot clean with a zero force matrix (optimizer footgun). Prefer
731 // writing raw forces (friend) so fixed-atom components survive RT; then
732 // mark clean without setComputedPotential's net-force adjustment on zeros.
733 const bool has_force_section = any_force || frame.has_forces();
734 if (meta.energy && has_force_section) {
735 m.restoreFileForces(forces, true, *meta.energy);
736 } else if (has_force_section) {
737 m.restoreFileForces(forces, false, 0.0);
738 } else {
739 // Classic geometry-only files: always recompute pot (main-era behavior).
740 m.recomputePotential = true;
741 }
742
743 // setPositions already applied PBC when enabled; no second wrap here.
744 return IoStatus::Ok;
745 } catch (const std::exception &e) {
746 EONC_LOG_ERROR("Failed to convert frame to matter: {}", e.what());
747 return IoStatus::ReadError;
748 }
749}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
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 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 restoreFileForces(const AtomMatrix &fileForces, bool trustEnergy, double energy)
Write .con forces without the fixed-atom mask setForces applies.
Definition Matter.cpp:967
bool recomputePotential
Definition Matter.h:375
void setMasses(const VectorXd &massesIn)
Definition Matter.cpp:558
std::array< std::string, 5 > headerCon
Definition Matter.h:381
void setFileToMatter(std::vector< long > map)
Definition Matter.h:325
ConFrameMetadata metadata_from_frame(const readcon::ConFrame &frame)
Extract known frame-level fields from a parsed readcon frame.
double safe_sqrt(double x)
Definition SafeMath.h:38

◆ con2matter() [2/2]

IoStatus eonc::io::con2matter ( Matter & m,
std::string filename )
nodiscard

Definition at line 603 of file ConFileIO.cpp.

603 {
604 if (auto foreign = foreign_input(filename)) {
605 return chemfiles2matter(m, *foreign);
606 }
607 filename = ensure_extension(std::move(filename), ".con");
608 try {
609 auto frame = readcon::read_first_frame(filename);
610 const IoStatus status = con2matter(m, frame, nullptr);
611 if (io_ok(status)) {
612 mirror_con_corpus(filename);
613 }
614 return status;
615 } catch (const std::exception &e) {
616 EONC_LOG_ERROR("Failed to read {}: {}", filename, e.what());
617 return IoStatus::ReadError;
618 }
619}
IoStatus chemfiles2matter(Matter &, const std::string &filename, const std::string &)
IoStatus con2matter(Matter &m, std::string filename)
IoStatus
Structured I/O result for the client surface (nanobind-friendly).
Definition ConFileIO.h:29
void mirror_con_corpus(const std::string &path)
Copy a con file into the run readcon-db corpus when libreadcon_db loads.
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38

◆ convel2matter()

IoStatus eonc::io::convel2matter ( Matter & m,
std::string filename )
nodiscard

Definition at line 771 of file ConFileIO.cpp.

771 {
772 if (auto foreign = foreign_input(filename)) {
773 return chemfiles2matter(m, *foreign);
774 }
775 filename = ensure_extension(std::move(filename), ".convel");
776 try {
777 auto frame = readcon::read_first_frame(filename);
778 const IoStatus status = con2matter(m, frame, nullptr);
779 if (io_ok(status)) {
780 mirror_con_corpus(filename);
781 }
782 return status;
783 } catch (const std::exception &e) {
784 EONC_LOG_ERROR("Failed to read convel {}: {}", filename, e.what());
785 return IoStatus::ReadError;
786 }
787}

◆ default_vacuum()

double eonc::io::default_vacuum ( )
nodiscardnoexcept

Definition at line 250 of file ChemfilesIO.cpp.

250{ return config_cell().vacuum; }

◆ inp2matter()

IoStatus eonc::io::inp2matter ( Matter & m,
const std::string & filename )
nodiscard

Input entry point: .con/.convel (and .gz/.zst) go to readcon, everything else goes to chemfiles.

An unknown extension is treated as .con, as before.

Definition at line 265 of file ChemfilesIO.cpp.

265 {
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}
IoStatus convel2matter(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,...

◆ io_ok()

bool eonc::io::io_ok ( IoStatus s)
nodiscardconstexprnoexcept

Definition at line 38 of file ConFileIO.h.

38 {
39 return s == IoStatus::Ok;
40}

◆ io_status_name()

const char * eonc::io::io_status_name ( IoStatus s)
nodiscardconstexprnoexcept

Human-readable label for logging / bindings.

Definition at line 43 of file ConFileIO.h.

43 {
44 switch (s) {
45 case IoStatus::Ok:
46 return "ok";
48 return "read_error";
50 return "write_error";
52 return "append_error";
54 return "open_error";
56 return "invalid_argument";
57 }
58 return "unknown";
59}

◆ is_chemfiles_path()

bool eonc::io::is_chemfiles_path ( std::string_view filename)
nodiscard

True for structure paths routed to chemfiles: a known extension (xyz, extxyz, pdb, cif, mmcif, gro, data, lmp, mol2, sdf, vasp, xtc, trr, dcd, nc, arc, cml, cssr, mmtf, tng) or a POSCAR/CONTCAR name.

Other dotted names keep the classic meaning and get .con appended.

Definition at line 188 of file ChemfilesIO.cpp.

188 {
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}

◆ is_readcon_path()

bool eonc::io::is_readcon_path ( std::string_view filename)
nodiscard

True for paths readcon owns: .con, .convel and their .gz/.zst forms.

Definition at line 176 of file ChemfilesIO.cpp.

176 {
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}

◆ last_cell_warning()

const std::string & eonc::io::last_cell_warning ( )
nodiscardnoexcept

Read the first frame of any chemfiles-supported file into Matter.

Maps positions, atomic numbers, masses and velocities when present. Fixed atoms come from per-atom extxyz properties: fixed (true = frozen) or ASE's move_mask (true = free), as a bool, a number, or a 3-vector for per-axis masks.

Cell precedence: the file's own cell (periodic); else [Main] cell with [Main] pbc; else a loud WARNING naming the file and both keys, and an orthorhombic, non-periodic box spanning the atoms plus [Main] default_vacuum (10 Angstrom) on every side.

format overrides chemfiles' extension guess ("" = guess). Text of the last default-cell warning on this thread ("" when the last read needed none). Lets tests and callers surface it.

Definition at line 263 of file ChemfilesIO.cpp.

263{ return g_last_cell_warning; }

◆ matter2con()

IoStatus eonc::io::matter2con ( Matter & m,
std::string filename,
bool append = false,
const ConFrameMetadata * metadata = nullptr )
nodiscard

Append a frame to a .con, or truncate and write one frame.

With append, an uncompressed target is extended in place through readcon::ConFrameWriter OpenMode::Append, so N appends cost N frame writes rather than N(N+1)/2. Earlier frames are never re-serialized, and the writer is flushed before the call returns, so every intermediate state on disk is a complete multi-frame .con.

A target that eOn did not write, or that changed size or mtime since eOn last wrote it, is parsed once before anything is added; an unparseable target yields IoStatus::AppendError with its bytes untouched. Gzip and zstd targets keep the read-all-and-rewrite path because a compressed member cannot be extended in place.

Definition at line 538 of file ConFileIO.cpp.

539 {
540 filename = ensure_extension(std::move(filename), ".con");
541
543
544 const fs::path path(filename);
545 const auto compression =
546 readcon::ConFrameWriter::compression_from_extension(path);
547 const bool streamable =
548 compression == readcon::ConFrameWriter::Compression::None;
549
550 // The lock covers the stamp table and the read-then-extend window on one
551 // path. Nothing under it evaluates a potential: frame_from_matter reads
552 // cached energy and forces only while the pot is clean.
553 const std::lock_guard<std::mutex> guard(append_mutex());
554 const auto key = append_key(path);
555 const bool exists = fs::exists(path);
556 const bool concatenate = append && exists && streamable;
557
558 // ConFrame is move-only (no default ctor), so frames carries the new frame
559 // either way. OpenMode::Append refuses gzip and zstd, and a compressed
560 // member cannot be extended in place. Those targets keep the whole-file
561 // rewrite.
562 std::vector<readcon::ConFrame> frames;
563 if (append && exists && !streamable) {
564 try {
565 // Prefer read_all_frames (single ownership hand-off) over the iterator
566 // path for append rewrite; simpler lifetime for ASAN/CI envs.
567 frames = readcon::read_all_frames(path);
568 } catch (const std::exception &e) {
569 EONC_LOG_ERROR("Failed to append to {}: {}", filename, e.what());
571 }
572 } else if (concatenate && !tail_is_ours(key, path)) {
573 // Refuse to extend a file eOn cannot parse, matching the rewrite path:
574 // the target keeps its bytes and the caller sees AppendError. Frames this
575 // process wrote and nobody touched since need no such check.
576 try {
577 [[maybe_unused]] const auto existing = readcon::read_all_frames(path);
578 } catch (const std::exception &e) {
579 EONC_LOG_ERROR("Failed to append to {}: {}", filename, e.what());
581 }
582 }
583 try {
584 frames.push_back(frame_from_matter(m, metadata, /*with_velocities=*/false));
585 } catch (const std::exception &e) {
586 EONC_LOG_ERROR("Failed to build frame for {}: {}", filename, e.what());
588 }
589
590 const auto status = concatenate ? append_frames(path, frames, kConPrecision)
591 : write_frames(path, frames, kConPrecision);
592 if (io_ok(status)) {
593 remember_stamp(key, path);
594 if (!concatenate) {
595 mirror_con_corpus(path.string());
596 }
597 } else {
598 append_stamps().erase(key);
599 }
600 return status;
601}
void applyPeriodicBoundaryIfEnabled()
Apply MIC wrap when periodic boundaries are enabled (I/O path).
Definition Matter.h:351

◆ matter2convel()

IoStatus eonc::io::matter2convel ( Matter & m,
std::string filename )
nodiscard

Definition at line 751 of file ConFileIO.cpp.

751 {
752 filename = ensure_extension(std::move(filename), ".convel");
753
755
756 try {
757 auto frame = frame_from_matter(m, nullptr, /*with_velocities=*/true);
758 std::vector<readcon::ConFrame> frames;
759 frames.push_back(std::move(frame));
760 const IoStatus status = write_frames(filename, frames, kConvelPrecision);
761 if (io_ok(status)) {
762 mirror_con_corpus(filename);
763 }
764 return status;
765 } catch (const std::exception &e) {
766 EONC_LOG_ERROR("Failed to write convel {}: {}", filename, e.what());
768 }
769}

◆ matter2xyz()

IoStatus eonc::io::matter2xyz ( Matter & m,
std::string filename,
bool append = false )
nodiscard

Write one extended-XYZ frame: Lattice= cell and 17-digit coordinates.

append concatenates another frame. A tail that does not end in a newline gets one before the next atom count, so the frames stay separate. A target whose last frame has a different atom count yields InvalidArgument and is left unchanged. Chemfiles in readcon is ingress (XYZ/PDB/GRO into ConFrame), not XYZ egress, so this writer emits the Lattice= comment ASE and chemfiles already read.

Definition at line 789 of file ConFileIO.cpp.

789 {
790 filename = ensure_extension(std::move(filename), ".xyz");
791
793 const long n = m.numberOfAtoms();
794
795 if (append && fs::exists(filename)) {
796 std::error_code ec;
797 const auto sz = fs::file_size(filename, ec);
798 if (!ec && sz > 0) {
799 const auto prev = last_xyz_natoms(filename);
800 if (!prev) {
801 EONC_LOG_ERROR("matter2xyz: cannot parse existing {}", filename);
803 }
804 if (*prev != n) {
806 "matter2xyz: append atom count {} != last frame {} in {}", n, *prev,
807 filename);
809 }
810 }
811 }
812
813 std::ofstream out;
814 out.open(filename,
815 append ? (std::ios::out | std::ios::app | std::ios::binary)
816 : (std::ios::out | std::ios::trunc | std::ios::binary));
817 if (!out) {
818 EONC_LOG_ERROR("matter2xyz: cannot open {}", filename);
819 return IoStatus::OpenError;
820 }
821
822 // A frame header must start its own line. eOn's own frames end in a
823 // newline; a hand-written or foreign tail may not.
824 if (append && !ends_with_newline(filename)) {
825 out.put('\n');
826 }
827
828 const Matrix3d cell = m.getCell();
829 out << std::format(
830 "{}\nLattice=\"{:.17g} {:.17g} {:.17g} {:.17g} {:.17g} {:.17g} "
831 "{:.17g} {:.17g} {:.17g}\" Properties=species:S:1:pos:R:3 Generated "
832 "by eOn\n",
833 n, cell(0, 0), cell(0, 1), cell(0, 2), cell(1, 0), cell(1, 1), cell(1, 2),
834 cell(2, 0), cell(2, 1), cell(2, 2));
835 const AtomMatrix pos = m.getPositions();
836 for (long i = 0; i < n; ++i) {
837 out << std::format("{}\t{:.17g}\t{:.17g}\t{:.17g}\n",
838 symbol_for_z(m.getAtomicNr(i)), pos(i, 0), pos(i, 1),
839 pos(i, 2));
840 }
841 // Close before testing: the destructor's flush is where a full disk or a
842 // short write surfaces, and by then the state is gone.
843 out.close();
844 if (!out) {
845 EONC_LOG_ERROR("matter2xyz: failed to write {}", filename);
847 }
848 return IoStatus::Ok;
849}
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
long int numberOfAtoms() const
Definition Matter.cpp:343
long getAtomicNr(long int atom) const
Definition Matter.cpp:565

◆ matterToConFrame()

readcon::ConFrame eonc::io::matterToConFrame ( Matter & m,
const ConFrameMetadata * metadata = nullptr )
nodiscard

Build a single stamped ConFrame from Matter (same builder as matter2con).

Does not write to disk.

Definition at line 482 of file ConFileIO.cpp.

483 {
484 return frame_from_matter(m, metadata, /*with_velocities=*/false);
485}

◆ metadata_from_frame()

ConFrameMetadata eonc::io::metadata_from_frame ( const readcon::ConFrame & frame)

Extract known frame-level fields from a parsed readcon frame.

Definition at line 495 of file ConFileIO.cpp.

495 {
496 ConFrameMetadata meta;
497 meta.energy = frame.energy_opt();
498 meta.frame_index = frame.frame_index_opt();
499 meta.time = frame.time_opt();
500 meta.timestep = frame.timestep_opt();
501 meta.neb_bead = frame.neb_bead_opt();
502 meta.neb_band = frame.neb_band_opt();
503 meta.potential_type = frame.potential_type();
504 const auto json = frame.metadata_json();
505 if (!json.empty() && json != "{}") {
506 meta.raw_json = json;
507 }
508 return meta;
509}
nlohmann::json json
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::optional< uint64_t > neb_band
Definition ConFileIO.h:77
std::optional< double > energy
Definition ConFileIO.h:73
std::optional< double > timestep
Definition ConFileIO.h:75
std::optional< double > time
Definition ConFileIO.h:74
std::optional< std::string > raw_json
Definition ConFileIO.h:81
std::optional< std::string > potential_type
Definition ConFileIO.h:78
std::optional< uint64_t > neb_bead
Definition ConFileIO.h:76

◆ mirror_con_corpus()

void eonc::io::mirror_con_corpus ( const std::string & path)

Copy a con file into the run readcon-db corpus when libreadcon_db loads.

Failure to load the library or to insert the blob does not change IoStatus.

Definition at line 251 of file ReadconDbMirror.cpp.

251 {
252 namespace fs = std::filesystem;
253 std::error_code ec;
254 if (!fs::is_regular_file(path, ec) || ec) {
255 return;
256 }
257 std::ifstream in(path);
258 if (!in) {
259 return;
260 }
261 std::ostringstream buf;
262 buf << in.rdbuf();
263 const std::string text = buf.str();
264 if (text.find_first_not_of(" \t\r\n") == std::string::npos) {
265 return;
266 }
267 fs::path canonical = fs::weakly_canonical(path, ec);
268 if (ec) {
269 canonical = fs::absolute(path);
270 }
271 const std::string resolved = canonical.string();
272 const auto corpus = corpus_dir(canonical);
273 if (!corpus) {
274 return;
275 }
276 const std::size_t id = corpus_handle(*corpus);
277 if (id == static_cast<std::size_t>(-1)) {
278 return;
279 }
280 const std::uint64_t tid = fnv1a(resolved + '\0' + text);
281 std::uint32_t nframes = 0;
282 api().append_str(id, tid, text.c_str(), resolved.c_str(), &nframes);
283}

◆ parse_cell_values()

std::vector< double > eonc::io::parse_cell_values ( const std::string & text)
nodiscard

Parse "a b c" or nine numbers; throws std::invalid_argument.

Definition at line 210 of file ChemfilesIO.cpp.

210 {
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}

◆ publish_structure_input()

void eonc::io::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.

Structure reads do not carry a Parameters object. Throws std::invalid_argument before changing any reader when cell is not empty, 3, or 9 numbers, or when default_vacuum is negative. "con" clears the format, as set_structure_input_format does.

Definition at line 252 of file ChemfilesIO.cpp.

253 {
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}
void set_structure_input_format(std::string fmt)
[Main] input_format: empty or "con" keeps readcon only.
std::vector< double > parse_cell_values(const std::string &text)
Parse "a b c" or nine numbers; throws std::invalid_argument.
void set_config_cell(const std::vector< double > &values, bool pbc)
Fallback cell for foreign files that carry none ([Main] cell / pbc).
void set_default_vacuum(double angstrom)
Vacuum padding per side (Angstrom) for the bounding-box default cell.

◆ readcon_db_loaded_version()

const char * eonc::io::readcon_db_loaded_version ( )

Version of the loaded library. Empty when the load failed.

Definition at line 292 of file ReadconDbMirror.cpp.

292 {
293 if (!readcon_db_mirror_ok()) {
294 return "";
295 }
297}
#define EON_READCON_DB_VERSION
bool readcon_db_mirror_ok()
True when the loaded rkrdb_open belongs to the linked readcon-db.

◆ readcon_db_mirror_ok()

bool eonc::io::readcon_db_mirror_ok ( )

True when the loaded rkrdb_open belongs to the linked readcon-db.

A missing library returns false and does not change IoStatus.

Definition at line 285 of file ReadconDbMirror.cpp.

285 {
286 const Api &fns = api();
287 return !fns.missing && fns.open != nullptr && fns.append_str != nullptr;
288}

◆ readcon_db_mirror_reset()

void eonc::io::readcon_db_mirror_reset ( )

Drop a cached load so a later call reads EON_READCON_DB_LIBRARY again.

Definition at line 290 of file ReadconDbMirror.cpp.

290{ mirror_epoch()++; }

◆ resetConAppendState()

void eonc::io::resetConAppendState ( )

Drop the per-path bookkeeping that lets append-mode writes skip re-parsing frames this process wrote.

Appends already re-parse a target whose size or mtime moved, so this only matters when a file is replaced with different content of the same size inside one filesystem timestamp tick.

Definition at line 533 of file ConFileIO.cpp.

533 {
534 const std::lock_guard<std::mutex> guard(append_mutex());
535 append_stamps().clear();
536}

◆ set_config_cell()

void eonc::io::set_config_cell ( const std::vector< double > & values,
bool pbc )

Fallback cell for foreign files that carry none ([Main] cell / pbc).

values holds 3 numbers (orthorhombic a b c) or 9 (row-major lattice, one vector per row). Empty clears it. Throws std::invalid_argument on any other count.

Definition at line 233 of file ChemfilesIO.cpp.

233 {
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}

◆ set_default_vacuum()

void eonc::io::set_default_vacuum ( double angstrom)

Vacuum padding per side (Angstrom) for the bounding-box default cell.

Definition at line 242 of file ChemfilesIO.cpp.

242 {
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}

◆ set_structure_input_format()

void eonc::io::set_structure_input_format ( std::string fmt)

[Main] input_format: empty or "con" keeps readcon only.

Any other value (xyz, pdb, cif, ...) makes a request for "pos.con" read "pos.<fmt>" when that file exists, so jobs that name .con inputs start from any format. Output stays .con only.

Definition at line 202 of file ChemfilesIO.cpp.

202 {
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}

◆ set_write_con_forces()

void eonc::io::set_write_con_forces ( bool enabled)
noexcept

Whether written .con frames carry "Forces of Component" sections.

Force sections enable force+energy co-loading on re-read (warm NEB restarts without re-evaluating the potential) but are not part of the classic con layout: external readers such as ASE's eon parser reject frames that carry them. Off unless [Main] write_con_forces enables it. A ConFrameMetadata.write_con_forces value, then the Matter Parameters field, override this process-wide flag for a single write. Reading force-bearing frames is always supported regardless of this flag.

Definition at line 487 of file ConFileIO.cpp.

487 {
488 g_write_con_forces.store(enabled, std::memory_order_relaxed);
489}

◆ structure_input_format()

const std::string & eonc::io::structure_input_format ( )
nodiscardnoexcept

Definition at line 208 of file ChemfilesIO.cpp.

208{ return input_fmt(); }

◆ write_con_forces()

bool eonc::io::write_con_forces ( )
nodiscardnoexcept

Definition at line 491 of file ConFileIO.cpp.

491 {
492 return g_write_con_forces.load(std::memory_order_relaxed);
493}

◆ writeConFrames()

IoStatus eonc::io::writeConFrames ( std::string filename,
const std::vector< readcon::ConFrame > & frames )
nodiscard

Write already-built ConFrames to a multi-frame .con (temp or durable).

Definition at line 943 of file ConFileIO.cpp.

944 {
945 if (frames.empty()) {
947 }
948 filename = ensure_extension(std::move(filename), ".con");
949 const fs::path path(filename);
950 const std::lock_guard<std::mutex> guard(append_mutex());
951 const auto key = append_key(path);
952 const auto status = write_frames(path, frames, kConPrecision);
953 if (io_ok(status)) {
954 remember_stamp(key, path);
955 mirror_con_corpus(path.string());
956 } else {
957 append_stamps().erase(key);
958 }
959 return status;
960}

◆ writeNebPath()

IoStatus eonc::io::writeNebPath ( std::string filename,
const std::vector< std::shared_ptr< Matter > > & path,
const std::vector< ConFrameMetadata > & metadata_per_image )
nodiscard

Write a full NEB path as one multi-frame .con using ConFrameBuilder::clone().

Seeds identity (symbols/fixed/mass/id/cell headers) from path[0] only, then for each image clones that template and bulk-updates positions/forces + metadata. Images must share atom count and topology with path[0] (standard NEB band invariant); heterogeneous multi-frame movies should not use this. Avoids re-reading the output file per image (legacy append path).

Parameters
filenameoutput path
pathlength must be numImages+2 (endpoints included)
metadata_per_imagelength must equal path.size()

Definition at line 962 of file ConFileIO.cpp.

964 {
965 auto frames = buildNebPathFrames(path, metadata_per_image);
966 if (frames.empty()) {
968 }
969 return writeConFrames(std::move(filename), frames);
970}
IoStatus writeConFrames(std::string filename, const std::vector< readcon::ConFrame > &frames)
Write already-built ConFrames to a multi-frame .con (temp or durable).
std::vector< readcon::ConFrame > buildNebPathFrames(const std::vector< std::shared_ptr< Matter > > &path, const std::vector< ConFrameMetadata > &metadata_per_image)
Build NEB band ConFrames without writing (clone builder path of writeNebPath).

◆ writeTibble()

IoStatus eonc::io::writeTibble ( Matter & m,
std::string fname )
nodiscard

Debug table (positions, optional cached forces). Not a structure format.

Definition at line 851 of file ConFileIO.cpp.

851 {
852 // Debug table, not a structure format. getForces()/getPotentialEnergy()
853 // run computePotential() on a dirty pot, which would charge a dump to
854 // the force-call count in results.dat. Cached values only; the header
855 // drops the columns it cannot fill. atmID is the CON column-5 id.
856 const bool have_forces = !m.needsForceUpdate();
857 if (!have_forces) {
859 "writeTibble: pot is dirty, {} omits the force and energy columns",
860 fname);
861 }
862 const AtomMatrix pos = m.getPositions();
863 std::ofstream out(fname);
864 if (!out) {
865 EONC_LOG_ERROR("writeTibble: cannot open {}", fname);
866 return IoStatus::OpenError;
867 }
868 out << (have_forces ? "x y z fx fy fz energy mass symbol atmID fixed\n"
869 : "x y z mass symbol atmID fixed\n");
870 const AtomMatrix fSys = have_forces ? m.getForces() : AtomMatrix();
871 const double eSys = have_forces ? m.getPotentialEnergy() : 0.0;
872 for (long idx = 0; idx < m.numberOfAtoms(); ++idx) {
873 out << std::format("{} {} {}", pos(idx, 0), pos(idx, 1), pos(idx, 2));
874 if (have_forces) {
875 out << std::format(" {} {} {} {}", fSys(idx, 0), fSys(idx, 1),
876 fSys(idx, 2), eSys);
877 }
878 const auto mask = m.getFixedMask(idx);
879 const int fixed_bits =
880 (mask[0] ? 1 : 0) | (mask[1] ? 2 : 0) | (mask[2] ? 4 : 0);
881 out << std::format(" {} {} {} {}\n", m.getMass(idx),
882 symbol_for_z(m.getAtomicNr(idx)), m.getAtomIndex(idx),
883 fixed_bits);
884 }
885 out.close();
886 if (!out) {
887 EONC_LOG_ERROR("writeTibble: failed to write {}", fname);
889 }
890 return IoStatus::Ok;
891}
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322
double getMass(long int atom) const
Definition Matter.cpp:548
double getPotentialEnergy() const
Definition Matter.cpp:624
bool needsForceUpdate() const
Whether forces need recomputation (positions or surface epoch changed).
Definition Matter.h:220
std::array< bool, 3 > getFixedMask(long int atom) const
Per-axis CON column-4 mask (bit0=x, bit1=y, bit2=z).
Definition Matter.cpp:590
std::int64_t getAtomIndex(long int atom) const
.con column-5 index (pre-grouping); public for I/O / bindings.
Definition Matter.cpp:959
const AtomMatrix & getForces() const
Definition Matter.cpp:482