source: src/moleculelist.cpp@ e08c46

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

Removed molecule::first, molecule::last.

  • molecule does not have a chained list of bonds.
  • we have to go through atoms and its bonds, by checking (*BondRunner)->leftatom against (*AtomRunner) we exclude the other half.
  • first,last were present in only a few structures.
  • new functions:
    • molecule::hasBondStructure() - replaces first->next != last construct
    • molecule::CountBonds() - replaces first->next->next == last (i.e. one bond present) and alikes.

Signed-off-by: Frederik Heber <heber@…>

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