source: src/moleculelist.cpp@ 1b2d30

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 1b2d30 was a3fded, checked in by Frederik Heber <heber@…>, 15 years ago

New class ThermoStatContainer containing all parameters and changes to ConfigFileBuffer.

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