source: src/moleculelist.cpp@ 5b4605

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 5b4605 was 88b400, checked in by Frederik Heber <heber@…>, 15 years ago

converted #define's to enums, consts and typedefs [Meyers, "Effective C++", item 1].

basic changes:

  • #define bla 1.3 -> const double bla = 1.3
  • #define bla "test" -> const char * const bla = "test
  • use class specific constants! (HULLEPSILON)

const int Class::bla = 1.3; (in .cpp)
static const int bla; (in .hpp inside class private section)

  • "enum hack": #define bla 5 -> enum { bla = 5 };
    • if const int bla=5; impossible
    • e.g. necessary if constant is used in array declaration (int blabla[bla];)

details:

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