source: src/moleculelist.cpp@ 5b4605

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 5b4605 was 88b400, checked in by Frederik Heber <heber@…>, 15 years ago

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

basic changes:

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

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

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

details:

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