source: src/moleculelist.cpp@ 437922

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

Fix indentation from tab to two spaces.

The trouble was caused at the merge e08f45e4539ffcc30e039dec5606cf06b45ab6be. Seemingly, I thought eclipse had pulled some shit which i didn't

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