source: src/molecules.hpp@ fb9364

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since fb9364 was 4aa03a, checked in by Frederik Heber <heber@…>, 16 years ago

new test function CheckForConnectedSubgraph() and bigger rewrite of PowerSetGenerator() and SPFragmentGenerator() to allow for ings

CheckForConnectedSubgraph(): Is an O(N2) function to check whether we do not create fragments we don't want to have (i.e. disconnected ones)
PowerSetGenerator(): Instead of adding the possible Walkers to an AtomStack, we use the bonds we store in the BondsPerSPList, which by the way have the necessary directional information (i.e. they come with the predecessor in Bond#leftatom). This way, we generate fragments in ring structures without any problems.
SPFragmentGenerator(): had to be adapted as the calling in PowerSetGenerator() had changed a bit. We already let the root be added by this function and don't add it in PowerSetGenerator(), which simplifies (no if-catch for first order) the code there a bit. Furthermore, we had to check whether an added vertex was not already in the keyset (this may happen, as both edge 1<->2 as 2<->1 may appear at different SPLevels in BondsPerSPLevel: Ring structures in contrast to tree structures don not allow for uniqueness! This is first realised through the hash map storing the keysets). This again caused a change in recognizing when the stack contains a fragment, as Suborder-bits (bits is the number of atoms added for this combination) is not the way anymore - we use an additional Counter "Added".

Test on Benzonitrile was successful. We counted the possible fragments by hand, checked them furthermore till order 5 and the numbers were ok up till full order 8 in the end.

  • Property mode set to 100644
File size: 15.4 KB
Line 
1/** \file molecules.hpp
2 *
3 * Class definitions of atom and molecule, element and periodentafel
4 */
5
6#ifndef MOLECULES_HPP_
7#define MOLECULES_HPP_
8
9using namespace std;
10
11// GSL headers
12#include <gsl/gsl_multimin.h>
13#include <gsl/gsl_vector.h>
14#include <gsl/gsl_matrix.h>
15#include <gsl/gsl_eigen.h>
16#include <gsl/gsl_heapsort.h>
17
18// STL headers
19#include <map>
20#include <set>
21#include <deque>
22
23#include "helpers.hpp"
24#include "periodentafel.hpp"
25#include "stackclass.hpp"
26#include "vector.hpp"
27
28class atom;
29class bond;
30class config;
31class molecule;
32class MoleculeListClass;
33class Verbose;
34
35/******************************** Some definitions for easier reading **********************************/
36
37#define KeyStack deque<int>
38#define KeySet set<int>
39#define NumberValuePair pair<int, double>
40#define Graph map <KeySet, NumberValuePair, KeyCompare >
41#define GraphPair pair <KeySet, NumberValuePair >
42#define KeySetTestPair pair<KeySet::iterator, bool>
43#define GraphTestPair pair<Graph::iterator, bool>
44
45struct KeyCompare
46{
47 bool operator() (const KeySet SubgraphA, const KeySet SubgraphB) const;
48};
49
50//bool operator < (KeySet SubgraphA, KeySet SubgraphB); //note: this declaration is important, otherwise normal < is used (producing wrong order)
51inline void InsertFragmentIntoGraph(ofstream *out, struct UniqueFragments *Fragment); // Insert a KeySet into a Graph
52inline void InsertGraphIntoGraph(ofstream *out, Graph &graph1, Graph &graph2, int *counter); // Insert all KeySet's in a Graph into another Graph
53int CompareDoubles (const void * a, const void * b);
54
55
56/************************************* Class definitions ****************************************/
57
58
59// some algebraic matrix stuff
60#define RDET3(a) ((a)[0]*(a)[4]*(a)[8] + (a)[3]*(a)[7]*(a)[2] + (a)[6]*(a)[1]*(a)[5] - (a)[2]*(a)[4]*(a)[6] - (a)[5]*(a)[7]*(a)[0] - (a)[8]*(a)[1]*(a)[3]) //!< hard-coded determinant of a 3x3 matrix
61#define RDET2(a0,a1,a2,a3) ((a0)*(a3)-(a1)*(a2)) //!< hard-coded determinant of a 2x2 matrix
62
63
64/** Parameter structure for least square minimsation.
65 */
66struct LSQ_params {
67 vector **vectors;
68 int num;
69};
70
71double LSQ(const gsl_vector * x, void * params);
72
73/** Parameter structure for least square minimsation.
74 */
75struct lsq_params {
76 gsl_vector *x;
77 const molecule *mol;
78 element *type;
79};
80
81
82
83/** Single atom.
84 * Class incoporates position, type
85 */
86class atom {
87 public:
88 vector x; //!< coordinate array of atom, giving position within cell
89 vector v; //!< velocity array of atom
90 element *type; //!< pointing to element
91 atom *previous; //!< previous atom in molecule list
92 atom *next; //!< next atom in molecule list
93 atom *father; //!< In many-body bond order fragmentations points to originating atom
94 atom *Ancestor; //!< "Father" in Depth-First-Search
95 char *Name; //!< unique name used during many-body bond-order fragmentation
96 int FixedIon; //!< config variable that states whether forces act on the ion or not
97 int *sort; //!< sort criteria
98 int nr; //!< continuous, unique number
99 int GraphNr; //!< unique number, given in DepthFirstSearchAnalysis()
100 int *ComponentNr;//!< belongs to this nonseparable components, given in DepthFirstSearchAnalysis() (if more than one, then is SeparationVertex)
101 int LowpointNr; //!< needed in DepthFirstSearchAnalysis() to detect nonseparable components, is the lowest possible number of an atom to reach via tree edges only followed by at most one back edge.
102 bool SeparationVertex; //!< whether this atom separates off subsets of atoms or not, determined in DepthFirstSearchAnalysis()
103 bool IsCyclic; //!< whether atom belong to as cycle or not, determined in DepthFirstSearchAnalysis()
104 unsigned char AdaptiveOrder; //!< current present bond order at site (0 means "not set")
105
106 atom();
107 ~atom();
108
109 bool Output(int ElementNo, int AtomNo, ofstream *out) const;
110 bool OutputXYZLine(ofstream *out) const;
111 atom *GetTrueFather();
112 bool Compare(atom &ptr);
113
114 private:
115};
116
117ostream & operator << (ostream &ost, atom &a);
118
119/** Bonds between atoms.
120 * Class incorporates bonds between atoms in a molecule,
121 * used to derive tge fragments in many-body bond order
122 * calculations.
123 */
124class bond {
125 public:
126 atom *leftatom; //!< first bond partner
127 atom *rightatom; //!< second bond partner
128 bond *previous; //!< previous atom in molecule list
129 bond *next; //!< next atom in molecule list
130 int HydrogenBond; //!< Number of hydrogen atoms in the bond
131 int BondDegree; //!< single, double, triple, ... bond
132 int nr; //!< unique number in a molecule, updated by molecule::CreateAdjacencyList()
133 bool Cyclic; //!< flag whether bond is part of a cycle or not, given in DepthFirstSearchAnalysis()
134 enum EdgeType Type;//!< whether this is a tree or back edge
135
136 atom * GetOtherAtom(atom *Atom) const;
137 bond * GetFirstBond();
138 bond * GetLastBond();
139
140 bool MarkUsed(enum Shading color);
141 enum Shading IsUsed();
142 void ResetUsed();
143 bool Contains(const atom *ptr);
144 bool Contains(const int nr);
145
146 bond();
147 bond(atom *left, atom *right);
148 bond(atom *left, atom *right, int degree);
149 bond(atom *left, atom *right, int degree, int number);
150 ~bond();
151
152 private:
153 enum Shading Used; //!< marker in depth-first search, DepthFirstSearchAnalysis()
154};
155
156ostream & operator << (ostream &ost, bond &b);
157
158class MoleculeLeafClass;
159
160/** The complete molecule.
161 * Class incorporates number of types
162 */
163class molecule {
164 public:
165 double cell_size[6];//!< cell size
166 periodentafel *elemente; //!< periodic table with each element
167 atom *start; //!< start of atom list
168 atom *end; //!< end of atom list
169 bond *first; //!< start of bond list
170 bond *last; //!< end of bond list
171 bond ***ListOfBondsPerAtom; //!< pointer list for each atom and each bond it has
172 int *NumberOfBondsPerAtom; //!< Number of Bonds each atom has
173 int AtomCount; //!< number of atoms, brought up-to-date by CountAtoms()
174 int BondCount; //!< number of atoms, brought up-to-date by CountBonds()
175 int ElementCount; //!< how many unique elements are therein
176 int ElementsInMolecule[MAX_ELEMENTS]; //!< list whether element (sorted by atomic number) is alread present or not
177 int NoNonHydrogen; //!< number of non-hydrogen atoms in molecule
178 int NoNonBonds; //!< number of non-hydrogen bonds in molecule
179 int NoCyclicBonds; //!< number of cyclic bonds in molecule, by DepthFirstSearchAnalysis()
180 double BondDistance; //!< typical bond distance used in CreateAdjacencyList() and furtheron
181
182 molecule(periodentafel *teil);
183 ~molecule();
184
185 /// remove atoms from molecule.
186 bool AddAtom(atom *pointer);
187 bool RemoveAtom(atom *pointer);
188 bool CleanupMolecule();
189
190 /// Add/remove atoms to/from molecule.
191 atom * AddCopyAtom(atom *pointer);
192 bool AddXYZFile(string filename);
193 bool AddHydrogenReplacementAtom(ofstream *out, bond *Bond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bond **BondList, int NumBond, bool IsAngstroem);
194 bond * AddBond(atom *first, atom *second, int degree);
195 bool RemoveBond(bond *pointer);
196 bool RemoveBonds(atom *BondPartner);
197
198 /// Find atoms.
199 atom * FindAtom(int Nr) const;
200 atom * AskAtom(string text);
201
202 /// Count and change present atoms' coordination.
203 void CountAtoms(ofstream *out);
204 void CountElements();
205 void CalculateOrbitals(class config &configuration);
206 bool CenterInBox(ofstream *out, vector *BoxLengths);
207 void CenterEdge(ofstream *out, vector *max);
208 void CenterOrigin(ofstream *out, vector *max);
209 void CenterGravity(ofstream *out, vector *max);
210 void Translate(const vector *x);
211 void Mirror(const vector *x);
212 void Align(vector *n);
213 void Scale(double **factor);
214 void DetermineCenter(vector &center);
215 vector * DetermineCenterOfGravity(ofstream *out);
216 void SetBoxDimension(vector *dim);
217 double * ReturnFullMatrixforSymmetric(double *cell_size);
218 void ScanForPeriodicCorrection(ofstream *out);
219 void PrincipalAxisSystem(ofstream *out, bool DoRotate);
220 double VolumeOfConvexEnvelope(ofstream *out, bool IsAngstroem);
221
222 bool CheckBounds(const vector *x) const;
223 void GetAlignVector(struct lsq_params * par) const;
224
225 /// Initialising routines in fragmentation
226 void CreateAdjacencyList(ofstream *out, double bonddistance, bool IsAngstroem);
227 void CreateListOfBondsPerAtom(ofstream *out);
228
229 // Graph analysis
230 MoleculeLeafClass * DepthFirstSearchAnalysis(ofstream *out, int *&MinimumRingSize);
231 void CyclicStructureAnalysis(ofstream *out, class StackClass<bond *> *BackEdgeStack, int *&MinimumRingSize);
232 bond * FindNextUnused(atom *vertex);
233 void SetNextComponentNumber(atom *vertex, int nr);
234 void InitComponentNumbers();
235 void OutputComponentNumber(ofstream *out, atom *vertex);
236 void ResetAllBondsToUnused();
237 void ResetAllAtomNumbers();
238 int CountCyclicBonds(ofstream *out);
239 bool CheckForConnectedSubgraph(ofstream *out, KeySet *Fragment);
240 string GetColor(enum Shading color);
241
242 molecule *CopyMolecule();
243
244 /// Fragment molecule by two different approaches:
245 void FragmentMolecule(ofstream *out, int Order, config *configuration);
246 bool CheckOrderAtSite(ofstream *out, bool *AtomMask, Graph *GlobalKeySetList, int Order, int *MinimumRingSize, char *path = NULL);
247 bool StoreAdjacencyToFile(ofstream *out, char *path);
248 bool CheckAdjacencyFileAgainstMolecule(ofstream *out, char *path, atom **ListOfAtoms);
249 bool ParseOrderAtSiteFromFile(ofstream *out, char *path);
250 bool StoreOrderAtSiteFile(ofstream *out, char *path);
251 bool ParseKeySetFile(ofstream *out, char *filename, Graph *&FragmentList);
252 bool StoreKeySetFile(ofstream *out, Graph &KeySetList, char *path);
253 bool StoreForcesFile(ofstream *out, MoleculeListClass *BondFragments, char *path, int *SortIndex);
254 bool CreateMappingLabelsToConfigSequence(ofstream *out, int *&SortIndex);
255 bool ScanBufferIntoKeySet(ofstream *out, char *buffer, KeySet &CurrentSet);
256 void BreadthFirstSearchAdd(ofstream *out, molecule *Mol, atom **&AddedAtomList, bond **&AddedBondList, atom *Root, bond *Bond, int BondOrder, bool IsAngstroem);
257 /// -# BOSSANOVA
258 void FragmentBOSSANOVA(ofstream *out, Graph *&FragmentList, KeyStack &RootStack, int *MinimumRingSize);
259 int PowerSetGenerator(ofstream *out, int Order, struct UniqueFragments &FragmentSearch, KeySet RestrictedKeySet);
260 bool BuildInducedSubgraph(ofstream *out, const molecule *Father);
261 molecule * StoreFragmentFromKeySet(ofstream *out, KeySet &Leaflet, bool IsAngstroem);
262 void SPFragmentGenerator(ofstream *out, struct UniqueFragments *FragmentSearch, int RootDistance, bond **BondsSet, int SetDimension, int SubOrder);
263 int LookForRemovalCandidate(ofstream *&out, KeySet *&Leaf, int *&ShortestPathList);
264 int GuesstimateFragmentCount(ofstream *out, int order);
265
266 // Recognize doubly appearing molecules in a list of them
267 int * IsEqualToWithinThreshold(ofstream *out, molecule *OtherMolecule, double threshold);
268 int * GetFatherSonAtomicMap(ofstream *out, molecule *OtherMolecule);
269
270 // Output routines.
271 bool Output(ofstream *out);
272 void OutputListOfBonds(ofstream *out) const;
273 bool OutputXYZ(ofstream *out) const;
274 bool Checkout(ofstream *out) const;
275
276 private:
277 int last_atom; //!< number given to last atom
278};
279
280/** A list of \a molecule classes.
281 */
282class MoleculeListClass {
283 public:
284 molecule **ListOfMolecules; //!< pointer list of fragment molecules to check for equality
285 int NumberOfMolecules; //!< Number of entries in \a **FragmentList and of to be returned one.
286 int NumberOfTopAtoms; //!< Number of atoms in the molecule from which all fragments originate
287
288 MoleculeListClass();
289 MoleculeListClass(int Num, int NumAtoms);
290 ~MoleculeListClass();
291
292 /// Output configs.
293 bool AddHydrogenCorrection(ofstream *out, char *path);
294 bool StoreForcesFile(ofstream *out, char *path, int *SortIndex);
295 bool OutputConfigForListOfFragments(ofstream *out, config *configuration, int *SortIndex);
296 void Output(ofstream *out);
297
298 private:
299};
300
301
302/** A leaf for a tree of \a molecule class
303 * Wraps molecules in a tree structure
304 */
305class MoleculeLeafClass {
306 public:
307 molecule *Leaf; //!< molecule of this leaf
308 //MoleculeLeafClass *UpLeaf; //!< Leaf one level up
309 //MoleculeLeafClass *DownLeaf; //!< First leaf one level down
310 MoleculeLeafClass *previous; //!< Previous leaf on this level
311 MoleculeLeafClass *next; //!< Next leaf on this level
312
313 //MoleculeLeafClass(MoleculeLeafClass *Up, MoleculeLeafClass *Previous);
314 MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf);
315 ~MoleculeLeafClass();
316
317 bool AddLeaf(molecule *ptr, MoleculeLeafClass *Previous);
318 bool FillBondStructureFromReference(ofstream *out, molecule *reference, int &FragmentCounter, atom ***&ListOfLocalAtoms, bool FreeList = false);
319 bool FillRootStackForSubgraphs(ofstream *out, KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter);
320 bool AssignKeySetsToFragment(ofstream *out, molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms, Graph **&FragmentList, int &FragmentCounter, bool FreeList = false);
321 bool FillListOfLocalAtoms(ofstream *out, atom ***&ListOfLocalAtoms, int &FragmentCounter, int GlobalAtomCount, bool &FreeList);
322 void TranslateIndicesToGlobalIDs(ofstream *out, Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph);
323 int Count() const;
324};
325
326/** The config file.
327 * The class contains all parameters that control a dft run also functions to load and save.
328 */
329class config {
330 public:
331 int PsiType;
332 int MaxPsiDouble;
333 int PsiMaxNoUp;
334 int PsiMaxNoDown;
335 int MaxMinStopStep;
336 int InitMaxMinStopStep;
337 int ProcPEGamma;
338 int ProcPEPsi;
339 char *configpath;
340 char *configname;
341 bool FastParsing;
342
343 private:
344 char *mainname;
345 char *defaultpath;
346 char *pseudopotpath;
347
348 int DoOutVis;
349 int DoOutMes;
350 int DoOutNICS;
351 int DoOutOrbitals;
352 int DoOutCurrent;
353 int DoFullCurrent;
354 int DoPerturbation;
355 int CommonWannier;
356 double SawtoothStart;
357 int VectorPlane;
358 double VectorCut;
359 int UseAddGramSch;
360 int Seed;
361
362 int MaxOuterStep;
363 double Deltat;
364 int OutVisStep;
365 int OutSrcStep;
366 double TargetTemp;
367 int ScaleTempStep;
368 int MaxPsiStep;
369 double EpsWannier;
370
371 int MaxMinStep;
372 double RelEpsTotalEnergy;
373 double RelEpsKineticEnergy;
374 int MaxMinGapStopStep;
375 int MaxInitMinStep;
376 double InitRelEpsTotalEnergy;
377 double InitRelEpsKineticEnergy;
378 int InitMaxMinGapStopStep;
379
380 //double BoxLength[NDIM*NDIM];
381
382 double ECut;
383 int MaxLevel;
384 int RiemannTensor;
385 int LevRFactor;
386 int RiemannLevel;
387 int Lev0Factor;
388 int RTActualUse;
389 int AddPsis;
390
391 double RCut;
392 int StructOpt;
393 int IsAngstroem;
394 int RelativeCoord;
395 int MaxTypes;
396
397
398 int ParseForParameter(int verbose, ifstream *file, const char *name, int sequential, int const xth, int const yth, int type, void *value, int repetition, int critical);
399
400 public:
401 config();
402 ~config();
403
404 int TestSyntax(char *filename, periodentafel *periode, molecule *mol);
405 void Load(char *filename, periodentafel *periode, molecule *mol);
406 void LoadOld(char *filename, periodentafel *periode, molecule *mol);
407 void RetrieveConfigPathAndName(string filename);
408 bool Save(ofstream *file, periodentafel *periode, molecule *mol) const;
409 void Edit(molecule *mol);
410 bool GetIsAngstroem() const;
411 char *GetDefaultPath() const;
412 void SetDefaultPath(const char *path);
413};
414
415#endif /*MOLECULES_HPP_*/
416
Note: See TracBrowser for help on using the repository browser.