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

RAII resource manager for the ARTn C library with global synchronization. More...

Namespaces

namespace  config
namespace  detail
namespace  dynlib
 Cross-platform dynamic library loading abstraction.
namespace  EpiCenters
namespace  exact
namespace  geometry
namespace  helpers
namespace  io
namespace  log
namespace  neb
namespace  pairhess
namespace  params_ssot
namespace  pathintegral
namespace  pbc
namespace  piqtst
namespace  pot
namespace  potential_owner
namespace  Prefactor
namespace  rng
namespace  rpc
namespace  safemath
namespace  tunneling
namespace  xtsci_eindir

Classes

struct  ams_options_t
struct  artn_options_t
class  ARTnResource
class  ARTnSaddleSearch
 Saddle search method using the Activation-Relaxation Technique nouveau. More...
struct  ase_nwchem_options_t
struct  ase_orca_options_t
class  AtomicGPDimer
struct  basin_hopping_options_t
class  BasinHoppingJob
class  BasinHoppingSaddleSearch
struct  bgsd_options_t
class  BGSDObjectiveFunction
class  BiasedGradientSquaredDescent
class  BondBoost
 Functionality relying on the conjugate gradients algorithm. More...
struct  CalculatorGroupUse
 How a job used its calculator groups: the seconds each group spent inside engine calls, the systems it evaluated, and the driver's wall time inside grouped requests. More...
class  CancelToken
 Shared flag. Copies observe the same request. More...
struct  catlearn_options_t
class  CollectiveIDPPObjectiveFunction
class  ConjugateGradients
 Decleration of the Conjugate Gradients optimizer. More...
struct  constants_t
struct  CutoffPair
class  Davidson
 Davidson method for the lowest Hessian curvature mode (min-mode). More...
struct  davidson_options_t
struct  debug_options_t
struct  DecodedDiv
struct  dftd_options_t
class  Dimer
 Classic dimer method to find the lowest curvature mode. More...
struct  dimer_options_t
class  DimerModeLostException
class  DimerModeRestoredException
struct  DimerRotationResult
 Result of a non-classical dimer rotation backend (mode estimate only). More...
class  Dynamics
struct  dynamics_options_t
struct  DynamicsConfig
 Configuration extracted from Parameters for Dynamics. More...
class  DynamicsJob
class  DynamicsSaddleSearch
struct  expr_options_t
class  FiniteDifferenceJob
class  FIRE
class  ForceCallTimer
 RAII wrapper for tracking force calls over a scope. More...
class  FPEGuard
class  FPEHandler
class  GleThermostat
 Colored-noise (generalized Langevin) thermostat. More...
struct  global_optimization_options_t
class  GlobalOptimization
class  GlobalOptimizationJob
struct  gp_surrogate_options_t
struct  gpr_dimer_options_t
class  GPSurrogateJob
class  GroupSchedule
 Which calculator group evaluates which system. More...
class  Hessian
struct  hessian_options_t
class  HessianJob
struct  HessianRangeOf
 Reported Hessian range for one rgpot kernel type. More...
struct  HessianRangeOf< rgpot::fortranpots::CuH2Pot >
 Cu-H2 EAM. More...
struct  HessianRangeOf< rgpot::fortranpots::EAMAlPot >
 Fortran EAM aluminium. More...
struct  HessianRangeOf< rgpot::fortranpots::EDIPPot >
 EDIP. More...
struct  HessianRangeOf< rgpot::fortranpots::FeHePot >
 Fe-He. More...
struct  HessianRangeOf< rgpot::fortranpots::LenoskyPot >
 Lenosky silicon. More...
struct  HessianRangeOf< rgpot::fortranpots::SWPot >
 Stillinger-Weber. More...
struct  HessianRangeOf< rgpot::fortranpots::TersoffPot >
 Tersoff. More...
struct  HessianRangeOf< rgpot::fortranpots::WaterHPot >
 potH-H2O. More...
struct  HessianRangeOf< rgpot::LJClusterPot >
struct  HessianRangeOf< rgpot::LJPot >
struct  HessianRangeOf< rgpot::MorsePot >
struct  HessianRangeOf< rgpot::ZBLPot >
 ZBL is a pair potential. More...
class  HostSurfacePotential
class  Hyperdynamics
struct  hyperdynamics_options_t
class  IARTnResource
class  IDPPObjectiveFunction
class  IIRAResource
class  ILammpsLoader
class  IMetatomicLoader
class  ImprovedDimer
struct  instanton_options_t
class  InstantonJob
 Ring-polymer instanton ([Instanton]): the tunnelling splitting between two minima beyond one-dimensional WKB (mode splitting), or the thermal rate through a saddle (mode rate): the ring below the crossover temperature, and the parabolic barrier factor times quantum harmonic transition-state theory above it. More...
class  IPluginLoader
class  IPotRegistry
struct  ira_options_t
class  IRACompare
 C++ wrapper for the IRA (Iterative Rotations and Assignments) library. More...
class  IRAResource
struct  IrcBranch
 Accepted points of one branch of the intrinsic reaction coordinate (IRC), in order away from the saddle. More...
struct  IrcPath
 Both branches of the IRC. More...
class  Job
 Declaration of job class. More...
class  JobCancelled
 Cooperative stop. Loops poll and throw; they do not abort the process. More...
struct  JobResultEnvelope
 In-memory JobResult scalars. More...
struct  JobResultProvenance
 Optimizer, xtsci, eindir, and rgpot identity carried on a JobResult. More...
class  LammpsLoader
class  Lanczos
struct  lanczos_options_t
class  LBFGS
class  LORRotation
class  LowestEigenmode
 Base for eigenmode solvers. More...
struct  main_options_t
class  Matter
struct  metatomic_options_t
class  MetatomicDynPot
class  MetatomicLoader
class  MinimizationJob
class  MinModeObjectiveFunction
class  MinModeSaddleSearch
struct  monte_carlo_options_t
class  MonteCarlo
class  MonteCarloJob
struct  mopac_options_t
struct  neb_options_t
class  NEBObjectiveFunction
class  NudgedElasticBand
class  NudgedElasticBandJob
class  ObjectiveFunction
struct  oh_tst_options_t
class  OHTSTJob
 Optimized hyperplanar transition state theory (OH-TST). More...
class  Optimizer
 Abstract base of the structure optimizers. More...
struct  optimizer_options_t
struct  OptimizerConfig
 Declaration of the optimizer class. More...
struct  parallel_replica_options_t
class  ParallelReplicaJob
class  Parameters
struct  ParametersLoadAccess
 Write hole for INI/JSON loaders and nanobind property setters. More...
class  PluginLoader
class  PointJob
class  Potential
struct  potential_options_t
class  PotentialConstructionScope
 RAII: Potential default construction records on this registry instead of PotRegistry::get(). More...
class  PotRegistry
struct  prefactor_options_t
class  PrefactorJob
struct  PrfoRefineResult
struct  process_search_options_t
class  ProcessSearchJob
 Declaration of the Process Search job. More...
class  Quickmin
struct  RegistryLifetime
 Outlives the registry object. More...
struct  replica_exchange_options_t
class  ReplicaDynamicsJob
 Base class for replica dynamics jobs (TAD, SafeHyper). More...
class  ReplicaExchangeJob
struct  rgpot_options_t
struct  RpcCapabilitiesView
 Fields read from Potential.getCapabilities. More...
struct  RpcServerCapabilitiesPair
class  Runtime
 Move-only composition root for process resources (dlopen loaders and the potential registry). More...
struct  saddle_search_options_t
class  SaddleSearchJob
 Declaration of the Saddle Search job. More...
class  SaddleSearchMethod
class  SafeHyperJob
struct  serve_options_t
struct  ServeEndpoint
 Configuration for a single serve endpoint. More...
struct  shared_flag
 Bool storage shared with Matter. More...
struct  socket_nwchem_options_t
class  SteepestDescent
class  StructureComparisonJob
struct  StructureComparisonOptions
 Options for Matter::compare / distance. More...
struct  SurfaceRecoverable
class  SurrogatePotential
struct  tad_options_t
class  TADJob
class  TestJob
struct  thermostat_options_t
class  VesinNeighbors
 RAII wrapper around vesin_neighbors for Matter-style boxes (double[9] row-major 3×3 cell, same layout as Matter::cell). More...
struct  X86DivRegs
struct  xtb_options_t
class  XtsciBand
 One rgsaddle band step. More...
class  XtsciMinMode
 Lowest-mode rotation through a rgsaddle minimum-mode session. More...
class  XtsciOptimizer
 rgmin backend (opt_method = xtsci, or opt_backend = rgmin). More...
struct  zbl_options_t
class  ZBLRepulsiveIDPPObjective

Concepts

concept  ThreadSafeQueryable
 Duck-typed thread-safety query.

Typedefs

using EigenmodeStrategy = LowestEigenmode
 Type-erased eigenmode solver. Layout is the same with or without gprd.
using JobFactory
using structure_comparison_options_t = StructureComparisonOptions
using ForceCallback
 Callback type for potential energy/force evaluation.

Enumerations

enum class  PotType {
  UNKNOWN = 0 , EMT , EXT_POT , LJ ,
  LJCLUSTER , MORSE_PT , CUH2 , TIP4P ,
  TIP4P_PT , TIP4P_H , SPCE , EAM_AL ,
  EDIP , FEHE , LENOSKY_SI , SW_SI ,
  TERSOFF_SI , VASP , LAMMPS , MPI ,
  AMS , AMS_IO , GPR , CatLearn ,
  XTB , ASE_ORCA , ASE_POT , ASE_NWCHEM ,
  METATOMIC , ZBL , SocketNWChem , RGPOT ,
  DFTD3 , DFTD4 , EXPR , MOPAC
}
enum class  JobType {
  Unknown = 0 , Process_Search , Saddle_Search , Minimization ,
  Point , Parallel_Replica , Safe_Hyperdynamics , TAD ,
  Replica_Exchange , Basin_Hopping , Hessian , Finite_Difference ,
  Nudged_Elastic_Band , Dynamics , Prefactor , Global_Optimization ,
  Structure_Comparison , Monte_Carlo , Test , GP_Surrogate ,
  OH_TST , Instanton
}
enum class  OptType {
  Unknown = -1 , None = 0 , QM , CG ,
  LBFGS , FIRE , SD , XTSCI
}
enum class  NEBInit {
  LINEAR , IDPP , IDPP_COLLECTIVE , SIDPP ,
  SIDPP_ZBL , FILE
}
enum class  RunStatus { GOOD = 0 , FAIL_MAX_ITERATIONS , FAIL_POTENTIAL_FAILED }
enum class  DimerRotationBackend { Classical = 0 , Lanczos , Davidson , LOR }
enum class  FdScheme { OneSided , Central , Fourth }
 Real finite-difference scheme for the assembled Hessian and for Lanczos/Davidson Hessian-vector products. More...
enum class  PbcConvention { Legacy = 0 , MinimumImage = 1 }
enum class  HessianLocality {
  Unknown , Pair , AtomCentred , MolecularSite ,
  MessagePassing
}
 How a kernel's energy couples atoms, which fixes the Hessian range. More...

Functions

int getBundleSize ()
std::vector< std::string > unbundle (int number)
void deleteUnbundledFiles (const std::vector< std::string > &unbundledFilenames)
void bundle (int number, const std::vector< std::string > &filenames, std::vector< std::string > *bundledFilenames)
void commandLine (int argc, char **argv)
std::shared_ptr< LowestEigenmode > buildEigenmodeStrategy (std::shared_ptr< Matter > matter, const Parameters &params, std::shared_ptr< Potential > pot)
double maxFreeAtomForceNorm (const double *forces, const double *fixed, long nAtoms)
 Max Euclidean norm over N x 3 row-major force rows.
template<typename Work>
void forEachImage (long n, Work &&work)
static DecodedDiv decode_div_insn (const unsigned char *code, bool long_mode)
static X86DivRegs x86_div_regs (void *scp)
static bool advance_integer_div (void *scp)
static void write_fault_rip (void *scp)
static void fpe_signal_handler (int sig, siginfo_t *sip, void *scp)
void enableFPE ()
void disableFPE ()
std::vector< int > greedyColorCutoffGraph (const std::vector< std::vector< int > > &adj)
 Greedy coloring of an undirected graph.
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 intersect, then greedy-colored.
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 atoms: x = q / sqrt(m), unit norm, zero on atoms outside atoms.
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_eigenvalue (eV / (Angstrom^2 amu)), hbar_omega (eV, negative for an imaginary mode) and wavenumber (cm^-1, same sign) as frame metadata.
bool trivialModeCountIsPhysical (long removed, long fixedAtoms)
 Whether removed zero-frequency modes are what the structure's symmetries give: 6 for a free cluster (3 translations and 3 rotations), 5 for a linear one, 3 for a periodic cell, where rotations are no symmetry of the lattice, and none once any atom is fixed.
void forceJobRegistration ()
std::map< JobType, JobFactory > & jobTable ()
void registerJob (JobType type, JobFactory factory)
JobResultProvenance provenanceForJob (const Parameters &params)
 Optimizer backend, engine identity, rgpot pin, and xts ABI from a job.
std::vector< CutoffPair > periodicCutoffNeighbors (const double *positions, size_t atoms, const double *cell, double cutoff, bool full)
bool canComputeConcurrently (std::span< Matter *const > systems)
 True when the systems can compute on separate threads at once: every potential instance that two of them share is safe to share.
void evaluateTogether (Potential &pot, std::span< Matter *const > systems, bool threads=false, std::span< const long > owners={})
 Evaluates every system that needs a force update.
bool atomListMeansAll (const std::string &atomList)
 Whether atomList means "every free atom" (empty, "all", case-insensitive).
VectorXi freeAtomIndices (const Matter *matter)
 Free (unfixed) atom indices in ascending order.
VectorXi resolveMobileAtoms (const Matter *matter, const std::string &atomList)
 PHVA-class mobile set for FD Hessian and matrix-free Krylov (Lanczos / Davidson).
VectorXi resolveMobileAtoms (const Matter *matter, const VectorXi &candidates)
 Explicit candidate indices, intersected with free flags (order preserved, duplicates dropped).
VectorXd packMobileRows (const AtomMatrix &full, const VectorXi &mobile)
 Pack full (n_atoms,3) rows of mobile atoms into a 3*n_mobile vector.
void unpackMobileRows (const VectorXd &packed, const VectorXi &mobile, AtomMatrix &full)
 Write a 3*n_mobile vector into full AtomMatrix rows (other rows unchanged).
VectorXd mobileForces (Matter *matter, const VectorXi &mobile)
 Force components on mobile atoms after Matter has a valid force cache (calls getForces under the hood if needed via the non-const Matter API).
AtomMatrix minImageRemoveRigidDrift (const Matter &reference, AtomMatrix diff, Eigen::RowVector3d *totalDrift)
 Minimum-image a free-atom difference and remove rigid translation.
static EonMtaConfig config_from_params (const Parameters &params)
double modeCurvature (const Matter &matter, const AtomMatrix &mode, double dr)
 Curvature along mode from one forward difference of the forces over dr Angstrom.
void requirePrfoRefine (const Parameters &params)
 Does nothing unless [Saddle Search] prfo_refine is on.
PrfoRefineResult prfoRefineSaddle (Matter &matter, const AtomMatrix &mode, double curvature, const Parameters &params)
 Partitioned rational function optimization (P-RFO) of a first-order saddle in the rgsaddle Sella order-1 session, configured by [Saddle Search] prfo_refine_*.
double harmonicModeFreeEnergy (double hbarOmegaEv, double temperature)
 kT ln(2 sinh(beta hbar omega / 2)) in eV.
Eigen::VectorXd complementEigenvalues (const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &removed)
 Eigenvalues of the mass-weighted Hessian on the orthogonal complement of the columns of removed, any spanning set of the directions to leave out: a zero column, or one in the span of the others, removes nothing more.
double complementHarmonicFreeEnergy (const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &removed, double temperature)
 Sum of harmonicModeFreeEnergy over the positive eigenvalues on the complement of removed.
Eigen::VectorXd perpendicularEigenvalues (const Eigen::MatrixXd &hessian, const Eigen::VectorXd &tangent)
 Eigenvalues of the mass-weighted Hessian after the tangent direction is removed: one fewer than the Hessian has rows.
double perpendicularHarmonicFreeEnergy (const Eigen::MatrixXd &hessian, const Eigen::VectorXd &tangent, double temperature)
 Sum of harmonicModeFreeEnergy over the positive perpendicular eigenvalues.
std::vector< double > quantumFreeEnergies (const std::vector< std::shared_ptr< Matter > > &path, const std::vector< std::shared_ptr< AtomMatrix > > &tangent, double temperature, const Parameters &params)
 F(s) = V(s) + the harmonic free energy of the vibrations, one entry per image.
RpcServerCapabilitiesPair readRpcServerCapabilities ()
 Call getCapabilities on both server classes through an in-process RPC.
void serveMode (const Parameters &params, const std::string &host, uint16_t port)
 Start a single rgpot-compatible Cap'n Proto RPC server.
void serveMultiple (const std::vector< ServeEndpoint > &endpoints, const Parameters &params)
 Serve multiple potentials concurrently on different ports.
void serveReplicated (const Parameters &params, const std::string &host, uint16_t base_port, size_t replicas)
 Serve N replicas of the same potential across sequential ports.
void serveGateway (const Parameters &params, const std::string &host, uint16_t port, size_t pool_size)
 Start a gateway server backed by a pool of potential instances.
void serveFromConfig (const Parameters &params)
 Start serve mode from config-file parameters.
std::vector< ServeEndpoint > parseServeSpec (const std::string &spec)
 Parse a serve configuration string into endpoints.
void startRpcServer (ForceCallback callback, const std::string &host, uint16_t port)
 Start a blocking Cap'n Proto RPC server using a force callback.
void startPooledRpcServer (std::vector< ForceCallback > pool, const std::string &host, uint16_t port)
 Start a blocking Cap'n Proto RPC server backed by a pool of force callbacks dispatched round-robin.
int xtsciBandSurface (void *user, void *request)
int xtsciSolidBandSurface (void *user, void *request)
bool ircAvailable ()
 True when this build can run followIrc: linked to rgsaddle at C ABI minor 14 or newer, at compile time and at load time.
IrcPath followIrc (const Matter &saddle, const AtomMatrix &mode, const Parameters &params)
 Follows the rgsaddle IRC from a converged saddle along both signs of its lowest mode.
