source: src/moleculelist.cpp@ 192f6e

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

MEMFIXES: ListOfLocalAtoms in molecule::FragmentMolecule() was not free'd correctly.

NOTE: All of these lists and maps are hard to understand and make the code very confusing. It's really high time for refactoring.

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

  • Property mode set to 100755
File size: 46.4 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 "log.hpp"
22#include "molecule.hpp"
23#include "memoryallocator.hpp"
24#include "periodentafel.hpp"
25#include "Helpers/Assert.hpp"
26
27#include "Helpers/Assert.hpp"
28
29/*********************************** Functions for class MoleculeListClass *************************/
30
31/** Constructor for MoleculeListClass.
32 */
33MoleculeListClass::MoleculeListClass(World *_world) :
34 Observable("MoleculeListClass"),
35 world(_world)
36{
37 // empty lists
38 ListOfMolecules.clear();
39 MaxIndex = 1;
40};
41
42/** Destructor for MoleculeListClass.
43 */
44MoleculeListClass::~MoleculeListClass()
45{
46 DoLog(4) && (Log() << Verbose(4) << "Clearing ListOfMolecules." << endl);
47 for(MoleculeList::iterator MolRunner = ListOfMolecules.begin(); MolRunner != ListOfMolecules.end(); ++MolRunner)
48 (*MolRunner)->signOff(this);
49 ListOfMolecules.clear(); // empty list
50};
51
52/** Insert a new molecule into the list and set its number.
53 * \param *mol molecule to add to list.
54 */
55void MoleculeListClass::insert(molecule *mol)
56{
57 OBSERVE;
58 mol->IndexNr = MaxIndex++;
59 ListOfMolecules.push_back(mol);
60 mol->signOn(this);
61};
62
63/** Erases a molecule from the list.
64 * \param *mol molecule to add to list.
65 */
66void MoleculeListClass::erase(molecule *mol)
67{
68 OBSERVE;
69 mol->signOff(this);
70 ListOfMolecules.remove(mol);
71};
72
73/** Compare whether two molecules are equal.
74 * \param *a molecule one
75 * \param *n molecule two
76 * \return lexical value (-1, 0, +1)
77 */
78int MolCompare(const void *a, const void *b)
79{
80 int *aList = NULL, *bList = NULL;
81 int Count, Counter, aCounter, bCounter;
82 int flag;
83
84 // sort each atom list and put the numbers into a list, then go through
85 //Log() << Verbose(0) << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
86 // Yes those types are awkward... but check it for yourself it checks out this way
87 molecule *const *mol1_ptr= static_cast<molecule *const *>(a);
88 molecule *mol1 = *mol1_ptr;
89 molecule *const *mol2_ptr= static_cast<molecule *const *>(b);
90 molecule *mol2 = *mol2_ptr;
91 if (mol1->getAtomCount() < mol2->getAtomCount()) {
92 return -1;
93 } else {
94 if (mol1->getAtomCount() > mol2->getAtomCount())
95 return +1;
96 else {
97 Count = mol1->getAtomCount();
98 aList = new int[Count];
99 bList = new int[Count];
100
101 // fill the lists
102 Counter = 0;
103 aCounter = 0;
104 bCounter = 0;
105 molecule::const_iterator aiter = mol1->begin();
106 molecule::const_iterator biter = mol2->begin();
107 for (;(aiter != mol1->end()) && (biter != mol2->end());
108 ++aiter, ++biter) {
109 if ((*aiter)->GetTrueFather() == NULL)
110 aList[Counter] = Count + (aCounter++);
111 else
112 aList[Counter] = (*aiter)->GetTrueFather()->nr;
113 if ((*biter)->GetTrueFather() == NULL)
114 bList[Counter] = Count + (bCounter++);
115 else
116 bList[Counter] = (*biter)->GetTrueFather()->nr;
117 Counter++;
118 }
119 // check if AtomCount was for real
120 flag = 0;
121 if ((aiter == mol1->end()) && (biter != mol2->end())) {
122 flag = -1;
123 } else {
124 if ((aiter != mol1->end()) && (biter == mol2->end()))
125 flag = 1;
126 }
127 if (flag == 0) {
128 // sort the lists
129 gsl_heapsort(aList, Count, sizeof(int), CompareDoubles);
130 gsl_heapsort(bList, Count, sizeof(int), CompareDoubles);
131 // compare the lists
132
133 flag = 0;
134 for (int i = 0; i < Count; i++) {
135 if (aList[i] < bList[i]) {
136 flag = -1;
137 } else {
138 if (aList[i] > bList[i])
139 flag = 1;
140 }
141 if (flag != 0)
142 break;
143 }
144 }
145 delete[] (aList);
146 delete[] (bList);
147 return flag;
148 }
149 }
150 return -1;
151};
152
153/** Output of a list of all molecules.
154 * \param *out output stream
155 */
156void MoleculeListClass::Enumerate(ostream *out)
157{
158 periodentafel *periode = World::getInstance().getPeriode();
159 std::map<atomicNumber_t,unsigned int> counts;
160 double size=0;
161 Vector Origin;
162
163 // header
164 (*out) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
165 (*out) << "-----------------------------------------------" << endl;
166 if (ListOfMolecules.size() == 0)
167 (*out) << "\tNone" << endl;
168 else {
169 Origin.Zero();
170 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
171 // count atoms per element and determine size of bounding sphere
172 size=0.;
173 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
174 counts[(*iter)->type->getNumber()]++;
175 if ((*iter)->x.DistanceSquared(Origin) > size)
176 size = (*iter)->x.DistanceSquared(Origin);
177 }
178 // output Index, Name, number of atoms, chemical formula
179 (*out) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->getAtomCount() << "\t";
180
181 std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
182 for(iter=counts.rbegin(); iter!=counts.rend();++iter){
183 atomicNumber_t Z =(*iter).first;
184 (*out) << periode->FindElement(Z)->getSymbol() << (*iter).second;
185 }
186 // Center and size
187 (*out) << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl;
188 }
189 }
190};
191
192/** Returns the molecule with the given index \a index.
193 * \param index index of the desired molecule
194 * \return pointer to molecule structure, NULL if not found
195 */
196molecule * MoleculeListClass::ReturnIndex(int index)
197{
198 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
199 if ((*ListRunner)->IndexNr == index)
200 return (*ListRunner);
201 return NULL;
202};
203
204/** Simple merge of two molecules into one.
205 * \param *mol destination molecule
206 * \param *srcmol source molecule
207 * \return true - merge successful, false - merge failed (probably due to non-existant indices
208 */
209bool MoleculeListClass::SimpleMerge(molecule *mol, molecule *srcmol)
210{
211 if (srcmol == NULL)
212 return false;
213
214 // put all molecules of src into mol
215 for (molecule::iterator iter = srcmol->begin(); !srcmol->empty(); iter=srcmol->begin()) {
216 atom * const Walker = *iter;
217 srcmol->UnlinkAtom(Walker);
218 mol->AddAtom(Walker);
219 }
220
221 // remove src
222 ListOfMolecules.remove(srcmol);
223 World::getInstance().destroyMolecule(srcmol);
224 return true;
225};
226
227/** Simple add of one molecules into another.
228 * \param *mol destination molecule
229 * \param *srcmol source molecule
230 * \return true - merge successful, false - merge failed (probably due to non-existant indices
231 */
232bool MoleculeListClass::SimpleAdd(molecule *mol, molecule *srcmol)
233{
234 if (srcmol == NULL)
235 return false;
236
237 // put all molecules of src into mol
238 atom *Walker = NULL;
239 for (molecule::iterator iter = srcmol->begin(); iter != srcmol->end(); ++iter) {
240 Walker = mol->AddCopyAtom((*iter));
241 Walker->father = Walker;
242 }
243
244 return true;
245};
246
247/** Simple merge of a given set of molecules into one.
248 * \param *mol destination molecule
249 * \param *src index of set of source molecule
250 * \param N number of source molecules
251 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
252 */
253bool MoleculeListClass::SimpleMultiMerge(molecule *mol, int *src, int N)
254{
255 bool status = true;
256 // check presence of all source molecules
257 for (int i=0;i<N;i++) {
258 molecule *srcmol = ReturnIndex(src[i]);
259 status = status && SimpleMerge(mol, srcmol);
260 }
261 insert(mol);
262 return status;
263};
264
265/** Simple add of a given set of molecules into one.
266 * \param *mol destination molecule
267 * \param *src index of set of source molecule
268 * \param N number of source molecules
269 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
270 */
271bool MoleculeListClass::SimpleMultiAdd(molecule *mol, int *src, int N)
272{
273 bool status = true;
274 // check presence of all source molecules
275 for (int i=0;i<N;i++) {
276 molecule *srcmol = ReturnIndex(src[i]);
277 status = status && SimpleAdd(mol, srcmol);
278 }
279 return status;
280};
281
282/** Scatter merge of a given set of molecules into one.
283 * Scatter merge distributes the molecules in such a manner that they don't overlap.
284 * \param *mol destination molecule
285 * \param *src index of set of source molecule
286 * \param N number of source molecules
287 * \return true - merge successful, false - merge failed (probably due to non-existant indices
288 * \TODO find scatter center for each src molecule
289 */
290bool MoleculeListClass::ScatterMerge(molecule *mol, int *src, int N)
291{
292 // check presence of all source molecules
293 for (int i=0;i<N;i++) {
294 // get pointer to src molecule
295 molecule *srcmol = ReturnIndex(src[i]);
296 if (srcmol == NULL)
297 return false;
298 }
299 // adapt each Center
300 for (int i=0;i<N;i++) {
301 // get pointer to src molecule
302 molecule *srcmol = ReturnIndex(src[i]);
303 //srcmol->Center.Zero();
304 srcmol->Translate(&srcmol->Center);
305 }
306 // perform a simple multi merge
307 SimpleMultiMerge(mol, src, N);
308 return true;
309};
310
311/** Embedding merge of a given set of molecules into one.
312 * Embedding merge inserts one molecule into the other.
313 * \param *mol destination molecule (fixed one)
314 * \param *srcmol source molecule (variable one, where atoms are taken from)
315 * \return true - merge successful, false - merge failed (probably due to non-existant indices)
316 * \TODO linked cell dimensions for boundary points has to be as big as inner diameter!
317 */
318bool MoleculeListClass::EmbedMerge(molecule *mol, molecule *srcmol)
319{
320 LinkedCell *LCList = NULL;
321 Tesselation *TesselStruct = NULL;
322 if ((srcmol == NULL) || (mol == NULL)) {
323 DoeLog(1) && (eLog()<< Verbose(1) << "Either fixed or variable molecule is given as NULL." << endl);
324 return false;
325 }
326
327 // calculate envelope for *mol
328 LCList = new LinkedCell(mol, 8.);
329 FindNonConvexBorder(mol, TesselStruct, (const LinkedCell *&)LCList, 4., NULL);
330 if (TesselStruct == NULL) {
331 DoeLog(1) && (eLog()<< Verbose(1) << "Could not tesselate the fixed molecule." << endl);
332 return false;
333 }
334 delete(LCList);
335 LCList = new LinkedCell(TesselStruct, 8.); // re-create with boundary points only!
336
337 // prepare index list for bonds
338 atom ** CopyAtoms = new atom*[srcmol->getAtomCount()];
339 for(int i=0;i<srcmol->getAtomCount();i++)
340 CopyAtoms[i] = NULL;
341
342 // for each of the source atoms check whether we are in- or outside and add copy atom
343 int nr=0;
344 for (molecule::const_iterator iter = srcmol->begin(); iter != srcmol->end(); ++iter) {
345 DoLog(2) && (Log() << Verbose(2) << "INFO: Current Walker is " << **iter << "." << endl);
346 if (!TesselStruct->IsInnerPoint((*iter)->x, LCList)) {
347 CopyAtoms[(*iter)->nr] = (*iter)->clone();
348 mol->AddAtom(CopyAtoms[(*iter)->nr]);
349 nr++;
350 } else {
351 // do nothing
352 }
353 }
354 DoLog(1) && (Log() << Verbose(1) << nr << " of " << srcmol->getAtomCount() << " atoms have been merged.");
355
356 // go through all bonds and add as well
357 for(molecule::iterator AtomRunner = srcmol->begin(); AtomRunner != srcmol->end(); ++AtomRunner)
358 for(BondList::iterator BondRunner = (*AtomRunner)->ListOfBonds.begin(); BondRunner != (*AtomRunner)->ListOfBonds.end(); ++BondRunner)
359 if ((*BondRunner)->leftatom == *AtomRunner) {
360 DoLog(3) && (Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[(*BondRunner)->leftatom->nr] << " and " << *CopyAtoms[(*BondRunner)->rightatom->nr]<< "." << endl);
361 mol->AddBond(CopyAtoms[(*BondRunner)->leftatom->nr], CopyAtoms[(*BondRunner)->rightatom->nr], (*BondRunner)->BondDegree);
362 }
363 delete(LCList);
364 return true;
365};
366
367/** Simple output of the pointers in ListOfMolecules.
368 * \param *out output stream
369 */
370void MoleculeListClass::Output(ofstream *out)
371{
372 DoLog(1) && (Log() << Verbose(1) << "MoleculeList: ");
373 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
374 DoLog(0) && (Log() << Verbose(0) << *ListRunner << "\t");
375 DoLog(0) && (Log() << Verbose(0) << endl);
376};
377
378/** Calculates necessary hydrogen correction due to unwanted interaction between saturated ones.
379 * If for a pair of two hydrogen atoms a and b, at least is a saturated one, and a and b are not
380 * bonded to the same atom, then we add for this pair a correction term constructed from a Morse
381 * potential function fit to QM calculations with respecting to the interatomic hydrogen distance.
382 * \param &path path to file
383 */
384bool MoleculeListClass::AddHydrogenCorrection(std::string &path)
385{
386 bond *Binder = NULL;
387 double ***FitConstant = NULL, **correction = NULL;
388 int a, b;
389 ofstream output;
390 ifstream input;
391 string line;
392 stringstream zeile;
393 double distance;
394 char ParsedLine[1023];
395 double tmp;
396 char *FragmentNumber = NULL;
397
398 DoLog(1) && (Log() << Verbose(1) << "Saving hydrogen saturation correction ... ");
399 // 0. parse in fit constant files that should have the same dimension as the final energy files
400 // 0a. find dimension of matrices with constants
401 line = path;
402 line += "1";
403 line += FITCONSTANTSUFFIX;
404 input.open(line.c_str());
405 if (input.fail()) {
406 DoLog(1) && (Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
407 return false;
408 }
409 a = 0;
410 b = -1; // we overcount by one
411 while (!input.eof()) {
412 input.getline(ParsedLine, 1023);
413 zeile.str(ParsedLine);
414 int i = 0;
415 while (!zeile.eof()) {
416 zeile >> distance;
417 i++;
418 }
419 if (i > a)
420 a = i;
421 b++;
422 }
423 DoLog(0) && (Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ");
424 input.close();
425
426 // 0b. allocate memory for constants
427 FitConstant = new double**[3];
428 for (int k = 0; k < 3; k++) {
429 FitConstant[k] = new double*[a];
430 for (int i = a; i--;) {
431 FitConstant[k][i] = new double[b];
432 for (int j = b; j--;) {
433 FitConstant[k][i][j] = 0.;
434 }
435 }
436 }
437 // 0c. parse in constants
438 for (int i = 0; i < 3; i++) {
439 line = path;
440 line.append("/");
441 line += FRAGMENTPREFIX;
442 sprintf(ParsedLine, "%d", i + 1);
443 line += ParsedLine;
444 line += FITCONSTANTSUFFIX;
445 input.open(line.c_str());
446 if (input == NULL) {
447 DoeLog(0) && (eLog()<< Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
448 performCriticalExit();
449 return false;
450 }
451 int k = 0, l;
452 while ((!input.eof()) && (k < b)) {
453 input.getline(ParsedLine, 1023);
454 //Log() << Verbose(0) << "Current Line: " << ParsedLine << endl;
455 zeile.str(ParsedLine);
456 zeile.clear();
457 l = 0;
458 while ((!zeile.eof()) && (l < a)) {
459 zeile >> FitConstant[i][l][k];
460 //Log() << Verbose(0) << FitConstant[i][l][k] << "\t";
461 l++;
462 }
463 //Log() << Verbose(0) << endl;
464 k++;
465 }
466 input.close();
467 }
468 for (int k = 0; k < 3; k++) {
469 DoLog(0) && (Log() << Verbose(0) << "Constants " << k << ":" << endl);
470 for (int j = 0; j < b; j++) {
471 for (int i = 0; i < a; i++) {
472 DoLog(0) && (Log() << Verbose(0) << FitConstant[k][i][j] << "\t");
473 }
474 DoLog(0) && (Log() << Verbose(0) << endl);
475 }
476 DoLog(0) && (Log() << Verbose(0) << endl);
477 }
478
479 // 0d. allocate final correction matrix
480 correction = new double*[a];
481 for (int i = a; i--;)
482 correction[i] = new double[b];
483
484 // 1a. go through every molecule in the list
485 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
486 // 1b. zero final correction matrix
487 for (int k = a; k--;)
488 for (int j = b; j--;)
489 correction[k][j] = 0.;
490 // 2. take every hydrogen that is a saturated one
491 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
492 //Log() << Verbose(1) << "(*iter): " << *(*iter) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
493 if (((*iter)->type->Z == 1) && (((*iter)->father == NULL)
494 || ((*iter)->father->type->Z != 1))) { // if it's a hydrogen
495 for (molecule::const_iterator runner = (*ListRunner)->begin(); runner != (*ListRunner)->end(); ++runner) {
496 //Log() << Verbose(2) << "Runner: " << *(*runner) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
497 // 3. take every other hydrogen that is the not the first and not bound to same bonding partner
498 Binder = *((*runner)->ListOfBonds.begin());
499 if (((*runner)->type->Z == 1) && ((*runner)->nr > (*iter)->nr) && (Binder->GetOtherAtom((*runner)) != Binder->GetOtherAtom((*iter)))) { // (hydrogens have only one bonding partner!)
500 // 4. evaluate the morse potential for each matrix component and add up
501 distance = (*runner)->x.distance((*iter)->x);
502 //Log() << Verbose(0) << "Fragment " << (*ListRunner)->name << ": " << *(*runner) << "<= " << distance << "=>" << *(*iter) << ":" << endl;
503 for (int k = 0; k < a; k++) {
504 for (int j = 0; j < b; j++) {
505 switch (k) {
506 case 1:
507 case 7:
508 case 11:
509 tmp = pow(FitConstant[0][k][j] * (1. - exp(-FitConstant[1][k][j] * (distance - FitConstant[2][k][j]))), 2);
510 break;
511 default:
512 tmp = FitConstant[0][k][j] * pow(distance, FitConstant[1][k][j]) + FitConstant[2][k][j];
513 };
514 correction[k][j] -= tmp; // ground state is actually lower (disturbed by additional interaction)
515 //Log() << Verbose(0) << tmp << "\t";
516 }
517 //Log() << Verbose(0) << endl;
518 }
519 //Log() << Verbose(0) << endl;
520 }
521 }
522 }
523 }
524 // 5. write final matrix to file
525 line = path;
526 line.append("/");
527 line += FRAGMENTPREFIX;
528 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), (*ListRunner)->IndexNr);
529 line += FragmentNumber;
530 delete[] (FragmentNumber);
531 line += HCORRECTIONSUFFIX;
532 output.open(line.c_str());
533 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
534 for (int j = 0; j < b; j++) {
535 for (int i = 0; i < a; i++)
536 output << correction[i][j] << "\t";
537 output << endl;
538 }
539 output.close();
540 }
541 for (int i = a; i--;)
542 delete[](correction[i]);
543 delete[](correction);
544
545 line = path;
546 line.append("/");
547 line += HCORRECTIONSUFFIX;
548 output.open(line.c_str());
549 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
550 for (int j = 0; j < b; j++) {
551 for (int i = 0; i < a; i++)
552 output << 0 << "\t";
553 output << endl;
554 }
555 output.close();
556 // 6. free memory of parsed matrices
557 for (int k = 0; k < 3; k++) {
558 for (int i = a; i--;) {
559 delete[](FitConstant[k][i]);
560 }
561 delete[](FitConstant[k]);
562 }
563 delete[](FitConstant);
564 DoLog(0) && (Log() << Verbose(0) << "done." << endl);
565 return true;
566};
567
568/** Store force indices, i.e. the connection between the nuclear index in the total molecule config and the respective atom in fragment config.
569 * \param &path path to file
570 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
571 * \return true - file written successfully, false - writing failed
572 */
573bool MoleculeListClass::StoreForcesFile(std::string &path, int *SortIndex)
574{
575 bool status = true;
576 string filename(path);
577 filename += FORCESFILE;
578 ofstream ForcesFile(filename.c_str());
579 periodentafel *periode=World::getInstance().getPeriode();
580
581 // open file for the force factors
582 DoLog(1) && (Log() << Verbose(1) << "Saving force factors ... ");
583 if (!ForcesFile.fail()) {
584 //Log() << Verbose(1) << "Final AtomicForcesList: ";
585 //output << prefix << "Forces" << endl;
586 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
587 periodentafel::const_iterator elemIter;
588 for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
589 if ((*ListRunner)->ElementsInMolecule[(*elemIter).first]) { // if this element got atoms
590 for(molecule::iterator atomIter = (*ListRunner)->begin(); atomIter !=(*ListRunner)->end();++atomIter){
591 if ((*atomIter)->type->getNumber() == (*elemIter).first) {
592 if (((*atomIter)->GetTrueFather() != NULL) && ((*atomIter)->GetTrueFather() != (*atomIter))) {// if there is a rea
593 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
594 ForcesFile << SortIndex[(*atomIter)->GetTrueFather()->nr] << "\t";
595 } else
596 // otherwise a -1 to indicate an added saturation hydrogen
597 ForcesFile << "-1\t";
598 }
599 }
600 }
601 }
602 ForcesFile << endl;
603 }
604 ForcesFile.close();
605 DoLog(1) && (Log() << Verbose(1) << "done." << endl);
606 } else {
607 status = false;
608 DoLog(1) && (Log() << Verbose(1) << "failed to open file " << filename << "." << endl);
609 }
610 ForcesFile.close();
611
612 return status;
613};
614
615/** Writes a config file for each molecule in the given \a **FragmentList.
616 * \param *out output stream for debugging
617 * \param &prefix path and prefix to the fragment config files
618 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
619 * \return true - success (each file was written), false - something went wrong.
620 */
621bool MoleculeListClass::OutputConfigForListOfFragments(std::string &prefix, int *SortIndex)
622{
623 ofstream outputFragment;
624 std::string FragmentName;
625 char PathBackup[MAXSTRINGSIZE];
626 bool result = true;
627 bool intermediateResult = true;
628 Vector BoxDimension;
629 char *FragmentNumber = NULL;
630 char *path = NULL;
631 int FragmentCounter = 0;
632 ofstream output;
633 double cell_size_backup[6];
634 double * const cell_size = World::getInstance().getDomain();
635
636 // backup cell_size
637 for (int i=0;i<6;i++)
638 cell_size_backup[i] = cell_size[i];
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 int j = -1;
677 for (int k = 0; k < NDIM; k++) {
678 j += k + 1;
679 BoxDimension[k] = 2.5 * (World::getInstance().getConfig()->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
680 cell_size[j] = BoxDimension[k] * 2.;
681 }
682 (*ListRunner)->Translate(&BoxDimension);
683
684 // also calculate necessary orbitals
685 (*ListRunner)->CountElements(); // this is a bugfix, atoms should shoulds actually be added correctly to this fragment
686 //(*ListRunner)->CalculateOrbitals(*World::getInstance().getConfig);
687
688 // change path in config
689 FragmentName = PathBackup;
690 FragmentName += "/";
691 FragmentName += FRAGMENTPREFIX;
692 FragmentName += FragmentNumber;
693 FragmentName += "/";
694 World::getInstance().getConfig()->SetDefaultPath(FragmentName.c_str());
695
696 // and save as config
697 FragmentName = prefix + FragmentNumber + ".conf";
698 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...");
699 if ((intermediateResult = World::getInstance().getConfig()->Save(FragmentName.c_str(), (*ListRunner)->elemente, (*ListRunner))))
700 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
701 else
702 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
703 result = result && intermediateResult;
704
705 // restore old config
706 World::getInstance().getConfig()->SetDefaultPath(PathBackup);
707
708 // and save as mpqc input file
709 FragmentName = prefix + FragmentNumber + ".conf";
710 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...");
711 if ((intermediateResult = World::getInstance().getConfig()->SaveMPQC(FragmentName.c_str(), (*ListRunner))))
712 DoLog(2) && (Log() << Verbose(2) << " done." << endl);
713 else
714 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
715
716 result = result && intermediateResult;
717 //outputFragment.close();
718 //outputFragment.clear();
719 delete[](FragmentNumber);
720 }
721 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
722
723 // printing final number
724 DoLog(2) && (Log() << Verbose(2) << "Final number of fragments: " << FragmentCounter << "." << endl);
725
726 // restore cell_size
727 for (int i=0;i<6;i++)
728 cell_size[i] = cell_size_backup[i];
729
730 return result;
731};
732
733/** Counts the number of molecules with the molecule::ActiveFlag set.
734 * \return number of molecules with ActiveFlag set to true.
735 */
736int MoleculeListClass::NumberOfActiveMolecules()
737{
738 int count = 0;
739 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
740 count += ((*ListRunner)->ActiveFlag ? 1 : 0);
741 return count;
742};
743
744/** Dissects given \a *mol into connected subgraphs and inserts them as new molecules but with old atoms into \a this.
745 * \param *out output stream for debugging
746 * \param *periode periodentafel
747 * \param *configuration config with BondGraph
748 */
749void MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration)
750{
751 // 0a. remove all present molecules
752 vector<molecule *> allmolecules = World::getInstance().getAllMolecules();
753 for (vector<molecule *>::iterator MolRunner = allmolecules.begin(); MolRunner != allmolecules.end(); ++MolRunner) {
754 erase(*MolRunner);
755 World::getInstance().destroyMolecule(*MolRunner);
756 }
757 // 0b. remove all bonds and construct a molecule with all atoms
758 molecule *mol = World::getInstance().createMolecule();
759 vector <atom *> allatoms = World::getInstance().getAllAtoms();
760 for(vector<atom *>::iterator AtomRunner = allatoms.begin(); AtomRunner != allatoms.end(); ++AtomRunner) {
761 for(BondList::iterator BondRunner = (*AtomRunner)->ListOfBonds.begin(); !(*AtomRunner)->ListOfBonds.empty(); BondRunner = (*AtomRunner)->ListOfBonds.begin())
762 delete(*BondRunner);
763 mol->AddAtom(*AtomRunner);
764 }
765
766 // 1. dissect the molecule into connected subgraphs
767 if (configuration->BG != NULL) {
768 if (!configuration->BG->ConstructBondGraph(mol)) {
769 World::getInstance().destroyMolecule(mol);
770 DoeLog(1) && (eLog()<< Verbose(1) << "There are no bonds." << endl);
771 return;
772 }
773 } else {
774 DoeLog(1) && (eLog()<< Verbose(1) << "There is no BondGraph class present to create bonds." << endl);
775 return;
776 }
777
778 // 2. scan for connected subgraphs
779 MoleculeLeafClass *Subgraphs = NULL; // list of subgraphs from DFS analysis
780 class StackClass<bond *> *BackEdgeStack = NULL;
781 Subgraphs = mol->DepthFirstSearchAnalysis(BackEdgeStack);
782 delete(BackEdgeStack);
783 if ((Subgraphs == NULL) || (Subgraphs->next == NULL)) {
784 World::getInstance().destroyMolecule(mol);
785 DoeLog(1) && (eLog()<< Verbose(1) << "There are no atoms." << endl);
786 return;
787 }
788
789 // 3. dissect (the following construct is needed to have the atoms not in the order of the DFS, but in
790 // the original one as parsed in)
791 // TODO: Optimize this, when molecules just contain pointer list of global atoms!
792
793 // 4a. create array of molecules to fill
794 const int MolCount = Subgraphs->next->Count();
795 char number[MAXSTRINGSIZE];
796 molecule **molecules = new molecule *[MolCount];
797 MoleculeLeafClass *MolecularWalker = Subgraphs;
798 for (int i=0;i<MolCount;i++) {
799 MolecularWalker = MolecularWalker->next;
800 molecules[i] = World::getInstance().createMolecule();
801 molecules[i]->ActiveFlag = true;
802 strncpy(molecules[i]->name, mol->name, MAXSTRINGSIZE);
803 if (MolCount > 1) {
804 sprintf(number, "-%d", i+1);
805 strncat(molecules[i]->name, number, MAXSTRINGSIZE - strlen(mol->name) - 1);
806 }
807 DoLog(1) && (Log() << Verbose(1) << "MolName is " << molecules[i]->name << ", id is " << molecules[i]->getId() << endl);
808 for (molecule::iterator iter = MolecularWalker->Leaf->begin(); iter != MolecularWalker->Leaf->end(); ++iter) {
809 DoLog(1) && (Log() << Verbose(1) << **iter << endl);
810 }
811 insert(molecules[i]);
812 }
813
814 // 4b. create and fill map of which atom is associated to which connected molecule (note, counting starts at 1)
815 int FragmentCounter = 0;
816 map<int, atom *> AtomToFragmentMap;
817 MolecularWalker = Subgraphs;
818 while (MolecularWalker->next != NULL) {
819 MolecularWalker = MolecularWalker->next;
820 for (molecule::iterator iter = MolecularWalker->Leaf->begin(); !MolecularWalker->Leaf->empty(); iter = MolecularWalker->Leaf->begin()) {
821 atom * Walker = *iter;
822 DoLog(1) && (Log() << Verbose(1) << "Re-linking " << Walker << "..." << endl);
823 MolecularWalker->Leaf->erase(iter);
824 molecules[FragmentCounter]->AddAtom(Walker); // counting starts at 1
825 }
826 FragmentCounter++;
827 }
828 World::getInstance().destroyMolecule(mol);
829
830 // 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
831 // TODO: check whether this is really not needed anymore
832 // 4e. free Leafs
833 MolecularWalker = Subgraphs;
834 while (MolecularWalker->next != NULL) {
835 MolecularWalker = MolecularWalker->next;
836 delete(MolecularWalker->previous);
837 }
838 delete(MolecularWalker);
839 delete[](molecules);
840 DoLog(1) && (Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl);
841};
842
843/** Count all atoms in each molecule.
844 * \return number of atoms in the MoleculeListClass.
845 * TODO: the inner loop should be done by some (double molecule::CountAtom()) function
846 */
847int MoleculeListClass::CountAllAtoms() const
848{
849 int AtomNo = 0;
850 for (MoleculeList::const_iterator MolWalker = ListOfMolecules.begin(); MolWalker != ListOfMolecules.end(); MolWalker++) {
851 AtomNo += (*MolWalker)->size();
852 }
853 return AtomNo;
854}
855
856/***********
857 * Methods Moved here from the menus
858 */
859
860void MoleculeListClass::flipChosen() {
861 int j;
862 Log() << Verbose(0) << "Enter index of molecule: ";
863 cin >> j;
864 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
865 if ((*ListRunner)->IndexNr == j)
866 (*ListRunner)->ActiveFlag = !(*ListRunner)->ActiveFlag;
867}
868
869void MoleculeListClass::createNewMolecule(periodentafel *periode) {
870 OBSERVE;
871 molecule *mol = NULL;
872 mol = World::getInstance().createMolecule();
873 insert(mol);
874};
875
876void MoleculeListClass::loadFromXYZ(periodentafel *periode){
877 molecule *mol = NULL;
878 Vector center;
879 char filename[MAXSTRINGSIZE];
880 Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
881 mol = World::getInstance().createMolecule();
882 do {
883 Log() << Verbose(0) << "Enter file name: ";
884 cin >> filename;
885 } while (!mol->AddXYZFile(filename));
886 mol->SetNameFromFilename(filename);
887 // center at set box dimensions
888 mol->CenterEdge(&center);
889 World::getInstance().getDomain()[0] = center[0];
890 World::getInstance().getDomain()[1] = 0;
891 World::getInstance().getDomain()[2] = center[1];
892 World::getInstance().getDomain()[3] = 0;
893 World::getInstance().getDomain()[4] = 0;
894 World::getInstance().getDomain()[5] = center[2];
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{
954 // if (Up != NULL)
955 // if (Up->DownLeaf == NULL) // are we the first down leaf for the upper leaf?
956 // Up->DownLeaf = this;
957 // UpLeaf = Up;
958 // DownLeaf = NULL;
959 Leaf = NULL;
960 previous = PreviousLeaf;
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)->type->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.