source: src/moleculelist.cpp@ 77a570

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 77a570 was 4e10f5, checked in by Tillmann Crueger <crueger@…>, 14 years ago

Merge branch 'stable' into StructureRefactoring

Conflicts:

src/Actions/WorldAction/CenterOnEdgeAction.cpp
src/Actions/WorldAction/ChangeBoxAction.cpp
src/Actions/WorldAction/RepeatBoxAction.cpp
src/Actions/WorldAction/ScaleBoxAction.cpp
src/World.cpp
src/boundary.cpp

  • 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.hpp"
26#include "linkedcell.hpp"
27#include "lists.hpp"
28#include "verbose.hpp"
29#include "log.hpp"
30#include "molecule.hpp"
31#include "periodentafel.hpp"
32#include "Helpers/Assert.hpp"
33#include "Matrix.hpp"
34#include "Box.hpp"
35#include "stackclass.hpp"
36
37#include "Helpers/Assert.hpp"
38
39/*********************************** Functions for class MoleculeListClass *************************/
40
41/** Constructor for MoleculeListClass.
42 */
43MoleculeListClass::MoleculeListClass(World *_world) :
44 Observable("MoleculeListClass"),
45 world(_world)
46{
47 // empty lists
48 ListOfMolecules.clear();
49 MaxIndex = 1;
50};
51
52/** Destructor for MoleculeListClass.
53 */
54MoleculeListClass::~MoleculeListClass()
55{
56 DoLog(4) && (Log() << Verbose(4) << "Clearing ListOfMolecules." << endl);
57 for(MoleculeList::iterator MolRunner = ListOfMolecules.begin(); MolRunner != ListOfMolecules.end(); ++MolRunner)
58 (*MolRunner)->signOff(this);
59 ListOfMolecules.clear(); // empty list
60};
61
62/** Insert a new molecule into the list and set its number.
63 * \param *mol molecule to add to list.
64 */
65void MoleculeListClass::insert(molecule *mol)
66{
67 OBSERVE;
68 mol->IndexNr = MaxIndex++;
69 ListOfMolecules.push_back(mol);
70 mol->signOn(this);
71};
72
73/** Erases a molecule from the list.
74 * \param *mol molecule to add to list.
75 */
76void MoleculeListClass::erase(molecule *mol)
77{
78 OBSERVE;
79 mol->signOff(this);
80 ListOfMolecules.remove(mol);
81};
82
83/** Compare whether two molecules are equal.
84 * \param *a molecule one
85 * \param *n molecule two
86 * \return lexical value (-1, 0, +1)
87 */
88int MolCompare(const void *a, const void *b)
89{
90 int *aList = NULL, *bList = NULL;
91 int Count, Counter, aCounter, bCounter;
92 int flag;
93
94 // sort each atom list and put the numbers into a list, then go through
95 //Log() << Verbose(0) << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
96 // Yes those types are awkward... but check it for yourself it checks out this way
97 molecule *const *mol1_ptr= static_cast<molecule *const *>(a);
98 molecule *mol1 = *mol1_ptr;
99 molecule *const *mol2_ptr= static_cast<molecule *const *>(b);
100 molecule *mol2 = *mol2_ptr;
101 if (mol1->getAtomCount() < mol2->getAtomCount()) {
102 return -1;
103 } else {
104 if (mol1->getAtomCount() > mol2->getAtomCount())
105 return +1;
106 else {
107 Count = mol1->getAtomCount();
108 aList = new int[Count];
109 bList = new int[Count];
110
111 // fill the lists
112 Counter = 0;
113 aCounter = 0;
114 bCounter = 0;
115 molecule::const_iterator aiter = mol1->begin();
116 molecule::const_iterator biter = mol2->begin();
117 for (;(aiter != mol1->end()) && (biter != mol2->end());
118 ++aiter, ++biter) {
119 if ((*aiter)->GetTrueFather() == NULL)
120 aList[Counter] = Count + (aCounter++);
121 else
122 aList[Counter] = (*aiter)->GetTrueFather()->nr;
123 if ((*biter)->GetTrueFather() == NULL)
124 bList[Counter] = Count + (bCounter++);
125 else
126 bList[Counter] = (*biter)->GetTrueFather()->nr;
127 Counter++;
128 }
129 // check if AtomCount was for real
130 flag = 0;
131 if ((aiter == mol1->end()) && (biter != mol2->end())) {
132 flag = -1;
133 } else {
134 if ((aiter != mol1->end()) && (biter == mol2->end()))
135 flag = 1;
136 }
137 if (flag == 0) {
138 // sort the lists
139 gsl_heapsort(aList, Count, sizeof(int), CompareDoubles);
140 gsl_heapsort(bList, Count, sizeof(int), CompareDoubles);
141 // compare the lists
142
143 flag = 0;
144 for (int i = 0; i < Count; i++) {
145 if (aList[i] < bList[i]) {
146 flag = -1;
147 } else {
148 if (aList[i] > bList[i])
149 flag = 1;
150 }
151 if (flag != 0)
152 break;
153 }
154 }
155 delete[] (aList);
156 delete[] (bList);
157 return flag;
158 }
159 }
160 return -1;
161};
162
163/** Output of a list of all molecules.
164 * \param *out output stream
165 */
166void MoleculeListClass::Enumerate(ostream *out)
167{
168 periodentafel *periode = World::getInstance().getPeriode();
169 std::map<atomicNumber_t,unsigned int> counts;
170 double size=0;
171 Vector Origin;
172
173 // header
174 (*out) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
175 (*out) << "-----------------------------------------------" << endl;
176 if (ListOfMolecules.size() == 0)
177 (*out) << "\tNone" << endl;
178 else {
179 Origin.Zero();
180 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
181 // count atoms per element and determine size of bounding sphere
182 size=0.;
183 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
184 counts[(*iter)->type->getNumber()]++;
185 if ((*iter)->x.DistanceSquared(Origin) > size)
186 size = (*iter)->x.DistanceSquared(Origin);
187 }
188 // output Index, Name, number of atoms, chemical formula
189 (*out) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->getAtomCount() << "\t";
190
191 std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
192 for(iter=counts.rbegin(); iter!=counts.rend();++iter){
193 atomicNumber_t Z =(*iter).first;
194 (*out) << periode->FindElement(Z)->getSymbol() << (*iter).second;
195 }
196 // Center and size
197 (*out) << "\t" << (*ListRunner)->Center << "\t" << sqrt(size) << endl;
198 }
199 }
200};
201
202/** Returns the molecule with the given index \a index.
203 * \param index index of the desired molecule
204 * \return pointer to molecule structure, NULL if not found
205 */
206molecule * MoleculeListClass::ReturnIndex(int index)
207{
208 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
209 if ((*ListRunner)->IndexNr == index)
210 return (*ListRunner);
211 return NULL;
212};
213
214/** Simple merge of two molecules into one.
215 * \param *mol destination molecule
216 * \param *srcmol source molecule
217 * \return true - merge successful, false - merge failed (probably due to non-existant indices
218 */
219bool MoleculeListClass::SimpleMerge(molecule *mol, molecule *srcmol)
220{
221 if (srcmol == NULL)
222 return false;
223
224 // put all molecules of src into mol
225 for (molecule::iterator iter = srcmol->begin(); !srcmol->empty(); iter=srcmol->begin()) {
226 atom * const Walker = *iter;
227 srcmol->UnlinkAtom(Walker);
228 mol->AddAtom(Walker);
229 }
230
231 // remove src
232 ListOfMolecules.remove(srcmol);
233 World::getInstance().destroyMolecule(srcmol);
234 return true;
235};
236
237/** Simple add of one molecules into another.
238 * \param *mol destination molecule
239 * \param *srcmol source molecule
240 * \return true - merge successful, false - merge failed (probably due to non-existant indices
241 */
242bool MoleculeListClass::SimpleAdd(molecule *mol, molecule *srcmol)
243{
244 if (srcmol == NULL)
245 return false;
246
247 // put all molecules of src into mol
248 atom *Walker = NULL;
249 for (molecule::iterator iter = srcmol->begin(); iter != srcmol->end(); ++iter) {
250 Walker = mol->AddCopyAtom((*iter));
251 Walker->father = Walker;
252 }
253
254 return true;
255};
256
257/** Simple merge of a given set of molecules into one.
258 * \param *mol destination molecule
259 * \param *src index of set of source molecule
260 * \param N number of source molecules
261 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
262 */
263bool MoleculeListClass::SimpleMultiMerge(molecule *mol, int *src, int N)
264{
265 bool status = true;
266 // check presence of all source molecules
267 for (int i=0;i<N;i++) {
268 molecule *srcmol = ReturnIndex(src[i]);
269 status = status && SimpleMerge(mol, srcmol);
270 }
271 insert(mol);
272 return status;
273};
274
275/** Simple add of a given set of molecules into one.
276 * \param *mol destination molecule
277 * \param *src index of set of source molecule
278 * \param N number of source molecules
279 * \return true - merge successful, false - some merges failed (probably due to non-existant indices)
280 */
281bool MoleculeListClass::SimpleMultiAdd(molecule *mol, int *src, int N)
282{
283 bool status = true;
284 // check presence of all source molecules
285 for (int i=0;i<N;i++) {
286 molecule *srcmol = ReturnIndex(src[i]);
287 status = status && SimpleAdd(mol, srcmol);
288 }
289 return status;
290};
291
292/** Scatter merge of a given set of molecules into one.
293 * Scatter merge distributes the molecules in such a manner that they don't overlap.
294 * \param *mol destination molecule
295 * \param *src index of set of source molecule
296 * \param N number of source molecules
297 * \return true - merge successful, false - merge failed (probably due to non-existant indices
298 * \TODO find scatter center for each src molecule
299 */
300bool MoleculeListClass::ScatterMerge(molecule *mol, int *src, int N)
301{
302 // check presence of all source molecules
303 for (int i=0;i<N;i++) {
304 // get pointer to src molecule
305 molecule *srcmol = ReturnIndex(src[i]);
306 if (srcmol == NULL)
307 return false;
308 }
309 // adapt each Center
310 for (int i=0;i<N;i++) {
311 // get pointer to src molecule
312 molecule *srcmol = ReturnIndex(src[i]);
313 //srcmol->Center.Zero();
314 srcmol->Translate(&srcmol->Center);
315 }
316 // perform a simple multi merge
317 SimpleMultiMerge(mol, src, N);
318 return true;
319};
320
321/** Embedding merge of a given set of molecules into one.
322 * Embedding merge inserts one molecule into the other.
323 * \param *mol destination molecule (fixed one)
324 * \param *srcmol source molecule (variable one, where atoms are taken from)
325 * \return true - merge successful, false - merge failed (probably due to non-existant indices)
326 * \TODO linked cell dimensions for boundary points has to be as big as inner diameter!
327 */
328bool MoleculeListClass::EmbedMerge(molecule *mol, molecule *srcmol)
329{
330 LinkedCell *LCList = NULL;
331 Tesselation *TesselStruct = NULL;
332 if ((srcmol == NULL) || (mol == NULL)) {
333 DoeLog(1) && (eLog()<< Verbose(1) << "Either fixed or variable molecule is given as NULL." << endl);
334 return false;
335 }
336
337 // calculate envelope for *mol
338 LCList = new LinkedCell(mol, 8.);
339 FindNonConvexBorder(mol, TesselStruct, (const LinkedCell *&)LCList, 4., NULL);
340 if (TesselStruct == NULL) {
341 DoeLog(1) && (eLog()<< Verbose(1) << "Could not tesselate the fixed molecule." << endl);
342 return false;
343 }
344 delete(LCList);
345 LCList = new LinkedCell(TesselStruct, 8.); // re-create with boundary points only!
346
347 // prepare index list for bonds
348 atom ** CopyAtoms = new atom*[srcmol->getAtomCount()];
349 for(int i=0;i<srcmol->getAtomCount();i++)
350 CopyAtoms[i] = NULL;
351
352 // for each of the source atoms check whether we are in- or outside and add copy atom
353 int nr=0;
354 for (molecule::const_iterator iter = srcmol->begin(); iter != srcmol->end(); ++iter) {
355 DoLog(2) && (Log() << Verbose(2) << "INFO: Current Walker is " << **iter << "." << endl);
356 if (!TesselStruct->IsInnerPoint((*iter)->x, LCList)) {
357 CopyAtoms[(*iter)->nr] = (*iter)->clone();
358 mol->AddAtom(CopyAtoms[(*iter)->nr]);
359 nr++;
360 } else {
361 // do nothing
362 }
363 }
364 DoLog(1) && (Log() << Verbose(1) << nr << " of " << srcmol->getAtomCount() << " atoms have been merged.");
365
366 // go through all bonds and add as well
367 for(molecule::iterator AtomRunner = srcmol->begin(); AtomRunner != srcmol->end(); ++AtomRunner)
368 for(BondList::iterator BondRunner = (*AtomRunner)->ListOfBonds.begin(); BondRunner != (*AtomRunner)->ListOfBonds.end(); ++BondRunner)
369 if ((*BondRunner)->leftatom == *AtomRunner) {
370 DoLog(3) && (Log() << Verbose(3) << "Adding Bond between " << *CopyAtoms[(*BondRunner)->leftatom->nr] << " and " << *CopyAtoms[(*BondRunner)->rightatom->nr]<< "." << endl);
371 mol->AddBond(CopyAtoms[(*BondRunner)->leftatom->nr], CopyAtoms[(*BondRunner)->rightatom->nr], (*BondRunner)->BondDegree);
372 }
373 delete(LCList);
374 return true;
375};
376
377/** Simple output of the pointers in ListOfMolecules.
378 * \param *out output stream
379 */
380void MoleculeListClass::Output(ofstream *out)
381{
382 DoLog(1) && (Log() << Verbose(1) << "MoleculeList: ");
383 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
384 DoLog(0) && (Log() << Verbose(0) << *ListRunner << "\t");
385 DoLog(0) && (Log() << Verbose(0) << endl);
386};
387
388/** Calculates necessary hydrogen correction due to unwanted interaction between saturated ones.
389 * If for a pair of two hydrogen atoms a and b, at least is a saturated one, and a and b are not
390 * bonded to the same atom, then we add for this pair a correction term constructed from a Morse
391 * potential function fit to QM calculations with respecting to the interatomic hydrogen distance.
392 * \param &path path to file
393 */
394bool MoleculeListClass::AddHydrogenCorrection(std::string &path)
395{
396 bond *Binder = NULL;
397 double ***FitConstant = NULL, **correction = NULL;
398 int a, b;
399 ofstream output;
400 ifstream input;
401 string line;
402 stringstream zeile;
403 double distance;
404 char ParsedLine[1023];
405 double tmp;
406 char *FragmentNumber = NULL;
407
408 DoLog(1) && (Log() << Verbose(1) << "Saving hydrogen saturation correction ... ");
409 // 0. parse in fit constant files that should have the same dimension as the final energy files
410 // 0a. find dimension of matrices with constants
411 line = path;
412 line += "1";
413 line += FITCONSTANTSUFFIX;
414 input.open(line.c_str());
415 if (input.fail()) {
416 DoLog(1) && (Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
417 return false;
418 }
419 a = 0;
420 b = -1; // we overcount by one
421 while (!input.eof()) {
422 input.getline(ParsedLine, 1023);
423 zeile.str(ParsedLine);
424 int i = 0;
425 while (!zeile.eof()) {
426 zeile >> distance;
427 i++;
428 }
429 if (i > a)
430 a = i;
431 b++;
432 }
433 DoLog(0) && (Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ");
434 input.close();
435
436 // 0b. allocate memory for constants
437 FitConstant = new double**[3];
438 for (int k = 0; k < 3; k++) {
439 FitConstant[k] = new double*[a];
440 for (int i = a; i--;) {
441 FitConstant[k][i] = new double[b];
442 for (int j = b; j--;) {
443 FitConstant[k][i][j] = 0.;
444 }
445 }
446 }
447 // 0c. parse in constants
448 for (int i = 0; i < 3; i++) {
449 line = path;
450 line.append("/");
451 line += FRAGMENTPREFIX;
452 sprintf(ParsedLine, "%d", i + 1);
453 line += ParsedLine;
454 line += FITCONSTANTSUFFIX;
455 input.open(line.c_str());
456 if (input == NULL) {
457 DoeLog(0) && (eLog()<< Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
458 performCriticalExit();
459 return false;
460 }
461 int k = 0, l;
462 while ((!input.eof()) && (k < b)) {
463 input.getline(ParsedLine, 1023);
464 //Log() << Verbose(0) << "Current Line: " << ParsedLine << endl;
465 zeile.str(ParsedLine);
466 zeile.clear();
467 l = 0;
468 while ((!zeile.eof()) && (l < a)) {
469 zeile >> FitConstant[i][l][k];
470 //Log() << Verbose(0) << FitConstant[i][l][k] << "\t";
471 l++;
472 }
473 //Log() << Verbose(0) << endl;
474 k++;
475 }
476 input.close();
477 }
478 for (int k = 0; k < 3; k++) {
479 DoLog(0) && (Log() << Verbose(0) << "Constants " << k << ":" << endl);
480 for (int j = 0; j < b; j++) {
481 for (int i = 0; i < a; i++) {
482 DoLog(0) && (Log() << Verbose(0) << FitConstant[k][i][j] << "\t");
483 }
484 DoLog(0) && (Log() << Verbose(0) << endl);
485 }
486 DoLog(0) && (Log() << Verbose(0) << endl);
487 }
488
489 // 0d. allocate final correction matrix
490 correction = new double*[a];
491 for (int i = a; i--;)
492 correction[i] = new double[b];
493
494 // 1a. go through every molecule in the list
495 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
496 // 1b. zero final correction matrix
497 for (int k = a; k--;)
498 for (int j = b; j--;)
499 correction[k][j] = 0.;
500 // 2. take every hydrogen that is a saturated one
501 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
502 //Log() << Verbose(1) << "(*iter): " << *(*iter) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
503 if (((*iter)->type->Z == 1) && (((*iter)->father == NULL)
504 || ((*iter)->father->type->Z != 1))) { // if it's a hydrogen
505 for (molecule::const_iterator runner = (*ListRunner)->begin(); runner != (*ListRunner)->end(); ++runner) {
506 //Log() << Verbose(2) << "Runner: " << *(*runner) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
507 // 3. take every other hydrogen that is the not the first and not bound to same bonding partner
508 Binder = *((*runner)->ListOfBonds.begin());
509 if (((*runner)->type->Z == 1) && ((*runner)->nr > (*iter)->nr) && (Binder->GetOtherAtom((*runner)) != Binder->GetOtherAtom((*iter)))) { // (hydrogens have only one bonding partner!)
510 // 4. evaluate the morse potential for each matrix component and add up
511 distance = (*runner)->x.distance((*iter)->x);
512 //Log() << Verbose(0) << "Fragment " << (*ListRunner)->name << ": " << *(*runner) << "<= " << distance << "=>" << *(*iter) << ":" << endl;
513 for (int k = 0; k < a; k++) {
514 for (int j = 0; j < b; j++) {
515 switch (k) {
516 case 1:
517 case 7:
518 case 11:
519 tmp = pow(FitConstant[0][k][j] * (1. - exp(-FitConstant[1][k][j] * (distance - FitConstant[2][k][j]))), 2);
520 break;
521 default:
522 tmp = FitConstant[0][k][j] * pow(distance, FitConstant[1][k][j]) + FitConstant[2][k][j];
523 };
524 correction[k][j] -= tmp; // ground state is actually lower (disturbed by additional interaction)
525 //Log() << Verbose(0) << tmp << "\t";
526 }
527 //Log() << Verbose(0) << endl;
528 }
529 //Log() << Verbose(0) << endl;
530 }
531 }
532 }
533 }
534 // 5. write final matrix to file
535 line = path;
536 line.append("/");
537 line += FRAGMENTPREFIX;
538 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), (*ListRunner)->IndexNr);
539 line += FragmentNumber;
540 delete[] (FragmentNumber);
541 line += HCORRECTIONSUFFIX;
542 output.open(line.c_str());
543 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
544 for (int j = 0; j < b; j++) {
545 for (int i = 0; i < a; i++)
546 output << correction[i][j] << "\t";
547 output << endl;
548 }
549 output.close();
550 }
551 for (int i = a; i--;)
552 delete[](correction[i]);
553 delete[](correction);
554
555 line = path;
556 line.append("/");
557 line += HCORRECTIONSUFFIX;
558 output.open(line.c_str());
559 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
560 for (int j = 0; j < b; j++) {
561 for (int i = 0; i < a; i++)
562 output << 0 << "\t";
563 output << endl;
564 }
565 output.close();
566 // 6. free memory of parsed matrices
567 for (int k = 0; k < 3; k++) {
568 for (int i = a; i--;) {
569 delete[](FitConstant[k][i]);
570 }
571 delete[](FitConstant[k]);
572 }
573 delete[](FitConstant);
574 DoLog(0) && (Log() << Verbose(0) << "done." << endl);
575 return true;
576};
577
578/** Store force indices, i.e. the connection between the nuclear index in the total molecule config and the respective atom in fragment config.
579 * \param &path path to file
580 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
581 * \return true - file written successfully, false - writing failed
582 */
583bool MoleculeListClass::StoreForcesFile(std::string &path, int *SortIndex)
584{
585 bool status = true;
586 string filename(path);
587 filename += FORCESFILE;
588 ofstream ForcesFile(filename.c_str());
589 periodentafel *periode=World::getInstance().getPeriode();
590
591 // open file for the force factors
592 DoLog(1) && (Log() << Verbose(1) << "Saving force factors ... ");
593 if (!ForcesFile.fail()) {
594 //Log() << Verbose(1) << "Final AtomicForcesList: ";
595 //output << prefix << "Forces" << endl;
596 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
597 periodentafel::const_iterator elemIter;
598 for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
599 if ((*ListRunner)->ElementsInMolecule[(*elemIter).first]) { // if this element got atoms
600 for(molecule::iterator atomIter = (*ListRunner)->begin(); atomIter !=(*ListRunner)->end();++atomIter){
601 if ((*atomIter)->type->getNumber() == (*elemIter).first) {
602 if (((*atomIter)->GetTrueFather() != NULL) && ((*atomIter)->GetTrueFather() != (*atomIter))) {// if there is a rea
603 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
604 ForcesFile << SortIndex[(*atomIter)->GetTrueFather()->nr] << "\t";
605 } else
606 // otherwise a -1 to indicate an added saturation hydrogen
607 ForcesFile << "-1\t";
608 }
609 }
610 }
611 }
612 ForcesFile << endl;
613 }
614 ForcesFile.close();
615 DoLog(1) && (Log() << Verbose(1) << "done." << endl);
616 } else {
617 status = false;
618 DoLog(1) && (Log() << Verbose(1) << "failed to open file " << filename << "." << endl);
619 }
620 ForcesFile.close();
621
622 return status;
623};
624
625/** Writes a config file for each molecule in the given \a **FragmentList.
626 * \param *out output stream for debugging
627 * \param &prefix path and prefix to the fragment config files
628 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
629 * \return true - success (each file was written), false - something went wrong.
630 */
631bool MoleculeListClass::OutputConfigForListOfFragments(std::string &prefix, int *SortIndex)
632{
633 ofstream outputFragment;
634 std::string FragmentName;
635 char PathBackup[MAXSTRINGSIZE];
636 bool result = true;
637 bool intermediateResult = true;
638 Vector BoxDimension;
639 char *FragmentNumber = NULL;
640 char *path = NULL;
641 int FragmentCounter = 0;
642 ofstream output;
643 Matrix cell_size = World::getInstance().getDomain().getM();
644 Matrix cell_size_backup = cell_size;
645
646 // store the fragments as config and as xyz
647 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
648 // save default path as it is changed for each fragment
649 path = World::getInstance().getConfig()->GetDefaultPath();
650 if (path != NULL)
651 strcpy(PathBackup, path);
652 else {
653 DoeLog(0) && (eLog()<< Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl);
654 performCriticalExit();
655 }
656
657 // correct periodic
658 (*ListRunner)->ScanForPeriodicCorrection();
659
660 // output xyz file
661 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), FragmentCounter++);
662 FragmentName = prefix + FragmentNumber + ".conf.xyz";
663 outputFragment.open(FragmentName.c_str(), ios::out);
664 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...");
665 if ((intermediateResult = (*ListRunner)->OutputXYZ(&outputFragment)))
666 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
667 else
668 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
669 result = result && intermediateResult;
670 outputFragment.close();
671 outputFragment.clear();
672
673 // list atoms in fragment for debugging
674 DoLog(2) && (Log() << Verbose(2) << "Contained atoms: ");
675 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
676 DoLog(0) && (Log() << Verbose(0) << (*iter)->getName() << " ");
677 }
678 DoLog(0) && (Log() << Verbose(0) << endl);
679
680 // center on edge
681 (*ListRunner)->CenterEdge(&BoxDimension);
682 (*ListRunner)->SetBoxDimension(&BoxDimension); // update Box of atoms by boundary
683 for (int k = 0; k < NDIM; k++) {
684 BoxDimension[k] = 2.5 * (World::getInstance().getConfig()->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
685 cell_size.at(k,k) = BoxDimension[k] * 2.;
686 }
687 World::getInstance().setDomain(cell_size);
688 (*ListRunner)->Translate(&BoxDimension);
689
690 // also calculate necessary orbitals
691 (*ListRunner)->CountElements(); // this is a bugfix, atoms should shoulds actually be added correctly to this fragment
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)->type->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.