constexpr bool usesAlternativeRotation (DimerRotationBackend backend) noexcept
std::optional< DimerRotationResult > runAlternativeRotation (DimerRotationBackend backend, const std::shared_ptr< Matter > &matter, const Parameters &params, const std::shared_ptr< Potential > &pot, const AtomMatrix &initialDirection, quill::Logger *log=nullptr)
 Run Lanczos, Davidson, or LOR.
AtomMatrix from_fortran_layout_vector (const std::vector< double > &flat_colmajor, int nat)
 Reconstruct AtomMatrix from a flat column-major vector (e.g.
void lattice_rows_to_fortran_box (const Matrix3d &cell, double *box)
 Pack an eOn cell for pARTn artn_step.
void eigenmodeCompute (LowestEigenmode &s, std::shared_ptr< Matter > matter, AtomMatrix direction)
double eigenmodeGetEigenvalue (LowestEigenmode &s)
AtomMatrix eigenmodeGetEigenvector (LowestEigenmode &s)
ImprovedDimer * asImprovedDimer (LowestEigenmode &s)
long eigenmodeTotalForceCalls (LowestEigenmode &s)
double eigenmodeStatsTorque (LowestEigenmode &s)
double eigenmodeStatsAngle (LowestEigenmode &s)
long eigenmodeStatsRotations (LowestEigenmode &s)
long eigenmodeTotalIterations (LowestEigenmode &s)
FdScheme parseFdScheme (std::string_view scheme)
template<class M>
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.
template<class Eval>
VectorXd fdHessianVector (FdScheme scheme, double dr, const VectorXd &force0, Eval &&eval)
 Energy Hessian-vector product -dF.
constexpr std::uint32_t maskWindowsMxcsrForContinue (std::uint32_t mxcsr)
ARTnResource & get_artn_resource ()
 Global access to thread-safe ARTn resource.
IRAResource & get_ira_resource ()
 Global access to thread-safe IRA resource.
void ensure_interpreter ()
double pmfScanS (long plane, long nScan, double guideLen)
 Uniform PMF-scan coordinate.
bool reversibleWorkPastRidge (double reversibleWork, double thermalEnergy)
 The reactant basin is force-free.
template<class P>
requires ThreadSafeQueryable<P>
bool potIsThreadSafe (const P &p) noexcept
template<class P>
requires requires(const P &p) { { p.isSharedInstanceThreadSafe() } -> std::convertible_to<bool>; }
bool potAllowsSharedInstance (const P &p) noexcept
bool lammpsWorkerReaped (long got, long child, int err)
 True when waitpid has collected the child. EINTR is not a collection.
std::int64_t lammpsScreenCursor (std::int64_t pos, std::int64_t fileSize, bool restarted)
 Byte offset at which to keep copying a LAMMPS screen file.
std::vector< std::string > lammpsOpenArgs (bool logging, bool with_omp, const std::string &screen)
 LAMMPS argv.
double acceptedHessianRange (double range) noexcept
 Drop a non-positive or non-finite range so coloring stays off.

Variables

static constexpr unsigned MXCSR_MASK_IM = 1u << 7
static constexpr unsigned MXCSR_MASK_ZM = 1u << 9
static constexpr unsigned MXCSR_MASK_OM = 1u << 10
constexpr std::uint32_t kWindowsMxcsrExceptionMasks = 0x1F80u
constexpr double kEvToWavenumber = 8065.543937349212
 1 eV in cm^-1, e / (h c) from the exact SI values.
constexpr double IM = 2147483647.0
constexpr double AM = 1.0 / IM
constexpr int NTAB = 32
constexpr int NDIV = 1 + (IM / NTAB)
constexpr double EPS = 1.2e-7
constexpr double RNMX = 1.0 - EPS
constexpr long IM1 = 2147483563
constexpr long IM2 = 2147483399
constexpr long IMM1 = IM1 - 1
constexpr long IA1 = 40014
constexpr long IA2 = 40692
constexpr long IQ1 = 53668
constexpr long IQ2 = 52774
constexpr long IR1 = 12211
constexpr long IR2 = 3791

Detailed Description

RAII resource manager for the ARTn C library with global synchronization.

Explicit Hessian-range contract for rgpot kernels.

Runtime loader for engine plugin shared libraries.

Runtime loader for the LAMMPS C library.

Contains all runtime parameters and results.

RAII resource manager for the IRA C library with global synchronization.

Uses dlopen (POSIX) or LoadLibrary (Windows) to load libartn at runtime. Implements global mutex to ensure thread-safety when multiple threads access the Fortran backend which has shared global state.

WARNING: Due to the non-thread-safe Fortran backend, all ARTn operations are serialized through a global mutex. Multiple threads calling ARTn simultaneously will execute sequentially, potentially creating a significant performance bottleneck in multi-threaded contexts. Consider process-level parallelism if true concurrent ARTn operations are required.

Uses dlopen (POSIX) or LoadLibrary (Windows) to load libira at runtime. Implements global mutex to ensure thread-safety when multiple threads access the Fortran backend which has shared global state.

WARNING: Due to the non-thread-safe Fortran backend, all IRA operations are serialized through a global mutex. Multiple threads calling IRA simultaneously will execute sequentially, potentially creating a significant performance bottleneck in multi-threaded contexts. Consider process-level parallelism if true concurrent IRA operations are required.

No functionality just bookkeeping.

Uses dlopen (POSIX) or LoadLibrary (Windows) to load liblammps at runtime rather than requiring it at compile time. This allows a single eOn binary to optionally use LAMMPS potentials if the library is installed.

Engines that ship as their own shared objects (the rgpot metatomic and xtb backends) are found by base name across a search path rather than by an absolute path, so a build, a wheel, and a conda prefix can each place them differently.

Uses dlopen (POSIX) or LoadLibrary (Windows) to load Fortran potential libraries at runtime. The search order is:

  1. Paths from the [Potential] potentials_path config key
  2. EON_POTENTIALS_PATH environment variable (';' on Windows, ':' elsewhere)
  3. Default system library search path (LD_LIBRARY_PATH, etc.)

Call add_config_paths() once at startup (before any potential constructor) to inject config-file paths into the singleton.

Coloring a finite-difference Hessian is exact only when every block between atoms farther apart than the reported distance is zero. The primary template reports that the range is unknown. A kernel opts in by specializing HessianRangeOf. The presence of config().cutoff is not an opt-in: many-body and message-passing kernels have a cutoff and still couple atoms beyond it.

Typedef Documentation

◆ EigenmodeStrategy

Type-erased eigenmode solver. Layout is the same with or without gprd.

Definition at line 25 of file EigenmodeStrategy.h.

◆ ForceCallback

Initial value:
std::function<void(long nAtoms, const double *positions,
const int *atomicNrs, double *forces,
double *energy, const double *box)>

Callback type for potential energy/force evaluation.

Flat-array interface that avoids any AtomMatrix type dependency, preventing collisions between eOn's Eigen-based AtomMatrix and rgpot's custom AtomMatrix.

Parameters
nAtomsNumber of atoms.
positionsFlat array [x1,y1,z1, x2,y2,z2, ...] (nAtoms*3).
atomicNrsAtomic numbers [Z1, Z2, ...] (nAtoms).
forcesOutput forces [Fx1,Fy1,Fz1, ...] (nAtoms*3).
energyOutput energy (single double).
boxSimulation cell flat 3x3 row-major (9 doubles).

Definition at line 36 of file ServeRpcServer.h.

◆ JobFactory

Initial value:
std::function<std::unique_ptr<Job>(std::unique_ptr<Parameters>, Runtime &)>
Move-only composition root for process resources (dlopen loaders and the potential registry).
Definition Runtime.h:27

Definition at line 16 of file JobRegistry.h.

◆ structure_comparison_options_t

Enumeration Type Documentation

◆ DimerRotationBackend

enum class eonc::DimerRotationBackend
strong
Enumerator
Classical 
Lanczos 
Davidson 
LOR 

Definition at line 122 of file BaseStructures.h.

◆ FdScheme

enum class eonc::FdScheme
strong

Real finite-difference scheme for the assembled Hessian and for Lanczos/Davidson Hessian-vector products.

Complex-step is not a scheme: cutoffs and external potentials are not holomorphic.

Enumerator
OneSided 
Central 
Fourth 

Definition at line 25 of file FiniteDifference.h.

◆ HessianLocality

enum class eonc::HessianLocality
strong

How a kernel's energy couples atoms, which fixes the Hessian range.

Enumerator
Unknown 

No proven finite range. Coloring stays off.

Pair 

Pair potential. Blocks vanish beyond the interaction cutoff.

AtomCentred 

Atom-centred many-body (EAM, Gupta, bond order, three-body).

Blocks vanish beyond twice the interaction cutoff.

MolecularSite 

Molecular site model.

The range is the intermolecular cutoff plus twice the largest intramolecular extent, when that extent is a hard bound.

MessagePassing 

Message passing.

The range is the layer count times the edge cutoff, when the layer count is part of the kernel.

Definition at line 47 of file HessianRange.h.

47 {
49 Unknown,
51 Pair,
62};
@ AtomCentred
Atom-centred many-body (EAM, Gupta, bond order, three-body).
@ MolecularSite
Molecular site model.
@ Pair
Pair potential. Blocks vanish beyond the interaction cutoff.
@ MessagePassing
Message passing.

◆ JobType

enum class eonc::JobType
strong
Enumerator
Unknown 
Process_Search 
Saddle_Search 
Minimization 
Point 
Parallel_Replica 
Safe_Hyperdynamics 
TAD 
Replica_Exchange 
Basin_Hopping 
Hessian 
Finite_Difference 
Nudged_Elastic_Band 
Dynamics 
Prefactor 
Global_Optimization 
Structure_Comparison 
Monte_Carlo 
Test 
GP_Surrogate 
OH_TST 
Instanton 

Definition at line 77 of file BaseStructures.h.

77 {
78 // Only add to the end of this!!!
79 Unknown = 0,
83 Point,
86 TAD,
89 Hessian,
97 Test,
99 OH_TST,
101};

◆ NEBInit

enum class eonc::NEBInit
strong
Enumerator
LINEAR 
IDPP 
IDPP_COLLECTIVE 
SIDPP 
SIDPP_ZBL 
FILE 

Definition at line 115 of file BaseStructures.h.

◆ OptType

enum class eonc::OptType
strong
Enumerator
Unknown 
None 
QM 
CG 
LBFGS 
FIRE 
SD 
XTSCI 

Definition at line 103 of file BaseStructures.h.

103 {
104 // Only add to the end of this!!!
105 Unknown = -1, // an error case
106 None = 0,
107 QM,
108 CG,
109 LBFGS,
110 FIRE,
111 SD,
112 XTSCI
113};

◆ PbcConvention

enum class eonc::PbcConvention
strong
Enumerator
Legacy 
MinimumImage 

Definition at line 38 of file Matter.h.

38 {
39 Legacy = 0,
40 MinimumImage = 1,
41};

◆ PotType

enum class eonc::PotType
strong
Enumerator
UNKNOWN 
EMT 
EXT_POT 
LJ 
LJCLUSTER 
MORSE_PT 
CUH2 
TIP4P 
TIP4P_PT 
TIP4P_H 
SPCE 
EAM_AL 
EDIP 
FEHE 
LENOSKY_SI 
SW_SI 
TERSOFF_SI 
VASP 
LAMMPS 
MPI 
AMS 
AMS_IO 
GPR 
CatLearn 
XTB 
ASE_ORCA 
ASE_POT 
ASE_NWCHEM 
METATOMIC 
ZBL 
SocketNWChem 
RGPOT 
DFTD3 
DFTD4 
EXPR 
MOPAC 

Definition at line 36 of file BaseStructures.h.

36 {
37 // Only add to the end of this!!!
38 UNKNOWN = 0,
39 EMT,
40 EXT_POT,
41 LJ,
44 CUH2,
45 TIP4P,
47 TIP4P_H,
48 SPCE,
49 EAM_AL,
50 EDIP,
51 FEHE,
53 SW_SI,
55 VASP,
56 LAMMPS,
57 MPI,
58 // Add newer entries here
59 AMS,
60 AMS_IO,
61 GPR,
63 XTB,
65 ASE_POT,
68 ZBL,
70 RGPOT,
71 DFTD3,
72 DFTD4,
73 EXPR,
74 MOPAC
75};

◆ RunStatus

enum class eonc::RunStatus
strong
Enumerator
GOOD 
FAIL_MAX_ITERATIONS 
FAIL_POTENTIAL_FAILED 

Definition at line 117 of file BaseStructures.h.

Function Documentation

◆ acceptedHessianRange()

double eonc::acceptedHessianRange ( double range)
inlinenodiscardnoexcept

Drop a non-positive or non-finite range so coloring stays off.

Definition at line 79 of file HessianRange.h.

79 {
80 if (!(range > 0.0) || !std::isfinite(range)) {
81 return 0.0;
82 }
83 return range;
84}

◆ advance_integer_div()

bool eonc::advance_integer_div ( void * scp)
static

Definition at line 249 of file fpe_handler.cpp.

249 {
250 X86DivRegs regs = x86_div_regs(scp);
251 if (regs.ip == nullptr || regs.ax == nullptr || regs.dx == nullptr) {
252 return false;
253 }
254 const auto *code = reinterpret_cast<const unsigned char *>(*regs.ip);
255 DecodedDiv div = decode_div_insn(code, sizeof(void *) == 8);
256 if (div.length == 0) {
257 return false;
258 }
259 if (div.width <= 2) {
260 *regs.ax &= ~uintptr_t{0xFFFFu};
261 if (div.width == 2) {
262 *regs.dx &= ~uintptr_t{0xFFFFu};
263 }
264 } else {
265 *regs.ax = 0;
266 *regs.dx = 0;
267 }
268 *regs.ip += static_cast<uintptr_t>(div.length);
269 return true;
270}
static X86DivRegs x86_div_regs(void *scp)
static DecodedDiv decode_div_insn(const unsigned char *code, bool long_mode)

◆ asImprovedDimer()

ImprovedDimer * eonc::asImprovedDimer ( LowestEigenmode & s)
inline

Definition at line 44 of file EigenmodeStrategy.h.

44 {
45 return dynamic_cast<ImprovedDimer *>(&s);
46}

◆ atomListMeansAll()

bool eonc::atomListMeansAll ( const std::string & atomList)

Whether atomList means "every free atom" (empty, "all", case-insensitive).

Definition at line 22 of file MobileAtoms.cpp.

22 {
23 if (atomList.empty()) {
24 return true;
25 }
26 // Trim and case-fold "all"
27 size_t b = 0;
28 while (b < atomList.size() &&
29 std::isspace(static_cast<unsigned char>(atomList[b]))) {
30 ++b;
31 }
32 size_t e = atomList.size();
33 while (e > b && std::isspace(static_cast<unsigned char>(atomList[e - 1]))) {
34 --e;
35 }
36 if (e <= b) {
37 return true;
38 }
39 if (e - b != 3) {
40 return false;
41 }
42 auto lower = [](char c) {
43 return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
44 };
45 return lower(atomList[b]) == 'a' && lower(atomList[b + 1]) == 'l' &&
46 lower(atomList[b + 2]) == 'l';
47}

◆ buildEigenmodeStrategy()

std::shared_ptr< LowestEigenmode > eonc::buildEigenmodeStrategy ( std::shared_ptr< Matter > matter,
const Parameters & params,
std::shared_ptr< Potential > pot )

Definition at line 32 of file EigenmodeStrategy.cpp.

33 {
36#ifdef WITH_RGSADDLE
37 return std::make_shared<XtsciMinMode>(matter, params, pot);
38#else
39 if (params.dimer_options().improved) {
40 return std::make_shared<ImprovedDimer>(matter, params, pot);
41 }
42 return std::make_shared<Dimer>(matter, params, pot);
43#endif
44 }
47#ifdef WITH_RGSADDLE
48 return std::make_shared<XtsciMinMode>(matter, params, pot);
49#else
50 return std::make_shared<Lanczos>(matter, params, pot);
51#endif
52 }
55 return std::make_shared<Davidson>(matter, params, pot);
56 }
59#ifdef WITH_RGSADDLE
60 return std::make_shared<XtsciMinMode>(matter, params, pot);
61#else
62 throw std::runtime_error(
63 "min_mode_method=xtsci requires -Dwith_rgsaddle=true");
64#endif
65 }
68#ifdef WITH_GPRD
69 return std::make_shared<AtomicGPDimer>(matter, params, pot);
70#else
71 throw std::runtime_error(
72 "min_mode_method=gprdimer needs a -Dwith_gprd build with the private "
73 "gpr_optim repository checked out in subprojects/gpr_optim "
74 "(rsync -a ../gpr_optim/ subprojects/gpr_optim/, then reconfigure)");
75#endif
76 }
77 return std::make_shared<ImprovedDimer>(matter, params, pot);
78}
static const char MINMODE_GPRDIMER[]
static const char MINMODE_DIMER[]
static const char MINMODE_LANCZOS[]
static const char MINMODE_DAVIDSON[]
static const char MINMODE_XTSCI[]
const dimer_options_t & dimer_options() const
const saddle_search_options_t & saddle_search_options() const

◆ bundle()

void eonc::bundle ( int number,
const std::vector< std::string > & filenames,
std::vector< std::string > * bundledFilenames )

Definition at line 180 of file Bundling.cpp.

181 {
182 for (const auto &filename : filenames) {
183 const auto [baseName, ext] = splitBundleExtension(filename);
184 const std::string newFilename =
185 std::format("{}_{}{}", baseName, number, ext);
186
187 try {
188 fs::rename(filename, newFilename);
189 bundledFilenames->push_back(newFilename);
190 } catch (const fs::filesystem_error &e) {
191 EONC_LOG_ERROR("bundle: cannot rename {} to {}: {}", filename,
192 newFilename, e.what());
193 }
194 }
195}
#define EONC_LOG_ERROR(...)
Definition EonLogger.h:328

◆ canComputeConcurrently()

bool eonc::canComputeConcurrently ( std::span< Matter *const > systems)
nodiscard

True when the systems can compute on separate threads at once: every potential instance that two of them share is safe to share.

Definition at line 981 of file Matter.cpp.

