source: src/moleculelist.cpp@ fa5a6a

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

Declared the Vector class as single point spaces

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