source: src/moleculelist.cpp@ f0674a

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

Extracted KeySet from graph.hpp and made into distinct class.

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