981 {
982 std::vector<const Potential *> seen;
983 seen.reserve(systems.size());
984 for (Matter *m : systems) {
985 const Potential *p = m->getPotential().get();
986 if (p == nullptr) {
987 return false;
988 }
989 if (std::find(seen.begin(), seen.end(), p) == seen.end()) {
990 seen.push_back(p);
991 } else if (!eonc::potAllowsSharedInstance(*p)) {
992 return false;
993 }
994 }
995 return true;
996}
bool potAllowsSharedInstance(const P &p) noexcept

◆ cartesianMode()

std::vector< double > eonc::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 atoms: x = q / sqrt(m), unit norm, zero on atoms outside atoms.

Row-major N x 3.

Definition at line 837 of file Hessian.cpp.

838 {
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}
long int numberOfAtoms() const
Definition Matter.cpp:343
double getMass(long int atom) const
Definition Matter.cpp:548

◆ colorMobileCutoffGraph()

std::vector< int > eonc::colorMobileCutoffGraph ( const Matter & matter,
const VectorXi & atoms,
double cutoff )

Conflict graph on atoms: two mobile atoms share an edge when their closed cutoff neighborhoods intersect, then greedy-colored.

Empty when the neighbor list cannot be built.

Definition at line 336 of file Hessian.cpp.

337 {
338 return buildMobileColoring(matter, atoms, cutoff).color;
339}

◆ commandLine()

void eonc::commandLine ( int argc,
char ** argv )

Definition at line 94 of file CommandLine.cpp.

94 {
95 bool sflag = false, mflag = false, pflag = false, cflag = false;
96 double optConvergedForce = 0.001;
97 std::string potential;
98 std::string confile;
99 std::string confileout;
100 std::string optimizer("cg");
101
102#ifdef WITH_SERVE_MODE
103 std::optional<std::string> config_path;
104 std::optional<std::string> serve_spec;
105 // Empty until the matching flag is passed. A value here makes has_value()
106 // true, so -p alone takes the serve path and never reads a structure file.
107 std::optional<std::string> serve_host;
108 std::optional<uint16_t> serve_port;
109 std::optional<size_t> replicas;
110 std::optional<bool> gateway;
111#endif
112
113 auto params = Parameters{};
114
115 const char *progname = (argc ? argv[0] : "eonclient");
116
117 Argum::Parser parser;
118
119 parser.add(Argum::Option("--help", "-h")
120 .help("show this help message and exit")
121 .handler([&]() {
122 // Format help with color
123 auto helpText = parser.formatHelp(progname);
124 std::cout << colorizer.heading("eOn Client - Help")
125 << "\n\n";
126 std::cout << helpText;
127 std::exit(EXIT_SUCCESS);
128 }));
129
130 parser.add(Argum::Option("--version", "-v")
131 .help("Print version information")
132 .handler([&]() {
133 std::cout << VERSION_STRING << '\n';
134 std::exit(EXIT_SUCCESS);
135 }));
136
137 parser.add(Argum::Option("--features")
138 .help("Print compile-time features")
139 .handler([&]() {
141 std::exit(EXIT_SUCCESS);
142 }));
143
144 parser.add(Argum::Option("--minimize", "-m")
145 .help("Minimization of inputConfile saves to outputConfile")
146 .handler([&]() { mflag = true; }));
147
148 parser.add(Argum::Option("--single", "-s")
149 .help("Single point energy of inputConfile")
150 .handler([&]() { sflag = true; }));
151
152 parser.add(Argum::Option("--compare", "-c")
153 .help("Compare structures of inputConfile to outputConfile")
154 .handler([&]() { cflag = true; }));
155
156 parser.add(
157 Argum::Option("--optimizer", "-o")
158 .argName("METHOD")
159 .help("Optimization method")
160 .handler([&](const std::string_view &value) { optimizer = value; }));
161
162 parser.add(Argum::Option("--force", "-f")
163 .argName("VALUE")
164 .help("Convergence force")
165 .handler([&](const std::string_view &value) {
166 optConvergedForce = Argum::parseFloatingPoint<double>(value);
167 }));
168
169 parser.add(
170 Argum::Option("--tolerance", "-t")
171 .argName("VALUE")
172 .help("Distance tolerance")
173 .handler([&](const std::string_view &value) {
175 .distance_difference = Argum::parseFloatingPoint<double>(value);
176 }));
177
178 parser.add(Argum::Option("--potential", "-p")
179 .argName("POTENTIAL")
180 .help("The potential (e.g. qsc, lj, eam_al)")
181 .handler([&](const std::string_view &value) {
182 pflag = true;
183 potential = value;
184 }));
185
186#ifdef WITH_SERVE_MODE
187 parser.add(
188 Argum::Option("--serve")
189 .argName("SPEC")
190 .help("Serve potential(s) over rgpot Cap'n Proto RPC. "
191 "Spec: 'potential:port' or 'pot1:port1,pot2:port2'")
192 .handler([&](const std::string_view &value) { serve_spec = value; }));
193
194 parser.add(
195 Argum::Option("--serve-host")
196 .argName("HOST")
197 .help("Host to bind RPC server(s) to")
198 .handler([&](const std::string_view &value) { serve_host = value; }));
199
200 parser.add(Argum::Option("--serve-port")
201 .argName("PORT")
202 .help("Port for single-potential serve mode (used with -p)")
203 .handler([&](const std::string_view &value) {
204 serve_port = Argum::parseIntegral<uint16_t>(value);
205 }));
206
207 parser.add(Argum::Option("--replicas")
208 .argName("N")
209 .help("Number of replicated server instances (used with -p)")
210 .handler([&](const std::string_view &value) {
211 replicas = Argum::parseIntegral<size_t>(value);
212 }));
213
214 parser.add(Argum::Option("--gateway")
215 .help("Run a single gateway port backed by N pool instances "
216 "(use with -p and --replicas)")
217 .handler([&]() { gateway = true; }));
218
219 parser.add(Argum::Option("--config")
220 .argName("FILE")
221 .help("Config file for potential parameters (INI format, "
222 "e.g. [Metatomic] model_path=model.pt)")
223 .handler([&](const std::string_view &value) {
224 config_path = value;
225 }));
226#endif
227
228 // One value each: the partitioner hands a greedy zeroOrMoreTimes positional
229 // every remaining argument, which leaves confileout empty and overwrites
230 // confile with the last one.
231 parser.add(
232 Argum::Positional("confile")
233 .help("Input structure file")
234 .occurs(Argum::zeroOrOneTime)
235 .handler([&](const std::string_view &value) { confile = value; }));
236
237 parser.add(
238 Argum::Positional("confileout")
239 .help("Output structure file (optional)")
240 .occurs(Argum::zeroOrOneTime)
241 .handler([&](const std::string_view &value) { confileout = value; }));
242
243 try {
244 parser.parse(argc, argv);
245 } catch (const Argum::ParsingException &ex) {
246 std::cerr << colorizer.error(ex.message()) << '\n';
247 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
248 std::exit(EXIT_FAILURE);
249 }
250
251 // Help, version, and features exit inside parse. Logger setup waits until
252 // a flag set commits to a potential, a compare, or a config load.
254
255 if (sflag && mflag) {
256 std::cerr << colorizer.error(
257 "Cannot specify both minimization and single point\n");
258 std::exit(EXIT_FAILURE);
259 }
260
261 if (!pflag && (sflag || mflag)) {
262 std::cerr << colorizer.error("Must specify a potential\n");
263 std::exit(EXIT_FAILURE);
264 }
265
266 if (cflag && confileout.empty()) {
267 std::cerr << colorizer.error(
268 "Comparison needs two structure files: the input con file and the "
269 "one to compare it against\n");
270 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
271 std::exit(EXIT_FAILURE);
272 }
273
274#ifdef WITH_SERVE_MODE
275 // Load config file if provided (for potential-specific parameters
276 // like model_path, device, length_unit, etc.)
277 if (config_path.has_value()) {
278 std::ifstream config_file(config_path.value());
279 if (!config_file.is_open()) {
280 std::cerr << colorizer.error("Cannot open config file: ")
281 << config_path.value() << '\n';
282 std::exit(EXIT_FAILURE);
283 }
284 params.load(config_path.value());
285 }
286
287 // Handle --serve mode (does not require a con file)
288 if (serve_spec.has_value()) {
289 auto endpoints = parseServeSpec(serve_spec.value());
290 if (endpoints.empty()) {
291 std::cerr << colorizer.error("No valid serve endpoints in spec: ")
292 << serve_spec.value() << '\n';
293 std::exit(EXIT_FAILURE);
294 }
295 serveMultiple(endpoints, params);
296 std::exit(EXIT_SUCCESS);
297 }
298
299 // Handle -p with serve flags (single potential serve mode).
300 // Defaults are applied below with value_or; has_value() is the flag.
301 if (pflag && !sflag && !mflag && !cflag &&
302 (serve_host.has_value() || serve_port.has_value() ||
303 replicas.has_value() || gateway.has_value())) {
304 for (auto &ch : potential) {
305 ch = std::tolower(static_cast<unsigned char>(ch));
306 }
308 magic_enum::enum_cast<PotType>(potential, magic_enum::case_insensitive)
309 .value_or(PotType::UNKNOWN);
310 auto host = serve_host.value_or("localhost");
311 auto port = serve_port.value_or(12345);
312 auto reps = replicas.value_or(1);
313 bool gw = gateway.value_or(false);
314
315 if (gw) {
316 serveGateway(params, host, port, reps);
317 } else if (reps > 1) {
318 serveReplicated(params, host, port, reps);
319 } else {
320 serveMode(params, host, port);
321 }
322 std::exit(EXIT_SUCCESS);
323 }
324
325 // Config-driven serve (no -p or --serve, just --config with [Serve])
326 if (!pflag && !sflag && !mflag && !cflag && config_path.has_value() &&
327 !serve_spec.has_value() &&
331 serveFromConfig(params);
332 std::exit(EXIT_SUCCESS);
333 }
334#endif
335
336 // Serve modes take no structure file and have already exited above.
337 if (confile.empty()) {
338 std::cerr << colorizer.error(
339 "At least one non-option argument is required: the con file\n");
340 std::cerr << colorizer.warning(parser.formatUsage(progname)) << '\n';
341 std::exit(EXIT_FAILURE);
342 }
343
344 if (!cflag) {
345 for (auto &ch : potential) {
346 ch = std::tolower(static_cast<unsigned char>(ch));
347 }
348 }
349
350 if (!cflag) {
352 magic_enum::enum_cast<PotType>(potential, magic_enum::case_insensitive)
353 .value_or(PotType::UNKNOWN);
354 }
355
356 if (!sflag) {
358 magic_enum::enum_cast<OptType>(optimizer, magic_enum::case_insensitive)
359 .value_or(OptType::CG);
361 optConvergedForce;
362 }
363
364 if (cflag) {
365 // Matter copies structure_comparison_options into its own structComp in
366 // the constructor, so the flag has to be set before the two below.
368 .check_rotation = true;
369 }
370
371 auto pot =
373 auto matter = std::make_unique<Matter>(pot, params);
374 auto matter2 = std::make_unique<Matter>(pot, params);
375 if (!eonc::io::io_ok(matter->con2matter(confile))) {
376 std::cerr << "Failed to load " << confile << '\n';
377 std::exit(EXIT_FAILURE);
378 }
379
380 if (sflag) {
381 singlePoint(std::move(matter));
382 } else if (mflag) {
383 minimize(std::move(matter), confileout);
384 } else if (cflag) {
385 if (!eonc::io::io_ok(matter2->con2matter(confileout))) {
386 std::cerr << "Failed to load " << confileout << '\n';
387 std::exit(EXIT_FAILURE);
388 }
389 Matter probe(*matter);
390 if (probe.compare(*matter2, true)) {
391 std::cout << "Structures match\n";
392 } else {
393 std::cout << colorizer.error("Structures do not match\n");
394 }
395 }
396}
void printFeatures()
void minimize(std::unique_ptr< eonc::Matter > matter, const std::string &confileout)
void singlePoint(std::unique_ptr< eonc::Matter > matter)
std::unique_ptr< Potential > makePotential(const Parameters &params)
Exclusive ownership.
std::shared_ptr< Potential > sharePotential(std::unique_ptr< Potential > pot)
Multi-owner boundary: one instance observed by several Matters, images, or a binding.
Definition Potential.h:292
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
quill::Logger * init_client() noexcept
Start the client backend and the combi / traceback loggers once.
Definition EonLogger.h:43
std::vector< ServeEndpoint > parseServeSpec(const std::string &spec)
Parse a serve configuration string into endpoints.
void serveGateway(const Parameters &params, const std::string &host, uint16_t port, size_t pool_size)
Start a gateway server backed by a pool of potential instances.
void serveMode(const Parameters &params, const std::string &host, uint16_t port)
Start a single rgpot-compatible Cap'n Proto RPC server.
Definition ServeMode.cpp:58
void serveFromConfig(const Parameters &params)
Start serve mode from config-file parameters.
void serveMultiple(const std::vector< ServeEndpoint > &endpoints, const Parameters &base_params)
Serve multiple potentials concurrently on different ports.
Definition ServeMode.cpp:82
void serveReplicated(const Parameters &params, const std::string &host, uint16_t base_port, size_t replicas)
Serve N replicas of the same potential across sequential ports.
static structure_comparison_options_t & structure_comparison_options(Parameters &p)
static optimizer_options_t & optimizer_options(Parameters &p)
static serve_options_t & serve_options(Parameters &p)
static potential_options_t & potential_options(Parameters &p)

◆ complementEigenvalues()

Eigen::VectorXd eonc::complementEigenvalues ( const Eigen::MatrixXd & hessian,
const Eigen::MatrixXd & removed )

Eigenvalues of the mass-weighted Hessian on the orthogonal complement of the columns of removed, any spanning set of the directions to leave out: a zero column, or one in the span of the others, removes nothing more.

No column leaves the whole spectrum.

Definition at line 126 of file QuantumFreeEnergy.cpp.

127 {
128 const long n = hessian.rows();
129 if (hessian.cols() != n || n < 1 ||
130 (removed.cols() > 0 && removed.rows() != n)) {
131 throw std::invalid_argument(
132 "the Hessian and the removed directions differ in size");
133 }
134 const Eigen::MatrixXd sym = 0.5 * (hessian + hessian.transpose());
135 // Unit columns, so that the rank decision compares directions and not
136 // their lengths. A column at round-off of the longest (the rotation about
137 // a linear molecule's axis) removes nothing, rather than a direction of
138 // noise scaled up.
139 Eigen::MatrixXd unit(n, removed.cols());
140 long kept = 0;
141 const double largest =
142 removed.cols() > 0 ? removed.colwise().norm().maxCoeff() : 0.0;
143 if (!std::isfinite(largest)) {
144 throw std::invalid_argument("a removed direction is not finite");
145 }
146 for (long c = 0; c < removed.cols(); ++c) {
147 const double norm = removed.col(c).norm();
148 if (norm > 1e-8 * largest) {
149 unit.col(kept++) = removed.col(c) / norm;
150 }
151 }
152 Eigen::MatrixXd complement = Eigen::MatrixXd::Identity(n, n);
153 if (kept > 0) {
154 Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(unit.leftCols(kept));
155 qr.setThreshold(1e-8);
156 const long rank = qr.rank();
157 const Eigen::MatrixXd q = qr.householderQ();
158 complement = q.rightCols(n - rank);
159 }
160 if (complement.cols() == 0) {
161 return Eigen::VectorXd();
162 }
163 const Eigen::MatrixXd reduced = complement.transpose() * sym * complement;
164 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(
165 0.5 * (reduced + reduced.transpose()), Eigen::EigenvaluesOnly);
166 if (solver.info() != Eigen::Success) {
167 throw std::runtime_error("the projected Hessian did not diagonalize");
168 }
169 return solver.eigenvalues();
170}
void * sym(Handle h, const char *name) noexcept
Definition DynLib.h:75
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...

◆ complementHarmonicFreeEnergy()

double eonc::complementHarmonicFreeEnergy ( const Eigen::MatrixXd & hessian,
const Eigen::MatrixXd & removed,
double temperature )

Sum of harmonicModeFreeEnergy over the positive eigenvalues on the complement of removed.

Definition at line 172 of file QuantumFreeEnergy.cpp.

174 {
175 const Eigen::VectorXd lambda = complementEigenvalues(hessian, removed);
176 double sum = 0.0;
177 for (long i = 0; i < lambda.size(); ++i) {
178 if (!(lambda(i) > 0.0)) {
179 continue;
180 }
181 const double hw = tunneling::kHbar * std::sqrt(lambda(i));
182 sum += harmonicModeFreeEnergy(hw, temperature);
183 }
184 return sum;
185}
double sum(const double *x, std::size_t n)
Round-to-nearest-even value of the exact sum of x[i].
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
double harmonicModeFreeEnergy(double hbarOmegaEv, double temperature)
kT ln(2 sinh(beta hbar omega / 2)) in eV.
Eigen::VectorXd complementEigenvalues(const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &removed)
Eigenvalues of the mass-weighted Hessian on the orthogonal complement of the columns of removed,...

◆ config_from_params()

EonMtaConfig eonc::config_from_params ( const Parameters & params)
static

Definition at line 16 of file MetatomicDynPot.cpp.

16 {
17 const auto &o = params.metatomic_options();
18 EonMtaConfig c{};
19 c.model_path = o.model_path.c_str();
20 c.device = o.device.c_str();
21 c.length_unit = o.length_unit.c_str();
22 c.extensions_directory = o.extensions_directory.c_str();
23 c.check_consistency = o.check_consistency ? 1 : 0;
24 c.uncertainty_threshold = o.uncertainty_threshold;
25 c.energy_output = o.energy_output.c_str();
26 c.energy_uncertainty_output = o.energy_uncertainty_output.c_str();
27 c.force_output = o.force_output.c_str();
28 c.non_conservative = o.non_conservative ? 1 : 0;
29 c.random_rotation = o.random_rotation ? 1 : 0;
30 c.n_symmetry_rotations = o.n_symmetry_rotations;
31 c.deterministic = o.deterministic ? 1 : 0;
32 c.deterministic_strict = o.deterministic_strict ? 1 : 0;
33 c.variant_base = o.variant.base.c_str();
34 c.variant_energy = o.variant.energy.c_str();
35 c.variant_energy_uncertainty = o.variant.energy_uncertainty.c_str();
36 c.variant_force = o.variant.force.c_str();
37 return c;
38}
const metatomic_options_t & metatomic_options() const
Flat config for create (mirrors eonc::Parameters::metatomic_options_t).
const char * device
const char * extensions_directory
const char * variant_force
const char * model_path
const char * length_unit
long n_symmetry_rotations
const char * energy_output
const char * force_output
const char * variant_base
const char * energy_uncertainty_output
const char * variant_energy
const char * variant_energy_uncertainty
double uncertainty_threshold

