source: src/moleculelist.cpp@ 37b2575

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

Some fixes to parsing files.

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