source: src/moleculelist.cpp@ cee0b57

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 cee0b57 was cee0b57, checked in by Frederik Heber <heber@…>, 15 years ago

class molecule implementation split up into six separate parts.

  • dynamics: Verlet integration and constraint potential
  • fragmentation: BOSSANOVA scheme
  • geometry: all operations acting on the Vector's inside the atom's
  • graph: supplementary functions for fragmentation, treating molecule as a bonding graph
  • pointcloud: implementations of virtual functions for pointcloud class, needed for Tesselation
  • Property mode set to 100755
File size: 39.9 KB
Line 
1/** \file MoleculeListClass.cpp
2 *
3 * Function implementations for the class MoleculeListClass.
4 *
5 */
6
7#include "boundary.hpp"
8#include "config.hpp"
9#include "molecule.hpp"
10#include "memoryallocator.hpp"
11
12/*********************************** Functions for class MoleculeListClass *************************/
13
14/** Constructor for MoleculeListClass.
15 */
16MoleculeListClass::MoleculeListClass()
17{
18 // empty lists
19 ListOfMolecules.clear();
20 MaxIndex = 1;
21};
22
23/** Destructor for MoleculeListClass.
24 */
25MoleculeListClass::~MoleculeListClass()
26{
27 cout << Verbose(3) << this << ": Freeing ListOfMolcules." << endl;
28 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
29 cout << Verbose(4) << "ListOfMolecules: Freeing " << *ListRunner << "." << endl;
30 delete (*ListRunner);
31 }
32 cout << Verbose(4) << "Freeing ListOfMolecules." << endl;
33 ListOfMolecules.clear(); // empty list
34};
35
36/** Insert a new molecule into the list and set its number.
37 * \param *mol molecule to add to list.
38 * \return true - add successful
39 */
40void MoleculeListClass::insert(molecule *mol)
41{
42 mol->IndexNr = MaxIndex++;
43 ListOfMolecules.push_back(mol);
44};
45
46/** Compare whether two molecules are equal.
47 * \param *a molecule one
48 * \param *n molecule two
49 * \return lexical value (-1, 0, +1)
50 */
51int MolCompare(const void *a, const void *b)
52{
53 int *aList = NULL, *bList = NULL;
54 int Count, Counter, aCounter, bCounter;
55 int flag;
56 atom *aWalker = NULL;
57 atom *bWalker = NULL;
58
59 // sort each atom list and put the numbers into a list, then go through
60 //cout << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
61 if ((**(molecule **) a).AtomCount < (**(molecule **) b).AtomCount) {
62 return -1;
63 } else {
64 if ((**(molecule **) a).AtomCount > (**(molecule **) b).AtomCount)
65 return +1;
66 else {
67 Count = (**(molecule **) a).AtomCount;
68 aList = new int[Count];
69 bList = new int[Count];
70
71 // fill the lists
72 aWalker = (**(molecule **) a).start;
73 bWalker = (**(molecule **) b).start;
74 Counter = 0;
75 aCounter = 0;
76 bCounter = 0;
77 while ((aWalker->next != (**(molecule **) a).end) && (bWalker->next != (**(molecule **) b).end)) {
78 aWalker = aWalker->next;
79 bWalker = bWalker->next;
80 if (aWalker->GetTrueFather() == NULL)
81 aList[Counter] = Count + (aCounter++);
82 else
83 aList[Counter] = aWalker->GetTrueFather()->nr;
84 if (bWalker->GetTrueFather() == NULL)
85 bList[Counter] = Count + (bCounter++);
86 else
87 bList[Counter] = bWalker->GetTrueFather()->nr;
88 Counter++;
89 }
90 // check if AtomCount was for real
91 flag = 0;
92 if ((aWalker->next == (**(molecule **) a).end) && (bWalker->next != (**(molecule **) b).end)) {
93 flag = -1;
94 } else {
95 if ((aWalker->next != (**(molecule **) a).end) && (bWalker->next == (**(molecule **) b).end))
96 flag = 1;
97 }
98 if (flag == 0) {
99 // sort the lists
100 gsl_heapsort(aList, Count, sizeof(int), CompareDoubles);
101 gsl_heapsort(bList, Count, sizeof(int), CompareDoubles);
102 // compare the lists
103
104 flag = 0;
105 for (int i = 0; i < Count; i++) {
106 if (aList[i] < bList[i]) {
107 flag = -1;
108 } else {
109 if (aList[i] > bList[i])
110 flag = 1;
111 }
112 if (flag != 0)
113 break;
114 }
115 }
116 delete[] (aList);
117 delete[] (bList);
118 return flag;
119 }
120 }
121 return -1;
122};
123
124/** Output of a list of all molecules.
125 * \param *out output stream
126 */
127void MoleculeListClass::Enumerate(ofstream *out)
128{
129 element* Elemental = NULL;
130 atom *Walker = NULL;
131 int Counts[MAX_ELEMENTS];
132 double size=0;
133 Vector Origin;
134
135 // header
136 *out << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
137 cout << Verbose(0) << "-----------------------------------------------" << endl;
138 if (ListOfMolecules.size() == 0)
139 *out << "\tNone" << endl;
140 else {
141 Origin.Zero();
142 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
143 // reset element counts
144 for (int j = 0; j<MAX_ELEMENTS;j++)
145 Counts[j] = 0;
146 // count atoms per element and determine size of bounding sphere
147 size=0.;
148 Walker = (*ListRunner)->start;
149 while (Walker->next != (*ListRunner)->end) {
150 Walker = Walker->next;
151 Counts[Walker->type->Z]++;
152 if (Walker->x.DistanceSquared(&Origin) > size)
153 size = Walker->x.DistanceSquared(&Origin);
154 }
155 // output Index, Name, number of atoms, chemical formula
156 *out << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->AtomCount << "\t";
157 Elemental = (*ListRunner)->elemente->end;
158 while(Elemental->previous != (*ListRunner)->elemente->start) {
159 Elemental = Elemental->previous;
160 if (Counts[Elemental->Z] != 0)
161 *out << Elemental->symbol << Counts[Elemental->Z];
162 }
163 // Center and size
164 *out << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl;
165 }
166 }
167};
168
169/** Returns the molecule with the given index \a index.
170 * \param index index of the desired molecule
171 * \return pointer to molecule structure, NULL if not found
172 */
173molecule * MoleculeListClass::ReturnIndex(int index)
174{
175 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
176 if ((*ListRunner)->IndexNr == index)
177 return (*ListRunner);
178 return NULL;
179};
180
181/** Simple merge of two molecules into one.
182 * \param *mol destination molecule
183 * \param *srcmol source molecule
184 * \return true - merge successful, false - merge failed (probably due to non-existant indices
185 */
186bool MoleculeListClass::SimpleMerge(molecule *mol, molecule *srcmol)
187{
188 if (srcmol == NULL)
189 return false;
190
191 // put all molecules of src into mol
192 atom *Walker = srcmol->start;
193 atom *NextAtom = Walker->next;
194 while (NextAtom != srcmol->end) {
195 Walker = NextAtom;
196 NextAtom = Walker->next;
197 srcmol->UnlinkAtom(Walker);
198 mol->AddAtom(Walker);
199 }
200
201 // remove src
202 ListOfMolecules.remove(srcmol);
203 delete(srcmol);
204 return true;
205};
206
207/** Simple add of one molecules into another.
208 * \param *mol destination molecule
209 * \param *srcmol source molecule
210 * \return true - merge successful, false - merge failed (probably due to non-existant indices
211 */
212bool MoleculeListClass::SimpleAdd(molecule *mol, molecule *srcmol)
213{
214 if (srcmol == NULL)
215 return false;
216
217 // put all molecules of src into mol
218 atom *Walker = srcmol->start;
219 atom *NextAtom = Walker->next;
220 while (NextAtom != srcmol->end) {
221 Walker = NextAtom;
222 NextAtom = Walker->next;
223 Walker = mol->AddCopyAtom(Walker);
224 Walker->father = Walker;
225 }
226
227 return true;
228};
229
230/** Simple merge of a given set of molecules into one.
231 * \param *mol destination molecule
232 * \param *src index of set of source molecule
233 * \param N number of source molecules
234 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
235 */
236bool MoleculeListClass::SimpleMultiMerge(molecule *mol, int *src, int N)
237{
238 bool status = true;
239 // check presence of all source molecules
240 for (int i=0;i<N;i++) {
241 molecule *srcmol = ReturnIndex(src[i]);
242 status = status && SimpleMerge(mol, srcmol);
243 }
244 return status;
245};
246
247/** Simple add of a given set of molecules into one.
248 * \param *mol destination molecule
249 * \param *src index of set of source molecule
250 * \param N number of source molecules
251 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
252 */
253bool MoleculeListClass::SimpleMultiAdd(molecule *mol, int *src, int N)
254{
255 bool status = true;
256 // check presence of all source molecules
257 for (int i=0;i<N;i++) {
258 molecule *srcmol = ReturnIndex(src[i]);
259 status = status && SimpleAdd(mol, srcmol);
260 }
261 return status;
262};
263
264/** Scatter merge of a given set of molecules into one.
265 * Scatter merge distributes the molecules in such a manner that they don't overlap.
266 * \param *mol destination molecule
267 * \param *src index of set of source molecule
268 * \param N number of source molecules
269 * \return true - merge successful, false - merge failed (probably due to non-existant indices
270 * \TODO find scatter center for each src molecule
271 */
272bool MoleculeListClass::ScatterMerge(molecule *mol, int *src, int N)
273{
274 // check presence of all source molecules
275 for (int i=0;i<N;i++) {
276 // get pointer to src molecule
277 molecule *srcmol = ReturnIndex(src[i]);
278 if (srcmol == NULL)
279 return false;
280 }
281 // adapt each Center
282 for (int i=0;i<N;i++) {
283 // get pointer to src molecule
284 molecule *srcmol = ReturnIndex(src[i]);
285 //srcmol->Center.Zero();
286 srcmol->Translate(&srcmol->Center);
287 }
288 // perform a simple multi merge
289 SimpleMultiMerge(mol, src, N);
290 return true;
291};
292
293/** Embedding merge of a given set of molecules into one.
294 * Embedding merge inserts one molecule into the other.
295 * \param *mol destination molecule (fixed one)
296 * \param *srcmol source molecule (variable one, where atoms are taken from)
297 * \return true - merge successful, false - merge failed (probably due to non-existant indices)
298 * \TODO linked cell dimensions for boundary points has to be as big as inner diameter!
299 */
300bool MoleculeListClass::EmbedMerge(molecule *mol, molecule *srcmol)
301{
302 if ((srcmol == NULL) || (mol == NULL)) {
303 cout << Verbose(1) << "ERROR: Either fixed or variable molecule is given as NULL." << endl;
304 return false;
305 }
306
307 // calculate envelope for *mol
308 LinkedCell *LCList = new LinkedCell(mol, 8.);
309 FindNonConvexBorder((ofstream *)&cout, mol, LCList, 4., NULL);
310 if (mol->TesselStruct == NULL) {
311 cout << Verbose(1) << "ERROR: Could not tesselate the fixed molecule." << endl;
312 return false;
313 }
314 delete(LCList);
315 LCList = new LinkedCell(mol->TesselStruct, 8.); // re-create with boundary points only!
316
317 // prepare index list for bonds
318 srcmol->CountAtoms((ofstream *)&cout);
319 atom ** CopyAtoms = new atom*[srcmol->AtomCount];
320 for(int i=0;i<srcmol->AtomCount;i++)
321 CopyAtoms[i] = NULL;
322
323 // for each of the source atoms check whether we are in- or outside and add copy atom
324 atom *Walker = srcmol->start;
325 int nr=0;
326 while (Walker->next != srcmol->end) {
327 Walker = Walker->next;
328 cout << Verbose(2) << "INFO: Current Walker is " << *Walker << "." << endl;
329 if (!mol->TesselStruct->IsInnerPoint((ofstream *)&cout, Walker->x, LCList)) {
330 CopyAtoms[Walker->nr] = new atom(Walker);
331 mol->AddAtom(CopyAtoms[Walker->nr]);
332 nr++;
333 } else {
334 // do nothing
335 }
336 }
337 cout << Verbose(1) << nr << " of " << srcmol->AtomCount << " atoms have been merged.";
338
339 // go through all bonds and add as well
340 bond *Binder = srcmol->first;
341 while(Binder->next != srcmol->last) {
342 Binder = Binder->next;
343 cout << Verbose(3) << "Adding Bond between " << *CopyAtoms[Binder->leftatom->nr] << " and " << *CopyAtoms[Binder->rightatom->nr]<< "." << endl;
344 mol->AddBond(CopyAtoms[Binder->leftatom->nr], CopyAtoms[Binder->rightatom->nr], Binder->BondDegree);
345 }
346 delete(LCList);
347 return true;
348};
349
350/** Simple output of the pointers in ListOfMolecules.
351 * \param *out output stream
352 */
353void MoleculeListClass::Output(ofstream *out)
354{
355 *out << Verbose(1) << "MoleculeList: ";
356 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
357 *out << *ListRunner << "\t";
358 *out << endl;
359};
360
361/** Calculates necessary hydrogen correction due to unwanted interaction between saturated ones.
362 * If for a pair of two hydrogen atoms a and b, at least is a saturated one, and a and b are not
363 * bonded to the same atom, then we add for this pair a correction term constructed from a Morse
364 * potential function fit to QM calculations with respecting to the interatomic hydrogen distance.
365 * \param *out output stream for debugging
366 * \param *path path to file
367 */
368bool MoleculeListClass::AddHydrogenCorrection(ofstream *out, char *path)
369{
370 atom *Walker = NULL;
371 atom *Runner = NULL;
372 double ***FitConstant = NULL, **correction = NULL;
373 int a, b;
374 ofstream output;
375 ifstream input;
376 string line;
377 stringstream zeile;
378 double distance;
379 char ParsedLine[1023];
380 double tmp;
381 char *FragmentNumber = NULL;
382
383 cout << Verbose(1) << "Saving hydrogen saturation correction ... ";
384 // 0. parse in fit constant files that should have the same dimension as the final energy files
385 // 0a. find dimension of matrices with constants
386 line = path;
387 line.append("/");
388 line += FRAGMENTPREFIX;
389 line += "1";
390 line += FITCONSTANTSUFFIX;
391 input.open(line.c_str());
392 if (input == NULL) {
393 cerr << endl << "Unable to open " << line << ", is the directory correct?"
394 << endl;
395 return false;
396 }
397 a = 0;
398 b = -1; // we overcount by one
399 while (!input.eof()) {
400 input.getline(ParsedLine, 1023);
401 zeile.str(ParsedLine);
402 int i = 0;
403 while (!zeile.eof()) {
404 zeile >> distance;
405 i++;
406 }
407 if (i > a)
408 a = i;
409 b++;
410 }
411 cout << "I recognized " << a << " columns and " << b << " rows, ";
412 input.close();
413
414 // 0b. allocate memory for constants
415 FitConstant = Malloc<double**>(3, "MoleculeListClass::AddHydrogenCorrection: ***FitConstant");
416 for (int k = 0; k < 3; k++) {
417 FitConstant[k] = Malloc<double*>(a, "MoleculeListClass::AddHydrogenCorrection: **FitConstant[]");
418 for (int i = a; i--;) {
419 FitConstant[k][i] = Malloc<double>(b, "MoleculeListClass::AddHydrogenCorrection: *FitConstant[][]");
420 }
421 }
422 // 0c. parse in constants
423 for (int i = 0; i < 3; i++) {
424 line = path;
425 line.append("/");
426 line += FRAGMENTPREFIX;
427 sprintf(ParsedLine, "%d", i + 1);
428 line += ParsedLine;
429 line += FITCONSTANTSUFFIX;
430 input.open(line.c_str());
431 if (input == NULL) {
432 cerr << endl << "Unable to open " << line << ", is the directory correct?" << endl;
433 return false;
434 }
435 int k = 0, l;
436 while ((!input.eof()) && (k < b)) {
437 input.getline(ParsedLine, 1023);
438 //cout << "Current Line: " << ParsedLine << endl;
439 zeile.str(ParsedLine);
440 zeile.clear();
441 l = 0;
442 while ((!zeile.eof()) && (l < a)) {
443 zeile >> FitConstant[i][l][k];
444 //cout << FitConstant[i][l][k] << "\t";
445 l++;
446 }
447 //cout << endl;
448 k++;
449 }
450 input.close();
451 }
452 for (int k = 0; k < 3; k++) {
453 cout << "Constants " << k << ":" << endl;
454 for (int j = 0; j < b; j++) {
455 for (int i = 0; i < a; i++) {
456 cout << FitConstant[k][i][j] << "\t";
457 }
458 cout << endl;
459 }
460 cout << endl;
461 }
462
463 // 0d. allocate final correction matrix
464 correction = Malloc<double*>(a, "MoleculeListClass::AddHydrogenCorrection: **correction");
465 for (int i = a; i--;)
466 correction[i] = Malloc<double>(b, "MoleculeListClass::AddHydrogenCorrection: *correction[]");
467
468 // 1a. go through every molecule in the list
469 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
470 // 1b. zero final correction matrix
471 for (int k = a; k--;)
472 for (int j = b; j--;)
473 correction[k][j] = 0.;
474 // 2. take every hydrogen that is a saturated one
475 Walker = (*ListRunner)->start;
476 while (Walker->next != (*ListRunner)->end) {
477 Walker = Walker->next;
478 //cout << Verbose(1) << "Walker: " << *Walker << " with first bond " << *(*Runner)->ListOfBondsPerAtom[Walker->nr][0] << "." << endl;
479 if ((Walker->type->Z == 1) && ((Walker->father == NULL)
480 || (Walker->father->type->Z != 1))) { // if it's a hydrogen
481 Runner = (*ListRunner)->start;
482 while (Runner->next != (*ListRunner)->end) {
483 Runner = Runner->next;
484 //cout << Verbose(2) << "Runner: " << *Runner << " with first bond " << *(*Runner)->ListOfBondsPerAtom[Runner->nr][0] << "." << endl;
485 // 3. take every other hydrogen that is the not the first and not bound to same bonding partner
486 if ((Runner->type->Z == 1) && (Runner->nr > Walker->nr) && ((*ListRunner)->ListOfBondsPerAtom[Runner->nr][0]->GetOtherAtom(Runner) != (*ListRunner)->ListOfBondsPerAtom[Walker->nr][0]->GetOtherAtom(Walker))) { // (hydrogens have only one bonding partner!)
487 // 4. evaluate the morse potential for each matrix component and add up
488 distance = Runner->x.Distance(&Walker->x);
489 //cout << "Fragment " << (*ListRunner)->name << ": " << *Runner << "<= " << distance << "=>" << *Walker << ":" << endl;
490 for (int k = 0; k < a; k++) {
491 for (int j = 0; j < b; j++) {
492 switch (k) {
493 case 1:
494 case 7:
495 case 11:
496 tmp = pow(FitConstant[0][k][j] * (1. - exp(-FitConstant[1][k][j] * (distance - FitConstant[2][k][j]))), 2);
497 break;
498 default:
499 tmp = FitConstant[0][k][j] * pow(distance, FitConstant[1][k][j]) + FitConstant[2][k][j];
500 };
501 correction[k][j] -= tmp; // ground state is actually lower (disturbed by additional interaction)
502 //cout << tmp << "\t";
503 }
504 //cout << endl;
505 }
506 //cout << endl;
507 }
508 }
509 }
510 }
511 // 5. write final matrix to file
512 line = path;
513 line.append("/");
514 line += FRAGMENTPREFIX;
515 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), (*ListRunner)->IndexNr);
516 line += FragmentNumber;
517 delete (FragmentNumber);
518 line += HCORRECTIONSUFFIX;
519 output.open(line.c_str());
520 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
521 for (int j = 0; j < b; j++) {
522 for (int i = 0; i < a; i++)
523 output << correction[i][j] << "\t";
524 output << endl;
525 }
526 output.close();
527 }
528 line = path;
529 line.append("/");
530 line += HCORRECTIONSUFFIX;
531 output.open(line.c_str());
532 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
533 for (int j = 0; j < b; j++) {
534 for (int i = 0; i < a; i++)
535 output << 0 << "\t";
536 output << endl;
537 }
538 output.close();
539 // 6. free memory of parsed matrices
540 FitConstant = Malloc<double**>(a, "MoleculeListClass::AddHydrogenCorrection: ***FitConstant");
541 for (int k = 0; k < 3; k++) {
542 FitConstant[k] = Malloc<double*>(a, "MoleculeListClass::AddHydrogenCorrection: **FitConstant[]");
543 for (int i = a; i--;) {
544 FitConstant[k][i] = Malloc<double>(b, "MoleculeListClass::AddHydrogenCorrection: *FitConstant[][]");
545 }
546 }
547 cout << "done." << endl;
548 return true;
549};
550
551/** Store force indices, i.e. the connection between the nuclear index in the total molecule config and the respective atom in fragment config.
552 * \param *out output stream for debugging
553 * \param *path path to file
554 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
555 * \return true - file written successfully, false - writing failed
556 */
557bool MoleculeListClass::StoreForcesFile(ofstream *out, char *path,
558 int *SortIndex)
559{
560 bool status = true;
561 ofstream ForcesFile;
562 stringstream line;
563 atom *Walker = NULL;
564 element *runner = NULL;
565
566 // open file for the force factors
567 *out << Verbose(1) << "Saving force factors ... ";
568 line << path << "/" << FRAGMENTPREFIX << FORCESFILE;
569 ForcesFile.open(line.str().c_str(), ios::out);
570 if (ForcesFile != NULL) {
571 //cout << Verbose(1) << "Final AtomicForcesList: ";
572 //output << prefix << "Forces" << endl;
573 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
574 runner = (*ListRunner)->elemente->start;
575 while (runner->next != (*ListRunner)->elemente->end) { // go through every element
576 runner = runner->next;
577 if ((*ListRunner)->ElementsInMolecule[runner->Z]) { // if this element got atoms
578 Walker = (*ListRunner)->start;
579 while (Walker->next != (*ListRunner)->end) { // go through every atom of this element
580 Walker = Walker->next;
581 if (Walker->type->Z == runner->Z) {
582 if ((Walker->GetTrueFather() != NULL) && (Walker->GetTrueFather() != Walker)) {// if there is a rea
583 //cout << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
584 ForcesFile << SortIndex[Walker->GetTrueFather()->nr] << "\t";
585 } else
586 // otherwise a -1 to indicate an added saturation hydrogen
587 ForcesFile << "-1\t";
588 }
589 }
590 }
591 }
592 ForcesFile << endl;
593 }
594 ForcesFile.close();
595 *out << Verbose(1) << "done." << endl;
596 } else {
597 status = false;
598 *out << Verbose(1) << "failed to open file " << line.str() << "." << endl;
599 }
600 ForcesFile.close();
601
602 return status;
603};
604
605/** Writes a config file for each molecule in the given \a **FragmentList.
606 * \param *out output stream for debugging
607 * \param *configuration standard configuration to attach atoms in fragment molecule to.
608 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
609 * \param DoPeriodic true - call ScanForPeriodicCorrection, false - don't
610 * \param DoCentering true - call molecule::CenterEdge(), false - don't
611 * \return true - success (each file was written), false - something went wrong.
612 */
613bool MoleculeListClass::OutputConfigForListOfFragments(ofstream *out, config *configuration, int *SortIndex)
614{
615 ofstream outputFragment;
616 char FragmentName[MAXSTRINGSIZE];
617 char PathBackup[MAXSTRINGSIZE];
618 bool result = true;
619 bool intermediateResult = true;
620 atom *Walker = NULL;
621 Vector BoxDimension;
622 char *FragmentNumber = NULL;
623 char *path = NULL;
624 int FragmentCounter = 0;
625 ofstream output;
626
627 // store the fragments as config and as xyz
628 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
629 // save default path as it is changed for each fragment
630 path = configuration->GetDefaultPath();
631 if (path != NULL)
632 strcpy(PathBackup, path);
633 else
634 cerr << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl;
635
636 // correct periodic
637 (*ListRunner)->ScanForPeriodicCorrection(out);
638
639 // output xyz file
640 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), FragmentCounter++);
641 sprintf(FragmentName, "%s/%s%s.conf.xyz", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
642 outputFragment.open(FragmentName, ios::out);
643 *out << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...";
644 if ((intermediateResult = (*ListRunner)->OutputXYZ(&outputFragment)))
645 *out << " done." << endl;
646 else
647 *out << " failed." << endl;
648 result = result && intermediateResult;
649 outputFragment.close();
650 outputFragment.clear();
651
652 // list atoms in fragment for debugging
653 *out << Verbose(2) << "Contained atoms: ";
654 Walker = (*ListRunner)->start;
655 while (Walker->next != (*ListRunner)->end) {
656 Walker = Walker->next;
657 *out << Walker->Name << " ";
658 }
659 *out << endl;
660
661 // center on edge
662 (*ListRunner)->CenterEdge(out, &BoxDimension);
663 (*ListRunner)->SetBoxDimension(&BoxDimension); // update Box of atoms by boundary
664 int j = -1;
665 for (int k = 0; k < NDIM; k++) {
666 j += k + 1;
667 BoxDimension.x[k] = 2.5 * (configuration->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
668 (*ListRunner)->cell_size[j] += BoxDimension.x[k] * 2.;
669 }
670 (*ListRunner)->Translate(&BoxDimension);
671
672 // also calculate necessary orbitals
673 (*ListRunner)->CountElements(); // this is a bugfix, atoms should shoulds actually be added correctly to this fragment
674 (*ListRunner)->CalculateOrbitals(*configuration);
675
676 // change path in config
677 //strcpy(PathBackup, configuration->configpath);
678 sprintf(FragmentName, "%s/%s%s/", PathBackup, FRAGMENTPREFIX, FragmentNumber);
679 configuration->SetDefaultPath(FragmentName);
680
681 // and save as config
682 sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
683 *out << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...";
684 if ((intermediateResult = configuration->Save(FragmentName, (*ListRunner)->elemente, (*ListRunner))))
685 *out << " done." << endl;
686 else
687 *out << " failed." << endl;
688 result = result && intermediateResult;
689
690 // restore old config
691 configuration->SetDefaultPath(PathBackup);
692
693 // and save as mpqc input file
694 sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
695 *out << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...";
696 if ((intermediateResult = configuration->SaveMPQC(FragmentName, (*ListRunner))))
697 *out << " done." << endl;
698 else
699 *out << " failed." << endl;
700
701 result = result && intermediateResult;
702 //outputFragment.close();
703 //outputFragment.clear();
704 delete (FragmentNumber);
705 //Free(&FragmentNumber);
706 }
707 cout << " done." << endl;
708
709 // printing final number
710 *out << "Final number of fragments: " << FragmentCounter << "." << endl;
711
712 return result;
713};
714
715/** Counts the number of molecules with the molecule::ActiveFlag set.
716 * \return number of molecules with ActiveFlag set to true.
717 */
718int MoleculeListClass::NumberOfActiveMolecules()
719{
720 int count = 0;
721 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
722 count += ((*ListRunner)->ActiveFlag ? 1 : 0);
723 return count;
724};
725
726
727/******************************************* Class MoleculeLeafClass ************************************************/
728
729/** Constructor for MoleculeLeafClass root leaf.
730 * \param *Up Leaf on upper level
731 * \param *PreviousLeaf NULL - We are the first leaf on this level, otherwise points to previous in list
732 */
733//MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *Up = NULL, MoleculeLeafClass *Previous = NULL)
734MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf = NULL)
735{
736 // if (Up != NULL)
737 // if (Up->DownLeaf == NULL) // are we the first down leaf for the upper leaf?
738 // Up->DownLeaf = this;
739 // UpLeaf = Up;
740 // DownLeaf = NULL;
741 Leaf = NULL;
742 previous = PreviousLeaf;
743 if (previous != NULL) {
744 MoleculeLeafClass *Walker = previous->next;
745 previous->next = this;
746 next = Walker;
747 } else {
748 next = NULL;
749 }
750};
751
752/** Destructor for MoleculeLeafClass.
753 */
754MoleculeLeafClass::~MoleculeLeafClass()
755{
756 // if (DownLeaf != NULL) {// drop leaves further down
757 // MoleculeLeafClass *Walker = DownLeaf;
758 // MoleculeLeafClass *Next;
759 // do {
760 // Next = Walker->NextLeaf;
761 // delete(Walker);
762 // Walker = Next;
763 // } while (Walker != NULL);
764 // // Last Walker sets DownLeaf automatically to NULL
765 // }
766 // remove the leaf itself
767 if (Leaf != NULL) {
768 delete (Leaf);
769 Leaf = NULL;
770 }
771 // remove this Leaf from level list
772 if (previous != NULL)
773 previous->next = next;
774 // } else { // we are first in list (connects to UpLeaf->DownLeaf)
775 // if ((NextLeaf != NULL) && (NextLeaf->UpLeaf == NULL))
776 // NextLeaf->UpLeaf = UpLeaf; // either null as we are top level or the upleaf of the first node
777 // if (UpLeaf != NULL)
778 // UpLeaf->DownLeaf = NextLeaf; // either null as we are only leaf or NextLeaf if we are just the first
779 // }
780 // UpLeaf = NULL;
781 if (next != NULL) // are we last in list
782 next->previous = previous;
783 next = NULL;
784 previous = NULL;
785};
786
787/** Adds \a molecule leaf to the tree.
788 * \param *ptr ptr to molecule to be added
789 * \param *Previous previous MoleculeLeafClass referencing level and which on the level
790 * \return true - success, false - something went wrong
791 */
792bool MoleculeLeafClass::AddLeaf(molecule *ptr, MoleculeLeafClass *Previous)
793{
794 return false;
795};
796
797/** Fills the bond structure of this chain list subgraphs that are derived from a complete \a *reference molecule.
798 * Calls this routine in each MoleculeLeafClass::next subgraph if it's not NULL.
799 * \param *out output stream for debugging
800 * \param *reference reference molecule with the bond structure to be copied
801 * \param &FragmentCounter Counter needed to address \a **ListOfLocalAtoms
802 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in \a *reference, may be NULL on start, then it is filled
803 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
804 * \return true - success, false - faoilure
805 */
806bool MoleculeLeafClass::FillBondStructureFromReference(ofstream *out, molecule *reference, int &FragmentCounter, atom ***&ListOfLocalAtoms, bool FreeList)
807{
808 atom *Walker = NULL, *OtherWalker = NULL;
809 bond *Binder = NULL;
810 bool status = true;
811 int AtomNo;
812
813 *out << Verbose(1) << "Begin of FillBondStructureFromReference." << endl;
814 // fill ListOfLocalAtoms if NULL was given
815 if (!FillListOfLocalAtoms(out, ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
816 *out << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
817 return false;
818 }
819
820 if (status) {
821 *out << Verbose(1) << "Creating adjacency list for subgraph " << this
822 << "." << endl;
823 Walker = Leaf->start;
824 while (Walker->next != Leaf->end) {
825 Walker = Walker->next;
826 AtomNo = Walker->GetTrueFather()->nr; // global id of the current walker
827 for (int i = 0; i < reference->NumberOfBondsPerAtom[AtomNo]; i++) { // go through father's bonds and copy them all
828 Binder = reference->ListOfBondsPerAtom[AtomNo][i];
829 OtherWalker = ListOfLocalAtoms[FragmentCounter][Binder->GetOtherAtom(Walker->GetTrueFather())->nr]; // local copy of current bond partner of walker
830 if (OtherWalker != NULL) {
831 if (OtherWalker->nr > Walker->nr)
832 Leaf->AddBond(Walker, OtherWalker, Binder->BondDegree);
833 } else {
834 *out << Verbose(1) << "OtherWalker = ListOfLocalAtoms[" << FragmentCounter << "][" << Binder->GetOtherAtom(Walker->GetTrueFather())->nr << "] is NULL!" << endl;
835 status = false;
836 }
837 }
838 }
839 Leaf->CreateListOfBondsPerAtom(out);
840 FragmentCounter++;
841 if (next != NULL)
842 status = next->FillBondStructureFromReference(out, reference, FragmentCounter, ListOfLocalAtoms);
843 FragmentCounter--;
844 }
845
846 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
847 // free the index lookup list
848 Free(&ListOfLocalAtoms[FragmentCounter]);
849 if (FragmentCounter == 0) // first fragments frees the initial pointer to list
850 Free(&ListOfLocalAtoms);
851 }
852 FragmentCounter--;
853 *out << Verbose(1) << "End of FillBondStructureFromReference." << endl;
854 return status;
855};
856
857/** Fills the root stack for sites to be used as root in fragmentation depending on order or adaptivity criteria
858 * Again, as in \sa FillBondStructureFromReference steps recursively through each Leaf in this chain list of molecule's.
859 * \param *out output stream for debugging
860 * \param *&RootStack stack to be filled
861 * \param *AtomMask defines true/false per global Atom::nr to mask in/out each nuclear site
862 * \param &FragmentCounter counts through the fragments in this MoleculeLeafClass
863 * \return true - stack is non-empty, fragmentation necessary, false - stack is empty, no more sites to update
864 */
865bool MoleculeLeafClass::FillRootStackForSubgraphs(ofstream *out,
866 KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter)
867{
868 atom *Walker = NULL, *Father = NULL;
869
870 if (RootStack != NULL) {
871 // find first root candidates
872 if (&(RootStack[FragmentCounter]) != NULL) {
873 RootStack[FragmentCounter].clear();
874 Walker = Leaf->start;
875 while (Walker->next != Leaf->end) { // go through all (non-hydrogen) atoms
876 Walker = Walker->next;
877 Father = Walker->GetTrueFather();
878 if (AtomMask[Father->nr]) // apply mask
879#ifdef ADDHYDROGEN
880 if (Walker->type->Z != 1) // skip hydrogen
881#endif
882 RootStack[FragmentCounter].push_front(Walker->nr);
883 }
884 if (next != NULL)
885 next->FillRootStackForSubgraphs(out, RootStack, AtomMask, ++FragmentCounter);
886 } else {
887 *out << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl;
888 return false;
889 }
890 FragmentCounter--;
891 return true;
892 } else {
893 *out << Verbose(1) << "Rootstack is NULL." << endl;
894 return false;
895 }
896};
897
898/** Fills a lookup list of father's Atom::nr -> atom for each subgraph.
899 * \param *out output stream fro debugging
900 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
901 * \param FragmentCounter counts the fragments as we move along the list
902 * \param GlobalAtomCount number of atoms in the complete molecule
903 * \param &FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
904 * \return true - succes, false - failure
905 */
906bool MoleculeLeafClass::FillListOfLocalAtoms(ofstream *out, atom ***&ListOfLocalAtoms, const int FragmentCounter, const int GlobalAtomCount, bool &FreeList)
907{
908 bool status = true;
909
910 int Counter = Count();
911 if (ListOfLocalAtoms == NULL) { // allocated initial pointer
912 // allocate and set each field to NULL
913 ListOfLocalAtoms = Malloc<atom**>(Counter, "MoleculeLeafClass::FillBondStructureFromReference - ***ListOfLocalAtoms");
914 if (ListOfLocalAtoms != NULL) {
915 for (int i = Counter; i--;)
916 ListOfLocalAtoms[i] = NULL;
917 FreeList = FreeList && true;
918 } else
919 status = false;
920 }
921
922 if ((ListOfLocalAtoms != NULL) && (ListOfLocalAtoms[FragmentCounter] == NULL)) { // allocate and fill list of this fragment/subgraph
923 status = status && CreateFatherLookupTable(out, Leaf->start, Leaf->end, ListOfLocalAtoms[FragmentCounter], GlobalAtomCount);
924 FreeList = FreeList && true;
925 }
926
927 return status;
928};
929
930/** The indices per keyset are compared to the respective father's Atom::nr in each subgraph and thus put into \a **&FragmentList.
931 * \param *out output stream fro debugging
932 * \param *reference reference molecule with the bond structure to be copied
933 * \param *KeySetList list with all keysets
934 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
935 * \param **&FragmentList list to be allocated and returned
936 * \param &FragmentCounter counts the fragments as we move along the list
937 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
938 * \retuen true - success, false - failure
939 */
940bool MoleculeLeafClass::AssignKeySetsToFragment(ofstream *out,
941 molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms,
942 Graph **&FragmentList, int &FragmentCounter, bool FreeList)
943{
944 bool status = true;
945 int KeySetCounter = 0;
946
947 *out << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl;
948 // fill ListOfLocalAtoms if NULL was given
949 if (!FillListOfLocalAtoms(out, ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
950 *out << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
951 return false;
952 }
953
954 // allocate fragment list
955 if (FragmentList == NULL) {
956 KeySetCounter = Count();
957 FragmentList = Malloc<Graph*>(KeySetCounter, "MoleculeLeafClass::AssignKeySetsToFragment - **FragmentList");
958 for (int i = KeySetCounter; i--;)
959 FragmentList[i] = NULL;
960 KeySetCounter = 0;
961 }
962
963 if ((KeySetList != NULL) && (KeySetList->size() != 0)) { // if there are some scanned keysets at all
964 // assign scanned keysets
965 if (FragmentList[FragmentCounter] == NULL)
966 FragmentList[FragmentCounter] = new Graph;
967 KeySet *TempSet = new KeySet;
968 for (Graph::iterator runner = KeySetList->begin(); runner != KeySetList->end(); runner++) { // key sets contain global numbers!
969 if (ListOfLocalAtoms[FragmentCounter][reference->FindAtom(*((*runner).first.begin()))->nr] != NULL) {// as we may assume that that bond structure is unchanged, we only test the first key in each set
970 // translate keyset to local numbers
971 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
972 TempSet->insert(ListOfLocalAtoms[FragmentCounter][reference->FindAtom(*sprinter)->nr]->nr);
973 // insert into FragmentList
974 FragmentList[FragmentCounter]->insert(GraphPair(*TempSet, pair<int, double> (KeySetCounter++, (*runner).second.second)));
975 }
976 TempSet->clear();
977 }
978 delete (TempSet);
979 if (KeySetCounter == 0) {// if there are no keysets, delete the list
980 *out << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl;
981 delete (FragmentList[FragmentCounter]);
982 } else
983 *out << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl;
984 FragmentCounter++;
985 if (next != NULL)
986 next->AssignKeySetsToFragment(out, reference, KeySetList, ListOfLocalAtoms, FragmentList, FragmentCounter, FreeList);
987 FragmentCounter--;
988 } else
989 *out << Verbose(1) << "KeySetList is NULL or empty." << endl;
990
991 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
992 // free the index lookup list
993 Free(&ListOfLocalAtoms[FragmentCounter]);
994 if (FragmentCounter == 0) // first fragments frees the initial pointer to list
995 Free(&ListOfLocalAtoms);
996 }
997 *out << Verbose(1) << "End of AssignKeySetsToFragment." << endl;
998 return status;
999};
1000
1001/** Translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
1002 * \param *out output stream for debugging
1003 * \param **FragmentList Graph with local numbers per fragment
1004 * \param &FragmentCounter counts the fragments as we move along the list
1005 * \param &TotalNumberOfKeySets global key set counter
1006 * \param &TotalGraph Graph to be filled with global numbers
1007 */
1008void MoleculeLeafClass::TranslateIndicesToGlobalIDs(ofstream *out,
1009 Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets,
1010 Graph &TotalGraph)
1011{
1012 *out << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl;
1013 KeySet *TempSet = new KeySet;
1014 if (FragmentList[FragmentCounter] != NULL) {
1015 for (Graph::iterator runner = FragmentList[FragmentCounter]->begin(); runner != FragmentList[FragmentCounter]->end(); runner++) {
1016 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
1017 TempSet->insert((Leaf->FindAtom(*sprinter))->GetTrueFather()->nr);
1018 TotalGraph.insert(GraphPair(*TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
1019 TempSet->clear();
1020 }
1021 delete (TempSet);
1022 } else {
1023 *out << Verbose(1) << "FragmentList is NULL." << endl;
1024 }
1025 if (next != NULL)
1026 next->TranslateIndicesToGlobalIDs(out, FragmentList, ++FragmentCounter, TotalNumberOfKeySets, TotalGraph);
1027 FragmentCounter--;
1028 *out << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl;
1029};
1030
1031/** Simply counts the number of items in the list, from given MoleculeLeafClass.
1032 * \return number of items
1033 */
1034int MoleculeLeafClass::Count() const
1035{
1036 if (next != NULL)
1037 return next->Count() + 1;
1038 else
1039 return 1;
1040};
1041
Note: See TracBrowser for help on using the repository browser.