◆ decode_div_insn()

DecodedDiv eonc::decode_div_insn ( const unsigned char * code,
bool long_mode )
static

Definition at line 120 of file fpe_handler.cpp.

120 {
121 DecodedDiv out{0, 0};
122 const unsigned char *p = code;
123 const unsigned char *limit = code + 15;
124 bool operand16 = false;
125 bool rex_w = false;
126 bool addr16 = false;
127 while (p < limit) {
128 unsigned char c = *p;
129 if (c == 0x66) {
130 operand16 = true;
131 ++p;
132 continue;
133 }
134 if (c == 0x67) {
135 if (!long_mode) {
136 addr16 = true;
137 }
138 ++p;
139 continue;
140 }
141 if (c == 0xF0 || c == 0xF2 || c == 0xF3 || c == 0x26 || c == 0x2E ||
142 c == 0x36 || c == 0x3E || c == 0x64 || c == 0x65) {
143 ++p;
144 continue;
145 }
146 if (long_mode && c >= 0x40 && c <= 0x4F) {
147 rex_w = (c & 0x08) != 0;
148 ++p;
149 continue;
150 }
151 break;
152 }
153 if (addr16 || p >= limit) {
154 return out;
155 }
156 unsigned char opcode = *p++;
157 if (opcode != 0xF6 && opcode != 0xF7) {
158 return out;
159 }
160 if (p >= limit) {
161 return out;
162 }
163 unsigned char modrm = *p++;
164 unsigned mod = modrm >> 6;
165 unsigned reg = (modrm >> 3) & 7u;
166 unsigned rm = modrm & 7u;
167 if (reg != 6u && reg != 7u) {
168 return out;
169 }
170 if (mod != 3u) {
171 bool have_sib = rm == 4u;
172 unsigned sib_base = 0;
173 if (have_sib) {
174 if (p >= limit) {
175 return out;
176 }
177 sib_base = static_cast<unsigned>(*p++ & 7u);
178 }
179 if ((mod == 0u && rm == 5u) || (have_sib && mod == 0u && sib_base == 5u) ||
180 mod == 2u) {
181 if (p + 4 > limit) {
182 return out;
183 }
184 p += 4;
185 } else if (mod == 1u) {
186 if (p + 1 > limit) {
187 return out;
188 }
189 ++p;
190 }
191 }
192 int length = static_cast<int>(p - code);
193 if (length < 2 || length > 15) {
194 return out;
195 }
196 out.length = length;
197 if (opcode == 0xF6) {
198 out.width = 1;
199 } else if (rex_w) {
200 out.width = 8;
201 } else if (operand16) {
202 out.width = 2;
203 } else {
204 out.width = 4;
205 }
206 return out;
207}

◆ deleteUnbundledFiles()

void eonc::deleteUnbundledFiles ( const std::vector< std::string > & unbundledFilenames)

Definition at line 145 of file Bundling.cpp.

145 {
146 for (const auto &filename : unbundledFilenames) {
147 std::error_code ec;
148 fs::remove(filename, ec);
149 if (ec) {
150 EONC_LOG_ERROR("deleteUnbundledFiles: cannot remove {}: {}", filename,
151 ec.message());
152 }
153 }
154}

◆ disableFPE()

void eonc::disableFPE ( )

Definition at line 600 of file fpe_handler.cpp.

600 {
601#ifdef _WIN32
602 // Mask all floating-point exceptions (restore default behavior)
603 unsigned int control;
604 _controlfp_s(&control, _MCW_EM, _MCW_EM);
605#elif defined(__unix__)
606 fedisableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
607#elif defined(__APPLE__)
608 fenv_t env;
609 fegetenv(&env);
610#if defined(__aarch64__)
611 env.__fpcr &= ~((1u << 8) | (1u << 9) | (1u << 10));
612#elif defined(__x86_64__)
613 // enableFPE clears MXCSR IM/ZM/OM. Restoring that environment unchanged
614 // leaves the traps armed.
615 env.__mxcsr |= (MXCSR_MASK_IM | MXCSR_MASK_ZM | MXCSR_MASK_OM);
616 env.__mxcsr &= ~0x3Fu;
617 env.__control = static_cast<unsigned short>(env.__control | (1u << 0) |
618 (1u << 2) | (1u << 3));
619 env.__status = static_cast<unsigned short>(env.__status & ~0x3Fu);
620#endif
621 fesetenv(&env);
622#if defined(__x86_64__)
623 _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() | _MM_MASK_INVALID |
624 _MM_MASK_DIV_ZERO | _MM_MASK_OVERFLOW);
625#endif
626#endif
627}
static constexpr unsigned MXCSR_MASK_ZM
static constexpr unsigned MXCSR_MASK_OM
static constexpr unsigned MXCSR_MASK_IM

◆ eigenmodeCompute()

void eonc::eigenmodeCompute ( LowestEigenmode & s,
std::shared_ptr< Matter > matter,
AtomMatrix direction )
inline

Definition at line 31 of file EigenmodeStrategy.h.

32 {
33 s.compute(matter, direction);
34}
virtual void compute(std::shared_ptr< Matter > matter, AtomMatrix initialDirection)=0

◆ eigenmodeGetEigenvalue()

double eonc::eigenmodeGetEigenvalue ( LowestEigenmode & s)
inline

Definition at line 36 of file EigenmodeStrategy.h.

36 {
37 return s.getEigenvalue();
38}
virtual double getEigenvalue()=0

◆ eigenmodeGetEigenvector()

AtomMatrix eonc::eigenmodeGetEigenvector ( LowestEigenmode & s)
inline

Definition at line 40 of file EigenmodeStrategy.h.

40 {
41 return s.getEigenvector();
42}
virtual AtomMatrix getEigenvector()=0

◆ eigenmodeStatsAngle()

double eonc::eigenmodeStatsAngle ( LowestEigenmode & s)
inline

Definition at line 54 of file EigenmodeStrategy.h.

54{ return s.statsAngle; }

◆ eigenmodeStatsRotations()

long eonc::eigenmodeStatsRotations ( LowestEigenmode & s)
inline

Definition at line 56 of file EigenmodeStrategy.h.

56 {
57 return s.statsRotations;
58}

◆ eigenmodeStatsTorque()

double eonc::eigenmodeStatsTorque ( LowestEigenmode & s)
inline

Definition at line 52 of file EigenmodeStrategy.h.

52{ return s.statsTorque; }

◆ eigenmodeTotalForceCalls()

long eonc::eigenmodeTotalForceCalls ( LowestEigenmode & s)
inline

Definition at line 48 of file EigenmodeStrategy.h.

48 {
49 return s.totalForceCalls;
50}

◆ eigenmodeTotalIterations()

long eonc::eigenmodeTotalIterations ( LowestEigenmode & s)
inline

Definition at line 60 of file EigenmodeStrategy.h.

60 {
61 return s.totalIterations;
62}

◆ enableFPE()

void eonc::enableFPE ( )

Definition at line 559 of file fpe_handler.cpp.

559 {
560#ifdef _WIN32
561 // Register Windows SEH handler for FPE reporting
562 SetUnhandledExceptionFilter(windowsFPEHandler);
563 // Enable floating-point exceptions on Windows
564 _controlfp_s(nullptr, 0, _MCW_EM);
565 _controlfp_s(nullptr, ~(_EM_ZERODIVIDE | _EM_INVALID | _EM_OVERFLOW),
566 _MCW_EM);
567#elif defined(__unix__)
568 // Enable floating-point exceptions on Unix
569 feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
570#elif defined(__APPLE__) && defined(__aarch64__)
571 // ARM: trap-enable bits live in FPCR (IOE/DZE/OFE), not FPSR flags.
572 fenv_t env;
573 fegetenv(&env);
574 env.__fpcr |= ((1u << 8) | (1u << 9) | (1u << 10));
575 fesetenv(&env);
576#elif defined(__APPLE__) && defined(__x86_64__)
577 // Enable floating-point exceptions on Intel macOS
578 _MM_SET_EXCEPTION_MASK(
579 _MM_MASK_MASK &
580 ~(_MM_MASK_INVALID | _MM_MASK_DIV_ZERO | _MM_MASK_OVERFLOW));
581#else
582 fprintf(stderr, "FPE trapping not supported on this platform.\n");
583#endif
584
585#ifndef _WIN32
586 // Register POSIX signal handler
587 struct sigaction act;
588 act.sa_sigaction = fpe_signal_handler;
589 sigemptyset(&act.sa_mask);
590 act.sa_flags = SA_SIGINFO;
591 sigaction(SIGFPE, &act, nullptr);
592#if defined(__APPLE__) && defined(__aarch64__)
593 // Same continue path as SIGFPE. apple_arm64_fp_trap rejects a real
594 // illegal instruction (its ESR is not EC 0x2C) and re-raises SIGILL.
595 sigaction(SIGILL, &act, nullptr);
596#endif
597#endif
598}
static void fpe_signal_handler(int sig, siginfo_t *sip, void *scp)

◆ ensure_interpreter()

void eonc::ensure_interpreter ( )
inline

Definition at line 21 of file NbGuard.h.

21 {
22 if (!Py_IsInitialized()) {
23 // 0 = skip signal handlers (same idea as pybind11 embed defaults)
24 Py_InitializeEx(0);
25 }
26}

◆ evaluateTogether()

void eonc::evaluateTogether ( Potential & pot,
std::span< Matter *const > systems,
bool threads = false,
std::span< const long > owners = {} )

Evaluates every system that needs a force update.

With a potential that batches, the dirty systems go through forceBatch in one call, so calculator groups take them together; otherwise each computes on its own. Systems that are current are left alone.

With threads set, systems that compute on their own run on the image pool (eonc::forEachImage) when no two of them share an instance that is unsafe to share. Each system's result is the one its own serial evaluation gives.

owners, when given, holds one identity per system (a NEB image), which a batch passes to forceBatchOwned so the potential keeps per-system state (stored orbitals) under it; empty, the batch carries no owners.

Definition at line 998 of file Matter.cpp.

999 {
1000 std::vector<Matter *> dirty;
1001 std::vector<long> dirtyOwners;
1002 for (size_t i = 0; i < systems.size(); ++i) {
1003 Matter *m = systems[i];
1004 if (m != nullptr && m->needsForceUpdate()) {
1005 dirty.push_back(m);
1006 dirtyOwners.push_back(i < owners.size() ? owners[i] : -1);
1007 }
1008 }
1009 if (dirty.empty()) {
1010 return;
1011 }
1012 if (dirty.size() == 1 || !pot.supportsBatchEvaluation()) {
1013 if (threads && dirty.size() > 1 && canComputeConcurrently(dirty)) {
1014 eonc::forEachImage(static_cast<long>(dirty.size()), [&dirty](long i) {
1015 dirty[static_cast<size_t>(i - 1)]->getForcesRaw();
1016 });
1017 return;
1018 }
1019 for (Matter *m : dirty) {
1020 m->getForcesRaw();
1021 }
1022 return;
1023 }
1024 const long n = dirty.size();
1025 const long atoms = dirty.front()->numberOfAtoms();
1026 std::vector<VectorXi> nrs(n);
1027 std::vector<Matrix3d> boxes(n);
1028 std::vector<const double *> posPtr, boxPtr;
1029 std::vector<const int *> nrsPtr;
1030 std::vector<double *> frcPtr;
1031 for (long j = 0; j < n; ++j) {
1032 Matter *m = dirty[j];
1033 if (m->numberOfAtoms() != atoms) {
1034 throw std::invalid_argument(
1035 "evaluateTogether: systems differ in atom count");
1036 }
1037 nrs[j] = m->getAtomicNrs();
1038 // A non-periodic system hands the potential a zero box, as
1039 // computePotential does. A host that owns the cell still sees it.
1040 boxes[j] = (m->getPeriodic() || pot.forwardsStoredCell())
1041 ? m->getCell()
1042 : Matrix3d::Zero().eval();
1043 }
1044 for (long j = 0; j < n; ++j) {
1045 posPtr.push_back(dirty[j]->getPositions().data());
1046 nrsPtr.push_back(nrs[j].data());
1047 frcPtr.push_back(dirty[j]->forcesData());
1048 boxPtr.push_back(boxes[j].data());
1049 }
1050 std::vector<double> energies(n), variances(n);
1051 if (owners.empty()) {
1052 pot.forceBatch(n, atoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
1053 energies.data(), variances.data(), boxPtr.data());
1054 } else {
1055 pot.forceBatchOwned(n, atoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
1056 energies.data(), variances.data(), boxPtr.data(),
1057 dirtyOwners.data());
1058 }
1059 for (long j = 0; j < n; ++j) {
1060 dirty[j]->setComputedPotential(energies[j], variances[j]);
1061 }
1062}
VectorXi getAtomicNrs() const
Definition Matter.cpp:786
bool getPeriodic() const noexcept
Definition Matter.h:338
Matrix3d getCell() const
Definition Matter.cpp:345
long int numberOfAtoms() const
Definition Matter.cpp:343
const AtomMatrix & getForcesRaw() const
Definition Matter.cpp:493
bool needsForceUpdate() const
Whether forces need recomputation (positions or surface epoch changed).
Definition Matter.h:220
void forEachImage(long n, Work &&work)
bool canComputeConcurrently(std::span< Matter *const > systems)
True when the systems can compute on separate threads at once: every potential instance that two of t...
Definition Matter.cpp:981

◆ fdForceDerivative()

template<class M>
M eonc::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.

Fourth-order central: [-f(+2h) + 8 f(+h) - 8 f(-h) + f(-2h)] / (12 h).

Definition at line 46 of file FiniteDifference.h.

47 {
48 M slope = fPlus;
49 switch (scheme) {
51 slope = (-fPlus2 + 8.0 * fPlus - 8.0 * fMinus + fMinus2) / (12.0 * dr);
52 break;
54 slope = (fPlus - fMinus) / (2.0 * dr);
55 break;
57 slope = (fPlus - f0) / dr;
58 break;
59 }
60 return slope;
61}

◆ fdHessianVector()

template<class Eval>
VectorXd eonc::fdHessianVector ( FdScheme scheme,
double dr,
const VectorXd & force0,
Eval && eval )

Energy Hessian-vector product -dF.

eval(scale) is the force at x + scale * dr * v. One-sided and central read only the samples they need; fourth reads scale in {1, -1, 2, -2}.

Definition at line 67 of file FiniteDifference.h.

68 {
69 const VectorXd zero = VectorXd::Zero(force0.size());
70 switch (scheme) {
71 case FdScheme::Fourth: {
72 const VectorXd fPlus = eval(1.0);
73 const VectorXd fMinus = eval(-1.0);
74 const VectorXd fPlus2 = eval(2.0);
75 const VectorXd fMinus2 = eval(-2.0);
76 return -fdForceDerivative(scheme, dr, force0, fPlus, fMinus, fPlus2,
77 fMinus2);
78 }
79 case FdScheme::Central: {
80 const VectorXd fPlus = eval(1.0);
81 const VectorXd fMinus = eval(-1.0);
82 return -fdForceDerivative(scheme, dr, force0, fPlus, fMinus, zero, zero);
83 }
85 break;
86 }
87 const VectorXd fPlus = eval(1.0);
88 return -fdForceDerivative(FdScheme::OneSided, dr, force0, fPlus, zero, zero,
89 zero);
90}
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.

◆ followIrc()

IrcPath eonc::followIrc ( const Matter & saddle,
const AtomMatrix & mode,
const Parameters & params )

Follows the rgsaddle IRC from a converged saddle along both signs of its lowest mode.

The walk is in mass-weighted coordinates of the free atoms. A branch stops at a point that rgsaddle reports as a minimum, or after irc_max_steps steps of [Saddle Search]. rgsaddle makes that report only after the first step and at a largest atomic force at or below irc_converged_force.

Definition at line 138 of file XtsciIrc.cpp.

139 {
140 if (!ircAvailable()) {
141 throw std::runtime_error("rgsaddle IRC is not available in this build");
142 }
143#ifdef EONC_RGSADDLE_IRC
144 const auto &opts = params.saddle_search_options().irc;
145 std::vector<double> masses;
146 std::vector<long> rows;
147 for (long i = 0; i < saddle.numberOfAtoms(); ++i) {
148 if (!saddle.getFixed(i)) {
149 masses.push_back(saddle.getMass(i));
150 rows.push_back(i);
151 }
152 }
153 if (rows.empty() || mode.rows() != saddle.numberOfAtoms()) {
154 throw std::runtime_error("IRC needs free atoms and one mode row per atom");
155 }
156 const auto nFree = static_cast<Eigen::Index>(rows.size());
157 AtomMatrix freeMode(nFree, 3);
158 for (Eigen::Index j = 0; j < nFree; ++j) {
159 freeMode.row(j) = mode.row(rows[static_cast<size_t>(j)]);
160 }
161 const Eigen::VectorXd x0 = saddle.getPositionsFreeV();
162
163 Matter probe(saddle);
164 IrcUser ctx{&probe, {}};
165 // One session per branch: a GS2 session halves dx on every rejected trial
166 // and keeps the shorter step through rgsaddle_irc_set_direction.
167 auto branch = [&](int32_t direction) {
168 rgsaddle_irc_config_t config{};
169 config.version = RGSADDLE_VERSION_INIT;
170 config.dx = opts.step_size;
171 config.force_tol = opts.converged_force;
172 config.force_gate = RGSADDLE_FORCE_MAX_ATOM;
173 config.max_move = params.optimizer_options().max_move;
174 config.max_inner = 10;
175 config.kind = RGSADDLE_IRC_GS2;
176 config.direction = direction;
177 std::unique_ptr<RgsaddleIrc, decltype(&rgsaddle_irc_free)> session(
178 rgsaddle_irc_create(&config, nFree, x0.data(), masses.data(),
179 freeMode.data()),
180 &rgsaddle_irc_free);
181 if (!session) {
182 throw std::runtime_error("rgsaddle_irc_create failed");
183 }
184 return followBranch(session.get(), ctx, opts.max_steps, 3 * nFree);
185 };
186 IrcBranch forward = branch(RGSADDLE_IRC_FORWARD);
187 IrcBranch reverse = branch(RGSADDLE_IRC_REVERSE);
188
189 // The forward kick takes its sign from rgsaddle.
190 const bool forwardAlongMode =
191 forward.positions.empty() ||
192 saddle.pbc(forward.positions.front() - saddle.getPositions())
193 .cwiseProduct(mode)
194 .sum() > 0.0;
195 IrcPath path;
196 path.plus = forwardAlongMode ? std::move(forward) : std::move(reverse);
197 path.minus = forwardAlongMode ? std::move(reverse) : std::move(forward);
198 return path;
199#else
200 static_cast<void>(saddle);
201 static_cast<void>(mode);
202 static_cast<void>(params);
203 return {};
204#endif
205}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
const optimizer_options_t & optimizer_options() const
constexpr long saddle
bool ircAvailable()
True when this build can run followIrc: linked to rgsaddle at C ABI minor 14 or newer,...
Definition XtsciIrc.cpp:128
Accepted points of one branch of the intrinsic reaction coordinate (IRC), in order away from the sadd...
Definition XtsciIrc.h:23
Both branches of the IRC.
Definition XtsciIrc.h:35
IrcBranch plus
Definition XtsciIrc.h:37
struct eonc::saddle_search_options_t::irc_t irc

