source: src/moleculelist.cpp@ 1434c9

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 1434c9 was 55240c4, checked in by Frederik Heber <heber@…>, 15 years ago

Merge branch 'stable' into PcpAndMpqcParser

Conflicts:

molecuilder/src/Makefile.am

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