source: src/moleculelist.cpp@ 9fe36b

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 9fe36b was 6adb96, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Added possibility for views to catch name changes of molecules

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