◆ forceJobRegistration()

void eonc::forceJobRegistration ( )

Definition at line 42 of file Job.cpp.

42{}

◆ forEachImage()

template<typename Work>
void eonc::forEachImage ( long n,
Work && work )
inline

Definition at line 191 of file ForEachImage.h.

191 {
192 const std::function<void(long)> f = std::ref(work);
194}
static ImagePool & instance()
void run(long n, const std::function< void(long)> &work)

◆ fpe_signal_handler()

void eonc::fpe_signal_handler ( int sig,
siginfo_t * sip,
void * scp )
static

Definition at line 323 of file fpe_handler.cpp.

323 {
324 // Async-signal-safe only: write(2) and sig_atomic_t. No iostream, malloc,
325 // backtrace, or fenv helpers (fedisableexcept / feclearexcept are not
326 // async-signal-safe). All continue-state is written into the saved ucontext
327 // so it is restored on sigreturn.
328 //
329 // x86 cannot "continue" past a trapped FP op by clearing sticky flags:
330 // flags are bits 0-5 of MXCSR/swd, but the exception MASK bits live at
331 // MXCSR 7-12. Clearing 0x3F leaves trapping armed, so the faulting
332 // instruction re-executes on the same operands and re-raises forever
333 // (report, sigreturn, refault) -- multi-GB identical stderr lines and a
334 // client stuck at ~100% CPU. Mask the class in the restored MXCSR so
335 // re-execution produces the IEEE default (Inf/NaN) and proceeds.
336 static volatile sig_atomic_t reported_div = 0;
337 static volatile sig_atomic_t reported_inv = 0;
338 static volatile sig_atomic_t reported_ovf = 0;
339 static volatile sig_atomic_t reported_unk = 0;
340 static volatile sig_atomic_t reported_int = 0;
341
342 static constexpr char prefix[] = "FPE (continuing, masking further): ";
343 static constexpr char msg_div[] = "division by zero\n";
344 static constexpr char msg_inv[] = "invalid operation\n";
345 static constexpr char msg_ovf[] = "overflow\n";
346 static constexpr char msg_unk[] = "unknown\n";
347
348 // Default: mask all three classes we enable at startup, so an unknown
349 // si_code cannot leave trapping armed and re-storm.
350 unsigned mxcsr_mask_bits = MXCSR_MASK_IM | MXCSR_MASK_ZM | MXCSR_MASK_OM;
351 volatile sig_atomic_t *reported = &reported_unk;
352 const char *msg = msg_unk;
353 size_t msg_len = sizeof(msg_unk) - 1;
354 bool classified = false;
355
356#if defined(__APPLE__) && defined(__aarch64__)
357 if (sig == SIGILL) {
358 unsigned trap_mask = 0;
359 if (!apple_arm64_fp_trap(scp, &trap_mask)) {
360 struct sigaction dfl;
361 dfl.sa_handler = SIG_DFL;
362 sigemptyset(&dfl.sa_mask);
363 dfl.sa_flags = 0;
364 sigaction(SIGILL, &dfl, nullptr);
365 raise(SIGILL);
366 return;
367 }
368 classified = true;
369 mxcsr_mask_bits = trap_mask;
370 if (trap_mask == MXCSR_MASK_ZM) {
371 reported = &reported_div;
372 msg = msg_div;
373 msg_len = sizeof(msg_div) - 1;
374 } else if (trap_mask == MXCSR_MASK_IM) {
375 reported = &reported_inv;
376 msg = msg_inv;
377 msg_len = sizeof(msg_inv) - 1;
378 } else if (trap_mask == MXCSR_MASK_OM) {
379 reported = &reported_ovf;
380 msg = msg_ovf;
381 msg_len = sizeof(msg_ovf) - 1;
382 }
383 }
384#endif
385
386 // Integer #DE has no mask bit. Returning here re-executes the divide.
387 if (!classified &&
388 (sip->si_code == FPE_INTDIV || sip->si_code == FPE_INTOVF)) {
389 if (reported_int == 0) {
390 reported_int = 1;
391 static constexpr char iprefix[] = "FPE (continuing, skipping divide): ";
392 static constexpr char msg_idiv[] = "integer divide\n";
393 static constexpr char msg_iovf[] = "integer overflow\n";
394 const char *imsg = sip->si_code == FPE_INTDIV ? msg_idiv : msg_iovf;
395 size_t imsg_len = sizeof(msg_iovf) - 1;
396 if (sip->si_code == FPE_INTDIV) {
397 imsg_len = sizeof(msg_idiv) - 1;
398 }
399 write(STDERR_FILENO, iprefix, sizeof(iprefix) - 1);
400 write(STDERR_FILENO, imsg, imsg_len);
401 write_fault_rip(scp);
402 }
403 if (!advance_integer_div(scp) && sip->si_code == FPE_INTDIV) {
404 static constexpr char stuck[] =
405 "FPE integer divide: could not skip faulting instruction\n";
406 write(STDERR_FILENO, stuck, sizeof(stuck) - 1);
407 _exit(128 + SIGFPE);
408 }
409 return;
410 }
411
412 if (!classified) {
413 switch (sip->si_code) {
414 case FPE_FLTDIV:
415 reported = &reported_div;
416 msg = msg_div;
417 msg_len = sizeof(msg_div) - 1;
418 mxcsr_mask_bits = MXCSR_MASK_ZM;
419 break;
420 case FPE_FLTINV:
421 reported = &reported_inv;
422 msg = msg_inv;
423 msg_len = sizeof(msg_inv) - 1;
424 mxcsr_mask_bits = MXCSR_MASK_IM;
425 break;
426 case FPE_FLTOVF:
427 reported = &reported_ovf;
428 msg = msg_ovf;
429 msg_len = sizeof(msg_ovf) - 1;
430 mxcsr_mask_bits = MXCSR_MASK_OM;
431 break;
432 default:
433 break;
434 }
435 }
436
437 if (*reported == 0) {
438 *reported = 1;
439 write(STDERR_FILENO, prefix, sizeof(prefix) - 1);
440 write(STDERR_FILENO, msg, msg_len);
441 // First-fault RIP for post-mortem addr2line / offline diagnosis.
442 write_fault_rip(scp);
443 }
444
445#if defined(__linux__) && (defined(__x86_64__) || defined(__i386__))
446 ucontext_t *ctx = static_cast<ucontext_t *>(scp);
447 if (ctx->uc_mcontext.fpregs) {
448 // Clear sticky exception FLAGS (bits 0-5) and arm the MASK bit(s) for
449 // the fault class (bits 7-12). Mask sticks after sigreturn because the
450 // restored MXCSR becomes the live CPU state.
451 ctx->uc_mcontext.fpregs->swd &= ~0x3Fu;
452 ctx->uc_mcontext.fpregs->mxcsr &= ~0x3Fu;
453 ctx->uc_mcontext.fpregs->mxcsr |= mxcsr_mask_bits;
454 // x87 control word: mask bits are 0-5 of cwd (IM, DM, ZM, OM, UM, PM).
455 // Set the matching masks so a legacy x87 fault cannot re-storm either.
456 if (mxcsr_mask_bits & MXCSR_MASK_ZM) {
457 ctx->uc_mcontext.fpregs->cwd |= (1u << 2); // x87 ZM
458 }
459 if (mxcsr_mask_bits & MXCSR_MASK_IM) {
460 ctx->uc_mcontext.fpregs->cwd |= (1u << 0); // x87 IM
461 }
462 if (mxcsr_mask_bits & MXCSR_MASK_OM) {
463 ctx->uc_mcontext.fpregs->cwd |= (1u << 3); // x87 OM
464 }
465 }
466#elif defined(__linux__) && defined(__aarch64__)
467 // ARM polarity is the opposite of MXCSR: FPCR trap-enable bits SET mean
468 // trap. Clearing sticky FPSR flags alone re-executes with trapping still
469 // armed on aarch64. Clear the matching FPCR enables.
470 constexpr uint32_t kFpsimdMagic = 0x46508001u;
471 constexpr unsigned kFpcrIoe = 1u << 8;
472 constexpr unsigned kFpcrDze = 1u << 9;
473 constexpr unsigned kFpcrOfe = 1u << 10;
474 unsigned fpcr_clear = kFpcrIoe | kFpcrDze | kFpcrOfe;
475 if (mxcsr_mask_bits == MXCSR_MASK_ZM) {
476 fpcr_clear = kFpcrDze;
477 } else if (mxcsr_mask_bits == MXCSR_MASK_IM) {
478 fpcr_clear = kFpcrIoe;
479 } else if (mxcsr_mask_bits == MXCSR_MASK_OM) {
480 fpcr_clear = kFpcrOfe;
481 }
482 auto *ctx = static_cast<ucontext_t *>(scp);
483 unsigned char *p =
484 reinterpret_cast<unsigned char *>(ctx->uc_mcontext.__reserved);
485 unsigned char *end = p + sizeof(ctx->uc_mcontext.__reserved);
486 struct A64Head {
487 uint32_t magic;
488 uint32_t size;
489 };
490 struct Fpsimd {
491 A64Head head;
492 uint32_t fpsr;
493 uint32_t fpcr;
494 };
495 while (p + sizeof(A64Head) <= end) {
496 auto *h = reinterpret_cast<A64Head *>(p);
497 if (h->magic == 0 || h->size < sizeof(A64Head)) {
498 break;
499 }
500 if (h->magic == kFpsimdMagic && h->size >= sizeof(Fpsimd) &&
501 p + h->size <= end) {
502 auto *f = reinterpret_cast<Fpsimd *>(p);
503 f->fpsr &= ~0x1Fu;
504 f->fpcr &= ~fpcr_clear;
505 break;
506 }
507 if (h->size == 0) {
508 break;
509 }
510 p += h->size;
511 }
512#elif defined(__APPLE__) && defined(__x86_64__)
513 // Darwin restores SSE state from uc_mcontext->__fs. Mask bits have the
514 // same polarity as Linux MXCSR: set means the class does not trap. Without
515 // that update the faulting instruction re-executes and re-raises forever.
516 auto *ctx = static_cast<ucontext_t *>(scp);
517 if (ctx->uc_mcontext) {
518 auto &fs = ctx->uc_mcontext->__fs;
519 fs.__fpu_mxcsr &= ~0x3Fu;
520 fs.__fpu_mxcsr |= mxcsr_mask_bits;
521 if (mxcsr_mask_bits & MXCSR_MASK_ZM) {
522 fs.__fpu_fcw.__zdiv = 1;
523 }
524 if (mxcsr_mask_bits & MXCSR_MASK_IM) {
525 fs.__fpu_fcw.__invalid = 1;
526 }
527 if (mxcsr_mask_bits & MXCSR_MASK_OM) {
528 fs.__fpu_fcw.__ovrfl = 1;
529 }
530 fs.__fpu_fsw.__invalid = 0;
531 fs.__fpu_fsw.__denorm = 0;
532 fs.__fpu_fsw.__zdiv = 0;
533 fs.__fpu_fsw.__ovrfl = 0;
534 fs.__fpu_fsw.__undfl = 0;
535 fs.__fpu_fsw.__precis = 0;
536 }
537#elif defined(__APPLE__) && defined(__aarch64__)
538 constexpr unsigned kFpcrIoe = 1u << 8;
539 constexpr unsigned kFpcrDze = 1u << 9;
540 constexpr unsigned kFpcrOfe = 1u << 10;
541 unsigned fpcr_clear = kFpcrIoe | kFpcrDze | kFpcrOfe;
542 if (mxcsr_mask_bits == MXCSR_MASK_ZM) {
543 fpcr_clear = kFpcrDze;
544 } else if (mxcsr_mask_bits == MXCSR_MASK_IM) {
545 fpcr_clear = kFpcrIoe;
546 } else if (mxcsr_mask_bits == MXCSR_MASK_OM) {
547 fpcr_clear = kFpcrOfe;
548 }
549 auto *ctx = static_cast<ucontext_t *>(scp);
550 if (ctx->uc_mcontext) {
551 ctx->uc_mcontext->__ns.__fpsr &= ~0x1Fu;
552 ctx->uc_mcontext->__ns.__fpcr &= ~fpcr_clear;
553 }
554#endif
555 static_cast<void>(sig);
556}
static void write_fault_rip(void *scp)
static bool advance_integer_div(void *scp)

◆ freeAtomIndices()

VectorXi eonc::freeAtomIndices ( const Matter * matter)

Free (unfixed) atom indices in ascending order.

Definition at line 49 of file MobileAtoms.cpp.

49 {
50 if (!matter) {
51 throw std::invalid_argument("freeAtomIndices: null Matter");
52 }
53 const long n = matter->numberOfAtoms();
54 std::vector<int> free;
55 free.reserve(static_cast<size_t>(matter->numberOfFreeAtoms()));
56 for (long i = 0; i < n; ++i) {
57 if (!matter->getFixed(i)) {
58 free.push_back(static_cast<int>(i));
59 }
60 }
61 VectorXi out(static_cast<Eigen::Index>(free.size()));
62 for (Eigen::Index k = 0; k < out.size(); ++k) {
63 out(k) = free[static_cast<size_t>(k)];
64 }
65 return out;
66}
long int numberOfFreeAtoms() const
Definition Matter.cpp:653
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575

◆ from_fortran_layout_vector()

AtomMatrix eonc::from_fortran_layout_vector ( const std::vector< double > & flat_colmajor,
int nat )
inline

Reconstruct AtomMatrix from a flat column-major vector (e.g.

from Fortran). RowMajor(N,3) and ColMajor(3,N) share the same contiguous memory layout, so this is effectively a reinterpretation of the flat data.

Definition at line 61 of file Eigen.h.

61 {
62 assert(flat_colmajor.size() >= static_cast<size_t>(3 * nat));
63 return Eigen::Map<const AtomMatrix>(flat_colmajor.data(), nat, 3);
64}

◆ get_artn_resource()

ARTnResource & eonc::get_artn_resource ( )
inline

Global access to thread-safe ARTn resource.

Definition at line 179 of file ARTnResource.h.

