source: src/moleculelist.cpp@ fc1b24

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 fc1b24 was 2ba827, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Changed all observed places to new observer structure

  • Property mode set to 100755
File size: 46.5 KB
Line 
1/** \file MoleculeListClass.cpp
2 *
3 * Function implementations for the class MoleculeListClass.
4 *
5 */
6
7#include <cstring>
8
9#include "atom.hpp"
10#include "bond.hpp"
11#include "boundary.hpp"
12#include "config.hpp"
13#include "element.hpp"
14#include "helpers.hpp"
15#include "linkedcell.hpp"
16#include "lists.hpp"
17#include "log.hpp"
18#include "molecule.hpp"
19#include "memoryallocator.hpp"
20#include "periodentafel.hpp"
21
22/*********************************** Functions for class MoleculeListClass *************************/
23
24/** Constructor for MoleculeListClass.
25 */
26MoleculeListClass::MoleculeListClass()
27{
28 // empty lists
29 ListOfMolecules.clear();
30 MaxIndex = 1;
31};
32
33/** Destructor for MoleculeListClass.
34 */
35MoleculeListClass::~MoleculeListClass()
36{
37 Log() << Verbose(3) << this << ": Freeing ListOfMolcules." << endl;
38 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
39 Log() << Verbose(4) << "ListOfMolecules: Freeing " << *ListRunner << "." << endl;
40 delete (*ListRunner);
41 }
42 Log() << Verbose(4) << "Freeing ListOfMolecules." << endl;
43 ListOfMolecules.clear(); // empty list
44};
45
46/** Insert a new molecule into the list and set its number.
47 * \param *mol molecule to add to list.
48 * \return true - add successful
49 */
50void MoleculeListClass::insert(molecule *mol)
51{
52 OBSERVE;
53 mol->IndexNr = MaxIndex++;
54 ListOfMolecules.push_back(mol);
55 mol->signOn(this);
56};
57
58/** Compare whether two molecules are equal.
59 * \param *a molecule one
60 * \param *n molecule two
61 * \return lexical value (-1, 0, +1)
62 */
63int MolCompare(const void *a, const void *b)
64{
65 int *aList = NULL, *bList = NULL;
66 int Count, Counter, aCounter, bCounter;
67 int flag;
68 atom *aWalker = NULL;
69 atom *bWalker = NULL;
70
71 // sort each atom list and put the numbers into a list, then go through
72 //Log() << Verbose(0) << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
73 if ((**(molecule **) a).AtomCount < (**(molecule **) b).AtomCount) {
74 return -1;
75 } else {
76 if ((**(molecule **) a).AtomCount > (**(molecule **) b).AtomCount)
77 return +1;
78 else {
79 Count = (**(molecule **) a).AtomCount;
80 aList = new int[Count];
81 bList = new int[Count];
82
83 // fill the lists
84 aWalker = (**(molecule **) a).start;
85 bWalker = (**(molecule **) b).start;
86 Counter = 0;
87 aCounter = 0;
88 bCounter = 0;
89 while ((aWalker->next != (**(molecule **) a).end) && (bWalker->next != (**(molecule **) b).end)) {
90 aWalker = aWalker->next;
91 bWalker = bWalker->next;
92 if (aWalker->GetTrueFather() == NULL)
93 aList[Counter] = Count + (aCounter++);
94 else
95 aList[Counter] = aWalker->GetTrueFather()->nr;
96 if (bWalker->GetTrueFather() == NULL)
97 bList[Counter] = Count + (bCounter++);
98 else
99 bList[Counter] = bWalker->GetTrueFather()->nr;
100 Counter++;
101 }
102 // check if AtomCount was for real
103 flag = 0;
104 if ((aWalker->next == (**(molecule **) a).end) && (bWalker->next != (**(molecule **) b).end)) {
105 flag = -1;
106 } else {
107 if ((aWalker->next != (**(molecule **) a).end) && (bWalker->next == (**(molecule **) b).end))
108 flag = 1;
109 }
110 if (flag == 0) {
111 // sort the lists
112 gsl_heapsort(aList, Count, sizeof(int), CompareDoubles);
113 gsl_heapsort(bList, Count, sizeof(int), CompareDoubles);
114 // compare the lists
115
116 flag = 0;
117 for (int i = 0; i < Count; i++) {
118 if (aList[i] < bList[i]) {
119 flag = -1;
120 } else {
121 if (aList[i] > bList[i])
122 flag = 1;
123 }
124 if (flag != 0)
125 break;
126 }
127 }
128 delete[] (aList);
129 delete[] (bList);
130 return flag;
131 }
132 }
133 return -1;
134};
135
136/** Output of a list of all molecules.
137 * \param *out output stream
138 */
139void MoleculeListClass::Enumerate(ofstream *out)
140{
141 element* Elemental = NULL;
142 atom *Walker = NULL;
143 int Counts[MAX_ELEMENTS];
144 double size=0;
145 Vector Origin;
146
147 // header
148 (*out) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
149 (*out) << "-----------------------------------------------" << endl;
150 if (ListOfMolecules.size() == 0)
151 (*out) << "\tNone" << endl;
152 else {
153 Origin.Zero();
154 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
155 // reset element counts
156 for (int j = 0; j<MAX_ELEMENTS;j++)
157 Counts[j] = 0;
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->Z]++;
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 Elemental = (*ListRunner)->elemente->end;
170 while(Elemental->previous != (*ListRunner)->elemente->start) {
171 Elemental = Elemental->previous;
172 if (Counts[Elemental->Z] != 0)
173 (*out) << Elemental->symbol << Counts[Elemental->Z];
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 delete(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 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 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 Log() << Verbose(2) << "INFO: Current Walker is " << *Walker << "." << endl;
343 if (!TesselStruct->IsInnerPoint(Walker->x, LCList)) {
344 CopyAtoms[Walker->nr] = new atom(Walker);
345 mol->AddAtom(CopyAtoms[Walker->nr]);
346 nr++;
347 } else {
348 // do nothing
349 }
350 }
351 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 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 Log() << Verbose(1) << "MoleculeList: ";
370 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
371 Log() << Verbose(0) << *ListRunner << "\t";
372 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 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 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 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 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 Log() << Verbose(0) << "Constants " << k << ":" << endl;
469 for (int j = 0; j < b; j++) {
470 for (int i = 0; i < a; i++) {
471 Log() << Verbose(0) << FitConstant[k][i][j] << "\t";
472 }
473 Log() << Verbose(0) << endl;
474 }
475 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 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 element *runner = NULL;
581
582 // open file for the force factors
583 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 runner = (*ListRunner)->elemente->start;
591 while (runner->next != (*ListRunner)->elemente->end) { // go through every element
592 runner = runner->next;
593 if ((*ListRunner)->ElementsInMolecule[runner->Z]) { // if this element got atoms
594 Walker = (*ListRunner)->start;
595 while (Walker->next != (*ListRunner)->end) { // go through every atom of this element
596 Walker = Walker->next;
597 if (Walker->type->Z == runner->Z) {
598 if ((Walker->GetTrueFather() != NULL) && (Walker->GetTrueFather() != Walker)) {// if there is a rea
599 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
600 ForcesFile << SortIndex[Walker->GetTrueFather()->nr] << "\t";
601 } else
602 // otherwise a -1 to indicate an added saturation hydrogen
603 ForcesFile << "-1\t";
604 }
605 }
606 }
607 }
608 ForcesFile << endl;
609 }
610 ForcesFile.close();
611 Log() << Verbose(1) << "done." << endl;
612 } else {
613 status = false;
614 Log() << Verbose(1) << "failed to open file " << line.str() << "." << endl;
615 }
616 ForcesFile.close();
617
618 return status;
619};
620
621/** Writes a config file for each molecule in the given \a **FragmentList.
622 * \param *out output stream for debugging
623 * \param *configuration standard configuration to attach atoms in fragment molecule to.
624 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
625 * \param DoPeriodic true - call ScanForPeriodicCorrection, false - don't
626 * \param DoCentering true - call molecule::CenterEdge(), false - don't
627 * \return true - success (each file was written), false - something went wrong.
628 */
629bool MoleculeListClass::OutputConfigForListOfFragments(config *configuration, int *SortIndex)
630{
631 ofstream outputFragment;
632 char FragmentName[MAXSTRINGSIZE];
633 char PathBackup[MAXSTRINGSIZE];
634 bool result = true;
635 bool intermediateResult = true;
636 atom *Walker = NULL;
637 Vector BoxDimension;
638 char *FragmentNumber = NULL;
639 char *path = NULL;
640 int FragmentCounter = 0;
641 ofstream output;
642
643 // store the fragments as config and as xyz
644 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
645 // save default path as it is changed for each fragment
646 path = configuration->GetDefaultPath();
647 if (path != NULL)
648 strcpy(PathBackup, path);
649 else {
650 eLog() << Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl;
651 performCriticalExit();
652 }
653
654 // correct periodic
655 (*ListRunner)->ScanForPeriodicCorrection();
656
657 // output xyz file
658 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), FragmentCounter++);
659 sprintf(FragmentName, "%s/%s%s.conf.xyz", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
660 outputFragment.open(FragmentName, ios::out);
661 Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...";
662 if ((intermediateResult = (*ListRunner)->OutputXYZ(&outputFragment)))
663 Log() << Verbose(0) << " done." << endl;
664 else
665 Log() << Verbose(0) << " failed." << endl;
666 result = result && intermediateResult;
667 outputFragment.close();
668 outputFragment.clear();
669
670 // list atoms in fragment for debugging
671 Log() << Verbose(2) << "Contained atoms: ";
672 Walker = (*ListRunner)->start;
673 while (Walker->next != (*ListRunner)->end) {
674 Walker = Walker->next;
675 Log() << Verbose(0) << Walker->Name << " ";
676 }
677 Log() << Verbose(0) << endl;
678
679 // center on edge
680 (*ListRunner)->CenterEdge(&BoxDimension);
681 (*ListRunner)->SetBoxDimension(&BoxDimension); // update Box of atoms by boundary
682 int j = -1;
683 for (int k = 0; k < NDIM; k++) {
684 j += k + 1;
685 BoxDimension.x[k] = 2.5 * (configuration->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
686 (*ListRunner)->cell_size[j] += BoxDimension.x[k] * 2.;
687 }
688 (*ListRunner)->Translate(&BoxDimension);
689
690 // also calculate necessary orbitals
691 (*ListRunner)->CountElements(); // this is a bugfix, atoms should shoulds actually be added correctly to this fragment
692 (*ListRunner)->CalculateOrbitals(*configuration);
693
694 // change path in config
695 //strcpy(PathBackup, configuration->configpath);
696 sprintf(FragmentName, "%s/%s%s/", PathBackup, FRAGMENTPREFIX, FragmentNumber);
697 configuration->SetDefaultPath(FragmentName);
698
699 // and save as config
700 sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
701 Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...";
702 if ((intermediateResult = configuration->Save(FragmentName, (*ListRunner)->elemente, (*ListRunner))))
703 Log() << Verbose(0) << " done." << endl;
704 else
705 Log() << Verbose(0) << " failed." << endl;
706 result = result && intermediateResult;
707
708 // restore old config
709 configuration->SetDefaultPath(PathBackup);
710
711 // and save as mpqc input file
712 sprintf(FragmentName, "%s/%s%s.conf", configuration->configpath, FRAGMENTPREFIX, FragmentNumber);
713 Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...";
714 if ((intermediateResult = configuration->SaveMPQC(FragmentName, (*ListRunner))))
715 Log() << Verbose(2) << " done." << endl;
716 else
717 Log() << Verbose(0) << " failed." << endl;
718
719 result = result && intermediateResult;
720 //outputFragment.close();
721 //outputFragment.clear();
722 Free(&FragmentNumber);
723 }
724 Log() << Verbose(0) << " done." << endl;
725
726 // printing final number
727 Log() << Verbose(2) << "Final number of fragments: " << FragmentCounter << "." << endl;
728
729 return result;
730};
731
732/** Counts the number of molecules with the molecule::ActiveFlag set.
733 * \return number of molecules with ActiveFlag set to true.
734 */
735int MoleculeListClass::NumberOfActiveMolecules()
736{
737 int count = 0;
738 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
739 count += ((*ListRunner)->ActiveFlag ? 1 : 0);
740 return count;
741};
742
743/** Dissects given \a *mol into connected subgraphs and inserts them as new molecules but with old atoms into \a this.
744 * \param *out output stream for debugging
745 * \param *periode periodentafel
746 * \param *configuration config with BondGraph
747 */
748void MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs(const periodentafel * const periode, config * const configuration)
749{
750 molecule *mol = new molecule(periode);
751 atom *Walker = NULL;
752 atom *Advancer = NULL;
753 bond *Binder = NULL;
754 bond *Stepper = NULL;
755 // 0. gather all atoms into single molecule
756 for (MoleculeList::iterator MolRunner = ListOfMolecules.begin(); !ListOfMolecules.empty(); MolRunner = ListOfMolecules.begin()) {
757 // shift all atoms to new molecule
758 Advancer = (*MolRunner)->start->next;
759 while (Advancer != (*MolRunner)->end) {
760 Walker = Advancer;
761 Advancer = Advancer->next;
762 Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl;
763 unlink(Walker);
764 Walker->father = Walker;
765 mol->AddAtom(Walker); // counting starts at 1
766 }
767 // remove all bonds
768 Stepper = (*MolRunner)->first->next;
769 while (Stepper != (*MolRunner)->last) {
770 Binder = Stepper;
771 Stepper = Stepper->next;
772 delete(Binder);
773 }
774 // remove the molecule
775 delete(*MolRunner);
776 ListOfMolecules.erase(MolRunner);
777 }
778
779 // 1. dissect the molecule into connected subgraphs
780 configuration->BG->ConstructBondGraph(mol);
781
782 // 2. scan for connected subgraphs
783 MoleculeLeafClass *Subgraphs = NULL; // list of subgraphs from DFS analysis
784 class StackClass<bond *> *BackEdgeStack = NULL;
785 Subgraphs = mol->DepthFirstSearchAnalysis(BackEdgeStack);
786 delete(BackEdgeStack);
787
788 // 3. dissect (the following construct is needed to have the atoms not in the order of the DFS, but in
789 // the original one as parsed in)
790 // TODO: Optimize this, when molecules just contain pointer list of global atoms!
791
792 // 4a. create array of molecules to fill
793 const int MolCount = Subgraphs->next->Count();
794 char number[MAXSTRINGSIZE];
795 molecule **molecules = Malloc<molecule *>(MolCount, "config::Load() - **molecules");
796 for (int i=0;i<MolCount;i++) {
797 molecules[i] = (molecule*) new molecule(mol->elemente);
798 molecules[i]->ActiveFlag = true;
799 strncpy(molecules[i]->name, mol->name, MAXSTRINGSIZE);
800 if (MolCount > 1) {
801 sprintf(number, "-%d", i+1);
802 strncat(molecules[i]->name, number, MAXSTRINGSIZE - strlen(mol->name) - 1);
803 }
804 cout << "MolName is " << molecules[i]->name << endl;
805 insert(molecules[i]);
806 }
807
808 // 4b. create and fill map of which atom is associated to which connected molecule (note, counting starts at 1)
809 int FragmentCounter = 0;
810 int *MolMap = Calloc<int>(mol->AtomCount, "config::Load() - *MolMap");
811 MoleculeLeafClass *MolecularWalker = Subgraphs;
812 Walker = NULL;
813 while (MolecularWalker->next != NULL) {
814 MolecularWalker = MolecularWalker->next;
815 Walker = MolecularWalker->Leaf->start;
816 while (Walker->next != MolecularWalker->Leaf->end) {
817 Walker = Walker->next;
818 MolMap[Walker->GetTrueFather()->nr] = FragmentCounter+1;
819 }
820 FragmentCounter++;
821 }
822
823 // 4c. relocate atoms to new molecules and remove from Leafs
824 Walker = NULL;
825 while (mol->start->next != mol->end) {
826 Walker = mol->start->next;
827 if ((Walker->nr <0) || (Walker->nr >= mol->AtomCount)) {
828 eLog() << Verbose(0) << "Index of atom " << *Walker << " is invalid!" << endl;
829 performCriticalExit();
830 }
831 FragmentCounter = MolMap[Walker->nr];
832 if (FragmentCounter != 0) {
833 Log() << Verbose(3) << "Re-linking " << *Walker << "..." << endl;
834 unlink(Walker);
835 molecules[FragmentCounter-1]->AddAtom(Walker); // counting starts at 1
836 } else {
837 eLog() << Verbose(0) << "Atom " << *Walker << " not associated to molecule!" << endl;
838 performCriticalExit();
839 }
840 }
841 // 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
842 Binder = mol->first;
843 while (mol->first->next != mol->last) {
844 Binder = mol->first->next;
845 Walker = Binder->leftatom;
846 unlink(Binder);
847 link(Binder,molecules[MolMap[Walker->nr]-1]->last); // counting starts at 1
848 }
849 // 4e. free Leafs
850 MolecularWalker = Subgraphs;
851 while (MolecularWalker->next != NULL) {
852 MolecularWalker = MolecularWalker->next;
853 delete(MolecularWalker->previous);
854 }
855 delete(MolecularWalker);
856 Free(&MolMap);
857 Free(&molecules);
858 Log() << Verbose(1) << "I scanned " << FragmentCounter << " molecules." << endl;
859};
860
861/** Count all atoms in each molecule.
862 * \return number of atoms in the MoleculeListClass.
863 * TODO: the inner loop should be done by some (double molecule::CountAtom()) function
864 */
865int MoleculeListClass::CountAllAtoms() const
866{
867 atom *Walker = NULL;
868 int AtomNo = 0;
869 for (MoleculeList::const_iterator MolWalker = ListOfMolecules.begin(); MolWalker != ListOfMolecules.end(); MolWalker++) {
870 Walker = (*MolWalker)->start;
871 while (Walker->next != (*MolWalker)->end) {
872 Walker = Walker->next;
873 AtomNo++;
874 }
875 }
876 return AtomNo;
877}
878
879/***********
880 * Methods Moved here from the menus
881 */
882
883void MoleculeListClass::flipChosen() {
884 int j;
885 Log() << Verbose(0) << "Enter index of molecule: ";
886 cin >> j;
887 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
888 if ((*ListRunner)->IndexNr == j)
889 (*ListRunner)->ActiveFlag = !(*ListRunner)->ActiveFlag;
890}
891
892void MoleculeListClass::createNewMolecule(periodentafel *periode) {
893 OBSERVE;
894 molecule *mol = NULL;
895 mol = new molecule(periode);
896 insert(mol);
897};
898
899void MoleculeListClass::loadFromXYZ(periodentafel *periode){
900 molecule *mol = NULL;
901 Vector center;
902 char filename[MAXSTRINGSIZE];
903 Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
904 mol = new molecule(periode);
905 do {
906 Log() << Verbose(0) << "Enter file name: ";
907 cin >> filename;
908 } while (!mol->AddXYZFile(filename));
909 mol->SetNameFromFilename(filename);
910 // center at set box dimensions
911 mol->CenterEdge(&center);
912 mol->cell_size[0] = center.x[0];
913 mol->cell_size[1] = 0;
914 mol->cell_size[2] = center.x[1];
915 mol->cell_size[3] = 0;
916 mol->cell_size[4] = 0;
917 mol->cell_size[5] = center.x[2];
918 insert(mol);
919}
920
921void MoleculeListClass::setMoleculeFilename() {
922 char filename[MAXSTRINGSIZE];
923 int nr;
924 molecule *mol = NULL;
925 do {
926 Log() << Verbose(0) << "Enter index of molecule: ";
927 cin >> nr;
928 mol = ReturnIndex(nr);
929 } while (mol == NULL);
930 Log() << Verbose(0) << "Enter name: ";
931 cin >> filename;
932 mol->SetNameFromFilename(filename);
933}
934
935void MoleculeListClass::parseXYZIntoMolecule(){
936 char filename[MAXSTRINGSIZE];
937 int nr;
938 molecule *mol = NULL;
939 mol = NULL;
940 do {
941 Log() << Verbose(0) << "Enter index of molecule: ";
942 cin >> nr;
943 mol = ReturnIndex(nr);
944 } while (mol == NULL);
945 Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
946 do {
947 Log() << Verbose(0) << "Enter file name: ";
948 cin >> filename;
949 } while (!mol->AddXYZFile(filename));
950 mol->SetNameFromFilename(filename);
951};
952
953void MoleculeListClass::eraseMolecule(){
954 int nr;
955 molecule *mol = NULL;
956 Log() << Verbose(0) << "Enter index of molecule: ";
957 cin >> nr;
958 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
959 if (nr == (*ListRunner)->IndexNr) {
960 mol = *ListRunner;
961 ListOfMolecules.erase(ListRunner);
962 delete(mol);
963 break;
964 }
965};
966
967
968/******************************************* Class MoleculeLeafClass ************************************************/
969
970/** Constructor for MoleculeLeafClass root leaf.
971 * \param *Up Leaf on upper level
972 * \param *PreviousLeaf NULL - We are the first leaf on this level, otherwise points to previous in list
973 */
974//MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *Up = NULL, MoleculeLeafClass *Previous = NULL)
975MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf = NULL)
976{
977 // if (Up != NULL)
978 // if (Up->DownLeaf == NULL) // are we the first down leaf for the upper leaf?
979 // Up->DownLeaf = this;
980 // UpLeaf = Up;
981 // DownLeaf = NULL;
982 Leaf = NULL;
983 previous = PreviousLeaf;
984 if (previous != NULL) {
985 MoleculeLeafClass *Walker = previous->next;
986 previous->next = this;
987 next = Walker;
988 } else {
989 next = NULL;
990 }
991};
992
993/** Destructor for MoleculeLeafClass.
994 */
995MoleculeLeafClass::~MoleculeLeafClass()
996{
997 // if (DownLeaf != NULL) {// drop leaves further down
998 // MoleculeLeafClass *Walker = DownLeaf;
999 // MoleculeLeafClass *Next;
1000 // do {
1001 // Next = Walker->NextLeaf;
1002 // delete(Walker);
1003 // Walker = Next;
1004 // } while (Walker != NULL);
1005 // // Last Walker sets DownLeaf automatically to NULL
1006 // }
1007 // remove the leaf itself
1008 if (Leaf != NULL) {
1009 delete (Leaf);
1010 Leaf = NULL;
1011 }
1012 // remove this Leaf from level list
1013 if (previous != NULL)
1014 previous->next = next;
1015 // } else { // we are first in list (connects to UpLeaf->DownLeaf)
1016 // if ((NextLeaf != NULL) && (NextLeaf->UpLeaf == NULL))
1017 // NextLeaf->UpLeaf = UpLeaf; // either null as we are top level or the upleaf of the first node
1018 // if (UpLeaf != NULL)
1019 // UpLeaf->DownLeaf = NextLeaf; // either null as we are only leaf or NextLeaf if we are just the first
1020 // }
1021 // UpLeaf = NULL;
1022 if (next != NULL) // are we last in list
1023 next->previous = previous;
1024 next = NULL;
1025 previous = NULL;
1026};
1027
1028/** Adds \a molecule leaf to the tree.
1029 * \param *ptr ptr to molecule to be added
1030 * \param *Previous previous MoleculeLeafClass referencing level and which on the level
1031 * \return true - success, false - something went wrong
1032 */
1033bool MoleculeLeafClass::AddLeaf(molecule *ptr, MoleculeLeafClass *Previous)
1034{
1035 return false;
1036};
1037
1038/** Fills the bond structure of this chain list subgraphs that are derived from a complete \a *reference molecule.
1039 * Calls this routine in each MoleculeLeafClass::next subgraph if it's not NULL.
1040 * \param *out output stream for debugging
1041 * \param *reference reference molecule with the bond structure to be copied
1042 * \param &FragmentCounter Counter needed to address \a **ListOfLocalAtoms
1043 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in \a *reference, may be NULL on start, then it is filled
1044 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
1045 * \return true - success, false - faoilure
1046 */
1047bool MoleculeLeafClass::FillBondStructureFromReference(const molecule * const reference, int &FragmentCounter, atom ***&ListOfLocalAtoms, bool FreeList)
1048{
1049 atom *Walker = NULL;
1050 atom *OtherWalker = NULL;
1051 atom *Father = NULL;
1052 bool status = true;
1053 int AtomNo;
1054
1055 Log() << Verbose(1) << "Begin of FillBondStructureFromReference." << endl;
1056 // fill ListOfLocalAtoms if NULL was given
1057 if (!FillListOfLocalAtoms(ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
1058 Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
1059 return false;
1060 }
1061
1062 if (status) {
1063 Log() << Verbose(1) << "Creating adjacency list for subgraph " << Leaf << "." << endl;
1064 // remove every bond from the list
1065 bond *Binder = NULL;
1066 while (Leaf->last->previous != Leaf->first) {
1067 Binder = Leaf->last->previous;
1068 Binder->leftatom->UnregisterBond(Binder);
1069 Binder->rightatom->UnregisterBond(Binder);
1070 removewithoutcheck(Binder);
1071 }
1072
1073 Walker = Leaf->start;
1074 while (Walker->next != Leaf->end) {
1075 Walker = Walker->next;
1076 Father = Walker->GetTrueFather();
1077 AtomNo = Father->nr; // global id of the current walker
1078 for (BondList::const_iterator Runner = Father->ListOfBonds.begin(); Runner != Father->ListOfBonds.end(); (++Runner)) {
1079 OtherWalker = ListOfLocalAtoms[FragmentCounter][(*Runner)->GetOtherAtom(Walker->GetTrueFather())->nr]; // local copy of current bond partner of walker
1080 if (OtherWalker != NULL) {
1081 if (OtherWalker->nr > Walker->nr)
1082 Leaf->AddBond(Walker, OtherWalker, (*Runner)->BondDegree);
1083 } else {
1084 Log() << Verbose(1) << "OtherWalker = ListOfLocalAtoms[" << FragmentCounter << "][" << (*Runner)->GetOtherAtom(Walker->GetTrueFather())->nr << "] is NULL!" << endl;
1085 status = false;
1086 }
1087 }
1088 }
1089 }
1090
1091 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
1092 // free the index lookup list
1093 Free(&ListOfLocalAtoms[FragmentCounter]);
1094 if (FragmentCounter == 0) // first fragments frees the initial pointer to list
1095 Free(&ListOfLocalAtoms);
1096 }
1097 Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl;
1098 return status;
1099};
1100
1101/** Fills the root stack for sites to be used as root in fragmentation depending on order or adaptivity criteria
1102 * Again, as in \sa FillBondStructureFromReference steps recursively through each Leaf in this chain list of molecule's.
1103 * \param *out output stream for debugging
1104 * \param *&RootStack stack to be filled
1105 * \param *AtomMask defines true/false per global Atom::nr to mask in/out each nuclear site
1106 * \param &FragmentCounter counts through the fragments in this MoleculeLeafClass
1107 * \return true - stack is non-empty, fragmentation necessary, false - stack is empty, no more sites to update
1108 */
1109bool MoleculeLeafClass::FillRootStackForSubgraphs(KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter)
1110{
1111 atom *Walker = NULL, *Father = NULL;
1112
1113 if (RootStack != NULL) {
1114 // find first root candidates
1115 if (&(RootStack[FragmentCounter]) != NULL) {
1116 RootStack[FragmentCounter].clear();
1117 Walker = Leaf->start;
1118 while (Walker->next != Leaf->end) { // go through all (non-hydrogen) atoms
1119 Walker = Walker->next;
1120 Father = Walker->GetTrueFather();
1121 if (AtomMask[Father->nr]) // apply mask
1122#ifdef ADDHYDROGEN
1123 if (Walker->type->Z != 1) // skip hydrogen
1124#endif
1125 RootStack[FragmentCounter].push_front(Walker->nr);
1126 }
1127 if (next != NULL)
1128 next->FillRootStackForSubgraphs(RootStack, AtomMask, ++FragmentCounter);
1129 } else {
1130 Log() << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl;
1131 return false;
1132 }
1133 FragmentCounter--;
1134 return true;
1135 } else {
1136 Log() << Verbose(1) << "Rootstack is NULL." << endl;
1137 return false;
1138 }
1139};
1140
1141/** Fills a lookup list of father's Atom::nr -> atom for each subgraph.
1142 * \param *out output stream from debugging
1143 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
1144 * \param FragmentCounter counts the fragments as we move along the list
1145 * \param GlobalAtomCount number of atoms in the complete molecule
1146 * \param &FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
1147 * \return true - success, false - failure
1148 */
1149bool MoleculeLeafClass::FillListOfLocalAtoms(atom ***&ListOfLocalAtoms, const int FragmentCounter, const int GlobalAtomCount, bool &FreeList)
1150{
1151 bool status = true;
1152
1153 if (ListOfLocalAtoms == NULL) { // allocated initial pointer
1154 // allocate and set each field to NULL
1155 const int Counter = Count();
1156 ListOfLocalAtoms = Calloc<atom**>(Counter, "MoleculeLeafClass::FillListOfLocalAtoms - ***ListOfLocalAtoms");
1157 if (ListOfLocalAtoms == NULL) {
1158 FreeList = FreeList && false;
1159 status = false;
1160 }
1161 }
1162
1163 if ((ListOfLocalAtoms != NULL) && (ListOfLocalAtoms[FragmentCounter] == NULL)) { // allocate and fill list of this fragment/subgraph
1164 status = status && CreateFatherLookupTable(Leaf->start, Leaf->end, ListOfLocalAtoms[FragmentCounter], GlobalAtomCount);
1165 FreeList = FreeList && true;
1166 }
1167
1168 return status;
1169};
1170
1171/** The indices per keyset are compared to the respective father's Atom::nr in each subgraph and thus put into \a **&FragmentList.
1172 * \param *out output stream fro debugging
1173 * \param *reference reference molecule with the bond structure to be copied
1174 * \param *KeySetList list with all keysets
1175 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
1176 * \param **&FragmentList list to be allocated and returned
1177 * \param &FragmentCounter counts the fragments as we move along the list
1178 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
1179 * \retuen true - success, false - failure
1180 */
1181bool MoleculeLeafClass::AssignKeySetsToFragment(molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms, Graph **&FragmentList, int &FragmentCounter, bool FreeList)
1182{
1183 bool status = true;
1184 int KeySetCounter = 0;
1185
1186 Log() << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl;
1187 // fill ListOfLocalAtoms if NULL was given
1188 if (!FillListOfLocalAtoms(ListOfLocalAtoms, FragmentCounter, reference->AtomCount, FreeList)) {
1189 Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl;
1190 return false;
1191 }
1192
1193 // allocate fragment list
1194 if (FragmentList == NULL) {
1195 KeySetCounter = Count();
1196 FragmentList = Calloc<Graph*>(KeySetCounter, "MoleculeLeafClass::AssignKeySetsToFragment - **FragmentList");
1197 KeySetCounter = 0;
1198 }
1199
1200 if ((KeySetList != NULL) && (KeySetList->size() != 0)) { // if there are some scanned keysets at all
1201 // assign scanned keysets
1202 if (FragmentList[FragmentCounter] == NULL)
1203 FragmentList[FragmentCounter] = new Graph;
1204 KeySet *TempSet = new KeySet;
1205 for (Graph::iterator runner = KeySetList->begin(); runner != KeySetList->end(); runner++) { // key sets contain global numbers!
1206 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
1207 // translate keyset to local numbers
1208 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
1209 TempSet->insert(ListOfLocalAtoms[FragmentCounter][reference->FindAtom(*sprinter)->nr]->nr);
1210 // insert into FragmentList
1211 FragmentList[FragmentCounter]->insert(GraphPair(*TempSet, pair<int, double> (KeySetCounter++, (*runner).second.second)));
1212 }
1213 TempSet->clear();
1214 }
1215 delete (TempSet);
1216 if (KeySetCounter == 0) {// if there are no keysets, delete the list
1217 Log() << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl;
1218 delete (FragmentList[FragmentCounter]);
1219 } else
1220 Log() << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl;
1221 FragmentCounter++;
1222 if (next != NULL)
1223 next->AssignKeySetsToFragment(reference, KeySetList, ListOfLocalAtoms, FragmentList, FragmentCounter, FreeList);
1224 FragmentCounter--;
1225 } else
1226 Log() << Verbose(1) << "KeySetList is NULL or empty." << endl;
1227
1228 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
1229 // free the index lookup list
1230 Free(&ListOfLocalAtoms[FragmentCounter]);
1231 if (FragmentCounter == 0) // first fragments frees the initial pointer to list
1232 Free(&ListOfLocalAtoms);
1233 }
1234 Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl;
1235 return status;
1236};
1237
1238/** Translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
1239 * \param *out output stream for debugging
1240 * \param **FragmentList Graph with local numbers per fragment
1241 * \param &FragmentCounter counts the fragments as we move along the list
1242 * \param &TotalNumberOfKeySets global key set counter
1243 * \param &TotalGraph Graph to be filled with global numbers
1244 */
1245void MoleculeLeafClass::TranslateIndicesToGlobalIDs(Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph)
1246{
1247 Log() << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl;
1248 KeySet *TempSet = new KeySet;
1249 if (FragmentList[FragmentCounter] != NULL) {
1250 for (Graph::iterator runner = FragmentList[FragmentCounter]->begin(); runner != FragmentList[FragmentCounter]->end(); runner++) {
1251 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
1252 TempSet->insert((Leaf->FindAtom(*sprinter))->GetTrueFather()->nr);
1253 TotalGraph.insert(GraphPair(*TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
1254 TempSet->clear();
1255 }
1256 delete (TempSet);
1257 } else {
1258 Log() << Verbose(1) << "FragmentList is NULL." << endl;
1259 }
1260 if (next != NULL)
1261 next->TranslateIndicesToGlobalIDs(FragmentList, ++FragmentCounter, TotalNumberOfKeySets, TotalGraph);
1262 FragmentCounter--;
1263 Log() << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl;
1264};
1265
1266/** Simply counts the number of items in the list, from given MoleculeLeafClass.
1267 * \return number of items
1268 */
1269int MoleculeLeafClass::Count() const
1270{
1271 if (next != NULL)
1272 return next->Count() + 1;
1273 else
1274 return 1;
1275};
1276
Note: See TracBrowser for help on using the repository browser.