source: src/moleculelist.cpp@ 796aa6

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 796aa6 was 389cc8, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Used the formual class instead of single variables inside molecule

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