179{ return ARTnResource::instance(); }
static ARTnResource & instance()
Thread-safe singleton accessor (Meyer's pattern).

◆ get_ira_resource()

IRAResource & eonc::get_ira_resource ( )
inline

Global access to thread-safe IRA resource.

Definition at line 135 of file IRAResource.h.

135{ return IRAResource::instance(); }
static IRAResource & instance()
Thread-safe singleton accessor (Meyer's pattern).

◆ getBundleSize()

int eonc::getBundleSize ( )

Definition at line 27 of file Bundling.cpp.

27 {
28 int num_bundle = -1;
29
30 for (const auto &entry : fs::directory_iterator(".")) {
31 std::string name = entry.path().filename().string();
32
33 if (name.empty() || name[0] == '.') {
34 continue;
35 }
36
37 // If "config" is not in the filename
38 // then skip.
39 if (name.find("config") == std::string::npos &&
40 name.find("ini") == std::string::npos) {
41 continue;
42 }
43
44 // Find the last underscore
45 auto upos = name.rfind('_');
46 if (upos == std::string::npos) {
47 continue;
48 }
49
50 // Find the last period
51 auto dpos = name.rfind('.');
52 if (dpos == std::string::npos || dpos <= upos) {
53 continue;
54 }
55
56 std::string numstr = name.substr(upos + 1, dpos - upos - 1);
57 int value = 0;
58 const auto parsed =
59 std::from_chars(numstr.data(), numstr.data() + numstr.size(), value);
60 if (parsed.ec == std::errc{} && parsed.ptr != numstr.data()) {
61 const int i = value + 1;
62 if (i > num_bundle) {
63 num_bundle = i;
64 }
65 }
66 }
67
68 return num_bundle;
69}

◆ greedyColorCutoffGraph()

std::vector< int > eonc::greedyColorCutoffGraph ( const std::vector< std::vector< int > > & adj)

Greedy coloring of an undirected graph.

adj[v] lists neighbors of v (self-loops ignored). Colors are dense from 0 in vertex order.

Definition at line 311 of file Hessian.cpp.

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

◆ harmonicModeFreeEnergy()

double eonc::harmonicModeFreeEnergy ( double hbarOmegaEv,
double temperature )

kT ln(2 sinh(beta hbar omega / 2)) in eV.

A non-positive temperature is the zero-temperature limit, hbar omega / 2.

Definition at line 114 of file QuantumFreeEnergy.cpp.

114 {
115 if (!(hbarOmegaEv > 0.0) || !std::isfinite(hbarOmegaEv)) {
116 throw std::invalid_argument(
117 "a perpendicular mode needs a positive hbar omega");
118 }
119 if (!(temperature > 0.0)) {
120 return 0.5 * hbarOmegaEv;
121 }
122 const double x = hbarOmegaEv / (2.0 * tunneling::kBoltzmann * temperature);
123 return tunneling::kBoltzmann * temperature * lnTwoSinh(x);
124}
constexpr double kBoltzmann
Boltzmann constant in eV / K, correctly rounded from the exact 1.380649e-23 J / K.
Definition Tunneling.h:43

◆ ircAvailable()

bool eonc::ircAvailable ( )

True when this build can run followIrc: linked to rgsaddle at C ABI minor 14 or newer, at compile time and at load time.

Definition at line 128 of file XtsciIrc.cpp.

128 {
129#ifdef EONC_RGSADDLE_IRC
130 rgsaddle_version_t abi{};
131 return rgsaddle_abi_stamp(&abi) == RGSADDLE_OK &&
132 abi.major == RGSADDLE_ABI_MAJOR && abi.minor >= 14;
133#else
134 return false;
135#endif
136}

◆ jobTable()

std::map< JobType, JobFactory > & eonc::jobTable ( )

Definition at line 14 of file JobRegistry.cpp.

14 {
15 static std::map<JobType, JobFactory> t;
16 return t;
17}

◆ lammpsOpenArgs()

std::vector< std::string > eonc::lammpsOpenArgs ( bool logging,
bool with_omp,
const std::string & screen )
inline

LAMMPS argv.

The log file stays off. A screen path is copied into the process logger by the caller.

Definition at line 51 of file LAMMPSPot.h.

52 {
53 std::vector<std::string> args{"liblammps", "-echo", "screen", "-log", "none"};
54 if (logging) {
55 args.insert(args.end(), {"-screen", screen});
56 } else {
57 args.insert(args.end(), {"-screen", "none"});
58 }
59 if (with_omp) {
60 args.insert(args.end(), {"-suffix", "omp"});
61 }
62 return args;
63}

◆ lammpsScreenCursor()

std::int64_t eonc::lammpsScreenCursor ( std::int64_t pos,
std::int64_t fileSize,
bool restarted )
inline

Byte offset at which to keep copying a LAMMPS screen file.

A new LAMMPS open truncates that file, so a restart or a shorter file reads from the start.

Definition at line 41 of file LAMMPSPot.h.

42 {
43 if (restarted || pos < 0 || fileSize < pos) {
44 return 0;
45 }
46 return pos;
47}

◆ lammpsWorkerReaped()

bool eonc::lammpsWorkerReaped ( long got,
long child,
int err )
inline

True when waitpid has collected the child. EINTR is not a collection.

Definition at line 31 of file LAMMPSPot.h.

31 {
32 if (got == child) {
33 return true;
34 }
35 return got < 0 && err != EINTR;
36}

◆ lattice_rows_to_fortran_box()

void eonc::lattice_rows_to_fortran_box ( const Matrix3d & cell,
double * box )
inline

Pack an eOn cell for pARTn artn_step.

Lattice vector i is row i here and Fortran column i there (box(:,i)). Row-major cell memory is already that column-major layout. Filling box so Fortran box(i,j) equals cell(i,j) sends the transpose.

Definition at line 71 of file Eigen.h.

71 {
72 for (int vec = 0; vec < 3; ++vec) {
73 for (int comp = 0; comp < 3; ++comp) {
74 box[vec * 3 + comp] = cell(vec, comp);
75 }
76 }
77}

◆ maskWindowsMxcsrForContinue()

std::uint32_t eonc::maskWindowsMxcsrForContinue ( std::uint32_t mxcsr)
constexpr

Definition at line 24 of file fpe_handler.h.

24 {
25 return (mxcsr & ~std::uint32_t{0x3Fu}) | kWindowsMxcsrExceptionMasks;
26}
constexpr std::uint32_t kWindowsMxcsrExceptionMasks
Definition fpe_handler.h:23

◆ maxFreeAtomForceNorm()

double eonc::maxFreeAtomForceNorm ( const double * forces,
const double * fixed,
long nAtoms )
nodiscard

Max Euclidean norm over N x 3 row-major force rows.

An atom is ignored when fixed is non-null and all three of its mask entries are greater than 0.5 (fully fixed). fixed == nullptr keeps every atom. Returns 0 when nAtoms is not positive, and NaN when any free atom's norm is NaN, on every SIMD target.

Definition at line 107 of file ForceNorm.cpp.

108 {
109 return detail::maxFreeAtomForceNormScalar(forces, fixed, 0, nAtoms);
110}
double maxFreeAtomForceNormScalar(const double *forces, const double *fixed, long begin, long nAtoms)
Scalar max of per-atom Euclidean norms on [begin, nAtoms).
Definition ForceNorm.h:25

◆ minImageRemoveRigidDrift()

AtomMatrix eonc::minImageRemoveRigidDrift ( const Matter & reference,
AtomMatrix diff,
Eigen::RowVector3d * totalDrift )

Minimum-image a free-atom difference and remove rigid translation.

One pbc pass wraps boundary atoms while a uniform drift remains, so the primary guideline and each symmetry product share this fixed point.

Definition at line 71 of file OHTSTJob.cpp.

72 {
73 // AV-embedded frames ride the defect (drift = one hop vector, a/2<011>
74 // observed). Atoms near a cell boundary min-image inconsistently until
75 // that drift is gone, so min-image and de-drift iterate to a fixed point.
76 // The residual is the localized reaction coordinate.
77 Eigen::RowVector3d total = Eigen::RowVector3d::Zero();
78 for (int pass = 0; pass < 6; ++pass) {
79 diff = reference.pbc(diff);
80 const Eigen::RowVector3d drift =
81 diff.colwise().sum() / static_cast<double>(diff.rows());
82 diff.rowwise() -= drift;
83 total += drift;
84 if (drift.norm() < 1e-6) {
85 break;
86 }
87 }
88 if (totalDrift != nullptr) {
89 *totalDrift = total;
90 }
91 return diff;
92}
AtomMatrix pbc(const AtomMatrix &diff) const
Definition Matter.cpp:943

◆ mobileForces()

VectorXd eonc::mobileForces ( Matter * matter,
const VectorXi & mobile )

Force components on mobile atoms after Matter has a valid force cache (calls getForces under the hood if needed via the non-const Matter API).

Definition at line 142 of file MobileAtoms.cpp.

142 {
143 const AtomMatrix forces = matter->getForces();
144 return packMobileRows(forces, mobile);
145}
const AtomMatrix & getForces() const
Definition Matter.cpp:482
VectorXd packMobileRows(const AtomMatrix &full, const VectorXi &mobile)
Pack full (n_atoms,3) rows of mobile atoms into a 3*n_mobile vector.

◆ modeCurvature()

double eonc::modeCurvature ( const Matter & matter,
const AtomMatrix & mode,
double dr )

Curvature along mode from one forward difference of the forces over dr Angstrom.

Costs one force call on a copy of matter.

Definition at line 26 of file PrfoRefine.cpp.

26 {
27 const AtomMatrix free = matter.getFree();
28 const AtomMatrix t = mode.cwiseProduct(free);
29 const double norm = t.norm();
30 if (!(norm > 0.0) || !(dr > 0.0)) {
31 throw std::invalid_argument("modeCurvature: zero mode or step");
32 }
33 const AtomMatrix unit = t / norm;
34 Matter probe(matter);
35 probe.setPositions(matter.getPositions() + dr * unit);
36 return -(probe.getForces() - matter.getForces()).cwiseProduct(unit).sum() /
37 dr;
38}
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
AtomMatrix getFree() const
Definition Matter.cpp:799

◆ packMobileRows()

VectorXd eonc::packMobileRows ( const AtomMatrix & full,
const VectorXi & mobile )

Pack full (n_atoms,3) rows of mobile atoms into a 3*n_mobile vector.

Definition at line 127 of file MobileAtoms.cpp.

127 {
128 VectorXd packed(3 * mobile.size());
129 for (Eigen::Index a = 0; a < mobile.size(); ++a) {
130 packed.segment<3>(3 * a) = full.row(mobile(a));
131 }
132 return packed;
133}

◆ parseFdScheme()

FdScheme eonc::parseFdScheme ( std::string_view scheme)
inline

Definition at line 27 of file FiniteDifference.h.

27 {
28 std::string lower;
29 lower.reserve(scheme.size());
30 for (unsigned char c : scheme) {
31 lower.push_back(static_cast<char>(std::tolower(c)));
32 }
33 if (lower == "central") {
34 return FdScheme::Central;
35 }
36 if (lower == "fourth" || lower == "fourth_order" || lower == "central4") {
37 return FdScheme::Fourth;
38 }
39 return FdScheme::OneSided;
40}

◆ parseServeSpec()

std::vector< ServeEndpoint > eonc::parseServeSpec ( const std::string & spec)

Parse a serve configuration string into endpoints.

Accepts comma-separated entries of the form "potential:port" or "potential:host:port". Examples: "lj:12345" "metatomic:12345,lj:12346" "metatomic:0.0.0.0:12345"

Parameters
specThe comma-separated endpoint specification.
Returns
A vector of ServeEndpoint structs.

Definition at line 235 of file ServeMode.cpp.

235 {
236 std::vector<ServeEndpoint> endpoints;
237 std::istringstream stream(spec);
238 std::string token;
239
240 while (std::getline(stream, token, ',')) {
241 // Trim whitespace
242 token.erase(0, token.find_first_not_of(" \t"));
243 token.erase(token.find_last_not_of(" \t") + 1);
244 if (token.empty())
245 continue;
246
247 // Parse "potential:port" or "potential:host:port"
248 size_t first_colon = token.find(':');
249 if (first_colon == std::string::npos) {
250 EONC_LOG_ERROR("Invalid serve spec '{}': expected 'potential:port'",
251 token);
252 continue;
253 }
254
255 std::string pot_str = token.substr(0, first_colon);
256 std::string rest = token.substr(first_colon + 1);
257
258 // Trim parts after colon split
259 pot_str.erase(0, pot_str.find_first_not_of(" \t"));
260 pot_str.erase(pot_str.find_last_not_of(" \t") + 1);
261 rest.erase(0, rest.find_first_not_of(" \t"));
262 rest.erase(rest.find_last_not_of(" \t") + 1);
263
264 // Lowercase the potential name
265 std::ranges::transform(pot_str, pot_str.begin(), [](unsigned char c) {
266 return static_cast<char>(std::tolower(c));
267 });
268
269 ServeEndpoint ep;
270 ep.potential =
271 magic_enum::enum_cast<PotType>(pot_str, magic_enum::case_insensitive)
272 .value_or(PotType::UNKNOWN);
273
274 if (ep.potential == PotType::UNKNOWN) {
275 EONC_LOG_ERROR("Unknown potential type '{}'", pot_str);
276 continue;
277 }
278
279 size_t second_colon = rest.find(':');
280 if (second_colon != std::string::npos) {
281 // "host:port" format
282 ep.host = rest.substr(0, second_colon);
283 ep.host.erase(0, ep.host.find_first_not_of(" \t"));
284 ep.host.erase(ep.host.find_last_not_of(" \t") + 1);
285 std::string port_str = rest.substr(second_colon + 1);
286 port_str.erase(0, port_str.find_first_not_of(" \t"));
287 port_str.erase(port_str.find_last_not_of(" \t") + 1);
288 ep.port = static_cast<uint16_t>(std::stoi(port_str));
289 } else {
290 // "port" only
291 ep.host = "localhost";
292 ep.port = static_cast<uint16_t>(std::stoi(rest));
293 }
294
295 QUILL_LOG_INFO(eonc::log::get(), "Parsed endpoint: {} on {}:{}",
296 std::string(magic_enum::enum_name(ep.potential)), ep.host,
297 ep.port);
298 endpoints.push_back(ep);
299 }
300
301 return endpoints;
302}
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111

◆ periodicCutoffNeighbors()

std::vector< CutoffPair > eonc::periodicCutoffNeighbors ( const double * positions,
size_t atoms,
const double * cell,
double cutoff,
bool full )

Definition at line 6 of file LinkCellNeighbors.cpp.

9 {
10 const auto box = linkcell::Cell::from_vectors({cell[0], cell[1], cell[2]},
11 {cell[3], cell[4], cell[5]},
12 {cell[6], cell[7], cell[8]});
13 const auto rows = linkcell::pairs_within(positions, atoms, box, cutoff,
14 nullptr, 0.0, !full);
15 std::vector<CutoffPair> result;
16 result.reserve(rows.size());
17 for (const auto &pair : rows)
18 result.push_back({pair.i, pair.j, pair.shift, pair.dist2});
19 return result;
20}

◆ perpendicularEigenvalues()

Eigen::VectorXd eonc::perpendicularEigenvalues ( const Eigen::MatrixXd & hessian,
const Eigen::VectorXd & tangent )

Eigenvalues of the mass-weighted Hessian after the tangent direction is removed: one fewer than the Hessian has rows.

tangent is mass-weighted and has one entry per Hessian row.

Definition at line 187 of file QuantumFreeEnergy.cpp.

188 {
189 const long n = hessian.rows();
190 if (hessian.cols() != n || tangent.size() != n || n < 1) {
191 throw std::invalid_argument("the Hessian and the tangent sizes differ");
192 }
193 const double norm = tangent.norm();
194 if (!(norm > 0.0) || !std::isfinite(norm)) {
195 throw std::invalid_argument("the tangent is zero");
196 }
197 return complementEigenvalues(hessian, tangent / norm);
198}

◆ perpendicularHarmonicFreeEnergy()

double eonc::perpendicularHarmonicFreeEnergy ( const Eigen::MatrixXd & hessian,
const Eigen::VectorXd & tangent,
double temperature )

Sum of harmonicModeFreeEnergy over the positive perpendicular eigenvalues.

Definition at line 200 of file QuantumFreeEnergy.cpp.

202 {
203 const Eigen::VectorXd lambda = perpendicularEigenvalues(hessian, tangent);
204 double sum = 0.0;
205 for (long i = 0; i < lambda.size(); ++i) {
206 if (!(lambda(i) > 0.0)) {
207 continue;
208 }
209 const double hw = tunneling::kHbar * std::sqrt(lambda(i));
210 sum += harmonicModeFreeEnergy(hw, temperature);
211 }
212 return sum;
213}
Eigen::VectorXd perpendicularEigenvalues(const Eigen::MatrixXd &hessian, const Eigen::VectorXd &tangent)
Eigenvalues of the mass-weighted Hessian after the tangent direction is removed: one fewer than the H...

◆ pmfScanS()

double eonc::pmfScanS ( long plane,
long nScan,
double guideLen )
inline

Uniform PMF-scan coordinate.

Plane 0 is the reactant (s = 0) and plane nScan-1 is the product (s = guideLen). s_init is not applied.

Definition at line 26 of file OHTSTJob.h.

26 {
27 const long n = nScan < 2L ? 2L : nScan;
28 return static_cast<double>(plane) * guideLen / static_cast<double>(n - 1);
29}

◆ potAllowsSharedInstance()

template<class P>
requires requires(const P &p) { { p.isSharedInstanceThreadSafe() } -> std::convertible_to<bool>; }
bool eonc::potAllowsSharedInstance ( const P & p)
nodiscardnoexcept

Definition at line 38 of file PotCapabilities.h.

38 {
39 return p.isSharedInstanceThreadSafe();
40}

◆ potIsThreadSafe()

template<class P>
requires ThreadSafeQueryable<P>
bool eonc::potIsThreadSafe ( const P & p)
nodiscardnoexcept

Definition at line 30 of file PotCapabilities.h.

30 {
31 return p.isThreadSafe();
32}

◆ prfoRefineSaddle()

PrfoRefineResult eonc::prfoRefineSaddle ( Matter & matter,
const AtomMatrix & mode,
double curvature,
const Parameters & params )

Partitioned rational function optimization (P-RFO) of a first-order saddle in the rgsaddle Sella order-1 session, configured by [Saddle Search] prfo_refine_*.

The session's Hessian model is the identity with mode seeded at curvature. Only free atoms move, with no rigid-body projection. matter ends at the last P-RFO point, or at its starting point when that has the smaller max-atom force. A build without rgsaddle, or against an application binary interface (ABI) older than 1.15, throws std::runtime_error.

Definition at line 240 of file PrfoRefine.cpp.

241 {
242 missingSession();
243}

◆ provenanceForJob()

JobResultProvenance eonc::provenanceForJob ( const Parameters & params)

Optimizer backend, engine identity, rgpot pin, and xts ABI from a job.

eindir fields stay at zero unless a real stamp filled them.

Definition at line 38 of file JobResultProvenance.cpp.

38 {
39 JobResultProvenance provenance;
40 provenance.backend = lower_name(
41 std::string(magic_enum::enum_name(params.optimizer_options().method)));
42 provenance.engine_version = VERSION;
43 provenance.engine_build_identity = GIT_HASH;
44 provenance.rgpot_name = lower_name(
45 std::string(magic_enum::enum_name(params.potential_options().potential)));
46#ifdef WITH_RGPOT
47 provenance.rgpot_version = std::string(JobResultProvenance::rgpot_pin);
48#endif
49#ifdef WITH_RGMIN
50 if (params.optimizer_options().method == OptType::XTSCI ||
52 params)) {
53 provenance.xtsci = true;
54 const auto stamp = rgmin_abi_stamp();
55 provenance.xts_abi_major = stamp.abi_major;
56 provenance.xts_abi_minor = stamp.abi_minor;
57 provenance.xts_abi_layout = stamp.layout_revision;
58 }
59#endif
60 return provenance;
61}
const potential_options_t & potential_options() const
std::optional< std::string > rgminBackendMethod(OptType a_otype, const Parameters &a_params)
rgminMethodFor without the objective test: what a minimization of a potential energy runs under opt_b...
Definition Optimizer.cpp:34
Optimizer, xtsci, eindir, and rgpot identity carried on a JobResult.
Definition JobResult.h:35
static constexpr std::string_view rgpot_pin
Definition JobResult.h:60

◆ quantumFreeEnergies()

std::vector< double > eonc::quantumFreeEnergies ( const std::vector< std::shared_ptr< Matter > > & path,
const std::vector< std::shared_ptr< AtomMatrix > > & tangent,
double temperature,
const Parameters & params )

F(s) = V(s) + the harmonic free energy of the vibrations, one entry per image.

With no atom fixed, the translations, and each rotation the first image's Hessian leaves null (a free cluster, periodic cell or not), are rigid motions and carry no vibration. The end images are minima, where every vibration counts, the one along the band included; between them the band tangent is the reaction coordinate and leaves the sum. The tangent is the Cartesian NEB tangent, mass-weighted inside.

Definition at line 216 of file QuantumFreeEnergy.cpp.

218 {
219 std::vector<double> freeEnergy;
220 freeEnergy.reserve(path.size());
221 const long last = static_cast<long>(path.size()) - 1;
222 std::array<bool, 3> rotations{{false, false, false}};
223 bool rotationsSet = false;
224 for (long image = 0; image <= last; ++image) {
225 Matter &matter = *path[static_cast<size_t>(image)];
226 const double potential = matter.getPotentialEnergy();
227 const Eigen::VectorXi mobile = mobileAtoms(matter);
228 if (mobile.size() == 0) {
229 freeEnergy.push_back(potential);
230 continue;
231 }
232 Hessian hess(params, &matter);
233 hess.writeHessianFile(false);
234 const Eigen::MatrixXd weighted = hess.getHessian(&matter, mobile);
235 if (weighted.rows() != 3 * mobile.size()) {
236 throw std::runtime_error("the image Hessian is empty");
237 }
238 std::vector<Eigen::VectorXd> removed;
239 if (mobile.size() == matter.numberOfAtoms()) {
240 const Eigen::MatrixXd generators = rigidGenerators(matter, mobile);
241 if (!rotationsSet) {
242 rotations = tunneling::rotationZeroModes(weighted, generators).zero;
243 rotationsSet = true;
244 }
245 for (int c = 0; c < 3; ++c) {
246 removed.emplace_back(generators.col(c));
247 if (rotations[static_cast<size_t>(c)]) {
248 removed.emplace_back(generators.col(3 + c));
249 }
250 }
251 }
252 if (image > 0 && image < last) {
253 removed.push_back(massWeightedTangent(
254 matter, mobile, imageTangent(path, tangent, image)));
255 }
256 Eigen::MatrixXd columns(weighted.rows(), static_cast<long>(removed.size()));
257 for (size_t k = 0; k < removed.size(); ++k) {
258 columns.col(static_cast<long>(k)) = removed[k];
259 }
260 freeEnergy.push_back(potential + complementHarmonicFreeEnergy(
261 weighted, columns, temperature));
262 }
263 return freeEnergy;
264}
double getPotentialEnergy() const
Definition Matter.cpp:624
RotationZeroModes rotationZeroModes(const MatrixXd &hess, const MatrixXd &generators, double fraction)
double complementHarmonicFreeEnergy(const Eigen::MatrixXd &hessian, const Eigen::MatrixXd &removed, double temperature)
Sum of harmonicModeFreeEnergy over the positive eigenvalues on the complement of removed.
std::array< bool, 3 > zero
Definition Tunneling.h:599

◆ readRpcServerCapabilities()

RpcServerCapabilitiesPair eonc::readRpcServerCapabilities ( )

Call getCapabilities on both server classes through an in-process RPC.

Definition at line 295 of file ServeRpcServer.cpp.

295 {
296 auto io = kj::setupAsyncIo();
298 out.callbackServer = readOne(io, kj::heap<CallbackPotImpl>(noopCallback()));
299 std::vector<ForceCallback> pool;
300 pool.push_back(noopCallback());
301 out.pooledServer =
302 readOne(io, kj::heap<PooledCallbackPotImpl>(std::move(pool)));
303 return out;
304}

◆ registerJob()

void eonc::registerJob ( JobType type,
JobFactory factory )

Definition at line 19 of file JobRegistry.cpp.

19 {
20 jobTable()[type] = std::move(factory);
21}
std::map< JobType, JobFactory > & jobTable()

◆ requirePrfoRefine()

void eonc::requirePrfoRefine ( const Parameters & params)

Does nothing unless [Saddle Search] prfo_refine is on.

Then it throws, before any force call, what prfoRefineSaddle would throw once the search converged: std::invalid_argument for the prfo_refine_* values, std::runtime_error for a build or loaded library without the session.

Definition at line 234 of file PrfoRefine.cpp.

234 {
236 missingSession();
237 }
238}
struct eonc::saddle_search_options_t::prfo_refine_t prfo_refine

