source: src/moleculelist.cpp@ 1024cb

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 Candidate_v1.7.0 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 1024cb was 1024cb, checked in by Frederik Heber <heber@…>, 15 years ago

Merge commit 'jupiter/MoleculeStartEndSwitch' into CommandLineActionMapping

Conflicts:

molecuilder/src/Makefile.am
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/helpers.hpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule_dynamics.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/unittests/AnalysisCorrelationToPointUnitTest.cpp
molecuilder/src/unittests/listofbondsunittest.cpp

Integration of MoleculeStartEndSwitch had the following consequences:

  • no more AtomCount -> getAtomCount()
  • no more start/end -> begin(), end() and iterator
  • no more decent ordering in atomic ids (hence, Simple_configuration/8 and Domain/5, Domain/6 now check by comparing sorted xyz, not confs)

There is still a huge problem with bonds. One test runs into an endless loop.

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

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