source: src/moleculelist.cpp@ 111387

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

Moved bond.* to Bond/, new class GraphEdge which contains graph parts of bond.

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