source: src/moleculelist.cpp@ c54da3

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

Framework for embedding one molecule into another, now the embedding center finding is "only" missing

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