◆ resolveMobileAtoms() [1/2]

VectorXi eonc::resolveMobileAtoms ( const Matter * matter,
const std::string & atomList )

PHVA-class mobile set for FD Hessian and matrix-free Krylov (Lanczos / Davidson).

free/fixed on Matter is the optimizer mask. The mobile set is a (possibly proper) subset of free atoms: those that are displaced in finite-difference Hessian-vector products (Li & Jensen, Theor. Chem. Acc. 107, 211 (2002)).

atomList empty or "all" -> all free atoms (backward-compatible default). Otherwise comma/space-separated 0-based indices, intersected with free flags; order follows the list (duplicates dropped). Out-of-range and fixed indices are skipped.

Definition at line 68 of file MobileAtoms.cpp.

68 {
69 if (!matter) {
70 throw std::invalid_argument("resolveMobileAtoms: null Matter");
71 }
72 if (atomListMeansAll(atomList)) {
73 return freeAtomIndices(matter);
74 }
75 const long n = matter->numberOfAtoms();
76 std::vector<int> mobile;
77 std::unordered_set<int> seen;
78 std::string token;
79 for (size_t p = 0; p <= atomList.size(); ++p) {
80 const char c = (p < atomList.size()) ? atomList[p] : ',';
81 if (c == ',' || c == ' ' || c == '\t' || p == atomList.size()) {
82 if (!token.empty()) {
83 try {
84 const long idx = std::stol(token);
85 if (idx >= 0 && idx < n && !matter->getFixed(idx) &&
86 seen.insert(static_cast<int>(idx)).second) {
87 mobile.push_back(static_cast<int>(idx));
88 }
89 } catch (const std::exception &) {
90 // skip non-integer tokens
91 }
92 token.clear();
93 }
94 } else {
95 token.push_back(c);
96 }
97 }
98 VectorXi out(static_cast<Eigen::Index>(mobile.size()));
99 for (Eigen::Index k = 0; k < out.size(); ++k) {
100 out(k) = mobile[static_cast<size_t>(k)];
101 }
102 return out;
103}
bool atomListMeansAll(const std::string &atomList)
Whether atomList means "every free atom" (empty, "all", case-insensitive).
VectorXi freeAtomIndices(const Matter *matter)
Free (unfixed) atom indices in ascending order.

◆ resolveMobileAtoms() [2/2]

VectorXi eonc::resolveMobileAtoms ( const Matter * matter,
const VectorXi & candidates )

Explicit candidate indices, intersected with free flags (order preserved, duplicates dropped).

Used by pyeonclient compute(..., atoms=...).

Definition at line 105 of file MobileAtoms.cpp.

105 {
106 if (!matter) {
107 throw std::invalid_argument("resolveMobileAtoms: null Matter");
108 }
109 const long n = matter->numberOfAtoms();
110 std::vector<int> mobile;
111 std::unordered_set<int> seen;
112 mobile.reserve(static_cast<size_t>(candidates.size()));
113 for (Eigen::Index k = 0; k < candidates.size(); ++k) {
114 const long idx = candidates(k);
115 if (idx >= 0 && idx < n && !matter->getFixed(idx) &&
116 seen.insert(static_cast<int>(idx)).second) {
117 mobile.push_back(static_cast<int>(idx));
118 }
119 }
120 VectorXi out(static_cast<Eigen::Index>(mobile.size()));
121 for (Eigen::Index k = 0; k < out.size(); ++k) {
122 out(k) = mobile[static_cast<size_t>(k)];
123 }
124 return out;
125}

◆ reversibleWorkPastRidge()

bool eonc::reversibleWorkPastRidge ( double reversibleWork,
double thermalEnergy )
inline

The reactant basin is force-free.

A sign change is the ridge only after the reversible work has passed two kT.

Definition at line 33 of file OHTSTJob.h.

34 {
35 return reversibleWork > 2.0 * thermalEnergy;
36}

◆ runAlternativeRotation()

std::optional< DimerRotationResult > eonc::runAlternativeRotation ( DimerRotationBackend backend,
const std::shared_ptr< Matter > & matter,
const Parameters & params,
const std::shared_ptr< Potential > & pot,
const AtomMatrix & initialDirection,
quill::Logger * log = nullptr )
inlinenodiscard

Run Lanczos, Davidson, or LOR.

Classical returns nullopt (stock rotation loop).

Definition at line 70 of file DimerRotationDispatch.h.

73 {
74 if (!usesAlternativeRotation(backend)) {
75 return std::nullopt;
76 }
77
78 const std::string_view backendName = magic_enum::enum_name(backend);
79
80 if (log) {
81 QUILL_LOG_INFO(log,
82 "[DimerRot] rotation_backend={} (skipping classical "
83 "constrained rotation loop)",
84 backendName);
85 }
86
88 switch (backend) {
90 result = detail::runRotationSolver<LORRotation>(matter, params, pot,
91 initialDirection);
92 break;
94 result = detail::runRotationSolver<Lanczos>(matter, params, pot,
95 initialDirection);
96 break;
98 result = detail::runRotationSolver<Davidson>(matter, params, pot,
99 initialDirection);
100 break;
102 return std::nullopt;
103 }
104
105 if (log) {
106 QUILL_LOG_INFO(log,
107 "[DimerRot] alternative rotation done backend={} "
108 "eigenvalue={:.6f} force_calls={}",
109 backendName, result.eigenvalue, result.forceCalls);
110 }
111 return result;
112}
DimerRotationResult runRotationSolver(const std::shared_ptr< Matter > &matter, const Parameters &params, const std::shared_ptr< Potential > &pot, const AtomMatrix &initialDirection)
constexpr bool usesAlternativeRotation(DimerRotationBackend backend) noexcept
Result of a non-classical dimer rotation backend (mode estimate only).

◆ serveFromConfig()

void eonc::serveFromConfig ( const Parameters & params)

Start serve mode from config-file parameters.

Reads serve_options from params and dispatches to the appropriate mode:

  • If endpoints is set, uses multi-model serve (serveMultiple).
  • If gateway_port > 0, uses gateway mode (serveGateway).
  • Otherwise, uses replicated mode (serveReplicated).
Parameters
paramsThe eOn parameters with serve_options populated.

Definition at line 206 of file ServeMode.cpp.

206 {
207 const auto &opts = params.serve_options();
208
209 // Multi-model endpoints take priority
210 if (!opts.endpoints.empty()) {
211 auto endpoints = parseServeSpec(opts.endpoints);
212 if (endpoints.empty()) {
213 EONC_LOG_ERROR("No valid endpoints in spec: {}", opts.endpoints);
214 return;
215 }
216 serveMultiple(endpoints, params);
217 return;
218 }
219
220 // Gateway mode
221 if (opts.gateway_port > 0) {
222 size_t pool = (opts.replicas > 0) ? opts.replicas : 1;
223 serveGateway(params, opts.host, opts.gateway_port, pool);
224 return;
225 }
226
227 // Replicated mode (default)
228 serveReplicated(params, opts.host, opts.port, opts.replicas);
229}
const serve_options_t & serve_options() const

◆ serveGateway()

void eonc::serveGateway ( const Parameters & params,
const std::string & host,
uint16_t port,
size_t pool_size )

Start a gateway server backed by a pool of potential instances.

Creates pool_size instances of the configured potential and serves them behind a single gateway port. Incoming requests are dispatched round-robin across the pool. This gives clients a single endpoint while spreading load.

Parameters
paramsThe eOn parameters (potential_options.potential must be set).
hostThe hostname to listen on.
portThe gateway port.
pool_sizeNumber of potential instances in the pool.

Definition at line 172 of file ServeMode.cpp.

173 {
174 if (pool_size == 0) {
175 EONC_LOG_ERROR("Pool size must be >= 1");
176 return;
177 }
178
179 auto pot_type = params.potential_options().potential;
180 EONC_LOG_INFO("Creating pool of {} {} instances for gateway on {}:{}",
181 pool_size, std::string(magic_enum::enum_name(pot_type)), host,
182 port);
183
184 std::vector<ForceCallback> pool;
185 pool.reserve(pool_size);
186
187 for (size_t i = 0; i < pool_size; ++i) {
188 auto eon_pot =
190 if (!eon_pot) {
191 EONC_LOG_ERROR("Failed to create potential instance {}/{}", i + 1,
192 pool_size);
193 return;
194 }
195 pool.push_back(makeForceCallback(std::move(eon_pot)));
196 }
197
198 EONC_LOG_INFO("Pool ready, starting gateway server");
199 startPooledRpcServer(std::move(pool), host, port);
200}
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
void startPooledRpcServer(std::vector< ForceCallback > pool, const std::string &host, uint16_t port)
Start a blocking Cap'n Proto RPC server backed by a pool of force callbacks dispatched round-robin.

◆ serveMode()

void eonc::serveMode ( const Parameters & params,
const std::string & host,
uint16_t port )

Start a single rgpot-compatible Cap'n Proto RPC server.

Wraps eOn's Potential::force() as an rgpot PotentialBase and serves it over Cap'n Proto RPC. Blocks until the server is killed.

Parameters
paramsThe eOn parameters (potential_options.potential must be set).
hostThe hostname to listen on (e.g., "localhost" or "*").
portThe TCP port to listen on.

Definition at line 58 of file ServeMode.cpp.

59 {
60 auto pot_type = params.potential_options().potential;
61 EONC_LOG_INFO("Creating potential: {}",
62 std::string(magic_enum::enum_name(pot_type)));
63
64 auto eon_pot =
66 if (!eon_pot) {
67 EONC_LOG_ERROR("Failed to create potential of type {}",
68 std::string(magic_enum::enum_name(pot_type)));
69 return;
70 }
71
72 auto callback = makeForceCallback(std::move(eon_pot));
73
74 // Blocks until killed (runs Cap'n Proto event loop)
75 startRpcServer(std::move(callback), host, port);
76}
void startRpcServer(ForceCallback callback, const std::string &host, uint16_t port)
Start a blocking Cap'n Proto RPC server using a force callback.

◆ serveMultiple()

void eonc::serveMultiple ( const std::vector< ServeEndpoint > & endpoints,
const Parameters & params )

Serve multiple potentials concurrently on different ports.

Each endpoint gets its own thread, its own potential instance, and its own Cap'n Proto event loop. All threads block until SIGINT/SIGTERM.

Parameters
endpointsList of {potential, host, port} configurations.
paramsBase eOn parameters (potential type is overridden per endpoint).

Definition at line 82 of file ServeMode.cpp.

83 {
84 if (endpoints.empty()) {
85 EONC_LOG_ERROR("No serve endpoints specified");
86 return;
87 }
88
89 // Single endpoint: run in the main thread (no extra overhead)
90 if (endpoints.size() == 1) {
91 auto params = base_params;
93 endpoints[0].potential;
94 serveMode(params, endpoints[0].host, endpoints[0].port);
95 return;
96 }
97
98 // Multiple endpoints: one thread per server
99 EONC_LOG_INFO("Starting {} concurrent RPC servers", endpoints.size());
100
101 std::vector<std::thread> threads;
102 threads.reserve(endpoints.size());
103
104 for (const auto &ep : endpoints) {
105 threads.emplace_back([&base_params, ep]() {
106 auto params = base_params;
108 auto pot_name = std::string(magic_enum::enum_name(ep.potential));
109
110 EONC_LOG_INFO("[{}:{}] Creating potential: {}", ep.host, ep.port,
111 pot_name);
112
113 auto eon_pot =
115 if (!eon_pot) {
116 EONC_LOG_ERROR("[{}:{}] Failed to create potential {}", ep.host,
117 ep.port, pot_name);
118 return;
119 }
120
121 auto callback = makeForceCallback(std::move(eon_pot));
122 startRpcServer(std::move(callback), ep.host, ep.port);
123 });
124 }
125
126 // Wait for all threads (they block until killed)
127 for (auto &t : threads) {
128 if (t.joinable()) {
129 t.join();
130 }
131 }
132}

◆ serveReplicated()

void eonc::serveReplicated ( const Parameters & params,
const std::string & host,
uint16_t base_port,
size_t replicas )

Serve N replicas of the same potential across sequential ports.

Starts replicas threads, each serving the same potential type on ports base_port, base_port+1, ..., base_port+replicas-1.

Parameters
paramsThe eOn parameters (potential_options.potential must be set).
hostThe hostname to listen on.
base_portThe first port; replicas use base_port+0 .. base_port+N-1.
replicasNumber of concurrent server instances.

Definition at line 138 of file ServeMode.cpp.

139 {
140 if (replicas == 0) {
141 EONC_LOG_ERROR("Replicas must be >= 1");
142 return;
143 }
144 if (replicas == 1) {
145 serveMode(params, host, base_port);
146 return;
147 }
148
149 EONC_LOG_INFO("Starting {} replicated servers on ports {}-{}", replicas,
150 base_port, base_port + replicas - 1);
151
152 std::vector<std::thread> threads;
153 threads.reserve(replicas);
154
155 for (size_t i = 0; i < replicas; ++i) {
156 uint16_t port = static_cast<uint16_t>(base_port + i);
157 threads.emplace_back(
158 [&params, &host, port]() { serveMode(params, host, port); });
159 }
160
161 for (auto &t : threads) {
162 if (t.joinable()) {
163 t.join();
164 }
165 }
166}

◆ startPooledRpcServer()

void eonc::startPooledRpcServer ( std::vector< ForceCallback > pool,
const std::string & host,
uint16_t port )

Start a blocking Cap'n Proto RPC server backed by a pool of force callbacks dispatched round-robin.

Parameters
poolVector of force callbacks (one per pool instance).
hostThe hostname to listen on.
portThe TCP port to listen on.

Definition at line 282 of file ServeRpcServer.cpp.

283 {
284 EONC_LOG_INFO("Starting pooled RPC gateway on {}:{} with {} instances", host,
285 port, pool.size());
286
287 capnp::EzRpcServer server(kj::heap<PooledCallbackPotImpl>(std::move(pool)),
288 host, port);
289
290 auto &waitScope = server.getWaitScope();
291 EONC_LOG_INFO("Gateway ready on port {}. Ctrl+C to stop.", port);
292 kj::NEVER_DONE.wait(waitScope);
293}

◆ startRpcServer()

void eonc::startRpcServer ( ForceCallback callback,
const std::string & host,
uint16_t port )

Start a blocking Cap'n Proto RPC server using a force callback.

Defined in a separate translation unit to avoid naming collision between eOn's class Potential and the capnp-generated Potential interface.

Parameters
callbackForce evaluation function.
hostThe hostname to listen on.
portThe TCP port to listen on.

Definition at line 195 of file ServeRpcServer.cpp.

