source: src/moleculelist.cpp@ ba94c5

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

Extracted Graph (map of KeySets) into own class from graph.hpp.

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