source: src/moleculelist.cpp@ 3e50ff

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

cstring header was missing in files, supplying definition of strlen, strcpy, and so on.

This was noted on laptop with gcc 4.1 (on workstation we have gcc 4.2)

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