32#define TOLCUTOFF 1.0E-2
38InterfaceLammps::InterfaceLammps() : myRank (0 ),
40 hasGlobalStructure (false),
52 char const*
const& emap,
72 string dir(directory);
73 char const separator =
'/';
74 if (dir.back() != separator) dir += separator;
79 bool collectStatistics =
false;
80 bool collectExtrapolationWarnings =
false;
82 bool stopOnExtrapolationWarnings =
false;
85 collectExtrapolationWarnings =
true;
88 collectExtrapolationWarnings,
90 stopOnExtrapolationWarnings);
94 log <<
"*** SETUP: LAMMPS INTERFACE *************"
95 "**************************************\n";
100 log <<
"Individual extrapolation warnings will be shown.\n";
104 log <<
"Individual extrapolation warnings will not be shown.\n";
109 log <<
strpr(
"Extrapolation warning summary will be shown every %d"
114 log <<
"Extrapolation warning summary will not be shown.\n";
119 log <<
strpr(
"The simulation will be stopped when %d extrapolation"
120 " warnings are exceeded.\n",
maxew);
124 log <<
"No extrapolation warning limit set.\n";
129 log <<
"Extrapolation warning counter is reset every time step.\n";
133 log <<
"Extrapolation warnings are accumulated over all time steps.\n";
136 log <<
"-----------------------------------------"
137 "--------------------------------------\n";
138 log <<
"CAUTION: If the LAMMPS unit system differs from the one used\n";
139 log <<
" during NN training, appropriate conversion factors\n";
140 log <<
" must be provided (see keywords cflength and cfenergy).\n";
146 log <<
"Checking consistency of cutoff radii (in LAMMPS units):\n";
147 log <<
strpr(
"LAMMPS Cutoff (via pair_coeff) : %11.3E\n", lammpsCutoff);
148 log <<
strpr(
"Maximum symmetry function cutoff: %11.3E\n", sfCutoff);
149 if (lammpsCutoff < sfCutoff)
151 throw runtime_error(
"ERROR: LAMMPS cutoff via pair_coeff keyword is"
152 " smaller than maximum symmetry function"
155 else if (fabs(sfCutoff - lammpsCutoff) / lammpsCutoff >
TOLCUTOFF)
157 log <<
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
158 log <<
"WARNING: Potential length units mismatch!\n";
159 log <<
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
163 log <<
"Cutoff radii are consistent.\n";
166 log <<
"-----------------------------------------"
167 "--------------------------------------\n";
168 log <<
"Element mapping string from LAMMPS to n2p2: \""
169 + this->emap +
"\"\n";
171 if (this->emap ==
"")
175 throw runtime_error(
strpr(
"ERROR: No element mapping given and "
176 "number of LAMMPS atom types (%d) and "
177 "NNP elements (%zu) does not match.\n",
180 log <<
"Element mapping string empty, creating default mapping.\n";
181 for (
int i = 0; i < lammpsNtypes; ++i)
194 throw runtime_error(
strpr(
"ERROR: Element mapping is inconsistent,"
195 " NNP elements: %zu,"
196 " emap elements: %zu.\n",
200 for (
string s : emapSplit)
202 vector<string> typeString =
split(s,
':');
203 if (typeString.size() != 2)
205 throw runtime_error(
strpr(
"ERROR: Invalid element mapping "
206 "string: \"%s\".\n", s.c_str()));
208 int t = stoi(typeString.at(0));
209 if (t > lammpsNtypes)
211 throw runtime_error(
strpr(
"ERROR: LAMMPS type \"%d\" not "
212 "present, there are only %d types "
213 "defined.\n", t, lammpsNtypes));
221 log <<
"CAUTION: Please ensure that this mapping between LAMMPS\n";
222 log <<
" atom types and NNP elements is consistent:\n";
224 log <<
"---------------------------\n";
225 log <<
"LAMMPS type | NNP element\n";
226 log <<
"---------------------------\n";
227 for (
int i = 1; i <= lammpsNtypes; ++i)
232 log <<
strpr(
"%11d <-> %2s (%3zu)\n",
245 log <<
"---------------------------\n";
247 log <<
"NNP setup for LAMMPS completed.\n";
249 log <<
"*****************************************"
250 "**************************************\n";
268 int const*
const atomType)
283 indexMap.resize(numAtomsLocal, numeric_limits<size_t>::max());
284 for (
int i = 0; i < numAtomsLocal; i++)
371 if (
structure.
box[0][1] > numeric_limits<double>::min() ||
381 for(
size_t i = 0; i < 3; ++i)
406 a.neighbors.reserve(numneigh[i]);
420 indexMap.at(i) == numeric_limits<size_t>::max())
return;
450 a.hasNeighborList =
true;
465#ifdef N2P2_NO_SF_GROUPS
536 double convForce = 1.0;
548 size_t const ia = a.index;
549 Vec3D selfForce = a.calculateSelfForceShort();
550 selfForce *= cfforce * convForce;
555#ifndef N2P2_FULL_SFD_MEMORY
556 vector<vector<size_t> >
const& tableFull
557 =
elements.at(a.element).getSymmetryFunctionTable();
562 size_t const numNeighbors = a.getStoredMinNumNeighbors(
maxCutoffRadius);
564 #pragma omp parallel for
566 for (
size_t k = 0; k < numNeighbors; ++k)
571 size_t const in = n.
index;
573#ifndef N2P2_FULL_SFD_MEMORY
574 Vec3D pairForce = a.calculatePairForceShort(n, &tableFull);
576 Vec3D pairForce = a.calculatePairForceShort(n);
578 pairForce *= cfforce * convForce;
591 #pragma omp parallel for
594 for (
size_t i = 0; i < s.
numAtoms; ++i)
596 auto const& ai = s.
atoms[i];
599 for (
auto const& aj : s.
atoms)
601 size_t const j = aj.index;
603#ifndef N2P2_FULL_SFD_MEMORY
604 vector<vector<size_t> >
const& tableFull
605 =
elements.at(aj.element).getSymmetryFunctionTable();
606 Vec3D dChidr = aj.calculateDChidr(ai.index,
610 Vec3D dChidr = aj.calculateDChidr(ai.index,
614 Vec3D remainingForce = -lambdaTotal(j) * (ai.dAdrQ[j] + dChidr);
630 #pragma omp parallel for
632 for (
size_t i = 0; i < s.
numAtoms; ++i)
634 atomQ[i] = s.
atoms[i].charge;
645 MPI_Pack_size(1,
MPI_SIZE_T, MPI_COMM_WORLD, &ss);
646 MPI_Pack_size(1, MPI_DOUBLE, MPI_COMM_WORLD, &ds);
647 MPI_Pack_size(1, MPI_CHAR , MPI_COMM_WORLD, &cs);
649 for (vector<Element>::const_iterator it =
elements.begin();
652 map<size_t, SymFncStatistics::Container>
const& m
653 = it->statistics.data;
655 for (map<size_t, SymFncStatistics::Container>::const_iterator
656 it2 = m.begin(); it2 != m.end(); ++it2)
664 bs += (it2->second.element.length() + 1) * cs;
665 size_t countEW = it2->second.countEW;
679 for (vector<Element>::const_iterator it =
elements.begin();
682 map<size_t, SymFncStatistics::Container>
const& m =
685 MPI_Pack((
void *) &(n), 1,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
686 for (map<size_t, SymFncStatistics::Container>::const_iterator
687 it2 = m.begin(); it2 != m.end(); ++it2)
689 MPI_Pack((
void *) &(it2->first ), 1,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
690 size_t countEW = it2->second.countEW;
691 MPI_Pack((
void *) &(countEW ), 1,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
692 MPI_Pack((
void *) &(it2->second.type ), 1,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
693 MPI_Pack((
void *) &(it2->second.Gmin ), 1, MPI_DOUBLE, buf, bs, &
p, MPI_COMM_WORLD);
694 MPI_Pack((
void *) &(it2->second.Gmax ), 1, MPI_DOUBLE, buf, bs, &
p, MPI_COMM_WORLD);
696 size_t ts = it2->second.element.length() + 1;
697 MPI_Pack((
void *) &ts , 1,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
698 MPI_Pack((
void *) it2->second.element.c_str() , ts, MPI_CHAR , buf, bs, &
p, MPI_COMM_WORLD);
699 MPI_Pack((
void *) &(it2->second.indexStructureEW.front()), countEW,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
700 MPI_Pack((
void *) &(it2->second.indexAtomEW.front() ), countEW,
MPI_SIZE_T, buf, bs, &
p, MPI_COMM_WORLD);
701 MPI_Pack((
void *) &(it2->second.valueEW.front() ), countEW, MPI_DOUBLE, buf, bs, &
p, MPI_COMM_WORLD);
712 for (vector<Element>::iterator it =
elements.begin();
716 MPI_Unpack((
void *) buf, bs, &
p, &(n), 1,
MPI_SIZE_T, MPI_COMM_WORLD);
717 for (
size_t i = 0; i < n; ++i)
720 MPI_Unpack((
void *) buf, bs, &
p, &(index), 1,
MPI_SIZE_T, MPI_COMM_WORLD);
723 MPI_Unpack((
void *) buf, bs, &
p, &(countEW ), 1,
MPI_SIZE_T, MPI_COMM_WORLD);
724 MPI_Unpack((
void *) buf, bs, &
p, &(
d.type ), 1,
MPI_SIZE_T, MPI_COMM_WORLD);
725 MPI_Unpack((
void *) buf, bs, &
p, &(
d.Gmin ), 1, MPI_DOUBLE, MPI_COMM_WORLD);
726 MPI_Unpack((
void *) buf, bs, &
p, &(
d.Gmax ), 1, MPI_DOUBLE, MPI_COMM_WORLD);
729 MPI_Unpack((
void *) buf, bs, &
p, &ts , 1,
MPI_SIZE_T, MPI_COMM_WORLD);
730 char* element =
new char[ts];
731 MPI_Unpack((
void *) buf, bs, &
p, element , ts, MPI_CHAR , MPI_COMM_WORLD);
735 d.indexStructureEW.resize(
d.countEW + countEW);
736 MPI_Unpack((
void *) buf, bs, &
p, &(
d.indexStructureEW[
d.countEW]), countEW,
MPI_SIZE_T, MPI_COMM_WORLD);
738 d.indexAtomEW.resize(
d.countEW + countEW);
739 MPI_Unpack((
void *) buf, bs, &
p, &(
d.indexAtomEW[
d.countEW] ), countEW,
MPI_SIZE_T, MPI_COMM_WORLD);
741 d.valueEW.resize(
d.countEW + countEW);
742 MPI_Unpack((
void *) buf, bs, &
p, &(
d.valueEW[
d.countEW] ), countEW, MPI_DOUBLE, MPI_COMM_WORLD);
744 d.countEW += countEW;
753 for (vector<Element>::const_iterator it =
elements.begin();
756 vector<string> vs = it->statistics.getExtrapolationWarningLines();
757 for (vector<string>::const_iterator it2 = vs.begin();
758 it2 != vs.end(); ++it2)
769 for (vector<Element>::iterator it =
elements.begin();
772 it->statistics.clear();
std::size_t size() const
Get element map size.
std::size_t atomicNumber(std::size_t index) const
Get atomic number from element index.
Contains element-specific data.
double getAtomicEnergyOffset() const
Get atomicEnergyOffset.
void logEwaldCutoffs(Log &log, double const lengthConversion) const
Use after Ewald summation!
Structure structure
Structure containing local atoms.
long getEWBufferSize() const
Calculate buffer size for extrapolation warning communication.
bool initialized
Initialization state.
void process()
Calculate symmetry functions, atomic neural networks and sum of local energy contributions.
void extractEWBuffer(char const *const &buf, int bs)
Extract given buffer to symmetry function statistics class.
std::map< int, bool > ignoreType
True if atoms of this LAMMPS type will be ignored.
void setLocalTags(int const *const atomTag)
Set atom tags (int version, -DLAMMPS_SMALLBIG).
void allocateNeighborlists(int const *const numneigh)
Allocate neighbor lists.
std::map< int, std::size_t > mapTypeToElement
Map from LAMMPS type to n2p2 element index.
void add3DVecToArray(double *const &arr, Vec3D const &v) const
Add a Vec3D vector to a 3D array in place.
double getMaxCutoffRadiusOverall()
Get largest cutoff including structure specific cutoff and screening cutoff.
bool hasGlobalStructure
Whether n2p2 knows about the global structure or only a local part.
void setLocalAtomPositions(double const *const *const atomPos)
Set absolute atom positions from LAMMPS (nnp/develop only).
double getEnergy() const
Return sum of local energy contributions.
void fillEWBuffer(char *const &buf, int bs) const
Fill provided buffer with extrapolation warning entries.
double getAtomicEnergy(int index) const
Return energy contribution of one atom.
void getForces(double *const *const &atomF) const
Calculate forces and add to LAMMPS atomic force arrays.
bool resetew
Corresponds to LAMMPS resetew keyword.
void writeExtrapolationWarnings()
Write extrapolation warnings to log.
void setBoxVectors(double const *boxlo, double const *boxhi, double const xy, double const xz, double const yz)
Set box vectors of structure stored in LAMMPS (nnp/develop only).
std::vector< size_t > indexMap
Map from LAMMPS index to n2p2 atom index.
bool getGlobalStructureStatus()
Check if n2p2 knows about global structure.
double cfenergy
Corresponds to LAMMPS cfenergy keyword.
void setLocalAtoms(int numAtomsLocal, int const *const atomType)
(Re)set structure to contain only local LAMMPS atoms.
bool showew
Corresponds to LAMMPS showew keyword.
void writeToFile(std::string const fileName, bool const append)
Write current structure to file in units used in training data.
void getCharges(double *const &atomQ) const
Transfer charges (in units of e) to LAMMPS atomic charge vector.
int showewsum
Corresponds to LAMMPS showewsum keyword.
void setGlobalStructureStatus(bool const status)
Specify whether n2p2 knows about global structure or only local structure.
void finalizeNeighborList()
Sorts neighbor list and creates cutoff map if necessary.
void clearExtrapolationWarnings()
Clear extrapolation warnings storage.
std::map< std::size_t, int > mapElementToType
Map from n2p2 element index to LAMMPS type.
double getMaxCutoffRadius() const
Get largest cutoff of symmetry functions.
int maxew
Corresponds to LAMMPS maxew keyword.
void addNeighbor(int i, int j, int64_t tag, int type, double dx, double dy, double dz, double d2)
Add one neighbor to atom (int64_t version, -DLAMMPS_BIGBIG).
double cflength
Corresponds to LAMMPS cflength keyword.
std::string emap
Corresponds to LAMMPS map keyword.
bool writeToStdout
Turn on/off output to stdout.
double physicalEnergy(Structure const &structure, bool ref=true) const
Undo normalization for a given energy of structure.
std::vector< std::vector< double > > cutoffs
Matrix storing all symmetry function cut-offs for all elements.
ElementMap elementMap
Global element map, populated by setupElementMap().
void addEnergyOffset(Structure &structure, bool ref=true)
Add atomic energy offsets to reference energy.
void initialize()
Write welcome message with version information.
void setupGeneric(std::string const &nnpDir="", bool skipNormalize=false, bool initialHardness=false)
Combine multiple setup routines and provide a basic NNP setup.
@ HDNNP_Q
Short range NNP with charge NN, no electrostatics/Qeq (M.
@ HDNNP_4G
NNP with electrostatics and non-local charge transfer (4G-HDNNP).
virtual void setupNeuralNetworkWeights(std::map< std::string, std::string > fileNameFormats=std::map< std::string, std::string >())
Set up neural network weights from files with given name format.
ScreeningFunction screeningFunction
void calculateAtomicNeuralNetworks(Structure &structure, bool const derivatives, std::string id="")
Calculate atomic neural networks for all atoms in given structure.
double physical(std::string const &property, double value) const
Undo normalization for a given property.
std::vector< Element > elements
void calculateEnergy(Structure &structure) const
Calculate potential energy for a given structure.
void calculateSymmetryFunctionGroups(Structure &structure, bool const derivatives)
Calculate all symmetry function groups for all atoms in given structure.
virtual void setupSymmetryFunctionScaling(std::string const &fileName="scaling.data")
Set up symmetry function scaling from file.
void calculateCharge(Structure &structure) const
Calculate total charge for a given structure.
void chargeEquilibration(Structure &structure, bool const derivativesElec)
Perform global charge equilibration method.
void calculateSymmetryFunctions(Structure &structure, bool const derivatives)
Calculate all symmetry functions for all atoms in given structure.
void setupSymmetryFunctionStatistics(bool collectStatistics, bool collectExtrapolationWarnings, bool writeExtrapolationWarnings, bool stopOnExtrapolationWarnings)
Set up symmetry function statistics collection.
void loadSettingsFile(std::string const &fileName="input.nn")
Open settings file and load all keywords into memory.
double getOuter() const
Getter for outer.
string strpr(const char *format,...)
String version of printf function.
string trim(string const &line, string const &whitespace)
Remove leading and trailing whitespaces from string.
vector< string > split(string const &input, char delimiter)
Split string at each delimiter.
string reduce(string const &line, string const &whitespace, string const &fill)
Replace multiple whitespaces with fill.
Struct to store information on neighbor atoms.
std::size_t index
Index of neighbor atom.
std::size_t element
Element index of neighbor atom.
double d
Distance to neighbor atom.
Vec3D dr
Distance vector to neighbor atom.
int64_t tag
Tag of neighbor atom.
Storage for a single atom.
std::vector< Neighbor > neighbors
Neighbor array (maximum number defined in macros.h.
Vec3D r
Cartesian coordinates.
bool hasSymmetryFunctionDerivatives
If symmetry function derivatives are saved for this atom.
std::size_t index
Index number of this atom.
std::size_t indexStructure
Index number of structure this atom belongs to.
std::size_t element
Element index of this atom.
bool hasSymmetryFunctions
If symmetry function values are saved for this atom.
double energy
Atomic energy determined by neural network.
std::vector< std::size_t > numNeighborsPerElement
Number of neighbors per element.
std::size_t numNeighbors
Total number of neighbors.
Storage for one atomic configuration.
void calculateVolume()
Calculate volume from box vectors.
void toPhysicalUnits(double meanEnergy, double convEnergy, double convLength, double convCharge)
Switch to physical units, shift energy and change energy, length and charge unit.
Vec3D box[3]
Simulation box vectors.
bool isTriclinic
If the simulation box is triclinic.
void setupNeighborCutoffMap(std::vector< std::vector< double > > cutoffs)
Set up a neighbor cut-off map which gives the index (value) of the last needed neighbor corresponding...
void sortNeighborList()
Sort all neighbor lists of this structure with respect to the distance.
std::vector< std::size_t > numAtomsPerElement
Number of atoms of each element in this structure.
void calculateMaxCutoffRadiusOverall(EwaldSetup &ewaldSetup, double rcutScreen, double maxCutoffRadius)
Calculate maximal cut-off if cut-off of screening and real part Ewald summation are also considered.
void writeToFile(std::string const fileName="output.data", bool const ref=true, bool const append=false) const
Write configuration to file.
bool isPeriodic
If periodic boundary conditions apply.
double maxCutoffRadiusOverall
Maximum cut-off radius with respect to symmetry functions, screening function and Ewald summation.
void setElementMap(ElementMap const &elementMap)
Set element map of structure.
std::size_t index
Index number of this structure.
void calculateInverseBox()
Calculate inverse box.
bool hasSymmetryFunctionDerivatives
If symmetry function derivatives are saved for each atom.
Eigen::VectorXd const calculateForceLambdaTotal() const
Calculate lambda_total vector which is needed for the total force calculation in 4G NN.
double energy
Potential energy determined by neural network.
void toNormalizedUnits(double meanEnergy, double convEnergy, double convLength, double convCharge)
Normalize structure, shift energy and change energy, length and charge unit.
std::size_t numAtoms
Total number of atoms present in this structure.
std::vector< Atom > atoms
Vector of all atoms in this structure.
bool hasNeighborList
If the neighbor list has been calculated.
bool hasSymmetryFunctions
If symmetry function values are saved for each atom.
Struct containing statistics gathered during symmetry function calculation.
Vector in 3 dimensional real space.