source: src/moleculelist.cpp@ 9cd807

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 9cd807 was 2b7d1b, checked in by Frederik Heber <heber@…>, 15 years ago

Merged MoleculeListClass::DissectMoleculeIntoConnectedSubgraphs() into FragmenationSubgraphDissectionAction.

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