source: src/moleculelist.cpp@ 0d1ad0

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 0d1ad0 was 35b698, checked in by Frederik Heber <heber@…>, 15 years ago

BIG CHANGE: config::load and config::save in ParseCommandLineOptions() and main() replaced with FormatParser replacements.

Fragmentation:

  • FIX: MoleculeFillWithMoleculeAction: filler atoms have to be removed before the system can be stored to file.
  • FIX: PcpParser::load() - has to put the molecule also into World's MoleculeListClass (otherwise the name cannot be set right after loading)
  • new Libparser.a
  • all sources from PARSER subdir are compiled into libparser such that only ParserUnitTest is recompiled.

Testfixes:

  • testsuite-fragmentation - changes to due to different -f calling syntax.
  • most of the xyz files had to be replaced due to a single whitespace at the end of each entry: Domain/6, Simple_configuration/2, Simple_configuration/3, Simple_configuration/4, Simple_configuration/5, Simple_configuration/8
  • in many cases were the number orbitals (and thus MaxMinStopStep) wrong: Filling/1, Simple_configuration/4, Simple_configuration/5

Signed-off-by: Frederik Heber <heber@…>

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