source: molecuilder/src/moleculelist.cpp@ 390a2b

Last change on this file since 390a2b was 390a2b, checked in by Saskia Metzler <metzler@…>, 16 years ago

Ticket 11: use templates and/or traits to fix Malloc/ReAlloc-Free warnings in a clean manner

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