source: src/moleculelist.cpp@ 458447

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

Shortened constructors [Meyers, "Effective C++" item 12]

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