196 {
197 EONC_LOG_INFO("Starting Cap'n Proto RPC server on {}:{}", host, port);
198
199 capnp::EzRpcServer server(kj::heap<CallbackPotImpl>(std::move(callback)),
200 host, port);
201
202 auto &waitScope = server.getWaitScope();
203 EONC_LOG_INFO("Server ready on port {}. Ctrl+C to stop.", port);
204 kj::NEVER_DONE.wait(waitScope);
205}

◆ trivialModeCountIsPhysical()

bool eonc::trivialModeCountIsPhysical ( long removed,
long fixedAtoms )

Whether removed zero-frequency modes are what the structure's symmetries give: 6 for a free cluster (3 translations and 3 rotations), 5 for a linear one, 3 for a periodic cell, where rotations are no symmetry of the lattice, and none once any atom is fixed.

Definition at line 887 of file Hessian.cpp.

887 {
888 if (fixedAtoms > 0) {
889 return removed == 0;
890 }
891 return removed == 3 || removed == 5 || removed == 6;
892}

◆ unbundle()

std::vector< std::string > eonc::unbundle ( int number)

Definition at line 71 of file Bundling.cpp.

71 {
72 std::vector<std::string> filenames;
73
74 for (const auto &entry : fs::directory_iterator(".")) {
75 std::string originalFilename = entry.path().filename().string();
76
77 if (originalFilename.empty() || originalFilename[0] == '.') {
78 continue;
79 }
80
81 if (std::ranges::count(originalFilename, '_') < 1) {
82 continue;
83 }
84
85 // Find the last underscore
86 auto upos = originalFilename.rfind('_');
87 if (upos == std::string::npos) {
88 continue;
89 }
90
91 // Find the last period
92 auto dpos = originalFilename.rfind('.');
93 if (dpos == std::string::npos || dpos <= upos) {
94 continue;
95 }
96
97 // bundle() writes results_3.con.gz. The span from the last underscore
98 // to the last dot is "3.con", so the index is only the digit run.
99 const size_t numBegin = upos + 1;
100 size_t numEnd = numBegin;
101 while (numEnd < originalFilename.size() &&
102 std::isdigit(static_cast<unsigned char>(originalFilename[numEnd]))) {
103 ++numEnd;
104 }
105 if (numEnd == numBegin || numEnd >= originalFilename.size() ||
106 originalFilename[numEnd] != '.') {
107 continue;
108 }
109 int bundleNumber = 0;
110 const auto parsed =
111 std::from_chars(originalFilename.data() + numBegin,
112 originalFilename.data() + numEnd, bundleNumber);
113 if (parsed.ec != std::errc{} ||
114 parsed.ptr != originalFilename.data() + numEnd) {
115 continue;
116 }
117 if (bundleNumber != number) {
118 continue;
119 }
120
121 std::string baseName = originalFilename.substr(0, upos);
122 // Drop the "_<n>" token and keep everything after it, so a compound
123 // extension (".con.gz", ".con.zst") survives whichever side of the
124 // underscore it sits on.
125 size_t extStart =
126 originalFilename.find_first_not_of("0123456789", upos + 1);
127 if (extStart == std::string::npos) {
128 extStart = originalFilename.size();
129 }
130 std::string newFilename = baseName + originalFilename.substr(extStart);
131
132 try {
133 fs::copy_file(originalFilename, newFilename,
134 fs::copy_options::overwrite_existing);
135 filenames.push_back(newFilename);
136 } catch (const fs::filesystem_error &e) {
137 EONC_LOG_ERROR("unbundle: problem copying {} to {}: {}", originalFilename,
138 newFilename, e.what());
139 }
140 }
141
142 return filenames;
143}

◆ unpackMobileRows()

void eonc::unpackMobileRows ( const VectorXd & packed,
const VectorXi & mobile,
AtomMatrix & full )

Write a 3*n_mobile vector into full AtomMatrix rows (other rows unchanged).

Definition at line 135 of file MobileAtoms.cpp.

136 {
137 for (Eigen::Index a = 0; a < mobile.size(); ++a) {
138 full.row(mobile(a)) = packed.segment<3>(3 * a);
139 }
140}

◆ usesAlternativeRotation()

bool eonc::usesAlternativeRotation ( DimerRotationBackend backend)
inlinenodiscardconstexprnoexcept

Definition at line 41 of file DimerRotationDispatch.h.

41 {
42 return backend != DimerRotationBackend::Classical;
43}

◆ write_fault_rip()

void eonc::write_fault_rip ( void * scp)
static

Definition at line 272 of file fpe_handler.cpp.

272 {
273#if defined(__linux__) && defined(__x86_64__)
274 auto *ctx_log = static_cast<ucontext_t *>(scp);
275 unsigned long rip =
276 static_cast<unsigned long>(ctx_log->uc_mcontext.gregs[REG_RIP]);
277 char hex[] = "FPE rip=0x0000000000000000\n";
278 for (int i = 0; i < 16; ++i) {
279 unsigned nibble = static_cast<unsigned>((rip >> (4 * (15 - i))) & 0xFu);
280 hex[10 + i] =
281 static_cast<char>(nibble < 10 ? '0' + nibble : 'a' + (nibble - 10));
282 }
283 write(STDERR_FILENO, hex, sizeof(hex) - 1);
284#else
285 static_cast<void>(scp);
286#endif
287}

◆ writeNormalModes()

bool eonc::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_eigenvalue (eV / (Angstrom^2 amu)), hbar_omega (eV, negative for an imaginary mode) and wavenumber (cm^-1, same sign) as frame metadata.

Definition at line 864 of file Hessian.cpp.

866 {
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);
874 io::ConFrameMetadata meta;
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}
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
constexpr double kEvToWavenumber
1 eV in cm^-1, e / (h c) from the exact SI values.
Definition Hessian.h:31
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

◆ x86_div_regs()

X86DivRegs eonc::x86_div_regs ( void * scp)
static

Definition at line 215 of file fpe_handler.cpp.

215 {
216 X86DivRegs regs{nullptr, nullptr, nullptr};
217 if (scp == nullptr) {
218 return regs;
219 }
220 auto *ctx = static_cast<ucontext_t *>(scp);
221#if defined(__linux__) && defined(__x86_64__)
222 regs.ip = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_RIP]);
223 regs.ax = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_RAX]);
224 regs.dx = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_RDX]);
225#elif defined(__linux__) && defined(__i386__)
226 regs.ip = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_EIP]);
227 regs.ax = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_EAX]);
228 regs.dx = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext.gregs[REG_EDX]);
229#elif defined(__APPLE__) && defined(__x86_64__)
230 if (ctx->uc_mcontext != nullptr) {
231 regs.ip = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__rip);
232 regs.ax = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__rax);
233 regs.dx = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__rdx);
234 }
235#elif defined(__APPLE__) && defined(__i386__)
236 if (ctx->uc_mcontext != nullptr) {
237 regs.ip = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__eip);
238 regs.ax = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__eax);
239 regs.dx = reinterpret_cast<uintptr_t *>(&ctx->uc_mcontext->__ss.__edx);
240 }
241#else
242 static_cast<void>(ctx);
243#endif
244 return regs;
245}

◆ xtsciBandSurface()

int eonc::xtsciBandSurface ( void * user,
void * request )

Definition at line 208 of file XtsciBand.cpp.

208 {
209 auto *self = static_cast<XtsciBand *>(user);
210 auto *req = static_cast<rgsaddle_surface_request_t *>(request);
211 if (self == nullptr || req == nullptr || req->positions == nullptr ||
212 req->energies == nullptr || req->gradients == nullptr) {
213 return RGSADDLE_SURFACE_FAILED;
214 }
215 try {
216 auto *neb = self->m_neb;
217 const auto band = static_cast<int64_t>(neb->numImages + 2);
218 const auto nAtoms = static_cast<int64_t>(neb->atoms);
219 if (req->version.major != RGSADDLE_ABI_MAJOR) {
220 return RGSADDLE_ABI_MISMATCH;
221 }
222 if (req->n_atoms != nAtoms) {
223 return RGSADDLE_SHAPE;
224 }
225 // Rows carried by this request and the band image of row 0. The
226 // session sends the whole band on its first evaluation, the interior
227 // images 1 .. band - 2 afterwards, or one image with
228 // RGSADDLE_REQ_ONE_IMAGE.
229 int64_t rows = 0;
230 int64_t first = 0;
231 if ((req->flags & RGSADDLE_REQ_ONE_IMAGE) != 0) {
232 if (req->n_images != band || req->image < 0 || req->image >= band) {
233 return RGSADDLE_SHAPE;
234 }
235 rows = 1;
236 first = req->image;
237 } else if (req->n_images == band) {
238 rows = band;
239 } else if (req->n_images == band - 2) {
240 rows = band - 2;
241 first = 1;
242 } else if (req->n_images == 1) {
243 // With RGSADDLE_BAND_NO_MIN_MODE set, only the estimate of the band
244 // metric's energy scale sends one row: a point off the band near
245 // image 1. A copy of image 1 takes it, so no band image moves. That
246 // row comes batched, with image -1 and no flags.
247 if (req->image >= 0 || req->flags != 0) {
248 return RGSADDLE_SHAPE;
249 }
250 Matter probe(*neb->path[1]);
251 moveTo(probe, AtomMatrix::Map(req->positions, nAtoms, 3));
252 req->energies[0] = probe.getPotentialEnergy();
253 const double *src = probe.getForces().data();
254 for (int64_t k = 0; k < 3 * nAtoms; ++k) {
255 req->gradients[k] = -src[k];
256 }
257 return RGSADDLE_OK;
258 } else {
259 return RGSADDLE_SHAPE;
260 }
261 const auto dof = static_cast<Eigen::Index>(3 * nAtoms);
262 std::vector<Matter *> carried;
263 std::vector<long> owners;
264 carried.reserve(static_cast<size_t>(rows));
265 owners.reserve(static_cast<size_t>(rows));
266 for (int64_t r = 0; r < rows; ++r) {
267 const auto i = static_cast<size_t>(first + r);
268 carried.push_back(neb->path[i].get());
269 owners.push_back(neb->imageOwner(i));
270 }
271 // Row r: the session's coordinates onto its image. The fixed endpoints
272 // and a start point the band already evaluated come back from the
273 // image's own cache.
274 auto place = [&](int64_t r) {
275 const auto i = static_cast<size_t>(first + r);
276 AtomMatrix pos = AtomMatrix::Map(req->positions + r * dof, nAtoms, 3);
277 if (i < self->m_fixed.size()) {
278 pinRows(self->m_fixed[i], *neb->path[i], &pos);
279 }
280 moveTo(*neb->path[i], pos);
281 };
282 auto report = [&](int64_t r) {
283 Matter &image = *carried[static_cast<size_t>(r)];
284 req->energies[r] = image.getPotentialEnergy();
285 const double *src = image.getForces().data();
286 double *grad = req->gradients + r * dof;
287 for (Eigen::Index k = 0; k < dof; ++k) {
288 grad[k] = -src[k];
289 }
290 };
291 Potential &pot = *carried.front()->getPotential();
292 if (self->m_threads && rows > 1 && !pot.supportsBatchEvaluation() &&
294 // One pass on the image pool: each row is placed, evaluated and
295 // read back on the thread that took it.
296 eonc::forEachImage(static_cast<long>(rows), [&](long k) {
297 const auto r = static_cast<int64_t>(k - 1);
298 place(r);
299 Matter &image = *carried[static_cast<size_t>(r)];
300 if (image.needsForceUpdate()) {
301 image.getForcesRaw();
302 }
303 report(r);
304 });
305 } else {
306 for (int64_t r = 0; r < rows; ++r) {
307 place(r);
308 }
309 // One batch for every carried image, so calculator groups or a
310 // batched model take them together; otherwise in turn. Each image
311 // carries its band identity, as in the classic update.
312 eonc::evaluateTogether(pot, carried, false, owners);
313 for (int64_t r = 0; r < rows; ++r) {
314 report(r);
315 }
316 }
317 return RGSADDLE_OK;
318 } catch (...) {
319 return RGSADDLE_SURFACE_FAILED;
320 }
321}
const AtomMatrix & getForcesRaw() const
Definition Matter.cpp:493
bool needsForceUpdate() const
Whether forces need recomputation (positions or surface epoch changed).
Definition Matter.h:220
const AtomMatrix & getForces() const
Definition Matter.cpp:482
One rgsaddle band step.
Definition XtsciBand.h:28
void evaluateTogether(Potential &pot, std::span< Matter *const > systems, bool threads, std::span< const long > owners)
Evaluates every system that needs a force update.
Definition Matter.cpp:998

◆ xtsciSolidBandSurface()

int eonc::xtsciSolidBandSurface ( void * user,
void * request )

Definition at line 323 of file XtsciBand.cpp.

324 {
325#if RGSADDLE_ABI_MINOR >= 17
326 auto *self = static_cast<XtsciBand *>(user);
327 auto *req = static_cast<rgsaddle_solid_surface_request_t *>(request);
328 if (self == nullptr || req == nullptr || req->positions == nullptr ||
329 req->cells == nullptr || req->energies == nullptr ||
330 req->gradients == nullptr || req->stresses == nullptr) {
331 return RGSADDLE_SURFACE_FAILED;
332 }
333 try {
334 auto *neb = self->m_neb;
335 const auto band = static_cast<int64_t>(neb->numImages + 2);
336 const auto nAtoms = static_cast<int64_t>(neb->atoms);
337 if (req->version.major != RGSADDLE_ABI_MAJOR) {
338 return RGSADDLE_ABI_MISMATCH;
339 }
340 if (req->n_atoms != nAtoms) {
341 return RGSADDLE_SHAPE;
342 }
343 int64_t rows = 0;
344 int64_t first = 0;
345 if ((req->flags & RGSADDLE_REQ_ONE_IMAGE) != 0) {
346 if (req->n_images != band || req->image < 0 || req->image >= band) {
347 return RGSADDLE_SHAPE;
348 }
349 rows = 1;
350 first = req->image;
351 } else if (req->n_images == band) {
352 rows = band;
353 } else if (req->n_images == band - 2) {
354 rows = band - 2;
355 first = 1;
356 } else {
357 return RGSADDLE_SHAPE;
358 }
359 const auto dof = static_cast<Eigen::Index>(3 * nAtoms);
360 for (int64_t r = 0; r < rows; ++r) {
361 const auto i = static_cast<size_t>(first + r);
362 Matter &image = *neb->path[i];
363 const Matrix3d cell = cellFromRowMajor(req->cells + 9 * r);
364 AtomMatrix pos = AtomMatrix::Map(req->positions + r * dof, nAtoms, 3);
365 if (i < self->m_fixed.size()) {
366 pinRows(self->m_fixed[i], image, &pos);
367 }
368 if (image.getCell() != cell) {
369 image.setCell(cell);
370 }
371 moveTo(image, pos);
372 // One image at a time: Matter keeps the stress that came with its
373 // own force call, so the stress read below costs no second call.
374 const AtomMatrix &force = image.getForces();
375 req->energies[r] = image.getPotentialEnergy();
376 double *grad = req->gradients + r * dof;
377 const double *src = force.data();
378 for (Eigen::Index k = 0; k < dof; ++k) {
379 grad[k] = -src[k];
380 }
381 cellToRowMajor(image.cauchyStress(), req->stresses + 9 * r);
382 }
383 return RGSADDLE_OK;
384 } catch (...) {
385 return RGSADDLE_SURFACE_FAILED;
386 }
387#else
388 return RGSADDLE_SURFACE_FAILED;
389#endif
390}
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
void setCell(const Matrix3d &newCell)
Definition Matter.cpp:347
Matrix3d cauchyStress()
Cauchy stress in eV/Angstrom^3.
Definition Matter.cpp:920

Variable Documentation

◆ AM

double eonc::AM = 1.0 / IM
constexpr

Definition at line 18 of file RandomNumbers.h.

◆ EPS

double eonc::EPS = 1.2e-7
constexpr

Definition at line 21 of file RandomNumbers.h.

◆ IA1

long eonc::IA1 = 40014
constexpr

Definition at line 26 of file RandomNumbers.h.

◆ IA2

long eonc::IA2 = 40692
constexpr

Definition at line 27 of file RandomNumbers.h.

◆ IM

double eonc::IM = 2147483647.0
constexpr

Definition at line 17 of file RandomNumbers.h.

◆ IM1

long eonc::IM1 = 2147483563
constexpr

Definition at line 23 of file RandomNumbers.h.

◆ IM2

long eonc::IM2 = 2147483399
constexpr

Definition at line 24 of file RandomNumbers.h.

◆ IMM1

long eonc::IMM1 = IM1 - 1
constexpr

Definition at line 25 of file RandomNumbers.h.

◆ IQ1

long eonc::IQ1 = 53668
constexpr

Definition at line 28 of file RandomNumbers.h.

◆ IQ2

long eonc::IQ2 = 52774
constexpr

Definition at line 29 of file RandomNumbers.h.

◆ IR1

long eonc::IR1 = 12211
constexpr

Definition at line 30 of file RandomNumbers.h.

◆ IR2

long eonc::IR2 = 3791
constexpr

Definition at line 31 of file RandomNumbers.h.

◆ kEvToWavenumber

double eonc::kEvToWavenumber = 8065.543937349212
inlineconstexpr

1 eV in cm^-1, e / (h c) from the exact SI values.

Definition at line 31 of file Hessian.h.

◆ kWindowsMxcsrExceptionMasks

std::uint32_t eonc::kWindowsMxcsrExceptionMasks = 0x1F80u
constexpr

Definition at line 23 of file fpe_handler.h.

◆ MXCSR_MASK_IM

unsigned eonc::MXCSR_MASK_IM = 1u << 7
staticconstexpr

Definition at line 106 of file fpe_handler.cpp.

◆ MXCSR_MASK_OM

unsigned eonc::MXCSR_MASK_OM = 1u << 10
staticconstexpr

Definition at line 108 of file fpe_handler.cpp.

◆ MXCSR_MASK_ZM

unsigned eonc::MXCSR_MASK_ZM = 1u << 9
staticconstexpr

Definition at line 107 of file fpe_handler.cpp.

◆ NDIV

int eonc::NDIV = 1 + (IM / NTAB)
constexpr

Definition at line 20 of file RandomNumbers.h.

◆ NTAB

int eonc::NTAB = 32
constexpr

Definition at line 19 of file RandomNumbers.h.

◆ RNMX

double eonc::RNMX = 1.0 - EPS
constexpr

Definition at line 22 of file RandomNumbers.h.