source: src/moleculelist.cpp@ cd5047

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

Added Logging capabilities to Observer Framework

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