source: src/moleculelist.cpp@ 84c494

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 84c494 was 84c494, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Made the world store the cell_size within a Box object.

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