source: src/moleculelist.cpp@ a7b761b

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

Merge branch 'MoleculeStartEndSwitch' into StructureRefactoring

Conflicts:

molecuilder/src/Helpers/Assert.cpp
molecuilder/src/Helpers/Assert.hpp
molecuilder/src/Legacy/oldmenu.cpp
molecuilder/src/Makefile.am
molecuilder/src/Patterns/Cacheable.hpp
molecuilder/src/Patterns/Observer.cpp
molecuilder/src/Patterns/Observer.hpp
molecuilder/src/analysis_correlation.cpp
molecuilder/src/boundary.cpp
molecuilder/src/builder.cpp
molecuilder/src/config.cpp
molecuilder/src/helpers.hpp
molecuilder/src/molecule.cpp
molecuilder/src/molecule.hpp
molecuilder/src/molecule_dynamics.cpp
molecuilder/src/molecule_fragmentation.cpp
molecuilder/src/molecule_geometry.cpp
molecuilder/src/molecule_graph.cpp
molecuilder/src/moleculelist.cpp
molecuilder/src/tesselation.cpp
molecuilder/src/unittests/AnalysisCorrelationToSurfaceUnitTest.cpp
molecuilder/src/unittests/ObserverTest.cpp
molecuilder/src/unittests/ObserverTest.hpp

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