source: src/moleculelist.cpp@ 986ed3

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 986ed3 was 36166d, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Removed left over parts from old memory-tracker

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