source: src/moleculelist.cpp@ e5c233

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

Removed FixedDigitNumber from Helpers/helpers.

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