source: src/moleculelist.cpp@ 73916f

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 73916f was a564be, checked in by Frederik Heber <heber@…>, 14 years ago

Removed ancient StackClass, replaced by std::deque.

  • all PopLast replaced by pop_front.
  • all PopFirst replaced by pop_front.
  • and we have two remove items in two steps, first get item, then pop.
  • Property mode set to 100755
File size: 36.1 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/** \file MoleculeListClass.cpp
9 *
10 * Function implementations for the class MoleculeListClass.
11 *
12 */
13
14// include config.h
15#ifdef HAVE_CONFIG_H
16#include <config.h>
17#endif
18
19#include "Helpers/MemDebug.hpp"
20
21#include <cstring>
22
23#include <gsl/gsl_inline.h>
24#include <gsl/gsl_heapsort.h>
25
26#include "World.hpp"
27#include "atom.hpp"
28#include "bond.hpp"
29#include "bondgraph.hpp"
30#include "boundary.hpp"
31#include "config.hpp"
32#include "element.hpp"
33#include "Helpers/helpers.hpp"
34#include "linkedcell.hpp"
35#include "lists.hpp"
36#include "Helpers/Verbose.hpp"
37#include "Helpers/Log.hpp"
38#include "molecule.hpp"
39#include "periodentafel.hpp"
40#include "tesselation.hpp"
41#include "Helpers/Assert.hpp"
42#include "LinearAlgebra/RealSpaceMatrix.hpp"
43#include "Box.hpp"
44
45#include "Helpers/Assert.hpp"
46
47/*********************************** Functions for class MoleculeListClass *************************/
48
49/** Constructor for MoleculeListClass.
50 */
51MoleculeListClass::MoleculeListClass(World *_world) :
52 Observable("MoleculeListClass"),
53 MaxIndex(1),
54 world(_world)
55{};
56
57/** Destructor for MoleculeListClass.
58 */
59MoleculeListClass::~MoleculeListClass()
60{
61 DoLog(4) && (Log() << Verbose(4) << "Clearing ListOfMolecules." << endl);
62 for(MoleculeList::iterator MolRunner = ListOfMolecules.begin(); MolRunner != ListOfMolecules.end(); ++MolRunner)
63 (*MolRunner)->signOff(this);
64 ListOfMolecules.clear(); // empty list
65};
66
67/** Insert a new molecule into the list and set its number.
68 * \param *mol molecule to add to list.
69 */
70void MoleculeListClass::insert(molecule *mol)
71{
72 OBSERVE;
73 mol->IndexNr = MaxIndex++;
74 ListOfMolecules.push_back(mol);
75 mol->signOn(this);
76};
77
78/** Erases a molecule from the list.
79 * \param *mol molecule to add to list.
80 */
81void MoleculeListClass::erase(molecule *mol)
82{
83 OBSERVE;
84 mol->signOff(this);
85 ListOfMolecules.remove(mol);
86};
87
88/** Compare whether two molecules are equal.
89 * \param *a molecule one
90 * \param *n molecule two
91 * \return lexical value (-1, 0, +1)
92 */
93int MolCompare(const void *a, const void *b)
94{
95 int *aList = NULL, *bList = NULL;
96 int Count, Counter, aCounter, bCounter;
97 int flag;
98
99 // sort each atom list and put the numbers into a list, then go through
100 //Log() << Verbose(0) << "Comparing fragment no. " << *(molecule **)a << " to " << *(molecule **)b << "." << endl;
101 // Yes those types are awkward... but check it for yourself it checks out this way
102 molecule *const *mol1_ptr= static_cast<molecule *const *>(a);
103 molecule *mol1 = *mol1_ptr;
104 molecule *const *mol2_ptr= static_cast<molecule *const *>(b);
105 molecule *mol2 = *mol2_ptr;
106 if (mol1->getAtomCount() < mol2->getAtomCount()) {
107 return -1;
108 } else {
109 if (mol1->getAtomCount() > mol2->getAtomCount())
110 return +1;
111 else {
112 Count = mol1->getAtomCount();
113 aList = new int[Count];
114 bList = new int[Count];
115
116 // fill the lists
117 Counter = 0;
118 aCounter = 0;
119 bCounter = 0;
120 molecule::const_iterator aiter = mol1->begin();
121 molecule::const_iterator biter = mol2->begin();
122 for (;(aiter != mol1->end()) && (biter != mol2->end());
123 ++aiter, ++biter) {
124 if ((*aiter)->GetTrueFather() == NULL)
125 aList[Counter] = Count + (aCounter++);
126 else
127 aList[Counter] = (*aiter)->GetTrueFather()->nr;
128 if ((*biter)->GetTrueFather() == NULL)
129 bList[Counter] = Count + (bCounter++);
130 else
131 bList[Counter] = (*biter)->GetTrueFather()->nr;
132 Counter++;
133 }
134 // check if AtomCount was for real
135 flag = 0;
136 if ((aiter == mol1->end()) && (biter != mol2->end())) {
137 flag = -1;
138 } else {
139 if ((aiter != mol1->end()) && (biter == mol2->end()))
140 flag = 1;
141 }
142 if (flag == 0) {
143 // sort the lists
144 gsl_heapsort(aList, Count, sizeof(int), CompareDoubles);
145 gsl_heapsort(bList, Count, sizeof(int), CompareDoubles);
146 // compare the lists
147
148 flag = 0;
149 for (int i = 0; i < Count; i++) {
150 if (aList[i] < bList[i]) {
151 flag = -1;
152 } else {
153 if (aList[i] > bList[i])
154 flag = 1;
155 }
156 if (flag != 0)
157 break;
158 }
159 }
160 delete[] (aList);
161 delete[] (bList);
162 return flag;
163 }
164 }
165 return -1;
166};
167
168/** Output of a list of all molecules.
169 * \param *out output stream
170 */
171void MoleculeListClass::Enumerate(ostream *out)
172{
173 periodentafel *periode = World::getInstance().getPeriode();
174 std::map<atomicNumber_t,unsigned int> counts;
175 double size=0;
176 Vector Origin;
177
178 // header
179 (*out) << "Index\tName\t\tAtoms\tFormula\tCenter\tSize" << endl;
180 (*out) << "-----------------------------------------------" << endl;
181 if (ListOfMolecules.size() == 0)
182 (*out) << "\tNone" << endl;
183 else {
184 Origin.Zero();
185 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
186 // count atoms per element and determine size of bounding sphere
187 size=0.;
188 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
189 counts[(*iter)->getType()->getNumber()]++;
190 if ((*iter)->DistanceSquared(Origin) > size)
191 size = (*iter)->DistanceSquared(Origin);
192 }
193 // output Index, Name, number of atoms, chemical formula
194 (*out) << ((*ListRunner)->ActiveFlag ? "*" : " ") << (*ListRunner)->IndexNr << "\t" << (*ListRunner)->name << "\t\t" << (*ListRunner)->getAtomCount() << "\t";
195
196 std::map<atomicNumber_t,unsigned int>::reverse_iterator iter;
197 for(iter=counts.rbegin(); iter!=counts.rend();++iter){
198 atomicNumber_t Z =(*iter).first;
199 (*out) << periode->FindElement(Z)->getSymbol() << (*iter).second;
200 }
201 // Center and size
202 Vector *Center = (*ListRunner)->DetermineCenterOfAll();
203 (*out) << "\t" << *Center << "\t" << sqrt(size) << endl;
204 delete(Center);
205 }
206 }
207};
208
209/** Returns the molecule with the given index \a index.
210 * \param index index of the desired molecule
211 * \return pointer to molecule structure, NULL if not found
212 */
213molecule * MoleculeListClass::ReturnIndex(int index)
214{
215 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
216 if ((*ListRunner)->IndexNr == index)
217 return (*ListRunner);
218 return NULL;
219};
220
221
222/** Simple output of the pointers in ListOfMolecules.
223 * \param *out output stream
224 */
225void MoleculeListClass::Output(ofstream *out)
226{
227 DoLog(1) && (Log() << Verbose(1) << "MoleculeList: ");
228 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
229 DoLog(0) && (Log() << Verbose(0) << *ListRunner << "\t");
230 DoLog(0) && (Log() << Verbose(0) << endl);
231};
232
233/** Calculates necessary hydrogen correction due to unwanted interaction between saturated ones.
234 * If for a pair of two hydrogen atoms a and b, at least is a saturated one, and a and b are not
235 * bonded to the same atom, then we add for this pair a correction term constructed from a Morse
236 * potential function fit to QM calculations with respecting to the interatomic hydrogen distance.
237 * \param &path path to file
238 */
239bool MoleculeListClass::AddHydrogenCorrection(std::string &path)
240{
241 bond *Binder = NULL;
242 double ***FitConstant = NULL, **correction = NULL;
243 int a, b;
244 ofstream output;
245 ifstream input;
246 string line;
247 stringstream zeile;
248 double distance;
249 char ParsedLine[1023];
250 double tmp;
251 char *FragmentNumber = NULL;
252
253 DoLog(1) && (Log() << Verbose(1) << "Saving hydrogen saturation correction ... ");
254 // 0. parse in fit constant files that should have the same dimension as the final energy files
255 // 0a. find dimension of matrices with constants
256 line = path;
257 line += "1";
258 line += FITCONSTANTSUFFIX;
259 input.open(line.c_str());
260 if (input.fail()) {
261 DoLog(1) && (Log() << Verbose(1) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
262 return false;
263 }
264 a = 0;
265 b = -1; // we overcount by one
266 while (!input.eof()) {
267 input.getline(ParsedLine, 1023);
268 zeile.str(ParsedLine);
269 int i = 0;
270 while (!zeile.eof()) {
271 zeile >> distance;
272 i++;
273 }
274 if (i > a)
275 a = i;
276 b++;
277 }
278 DoLog(0) && (Log() << Verbose(0) << "I recognized " << a << " columns and " << b << " rows, ");
279 input.close();
280
281 // 0b. allocate memory for constants
282 FitConstant = new double**[3];
283 for (int k = 0; k < 3; k++) {
284 FitConstant[k] = new double*[a];
285 for (int i = a; i--;) {
286 FitConstant[k][i] = new double[b];
287 for (int j = b; j--;) {
288 FitConstant[k][i][j] = 0.;
289 }
290 }
291 }
292 // 0c. parse in constants
293 for (int i = 0; i < 3; i++) {
294 line = path;
295 line.append("/");
296 line += FRAGMENTPREFIX;
297 sprintf(ParsedLine, "%d", i + 1);
298 line += ParsedLine;
299 line += FITCONSTANTSUFFIX;
300 input.open(line.c_str());
301 if (input == NULL) {
302 DoeLog(0) && (eLog()<< Verbose(0) << endl << "Unable to open " << line << ", is the directory correct?" << endl);
303 performCriticalExit();
304 return false;
305 }
306 int k = 0, l;
307 while ((!input.eof()) && (k < b)) {
308 input.getline(ParsedLine, 1023);
309 //Log() << Verbose(0) << "Current Line: " << ParsedLine << endl;
310 zeile.str(ParsedLine);
311 zeile.clear();
312 l = 0;
313 while ((!zeile.eof()) && (l < a)) {
314 zeile >> FitConstant[i][l][k];
315 //Log() << Verbose(0) << FitConstant[i][l][k] << "\t";
316 l++;
317 }
318 //Log() << Verbose(0) << endl;
319 k++;
320 }
321 input.close();
322 }
323 for (int k = 0; k < 3; k++) {
324 DoLog(0) && (Log() << Verbose(0) << "Constants " << k << ":" << endl);
325 for (int j = 0; j < b; j++) {
326 for (int i = 0; i < a; i++) {
327 DoLog(0) && (Log() << Verbose(0) << FitConstant[k][i][j] << "\t");
328 }
329 DoLog(0) && (Log() << Verbose(0) << endl);
330 }
331 DoLog(0) && (Log() << Verbose(0) << endl);
332 }
333
334 // 0d. allocate final correction matrix
335 correction = new double*[a];
336 for (int i = a; i--;)
337 correction[i] = new double[b];
338
339 // 1a. go through every molecule in the list
340 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
341 // 1b. zero final correction matrix
342 for (int k = a; k--;)
343 for (int j = b; j--;)
344 correction[k][j] = 0.;
345 // 2. take every hydrogen that is a saturated one
346 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
347 //Log() << Verbose(1) << "(*iter): " << *(*iter) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
348 if (((*iter)->getType()->getAtomicNumber() == 1) && (((*iter)->father == NULL)
349 || ((*iter)->father->getType()->getAtomicNumber() != 1))) { // if it's a hydrogen
350 for (molecule::const_iterator runner = (*ListRunner)->begin(); runner != (*ListRunner)->end(); ++runner) {
351 //Log() << Verbose(2) << "Runner: " << *(*runner) << " with first bond " << *((*iter)->ListOfBonds.begin()) << "." << endl;
352 // 3. take every other hydrogen that is the not the first and not bound to same bonding partner
353 Binder = *((*runner)->ListOfBonds.begin());
354 if (((*runner)->getType()->getAtomicNumber() == 1) && ((*runner)->nr > (*iter)->nr) && (Binder->GetOtherAtom((*runner)) != Binder->GetOtherAtom((*iter)))) { // (hydrogens have only one bonding partner!)
355 // 4. evaluate the morse potential for each matrix component and add up
356 distance = (*runner)->distance(*(*iter));
357 //Log() << Verbose(0) << "Fragment " << (*ListRunner)->name << ": " << *(*runner) << "<= " << distance << "=>" << *(*iter) << ":" << endl;
358 for (int k = 0; k < a; k++) {
359 for (int j = 0; j < b; j++) {
360 switch (k) {
361 case 1:
362 case 7:
363 case 11:
364 tmp = pow(FitConstant[0][k][j] * (1. - exp(-FitConstant[1][k][j] * (distance - FitConstant[2][k][j]))), 2);
365 break;
366 default:
367 tmp = FitConstant[0][k][j] * pow(distance, FitConstant[1][k][j]) + FitConstant[2][k][j];
368 };
369 correction[k][j] -= tmp; // ground state is actually lower (disturbed by additional interaction)
370 //Log() << Verbose(0) << tmp << "\t";
371 }
372 //Log() << Verbose(0) << endl;
373 }
374 //Log() << Verbose(0) << endl;
375 }
376 }
377 }
378 }
379 // 5. write final matrix to file
380 line = path;
381 line.append("/");
382 line += FRAGMENTPREFIX;
383 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), (*ListRunner)->IndexNr);
384 line += FragmentNumber;
385 delete[] (FragmentNumber);
386 line += HCORRECTIONSUFFIX;
387 output.open(line.c_str());
388 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
389 for (int j = 0; j < b; j++) {
390 for (int i = 0; i < a; i++)
391 output << correction[i][j] << "\t";
392 output << endl;
393 }
394 output.close();
395 }
396 for (int i = a; i--;)
397 delete[](correction[i]);
398 delete[](correction);
399
400 line = path;
401 line.append("/");
402 line += HCORRECTIONSUFFIX;
403 output.open(line.c_str());
404 output << "Time\t\tTotal\t\tKinetic\t\tNonLocal\tCorrelation\tExchange\tPseudo\t\tHartree\t\t-Gauss\t\tEwald\t\tIonKin\t\tETotal" << endl;
405 for (int j = 0; j < b; j++) {
406 for (int i = 0; i < a; i++)
407 output << 0 << "\t";
408 output << endl;
409 }
410 output.close();
411 // 6. free memory of parsed matrices
412 for (int k = 0; k < 3; k++) {
413 for (int i = a; i--;) {
414 delete[](FitConstant[k][i]);
415 }
416 delete[](FitConstant[k]);
417 }
418 delete[](FitConstant);
419 DoLog(0) && (Log() << Verbose(0) << "done." << endl);
420 return true;
421};
422
423/** Store force indices, i.e. the connection between the nuclear index in the total molecule config and the respective atom in fragment config.
424 * \param &path path to file
425 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
426 * \return true - file written successfully, false - writing failed
427 */
428bool MoleculeListClass::StoreForcesFile(std::string &path, int *SortIndex)
429{
430 bool status = true;
431 string filename(path);
432 filename += FORCESFILE;
433 ofstream ForcesFile(filename.c_str());
434 periodentafel *periode=World::getInstance().getPeriode();
435
436 // open file for the force factors
437 DoLog(1) && (Log() << Verbose(1) << "Saving force factors ... ");
438 if (!ForcesFile.fail()) {
439 //Log() << Verbose(1) << "Final AtomicForcesList: ";
440 //output << prefix << "Forces" << endl;
441 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
442 periodentafel::const_iterator elemIter;
443 for(elemIter=periode->begin();elemIter!=periode->end();++elemIter){
444 if ((*ListRunner)->hasElement((*elemIter).first)) { // if this element got atoms
445 for(molecule::iterator atomIter = (*ListRunner)->begin(); atomIter !=(*ListRunner)->end();++atomIter){
446 if ((*atomIter)->getType()->getNumber() == (*elemIter).first) {
447 if (((*atomIter)->GetTrueFather() != NULL) && ((*atomIter)->GetTrueFather() != (*atomIter))) {// if there is a rea
448 //Log() << Verbose(0) << "Walker is " << *Walker << " with true father " << *( Walker->GetTrueFather()) << ", it
449 ForcesFile << SortIndex[(*atomIter)->GetTrueFather()->nr] << "\t";
450 } else
451 // otherwise a -1 to indicate an added saturation hydrogen
452 ForcesFile << "-1\t";
453 }
454 }
455 }
456 }
457 ForcesFile << endl;
458 }
459 ForcesFile.close();
460 DoLog(1) && (Log() << Verbose(1) << "done." << endl);
461 } else {
462 status = false;
463 DoLog(1) && (Log() << Verbose(1) << "failed to open file " << filename << "." << endl);
464 }
465 ForcesFile.close();
466
467 return status;
468};
469
470/** Writes a config file for each molecule in the given \a **FragmentList.
471 * \param *out output stream for debugging
472 * \param &prefix path and prefix to the fragment config files
473 * \param *SortIndex Index to map from the BFS labeling to the sequence how of Ion_Type in the config
474 * \return true - success (each file was written), false - something went wrong.
475 */
476bool MoleculeListClass::OutputConfigForListOfFragments(std::string &prefix, int *SortIndex)
477{
478 ofstream outputFragment;
479 std::string FragmentName;
480 char PathBackup[MAXSTRINGSIZE];
481 bool result = true;
482 bool intermediateResult = true;
483 Vector BoxDimension;
484 char *FragmentNumber = NULL;
485 char *path = NULL;
486 int FragmentCounter = 0;
487 ofstream output;
488 RealSpaceMatrix cell_size = World::getInstance().getDomain().getM();
489 RealSpaceMatrix cell_size_backup = cell_size;
490
491 // store the fragments as config and as xyz
492 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++) {
493 // save default path as it is changed for each fragment
494 path = World::getInstance().getConfig()->GetDefaultPath();
495 if (path != NULL)
496 strcpy(PathBackup, path);
497 else {
498 DoeLog(0) && (eLog()<< Verbose(0) << "OutputConfigForListOfFragments: NULL default path obtained from config!" << endl);
499 performCriticalExit();
500 }
501
502 // correct periodic
503 (*ListRunner)->ScanForPeriodicCorrection();
504
505 // output xyz file
506 FragmentNumber = FixedDigitNumber(ListOfMolecules.size(), FragmentCounter++);
507 FragmentName = prefix + FragmentNumber + ".conf.xyz";
508 outputFragment.open(FragmentName.c_str(), ios::out);
509 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as XYZ ...");
510 if ((intermediateResult = (*ListRunner)->OutputXYZ(&outputFragment)))
511 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
512 else
513 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
514 result = result && intermediateResult;
515 outputFragment.close();
516 outputFragment.clear();
517
518 // list atoms in fragment for debugging
519 DoLog(2) && (Log() << Verbose(2) << "Contained atoms: ");
520 for (molecule::const_iterator iter = (*ListRunner)->begin(); iter != (*ListRunner)->end(); ++iter) {
521 DoLog(0) && (Log() << Verbose(0) << (*iter)->getName() << " ");
522 }
523 DoLog(0) && (Log() << Verbose(0) << endl);
524
525 // center on edge
526 (*ListRunner)->CenterEdge(&BoxDimension);
527 (*ListRunner)->SetBoxDimension(&BoxDimension); // update Box of atoms by boundary
528 for (int k = 0; k < NDIM; k++) {
529 BoxDimension[k] = 2.5 * (World::getInstance().getConfig()->GetIsAngstroem() ? 1. : 1. / AtomicLengthToAngstroem);
530 cell_size.at(k,k) = BoxDimension[k] * 2.;
531 }
532 World::getInstance().setDomain(cell_size);
533 (*ListRunner)->Translate(&BoxDimension);
534
535 // also calculate necessary orbitals
536 //(*ListRunner)->CalculateOrbitals(*World::getInstance().getConfig);
537
538 // change path in config
539 FragmentName = PathBackup;
540 FragmentName += "/";
541 FragmentName += FRAGMENTPREFIX;
542 FragmentName += FragmentNumber;
543 FragmentName += "/";
544 World::getInstance().getConfig()->SetDefaultPath(FragmentName.c_str());
545
546 // and save as config
547 FragmentName = prefix + FragmentNumber + ".conf";
548 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as config ...");
549 if ((intermediateResult = World::getInstance().getConfig()->Save(FragmentName.c_str(), (*ListRunner)->elemente, (*ListRunner))))
550 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
551 else
552 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
553 result = result && intermediateResult;
554
555 // restore old config
556 World::getInstance().getConfig()->SetDefaultPath(PathBackup);
557
558 // and save as mpqc input file
559 FragmentName = prefix + FragmentNumber + ".conf";
560 DoLog(2) && (Log() << Verbose(2) << "Saving bond fragment No. " << FragmentNumber << "/" << FragmentCounter - 1 << " as mpqc input ...");
561 if ((intermediateResult = World::getInstance().getConfig()->SaveMPQC(FragmentName.c_str(), (*ListRunner))))
562 DoLog(2) && (Log() << Verbose(2) << " done." << endl);
563 else
564 DoLog(0) && (Log() << Verbose(0) << " failed." << endl);
565
566 result = result && intermediateResult;
567 //outputFragment.close();
568 //outputFragment.clear();
569 delete[](FragmentNumber);
570 }
571 DoLog(0) && (Log() << Verbose(0) << " done." << endl);
572
573 // printing final number
574 DoLog(2) && (Log() << Verbose(2) << "Final number of fragments: " << FragmentCounter << "." << endl);
575
576 // restore cell_size
577 World::getInstance().setDomain(cell_size_backup);
578
579 return result;
580};
581
582/** Counts the number of molecules with the molecule::ActiveFlag set.
583 * \return number of molecules with ActiveFlag set to true.
584 */
585int MoleculeListClass::NumberOfActiveMolecules()
586{
587 int count = 0;
588 for (MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
589 count += ((*ListRunner)->ActiveFlag ? 1 : 0);
590 return count;
591};
592
593/** Count all atoms in each molecule.
594 * \return number of atoms in the MoleculeListClass.
595 * TODO: the inner loop should be done by some (double molecule::CountAtom()) function
596 */
597int MoleculeListClass::CountAllAtoms() const
598{
599 int AtomNo = 0;
600 for (MoleculeList::const_iterator MolWalker = ListOfMolecules.begin(); MolWalker != ListOfMolecules.end(); MolWalker++) {
601 AtomNo += (*MolWalker)->size();
602 }
603 return AtomNo;
604}
605
606/***********
607 * Methods Moved here from the menus
608 */
609
610void MoleculeListClass::createNewMolecule(periodentafel *periode) {
611 OBSERVE;
612 molecule *mol = NULL;
613 mol = World::getInstance().createMolecule();
614 insert(mol);
615};
616
617void MoleculeListClass::loadFromXYZ(periodentafel *periode){
618 molecule *mol = NULL;
619 Vector center;
620 char filename[MAXSTRINGSIZE];
621 Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
622 mol = World::getInstance().createMolecule();
623 do {
624 Log() << Verbose(0) << "Enter file name: ";
625 cin >> filename;
626 } while (!mol->AddXYZFile(filename));
627 mol->SetNameFromFilename(filename);
628 // center at set box dimensions
629 mol->CenterEdge(&center);
630 RealSpaceMatrix domain;
631 for(int i =0;i<NDIM;++i)
632 domain.at(i,i) = center[i];
633 World::getInstance().setDomain(domain);
634 insert(mol);
635}
636
637void MoleculeListClass::setMoleculeFilename() {
638 char filename[MAXSTRINGSIZE];
639 int nr;
640 molecule *mol = NULL;
641 do {
642 Log() << Verbose(0) << "Enter index of molecule: ";
643 cin >> nr;
644 mol = ReturnIndex(nr);
645 } while (mol == NULL);
646 Log() << Verbose(0) << "Enter name: ";
647 cin >> filename;
648 mol->SetNameFromFilename(filename);
649}
650
651void MoleculeListClass::parseXYZIntoMolecule(){
652 char filename[MAXSTRINGSIZE];
653 int nr;
654 molecule *mol = NULL;
655 mol = NULL;
656 do {
657 Log() << Verbose(0) << "Enter index of molecule: ";
658 cin >> nr;
659 mol = ReturnIndex(nr);
660 } while (mol == NULL);
661 Log() << Verbose(0) << "Format should be XYZ with: ShorthandOfElement\tX\tY\tZ" << endl;
662 do {
663 Log() << Verbose(0) << "Enter file name: ";
664 cin >> filename;
665 } while (!mol->AddXYZFile(filename));
666 mol->SetNameFromFilename(filename);
667};
668
669void MoleculeListClass::eraseMolecule(){
670 int nr;
671 molecule *mol = NULL;
672 Log() << Verbose(0) << "Enter index of molecule: ";
673 cin >> nr;
674 for(MoleculeList::iterator ListRunner = ListOfMolecules.begin(); ListRunner != ListOfMolecules.end(); ListRunner++)
675 if (nr == (*ListRunner)->IndexNr) {
676 mol = *ListRunner;
677 ListOfMolecules.erase(ListRunner);
678 World::getInstance().destroyMolecule(mol);
679 break;
680 }
681};
682
683
684/******************************************* Class MoleculeLeafClass ************************************************/
685
686/** Constructor for MoleculeLeafClass root leaf.
687 * \param *Up Leaf on upper level
688 * \param *PreviousLeaf NULL - We are the first leaf on this level, otherwise points to previous in list
689 */
690//MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *Up = NULL, MoleculeLeafClass *Previous = NULL)
691MoleculeLeafClass::MoleculeLeafClass(MoleculeLeafClass *PreviousLeaf = NULL) :
692 Leaf(NULL),
693 previous(PreviousLeaf)
694{
695 // if (Up != NULL)
696 // if (Up->DownLeaf == NULL) // are we the first down leaf for the upper leaf?
697 // Up->DownLeaf = this;
698 // UpLeaf = Up;
699 // DownLeaf = NULL;
700 if (previous != NULL) {
701 MoleculeLeafClass *Walker = previous->next;
702 previous->next = this;
703 next = Walker;
704 } else {
705 next = NULL;
706 }
707};
708
709/** Destructor for MoleculeLeafClass.
710 */
711MoleculeLeafClass::~MoleculeLeafClass()
712{
713 // if (DownLeaf != NULL) {// drop leaves further down
714 // MoleculeLeafClass *Walker = DownLeaf;
715 // MoleculeLeafClass *Next;
716 // do {
717 // Next = Walker->NextLeaf;
718 // delete(Walker);
719 // Walker = Next;
720 // } while (Walker != NULL);
721 // // Last Walker sets DownLeaf automatically to NULL
722 // }
723 // remove the leaf itself
724 if (Leaf != NULL) {
725 World::getInstance().destroyMolecule(Leaf);
726 Leaf = NULL;
727 }
728 // remove this Leaf from level list
729 if (previous != NULL)
730 previous->next = next;
731 // } else { // we are first in list (connects to UpLeaf->DownLeaf)
732 // if ((NextLeaf != NULL) && (NextLeaf->UpLeaf == NULL))
733 // NextLeaf->UpLeaf = UpLeaf; // either null as we are top level or the upleaf of the first node
734 // if (UpLeaf != NULL)
735 // UpLeaf->DownLeaf = NextLeaf; // either null as we are only leaf or NextLeaf if we are just the first
736 // }
737 // UpLeaf = NULL;
738 if (next != NULL) // are we last in list
739 next->previous = previous;
740 next = NULL;
741 previous = NULL;
742};
743
744/** Adds \a molecule leaf to the tree.
745 * \param *ptr ptr to molecule to be added
746 * \param *Previous previous MoleculeLeafClass referencing level and which on the level
747 * \return true - success, false - something went wrong
748 */
749bool MoleculeLeafClass::AddLeaf(molecule *ptr, MoleculeLeafClass *Previous)
750{
751 return false;
752};
753
754/** Fills the bond structure of this chain list subgraphs that are derived from a complete \a *reference molecule.
755 * Calls this routine in each MoleculeLeafClass::next subgraph if it's not NULL.
756 * \param *out output stream for debugging
757 * \param *reference reference molecule with the bond structure to be copied
758 * \param **&ListOfLocalAtoms Lookup table for this subgraph and index of each atom in \a *reference, may be NULL on start, then it is filled
759 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
760 * \return true - success, false - faoilure
761 */
762bool MoleculeLeafClass::FillBondStructureFromReference(const molecule * const reference, atom **&ListOfLocalAtoms, bool FreeList)
763{
764 atom *OtherWalker = NULL;
765 atom *Father = NULL;
766 bool status = true;
767 int AtomNo;
768
769 DoLog(1) && (Log() << Verbose(1) << "Begin of FillBondStructureFromReference." << endl);
770 // fill ListOfLocalAtoms if NULL was given
771 if (!FillListOfLocalAtoms(ListOfLocalAtoms, reference->getAtomCount(), FreeList)) {
772 DoLog(1) && (Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl);
773 return false;
774 }
775
776 if (status) {
777 DoLog(1) && (Log() << Verbose(1) << "Creating adjacency list for subgraph " << Leaf << "." << endl);
778 // remove every bond from the list
779 for(molecule::iterator AtomRunner = Leaf->begin(); AtomRunner != Leaf->end(); ++AtomRunner)
780 for(BondList::iterator BondRunner = (*AtomRunner)->ListOfBonds.begin(); !(*AtomRunner)->ListOfBonds.empty(); BondRunner = (*AtomRunner)->ListOfBonds.begin())
781 if ((*BondRunner)->leftatom == *AtomRunner)
782 delete((*BondRunner));
783
784 for(molecule::const_iterator iter = Leaf->begin(); iter != Leaf->end(); ++iter) {
785 Father = (*iter)->GetTrueFather();
786 AtomNo = Father->nr; // global id of the current walker
787 for (BondList::const_iterator Runner = Father->ListOfBonds.begin(); Runner != Father->ListOfBonds.end(); (++Runner)) {
788 OtherWalker = ListOfLocalAtoms[(*Runner)->GetOtherAtom((*iter)->GetTrueFather())->nr]; // local copy of current bond partner of walker
789 if (OtherWalker != NULL) {
790 if (OtherWalker->nr > (*iter)->nr)
791 Leaf->AddBond((*iter), OtherWalker, (*Runner)->BondDegree);
792 } else {
793 DoLog(1) && (Log() << Verbose(1) << "OtherWalker = ListOfLocalAtoms[" << (*Runner)->GetOtherAtom((*iter)->GetTrueFather())->nr << "] is NULL!" << endl);
794 status = false;
795 }
796 }
797 }
798 }
799
800 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
801 // free the index lookup list
802 delete[](ListOfLocalAtoms);
803 }
804 DoLog(1) && (Log() << Verbose(1) << "End of FillBondStructureFromReference." << endl);
805 return status;
806};
807
808/** Fills the root stack for sites to be used as root in fragmentation depending on order or adaptivity criteria
809 * Again, as in \sa FillBondStructureFromReference steps recursively through each Leaf in this chain list of molecule's.
810 * \param *out output stream for debugging
811 * \param *&RootStack stack to be filled
812 * \param *AtomMask defines true/false per global Atom::nr to mask in/out each nuclear site
813 * \param &FragmentCounter counts through the fragments in this MoleculeLeafClass
814 * \return true - stack is non-empty, fragmentation necessary, false - stack is empty, no more sites to update
815 */
816bool MoleculeLeafClass::FillRootStackForSubgraphs(KeyStack *&RootStack, bool *AtomMask, int &FragmentCounter)
817{
818 atom *Father = NULL;
819
820 if (RootStack != NULL) {
821 // find first root candidates
822 if (&(RootStack[FragmentCounter]) != NULL) {
823 RootStack[FragmentCounter].clear();
824 for(molecule::const_iterator iter = Leaf->begin(); iter != Leaf->end(); ++iter) {
825 Father = (*iter)->GetTrueFather();
826 if (AtomMask[Father->nr]) // apply mask
827#ifdef ADDHYDROGEN
828 if ((*iter)->getType()->getAtomicNumber() != 1) // skip hydrogen
829#endif
830 RootStack[FragmentCounter].push_front((*iter)->nr);
831 }
832 if (next != NULL)
833 next->FillRootStackForSubgraphs(RootStack, AtomMask, ++FragmentCounter);
834 } else {
835 DoLog(1) && (Log() << Verbose(1) << "Rootstack[" << FragmentCounter << "] is NULL." << endl);
836 return false;
837 }
838 FragmentCounter--;
839 return true;
840 } else {
841 DoLog(1) && (Log() << Verbose(1) << "Rootstack is NULL." << endl);
842 return false;
843 }
844};
845
846/** Fills a lookup list of father's Atom::nr -> atom for each subgraph.
847 * \param *out output stream from debugging
848 * \param **&ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
849 * \param GlobalAtomCount number of atoms in the complete molecule
850 * \param &FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
851 * \return true - success, false - failure (ListOfLocalAtoms != NULL)
852 */
853bool MoleculeLeafClass::FillListOfLocalAtoms(atom **&ListOfLocalAtoms, const int GlobalAtomCount, bool &FreeList)
854{
855 bool status = true;
856
857 if (ListOfLocalAtoms == NULL) { // allocate and fill list of this fragment/subgraph
858 status = status && Leaf->CreateFatherLookupTable(ListOfLocalAtoms, GlobalAtomCount);
859 FreeList = FreeList && true;
860 } else
861 return false;
862
863 return status;
864};
865
866/** The indices per keyset are compared to the respective father's Atom::nr in each subgraph and thus put into \a **&FragmentList.
867 * \param *out output stream fro debugging
868 * \param *reference reference molecule with the bond structure to be copied
869 * \param *KeySetList list with all keysets
870 * \param ***ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
871 * \param **&FragmentList list to be allocated and returned
872 * \param &FragmentCounter counts the fragments as we move along the list
873 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
874 * \retuen true - success, false - failure
875 */
876bool MoleculeLeafClass::AssignKeySetsToFragment(molecule *reference, Graph *KeySetList, atom ***&ListOfLocalAtoms, Graph **&FragmentList, int &FragmentCounter, bool FreeList)
877{
878 bool status = true;
879 int KeySetCounter = 0;
880
881 DoLog(1) && (Log() << Verbose(1) << "Begin of AssignKeySetsToFragment." << endl);
882 // fill ListOfLocalAtoms if NULL was given
883 if (!FillListOfLocalAtoms(ListOfLocalAtoms[FragmentCounter], reference->getAtomCount(), FreeList)) {
884 DoLog(1) && (Log() << Verbose(1) << "Filling of ListOfLocalAtoms failed." << endl);
885 return false;
886 }
887
888 // allocate fragment list
889 if (FragmentList == NULL) {
890 KeySetCounter = Count();
891 FragmentList = new Graph*[KeySetCounter];
892 for (int i=0;i<KeySetCounter;i++)
893 FragmentList[i] = NULL;
894 KeySetCounter = 0;
895 }
896
897 if ((KeySetList != NULL) && (KeySetList->size() != 0)) { // if there are some scanned keysets at all
898 // assign scanned keysets
899 if (FragmentList[FragmentCounter] == NULL)
900 FragmentList[FragmentCounter] = new Graph;
901 KeySet *TempSet = new KeySet;
902 for (Graph::iterator runner = KeySetList->begin(); runner != KeySetList->end(); runner++) { // key sets contain global numbers!
903 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
904 // translate keyset to local numbers
905 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
906 TempSet->insert(ListOfLocalAtoms[FragmentCounter][reference->FindAtom(*sprinter)->nr]->nr);
907 // insert into FragmentList
908 FragmentList[FragmentCounter]->insert(GraphPair(*TempSet, pair<int, double> (KeySetCounter++, (*runner).second.second)));
909 }
910 TempSet->clear();
911 }
912 delete (TempSet);
913 if (KeySetCounter == 0) {// if there are no keysets, delete the list
914 DoLog(1) && (Log() << Verbose(1) << "KeySetCounter is zero, deleting FragmentList." << endl);
915 delete (FragmentList[FragmentCounter]);
916 } else
917 DoLog(1) && (Log() << Verbose(1) << KeySetCounter << " keysets were assigned to subgraph " << FragmentCounter << "." << endl);
918 FragmentCounter++;
919 if (next != NULL)
920 next->AssignKeySetsToFragment(reference, KeySetList, ListOfLocalAtoms, FragmentList, FragmentCounter, FreeList);
921 FragmentCounter--;
922 } else
923 DoLog(1) && (Log() << Verbose(1) << "KeySetList is NULL or empty." << endl);
924
925 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
926 // free the index lookup list
927 delete[](ListOfLocalAtoms[FragmentCounter]);
928 }
929 DoLog(1) && (Log() << Verbose(1) << "End of AssignKeySetsToFragment." << endl);
930 return status;
931};
932
933/** Translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
934 * \param *out output stream for debugging
935 * \param **FragmentList Graph with local numbers per fragment
936 * \param &FragmentCounter counts the fragments as we move along the list
937 * \param &TotalNumberOfKeySets global key set counter
938 * \param &TotalGraph Graph to be filled with global numbers
939 */
940void MoleculeLeafClass::TranslateIndicesToGlobalIDs(Graph **FragmentList, int &FragmentCounter, int &TotalNumberOfKeySets, Graph &TotalGraph)
941{
942 DoLog(1) && (Log() << Verbose(1) << "Begin of TranslateIndicesToGlobalIDs." << endl);
943 KeySet *TempSet = new KeySet;
944 if (FragmentList[FragmentCounter] != NULL) {
945 for (Graph::iterator runner = FragmentList[FragmentCounter]->begin(); runner != FragmentList[FragmentCounter]->end(); runner++) {
946 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
947 TempSet->insert((Leaf->FindAtom(*sprinter))->GetTrueFather()->nr);
948 TotalGraph.insert(GraphPair(*TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
949 TempSet->clear();
950 }
951 delete (TempSet);
952 } else {
953 DoLog(1) && (Log() << Verbose(1) << "FragmentList is NULL." << endl);
954 }
955 if (next != NULL)
956 next->TranslateIndicesToGlobalIDs(FragmentList, ++FragmentCounter, TotalNumberOfKeySets, TotalGraph);
957 FragmentCounter--;
958 DoLog(1) && (Log() << Verbose(1) << "End of TranslateIndicesToGlobalIDs." << endl);
959};
960
961/** Simply counts the number of items in the list, from given MoleculeLeafClass.
962 * \return number of items
963 */
964int MoleculeLeafClass::Count() const
965{
966 if (next != NULL)
967 return next->Count() + 1;
968 else
969 return 1;
970};
971
Note: See TracBrowser for help on using the repository browser.